diff --git a/.travis.yml b/.travis.yml index 055c1aa17..da3799985 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,6 @@ sudo: required language: java -services: - - docker - jdk: - openjdk8 # - openjdk11 @@ -12,14 +9,6 @@ matrix: allow_failures: - jdk: openjdk11 -before_install: - # Disable services enabled by default - - sudo service mysql stop - - sudo /etc/init.d/postgresql stop - - # Run my databases in the background - - docker-compose -f docker/docker-compose-travis.yml up -d - install: - TERM=dumb ./gradlew assemble diff --git a/README.md b/README.md index 71c3905d3..fdb7b364e 100644 --- a/README.md +++ b/README.md @@ -21,9 +21,9 @@ Welcome to the **Jodd** - a unique, alternative world of Java :) You can find he Check the official web-site: https://jodd.org -## ‼️ The Future and Jodd Versions +## ‼️ The Future and Jodd Versions ‼️ -Version **v6** is the maintained version, working on Java 8 and 11. Only few components are promoted to v6: +Version **v6** is the maintained version, working on Java 8 and 11. the following components are promoted to v6: + [jodd-util](https://github.com/oblac/jodd-util) ⭐ + [jodd-mail](https://github.com/oblac/jodd-mail) ⭐ @@ -31,6 +31,9 @@ Version **v6** is the maintained version, working on Java 8 and 11. Only few com + [jodd-lagarto](https://github.com/oblac/jodd-lagarto) ⭐ + [jodd-http](https://github.com/oblac/jodd-http) ⭐ + [jodd-props](https://github.com/oblac/jodd-props) ⭐ ++ [jodd-petite](https://github.com/oblac/jodd-petite) ⭐ ++ [jodd-proxetta](https://github.com/oblac/jodd-proxetta) ⭐ ++ [jodd-db](https://github.com/oblac/jodd-db) ⭐ The decision which component is promoted is based on the Maven Central Repo statistics. @@ -54,10 +57,10 @@ _Use what you like._ **Thank you.** 🙏 **Micro-frameworks**: + `jodd-madvoc` - slick MVC framework. -+ `jodd-petite` - pragmatic DI container. -+ `jodd-proxetta` - dynamic proxies and `Paramo`. -+ `jodd-db` - thin database layer and object mapper. -+ `jodd-jtx` - transactions management. ++ `jodd-petite` - pragmatic DI container. ⭐ ++ `jodd-proxetta` - dynamic proxies and `Paramo`. ⭐ ++ `jodd-db` - thin database layer and object mapper. ⭐ ++ `jodd-jtx` - transactions management. ⭐ **Less used tools**: diff --git a/docker/docker-compose-test.yml b/docker/docker-compose-test.yml deleted file mode 100644 index 451cc7730..000000000 --- a/docker/docker-compose-test.yml +++ /dev/null @@ -1,25 +0,0 @@ -version: '2' -services: - - postgres: - image: postgres:9.4.4 - environment: - - POSTGRES_DB=jodd_test - - POSTGRES_USER=postgres - - POSTGRES_PASSWORD=root! - - LC_ALL=C.UTF-8 - ports: - - "5432:5432" - - mysql: - image: mysql:5.6 - environment: - - MYSQL_DATABASE=jodd_test - - MYSQL_ROOT_PASSWORD=root! - ports: - - "3306:3306" - - mssql: - build: mssql/. - ports: - - "1433:1433" diff --git a/docker/docker-compose-travis.yml b/docker/docker-compose-travis.yml deleted file mode 100644 index e086faa69..000000000 --- a/docker/docker-compose-travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -version: '2' -services: - - postgres: - image: postgres:9.4.4 - environment: - - POSTGRES_DB=jodd_test - - POSTGRES_USER=postgres - - POSTGRES_PASSWORD=root! - - LC_ALL=C.UTF-8 - ports: - - "5432:5432" - mysql: - image: mysql:5.6 - environment: - - MYSQL_DATABASE=jodd_test - - MYSQL_ROOT_PASSWORD=root! - ports: - - "3306:3306" diff --git a/docker/mssql/Dockerfile b/docker/mssql/Dockerfile deleted file mode 100644 index b335e8419..000000000 --- a/docker/mssql/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -FROM microsoft/mssql-server-linux - -ENV ACCEPT_EULA=Y -ENV SA_PASSWORD=root!R00t! - -COPY create-db.sql . -COPY create-db.sh . - -RUN chmod +x ./create-db.sh - -CMD /bin/bash ./create-db.sh \ No newline at end of file diff --git a/docker/mssql/create-db.sh b/docker/mssql/create-db.sh deleted file mode 100644 index d3cfd093b..000000000 --- a/docker/mssql/create-db.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env bash - -set -e - -readonly run_cmd="/opt/mssql-tools/bin/sqlcmd -U sa -P 'root!R00t!' -l 30 -i create-db.sql" - ->&2 echo "Allowing 30 seconds for SQL Server to bootstrap, then creating database.." - -until $run_cmd -do - >&2 echo "This should not be executing!" -done \ No newline at end of file diff --git a/docker/mssql/create-db.sql b/docker/mssql/create-db.sql deleted file mode 100644 index 207a784e5..000000000 --- a/docker/mssql/create-db.sql +++ /dev/null @@ -1,7 +0,0 @@ -USE master -GO -IF EXISTS(SELECT * FROM sys.databases WHERE name='jodd_test') - DROP DATABASE jodd_test -GO -CREATE DATABASE jodd_test -GO \ No newline at end of file diff --git a/jodd-db/build.gradle b/jodd-db/build.gradle deleted file mode 100755 index 7472f9276..000000000 --- a/jodd-db/build.gradle +++ /dev/null @@ -1,22 +0,0 @@ - -ext.moduleName = 'Jodd DbOom' -ext.moduleDescription = 'Jodd DB is efficient and thin database facade; DbOom is convenient database object mapper.' - -apply plugin: 'kotlin' - -dependencies { - api project(':jodd-core') - api project(':jodd-jtx') - api 'org.jodd:jodd-props:6.0.1' - api 'org.slf4j:slf4j-api:1.7.30' - - testImplementation lib.junit5 - testImplementation lib.hsqldb - testImplementation lib.h2db - testImplementation lib.mysql - testImplementation lib.postgresql - testImplementation lib.mssql - testImplementation lib.mockito - testImplementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" - testImplementation 'org.apache.commons:commons-lang3:3.9' -} diff --git a/jodd-db/src/main/java/jodd/db/DbCallResult.java b/jodd-db/src/main/java/jodd/db/DbCallResult.java deleted file mode 100755 index e31bc9819..000000000 --- a/jodd-db/src/main/java/jodd/db/DbCallResult.java +++ /dev/null @@ -1,300 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.db; - -import java.sql.CallableStatement; -import java.sql.SQLException; - -/** - * Result of a CALL statement. - */ -public class DbCallResult { - private final DbQueryParser query; - private final CallableStatement statement; - - DbCallResult(final DbQueryParser parser, final CallableStatement callableStatement) { - this.query = parser; - this.statement = callableStatement; - } - - // ---------------------------------------------------------------- integer - - public int getInteger(final int index) { - try { - return statement.getInt(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public int getInteger(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getInt(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public int[] getAllInteger(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final int[] result = new int[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getInt(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - // ---------------------------------------------------------------- boolean - - public boolean getBoolean(final int index) { - try { - return statement.getBoolean(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public boolean getBoolean(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getBoolean(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public boolean[] getAllBoolean(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final boolean[] result = new boolean[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getBoolean(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - // ---------------------------------------------------------------- byte - - public byte getByte(final int index) { - try { - return statement.getByte(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public byte getByte(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getByte(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public byte[] getAllByte(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final byte[] result = new byte[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getByte(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - // ---------------------------------------------------------------- doublw - - public double getDouble(final int index) { - try { - return statement.getDouble(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public double getDouble(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getDouble(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public double[] getAllDouble(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final double[] result = new double[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getDouble(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - // ---------------------------------------------------------------- float - - public float getFloat(final int index) { - try { - return statement.getFloat(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public float getFloat(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getFloat(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public float[] getAllFloat(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final float[] result = new float[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getFloat(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - - // ---------------------------------------------------------------- string - - public String getString(final int index) { - try { - return statement.getString(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public String getString(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getString(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public String[] getAllString(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final String[] result = new String[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getString(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - // ---------------------------------------------------------------- long - - public long getLong(final int index) { - try { - return statement.getLong(index); - } catch (SQLException sex) { - throw newGetParamError(index, sex); - } - } - - public long getLong(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - try { - if (positions.length == 1) { - return statement.getLong(positions[0]); - } - throw newGetParamError(param); - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - public long[] getAllLong(final String param) { - final int[] positions = query.getNamedParameterIndices(param); - final long[] result = new long[positions.length]; - try { - for (int i = 0; i < positions.length; i++) { - result[i] = statement.getLong(positions[i]); - } - return result; - } catch (SQLException sex) { - throw newGetParamError(param, sex); - } - } - - // ---------------------------------------------------------------- exception - - private DbSqlException newGetParamError(final int index, final Exception ex) { - return new DbSqlException("Invalid SQL parameter with index: " + index, ex); - } - private DbSqlException newGetParamError(final String param, final Exception ex) { - return new DbSqlException("Invalid SQL parameter with name: " + param, ex); - } - private DbSqlException newGetParamError(final String param) { - return new DbSqlException("Invalid number of parameter with name: " + param); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/DbDetector.java b/jodd-db/src/main/java/jodd/db/DbDetector.java deleted file mode 100644 index b34df4b85..000000000 --- a/jodd-db/src/main/java/jodd/db/DbDetector.java +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.db; - -import jodd.db.connection.ConnectionProvider; -import jodd.db.oom.DbOomConfig; -import jodd.db.servers.Db2DbServer; -import jodd.db.servers.DbServer; -import jodd.db.servers.DerbyDbServer; -import jodd.db.servers.GenericDbServer; -import jodd.db.servers.HsqlDbServer; -import jodd.db.servers.InformixDbServer; -import jodd.db.servers.MySqlDbServer; -import jodd.db.servers.OracleDbServer; -import jodd.db.servers.PostgreSqlDbServer; -import jodd.db.servers.SQLiteDbServer; -import jodd.db.servers.SqlServerDbServer; -import jodd.db.servers.SybaseDbServer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.SQLException; - -/** - * Database detector and DbOom configurator. - */ -public class DbDetector { - - private static final Logger log = LoggerFactory.getLogger(DbDetector.class); - - /** - * Detects database and configure DbOom engine. - */ - public DbServer detectDatabaseAndConfigureDbOom( - final ConnectionProvider cp, - final DbOomConfig dbOomConfig) { - - cp.init(); - - final Connection connection = cp.getConnection(); - - final DbServer dbServer = detectDatabase(connection); - - cp.closeConnection(connection); - - dbServer.accept(dbOomConfig); - - return dbServer; - } - - /** - * Detects database and returns {@link DbServer}. - */ - public DbServer detectDatabase(final Connection connection) { - final String dbName; - final int dbMajorVersion; - final String version; - - try { - log.info("Detecting database..."); - - final DatabaseMetaData databaseMetaData = connection.getMetaData(); - dbName = databaseMetaData.getDatabaseProductName(); - dbMajorVersion = databaseMetaData.getDatabaseMajorVersion(); - final int dbMinorVersion = databaseMetaData.getDatabaseMinorVersion(); - version = dbMajorVersion + "." + dbMinorVersion; - - log.info("Database: " + dbName + " v" + dbMajorVersion + "." + dbMinorVersion); - } - catch (final SQLException sex) { - final String msg = sex.getMessage(); - - if (msg.contains("explicitly set for database: DB2")) { - return new Db2DbServer(); - } - - throw new DbSqlException(sex); - } - - if (dbName.equals("Apache Derby")) { - return new DerbyDbServer(version); - } - if (dbName.startsWith("DB2/")) { - return new Db2DbServer(version); - } - if (dbName.equals("HSQL Database Engine")) { - return new HsqlDbServer(version); - } - if (dbName.equals("Informix Dynamic Server")) { - return new InformixDbServer(version); - } - if (dbName.startsWith("Microsoft SQL Server")) { - return new SqlServerDbServer(version); - } - if (dbName.equals("MySQL")) { - return new MySqlDbServer(version); - } - if (dbName.equals("Oracle")) { - return new OracleDbServer(version); - } - if (dbName.equals("PostgreSQL")) { - return new PostgreSqlDbServer(version); - } - if (dbName.equals("Sybase SQL Server")) { - return new SybaseDbServer(version); - } - if (dbName.equals("ASE") && (dbMajorVersion == 15)) { - return new SybaseDbServer(version); - } - if (dbName.equals("SQLite")) { - return new SQLiteDbServer(version); - } - - return new GenericDbServer(); - } -} diff --git a/jodd-db/src/main/java/jodd/db/DbOom.java b/jodd-db/src/main/java/jodd/db/DbOom.java deleted file mode 100644 index 0ce36564a..000000000 --- a/jodd-db/src/main/java/jodd/db/DbOom.java +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.db.connection.ConnectionProvider; -import jodd.db.oom.DbEntityManager; -import jodd.db.oom.DbOomConfig; -import jodd.db.oom.DbOomQuery; -import jodd.db.oom.DbSqlGenerator; -import jodd.db.oom.sqlgen.DbEntitySql; -import jodd.db.oom.sqlgen.DbSqlBuilder; -import jodd.db.pool.CoreConnectionPool; -import jodd.db.querymap.EmptyQueryMap; -import jodd.db.querymap.QueryMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Starting class that all DBOOM starts from. - * It encapsulate the database and works like a factory for all - * db-related classes. This way you can have multiple connections. - */ -public class DbOom { - - private static final Logger log = LoggerFactory.getLogger(DbOom.class); - - /** - * The first DbOom is the default one, when only one is set. - * When you have two or more DbOom's the default dbOom is deregistered. - */ - private static DbOom defaultDbOom; - - /** - * Returns default DbOom instance. If multiple DbOoms are in use, - * an exception is thrown. - */ - public static DbOom get() { - if (defaultDbOom == null) { - throw new DbSqlException( - "No default DbOom available. Use DbOom to create one.\n" + - "If more then one DbOom is in use, there is no default instance."); - } - return defaultDbOom; - } - - // ---------------------------------------------------------------- builder - - /** - * Creates a new DbOom builder. - */ - public static Builder create() { - return new Builder(); - } - - public static class Builder { - private ConnectionProvider connectionProvider; - private DbSessionProvider dbSessionProvider; - private QueryMap queryMap; - - public Builder withSessionProvider(final DbSessionProvider sessionProvider) { - this.dbSessionProvider = sessionProvider; - return this; - } - - public Builder withConnectionProvider(final ConnectionProvider connectionProvider) { - this.connectionProvider = connectionProvider; - return this; - } - - public Builder withQueryMap(final QueryMap queryMap) { - this.queryMap = queryMap; - return this; - } - - /** - * Creates new DbOom. - */ - public DbOom get() { - if (connectionProvider == null) { - connectionProvider = new CoreConnectionPool(); - } - if (dbSessionProvider == null) { - dbSessionProvider = new ThreadDbSessionProvider(); - } - if (queryMap == null) { - queryMap = new EmptyQueryMap(); - } - return new DbOom(connectionProvider, dbSessionProvider, queryMap); - } - } - - private final ConnectionProvider connectionProvider; - private final DbSessionProvider dbSessionProvider; - private final QueryMap queryMap; - - private final DbQueryConfig dbQueryConfig; - private final DbOomConfig dbOomConfig; - private final DbEntityManager dbEntityManager; - private final DbEntitySql dbEntitySql; - - // ---------------------------------------------------------------- class - - /** - * Creates new DbOom. - */ - public DbOom( - final ConnectionProvider connectionProvider, - final DbSessionProvider dbSessionProvider, - final QueryMap queryMap) { - this.connectionProvider = connectionProvider; - this.dbSessionProvider = dbSessionProvider; - this.queryMap = queryMap; - - this.dbOomConfig = new DbOomConfig(); - this.dbQueryConfig = new DbQueryConfig(); - this.dbEntityManager = new DbEntityManager(dbOomConfig); - this.dbEntitySql = new DbEntitySql(this); - - // static init - - if (defaultDbOom == null) { - log.info("Default DbOom is created."); - defaultDbOom = this; - } - else { - log.warn("Multiple DbOom detected."); - defaultDbOom = null; - } - } - - /** - * Initializes the DbOom by connecting to the database. Database will be detected - * and DbOom will be configured to match it. - */ - public DbOom connect() { - connectionProvider.init(); - - final DbDetector dbDetector = new DbDetector(); - - dbDetector.detectDatabaseAndConfigureDbOom(connectionProvider, dbOomConfig); - - return this; - } - - /** - * Closes the DbOom. - */ - public void shutdown() { - if (defaultDbOom == this) { - defaultDbOom = null; - } - connectionProvider.close(); - } - - // ---------------------------------------------------------------- instances - - /** - * Returns DbOom configuration. - */ - public DbOomConfig config() { - return dbOomConfig; - } - - /** - * Returns default query configuration. - */ - public DbQueryConfig queryConfig() { - return dbQueryConfig; - } - - /** - * Returns DbOoom entity manager. - */ - public DbEntityManager entityManager() { - return dbEntityManager; - } - - /** - * Returns DbSession provider. - */ - public DbSessionProvider sessionProvider() { - return dbSessionProvider; - } - - /** - * Returns connection provider. - */ - public ConnectionProvider connectionProvider() { - return connectionProvider; - } - - /** - * Returns a query map. - */ - public QueryMap queryMap() { - return queryMap; - } - - // ---------------------------------------------------------------- entity - - /** - * Returns Entity SQL factory. - */ - public DbEntitySql entities() { - return dbEntitySql; - } - - // ---------------------------------------------------------------- factories - - /** - * Creates new T-SQL builder. - */ - public DbSqlBuilder sql(final String sql) { - return new DbSqlBuilder(this, sql); - } - - /** - * Creates new empty T-SQL builder. - */ - public DbSqlBuilder sql() { - return new DbSqlBuilder(this); - } - - /** - * Creates a query. - */ - public DbOomQuery query(final String sql) { - return new DbOomQuery(this, sessionProvider().getDbSession(), sql); - } - - /** - * Creates a query from a sql generator. - */ - public DbOomQuery query(final DbSqlGenerator sql) { - return new DbOomQuery(this, sessionProvider().getDbSession(), sql); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/DbQuery.java b/jodd-db/src/main/java/jodd/db/DbQuery.java deleted file mode 100755 index e1220acd3..000000000 --- a/jodd-db/src/main/java/jodd/db/DbQuery.java +++ /dev/null @@ -1,1267 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.bean.BeanUtil; -import jodd.db.type.SqlType; -import jodd.db.type.SqlTypeManager; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.net.URL; -import java.sql.Array; -import java.sql.Blob; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.Date; -import java.sql.Ref; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Time; -import java.sql.Timestamp; -import java.sql.Types; -import java.util.Map; - -/** - * Encapsulates {@link Statement} and all its operations. - *

- * It may be: - *

- *

- * Query life-cycle states: - *

- */ -public class DbQuery extends DbQueryBase { - - /** - * Creates new query. - */ - public DbQuery(final DbOom dbOom, final Connection conn, final String sqlString) { - super(dbOom); - this.connection = conn; - this.sqlString = sqlString; - } - - public static DbQuery query(final Connection conn, final String sqlString) { - return new DbQuery(DbOom.get(), conn, sqlString); - } - - /** - * Creates a new query from {@link DbSession}. - */ - public DbQuery(final DbOom dbOom, final DbSession session, final String sqlString) { - super(dbOom); - initSession(session); - this.session.attachQuery(this); - this.sqlString = sqlString; - } - - public static DbQuery query(final DbSession session, final String sqlString) { - return new DbQuery(DbOom.get(), session, sqlString); - } - - /** - * Creates a new query using default session provider. - */ - public DbQuery(final DbOom dbOom, final String sqlString) { - this(dbOom, (DbSession)null, sqlString); - } - - public static DbQuery query(final String sqlString) { - return new DbQuery(DbOom.get(), sqlString); - } - - - // ---------------------------------------------------------------- additional statement parameters - - /** - * Clears the current parameter values immediately. - *

- * In general, parameter values remain in force for repeated use of a - * statement. Setting a parameter value automatically clears its - * previous value. However, in some cases it is useful to immediately - * release the resources used by the current parameter values; this can - * be done by calling the method clearParameters. - */ - public Q clearParameters() { - init(); - if (preparedStatement == null) { - return _this(); - } - try { - preparedStatement.clearParameters(); - } catch (SQLException sex) { - throw new DbSqlException(sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- methods for setting statement parameters - - private void throwSetParamError(final int index, final Exception ex) { - throw new DbSqlException(this, "Invalid SQL parameter with index: " + index, ex); - } - - private void throwSetParamError(final String param, final Exception ex) { - throw new DbSqlException(this, "Invalid SQL parameter with name: " + param, ex); - } - - // ---------------------------------------------------------------- null - - public Q setNull(final int index, final int type) { - initPrepared(); - try { - preparedStatement.setNull(index, type); - } catch (SQLException sex) { - throw new DbSqlException(this, "Failed to set null to parameter: " + index, sex); - } - return _this(); - } - - public Q setNull(final String param, final int type) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setNull(position, type); - } - } catch (SQLException sex) { - throw new DbSqlException(this, "Failed to set null to parameter: " + param, sex); - } - return _this(); - } - - public Q setNull(final int index, final int type, final String typeName) { - initPrepared(); - try { - preparedStatement.setNull(index, type, typeName); - } catch (SQLException sex) { - throw new DbSqlException(this, "Failed to set null to parameter: " + index, sex); - } - return _this(); - } - - public Q setNull(final String param, final int value, final String typeName) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setNull(position, value, typeName); - } - } catch (SQLException sex) { - throw new DbSqlException(this, "Failed to set null to parameter: " + param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- int - - public Q setInteger(final int index, final int value) { - initPrepared(); - try { - preparedStatement.setInt(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setInteger(final String param, final int value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setInt(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q outInteger(final int index) { - return registerOutParameter(index, Types.INTEGER); - } - public Q outInteger(final String param) { - return registerOutParameter(param, Types.INTEGER); - } - - // ---------------------------------------------------------------- Integer - - public Q setInteger(final int index, final Number value) { - if (value == null) { - setNull(index, Types.INTEGER); - } - else { - setInteger(index, value.intValue()); - } - return _this(); - } - - public Q setInteger(final String param, final Number value) { - if (value == null) { - setNull(param, Types.INTEGER); - } - else { - setInteger(param, value.intValue()); - } - return _this(); - } - - // ---------------------------------------------------------------- boolean - - public Q setBoolean(final int index, final boolean value) { - initPrepared(); - try { - preparedStatement.setBoolean(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setBoolean(final String param, final boolean value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setBoolean(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q outBoolean(final int index) { - return registerOutParameter(index, Types.BOOLEAN); - } - public Q outBoolean(final String param) { - return registerOutParameter(param, Types.BOOLEAN); - } - - // ---------------------------------------------------------------- Boolean - - public Q setBoolean(final int index, final Boolean value) { - if (value == null) { - setNull(index, Types.BOOLEAN); - } - else { - setBoolean(index, value.booleanValue()); - } - return _this(); - } - - public Q setBoolean(final String param, final Boolean value) { - if (value == null) { - setNull(param, Types.BOOLEAN); - } - else { - setBoolean(param, value.booleanValue()); - } - return _this(); - } - - // ---------------------------------------------------------------- long - - public Q setLong(final int index, final long value) { - initPrepared(); - try { - preparedStatement.setLong(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setLong(final String param, final long value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setLong(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- Long - - public Q setLong(final int index, final Number value) { - if (value == null) { - setNull(index, Types.BIGINT); - } - else { - setLong(index, value.longValue()); - } - return _this(); - } - - public Q setLong(final String param, final Number value) { - if (value == null) { - setNull(param, Types.BIGINT); - } - else { - setLong(param, value.longValue()); - } - return _this(); - } - - public Q outLong(final int index) { - return registerOutParameter(index, Types.BIGINT); - } - public Q outLong(final String param) { - return registerOutParameter(param, Types.BIGINT); - } - - // ---------------------------------------------------------------- byte - - public Q setByte(final int index, final byte value) { - initPrepared(); - try { - preparedStatement.setByte(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setByte(final String param, final byte value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setByte(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q outByte(final int index) { - return registerOutParameter(index, Types.SMALLINT); - } - public Q outByte(final String param) { - return registerOutParameter(param, Types.SMALLINT); - } - - // ---------------------------------------------------------------- Byte - - public Q setByte(final int index, final Number value) { - if (value == null) { - setNull(index, Types.SMALLINT); - } - else { - setByte(index, value.byteValue()); - } - return _this(); - } - - public Q setByte(final String param, final Number value) { - if (value == null) { - setNull(param, Types.SMALLINT); - } - else { - setByte(param, value.byteValue()); - } - return _this(); - } - - // ---------------------------------------------------------------- bytes[] - - public Q setBytes(final int index, final byte[] value) { - initPrepared(); - try { - preparedStatement.setBytes(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setBytes(final String param, final byte[] value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setBytes(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- double - - public Q setDouble(final int index, final double value) { - initPrepared(); - try { - preparedStatement.setDouble(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setDouble(final String param, final double value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setDouble(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q outDouble(final int index) { - return registerOutParameter(index, Types.DOUBLE); - } - public Q outDouble(final String param) { - return registerOutParameter(param, Types.DOUBLE); - } - - // ---------------------------------------------------------------- Double - - public Q setDouble(final int index, final Number value) { - if (value == null) { - setNull(index, Types.DOUBLE); - } - else { - setDouble(index, value.doubleValue()); - } - return _this(); - } - - public Q setDouble(final String param, final Number value) { - if (value == null) { - setNull(param, Types.DOUBLE); - } - else { - setDouble(param, value.doubleValue()); - } - return _this(); - } - - - // ---------------------------------------------------------------- float - - public Q setFloat(final int index, final float value) { - initPrepared(); - try { - preparedStatement.setFloat(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setFloat(final String param, final float value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setFloat(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q outFloat(final int index) { - return registerOutParameter(index, Types.FLOAT); - } - public Q outFloat(final String param) { - return registerOutParameter(param, Types.FLOAT); - } - - // ---------------------------------------------------------------- Float - - public Q setFloat(final int index, final Number value) { - if (value == null) { - setNull(index, Types.FLOAT); - } - else { - setFloat(index, value.floatValue()); - } - return _this(); - } - - public Q setFloat(final String param, final Number value) { - if (value == null) { - setNull(param, Types.FLOAT); - } - else { - setFloat(param, value.floatValue()); - } - return _this(); - } - - - // ---------------------------------------------------------------- short - - public Q setShort(final int index, final short value) { - initPrepared(); - try { - preparedStatement.setShort(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setShort(final String param, final short value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - final int index = position; - preparedStatement.setShort(index, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- Short - - public Q setShort(final int index, final Number value) { - if (value == null) { - setNull(index, Types.SMALLINT); - } - else { - setShort(index, value.shortValue()); - } - return _this(); - } - - public Q setShort(final String param, final Number value) { - if (value == null) { - setNull(param, Types.SMALLINT); - } - else { - setShort(param, value.shortValue()); - } - return _this(); - } - - // ---------------------------------------------------------------- string - - public Q setString(final int index, final String value) { - initPrepared(); - try { - preparedStatement.setString(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setString(final String param, final String value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setString(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q outString(final int index) { - return registerOutParameter(index, Types.VARCHAR); - } - public Q outString(final String param) { - return registerOutParameter(param, Types.VARCHAR); - } - - - // ---------------------------------------------------------------- date - - public Q setDate(final int index, final Date value) { - initPrepared(); - try { - preparedStatement.setDate(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setDate(final String param, final Date value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setDate(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- time - - public Q setTime(final int index, final Time value) { - initPrepared(); - try { - preparedStatement.setTime(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setTime(final String param, final Time value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setTime(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- timestamp - - public Q setTimestamp(final int index, final Timestamp value) { - initPrepared(); - try { - preparedStatement.setTimestamp(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setTimestamp(final String param, final Timestamp value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setTimestamp(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- big decimal - - public Q setBigDecimal(final int index, final BigDecimal value) { - initPrepared(); - try { - preparedStatement.setBigDecimal(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setBigDecimal(final String param, final BigDecimal value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setBigDecimal(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- big integer - - public Q setBigInteger(final int index, final BigInteger value) { - if (value == null) { - setNull(index, Types.NUMERIC); - } - else { - setLong(index, value.longValue()); - } - return _this(); - } - - public Q setBigInteger(final String param, final BigInteger value) { - if (value == null) { - setNull(param, Types.NUMERIC); - } - else { - setLong(param, value.longValue()); - } - return _this(); - } - - - // ---------------------------------------------------------------- URL - - - public Q setURL(final int index, final URL value) { - initPrepared(); - try { - preparedStatement.setURL(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setURL(final String param, final URL value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setURL(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- BLOB - - public Q setBlob(final int index, final Blob value) { - initPrepared(); - try { - preparedStatement.setBlob(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setBlob(final String param, final Blob value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setBlob(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- CLOB - - public Q setClob(final int index, final Clob value) { - initPrepared(); - try { - preparedStatement.setClob(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setClob(final String param, final Clob value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setClob(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- Array - - public Q setArray(final int index, final Array value) { - initPrepared(); - try { - preparedStatement.setArray(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setArray(final String param, final Array value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setArray(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- Ref - - public Q setRef(final int index, final Ref value) { - initPrepared(); - try { - preparedStatement.setRef(index, value); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setRef(final String param, final Ref value) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setRef(position, value); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- ascii streams - - public Q setAsciiStream(final int index, final InputStream stream) { - initPrepared(); - try { - preparedStatement.setAsciiStream(index, stream, stream.available()); - } catch (IOException | SQLException ioex) { - throwSetParamError(index, ioex); - } - return _this(); - } - - public Q setAsciiStream(final String param, final InputStream stream) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setAsciiStream(position, stream, stream.available()); - } - } catch (IOException | SQLException ioex) { - throwSetParamError(param, ioex); - } - return _this(); - } - - public Q setAsciiStream(final int index, final InputStream stream, final int length) { - initPrepared(); - try { - preparedStatement.setAsciiStream(index, stream, length); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setAsciiStream(final String param, final InputStream stream, final int length) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setAsciiStream(position, stream, length); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - public Q setCharacterStream(final int index, final Reader reader, final int length) { - initPrepared(); - try { - preparedStatement.setCharacterStream(index, reader, length); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - public Q setCharacterStream(final String param, final Reader reader, final int length) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setCharacterStream(position, reader, length); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - - // ---------------------------------------------------------------- bean - - /** - * Sets bean parameters from bean. Non-existing bean properties are ignored. - */ - public Q setBean(final String beanName, final Object bean) { - if (bean == null) { - return _this(); - } - init(); - final String beanNamePrefix = beanName + '.'; - - query.forEachNamedParameter(p -> { - final String paramName = p.name; - - if (paramName.startsWith(beanNamePrefix)) { - final String propertyName = paramName.substring(beanNamePrefix.length()); - - if (BeanUtil.declared.hasRootProperty(bean, propertyName)) { - final Object value = BeanUtil.declared.getProperty(bean, propertyName); - setObject(paramName, value); - } - } - - }); - - return _this(); - } - - // ---------------------------------------------------------------- map - - /** - * Sets properties from the map. - */ - public Q setMap(final Map parameters) { - if (parameters == null) { - return _this(); - } - init(); - query.forEachNamedParameter(p -> { - final String paramName = p.name; - setObject(paramName, parameters.get(paramName)); - }); - return _this(); - } - - - // ---------------------------------------------------------------- objects - - /** - * Sets the value of the designated parameter with the given object. - * This method is like the method setObject - * above, except that it assumes a scale of zero. - */ - public Q setObject(final int index, final Object object, final int targetSqlType) { - initPrepared(); - try { - preparedStatement.setObject(index, object, targetSqlType); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - /** - * Sets the value of the designated parameter with the given object. - * This method is like the method setObject - * above, except that it assumes a scale of zero. - */ - public Q setObject(final String param, final Object object, final int targetSqlType) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setObject(position, object, targetSqlType); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - /** - * Sets the value of the designated parameter with the given object. - * This method is like the method setObject - * above, except that it assumes a scale of zero. - */ - void setObject(final int index, final Object object, final int targetSqlType, final int scale) { - initPrepared(); - try { - preparedStatement.setObject(index, object, targetSqlType, scale); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - } - - /** - * Sets the value of the designated parameter with the given object. - * This method is like the method setObject - * above, except that it assumes a scale of zero. - */ - void setObject(final String param, final Object object, final int targetSqlType, final int scale) { - initPrepared(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - preparedStatement.setObject(position, object, targetSqlType, scale); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - } - - - - // ---------------------------------------------------------------- object ex - - /** - * @see #setObject(String, Object, Class, int) - */ - public Q setObject(final int index, final Object value) { - setObject(index, value, null, Types.OTHER); - return _this(); - } - - /** - * Sets object parameter in an advanced way. - *

- * First, it checks if object is null and invokes setNull if so. - * If object is not null, it tries to resolve {@link SqlType sql type} (by looking up - * or using provided class) and use it for setting data. - * If sql type is not found, default setObject is invoked. - */ - @SuppressWarnings({"unchecked"}) - public Q setObject(final int index, final Object value, final Class sqlTypeClass, final int dbSqlType) { - init(); - if (value == null) { - setNull(index, Types.NULL); - return _this(); - } - final SqlType sqlType; - if (sqlTypeClass != null) { - sqlType = SqlTypeManager.get().lookupSqlType(sqlTypeClass); - } else { - sqlType = SqlTypeManager.get().lookup(value.getClass()); - } - try { - if ((sqlType != null) && (dbSqlType != SqlType.DB_SQLTYPE_NOT_AVAILABLE)) { - sqlType.storeValue(preparedStatement, index, value, dbSqlType); - } else { - DbUtil.setPreparedStatementObject(preparedStatement, index, value, dbSqlType); - } - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - - /** - * @see #setObject(String, Object, Class, int) - */ - public Q setObject(final String param, final Object value) { - setObject(param, value, null, Types.OTHER); - return _this(); - } - - /** - * @see #setObject(String, Object, Class, int) - */ - public Q setObject(final String param, final Object value, final Class sqlTypeClass, final int dbSqlType) { - init(); - final int[] positions = query.getNamedParameterIndices(param); - for (final int position : positions) { - setObject(position, value, sqlTypeClass, dbSqlType); - } - return _this(); - } - - - // ---------------------------------------------------------------- set object shortcuts - - /** - * Sets an array of objects parameters in given order. - */ - public Q setObjects(final Object... objects) { - int index = 1; - for (final Object object : objects) { - setObject(index++, object); - } - return _this(); - } - - /** - * Sets sql parameters from two arrays: names and values. - */ - public Q setObjects(final String[] names, final Object[] values) { - init(); - if (names.length != values.length) { - throw new DbSqlException(this, "Different number of parameter names and values"); - } - for (int i = 0; i < names.length; i++) { - setObject(names[i], values[i]); - } - return _this(); - } - - // ---------------------------------------------------------------- batch - - /** - * Sets batch parameters with given array of values. - */ - public Q setBatch(final String name, final int[] array, int startingIndex) { - init(); - final int batchSize = query.getBatchParameterSize(name); - - for (int i = 1; i <= batchSize; i++) { - final String paramName = name + '.' + i; - - if (startingIndex < array.length) { - setInteger(paramName, array[startingIndex]); - } else { - setNull(paramName, Types.INTEGER); - } - startingIndex++; - } - return _this(); - } - /** - * Sets batch parameters with given array of values. - */ - public Q setBatch(final String name, final long[] array, int startingIndex) { - init(); - final int batchSize = query.getBatchParameterSize(name); - - for (int i = 1; i <= batchSize; i++) { - final String paramName = name + '.' + i; - - if (startingIndex < array.length) { - setLong(paramName, array[startingIndex]); - } else { - setNull(paramName, Types.INTEGER); - } - startingIndex++; - } - return _this(); - } - - /** - * Sets batch parameters with given array of values. - */ - public Q setBatch(final String name, final Object[] array, int startingIndex) { - init(); - final int batchSize = query.getBatchParameterSize(name); - - for (int i = 1; i <= batchSize; i++) { - final String paramName = name + '.' + i; - - if (startingIndex < array.length) { - setObject(paramName, array[startingIndex]); - } else { - setObject(paramName, null); - } - startingIndex++; - } - return _this(); - } - - // ---------------------------------------------------------------- utils - - private void initPrepared() { - init(); - if (preparedStatement == null) { - throw new DbSqlException("Prepared statement not initialized."); - } - } - private void initCallable() { - init(); - if (callableStatement == null) { - throw new DbSqlException("Callable statement not initialized."); - } - } - - private Q registerOutParameter(final int index, final int type) { - initCallable(); - try { - callableStatement.registerOutParameter(index,type); - } catch (SQLException sex) { - throwSetParamError(index, sex); - } - return _this(); - } - private Q registerOutParameter(final String param, final int type) { - initCallable(); - final int[] positions = query.getNamedParameterIndices(param); - try { - for (final int position : positions) { - callableStatement.registerOutParameter(position, type); - } - } catch (SQLException sex) { - throwSetParamError(param, sex); - } - return _this(); - } - - // ---------------------------------------------------------------- close - - /** - * {@inheritDoc} - */ - @Override - public Q autoClose() { - super.autoClose(); - return _this(); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/DbQueryBase.java b/jodd-db/src/main/java/jodd/db/DbQueryBase.java deleted file mode 100644 index 8368eab00..000000000 --- a/jodd-db/src/main/java/jodd/db/DbQueryBase.java +++ /dev/null @@ -1,1004 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.db.debug.LoggableCallableStatement; -import jodd.db.debug.LoggablePreparedStatement; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static jodd.db.DbQueryBase.State.CLOSED; -import static jodd.db.DbQueryBase.State.CREATED; -import static jodd.db.DbQueryBase.State.INITIALIZED; - -/** - * Support for {@link DbQuery} holds all configuration, initialization and the execution code. - */ -abstract class DbQueryBase implements AutoCloseable { - - private static final Logger log = LoggerFactory.getLogger(DbQueryBase.class); - - protected final DbOom dbOom; - - // ---------------------------------------------------------------- ctor - - protected DbQueryBase(final DbOom dbOom) { - this.dbOom = dbOom; - this.forcePreparedStatement = dbOom.queryConfig().isForcePreparedStatement(); - this.type = dbOom.queryConfig().getType(); - this.concurrencyType = dbOom.queryConfig().getConcurrencyType(); - this.holdability = dbOom.queryConfig().getHoldability(); - this.debug = dbOom.queryConfig().isDebug(); - this.fetchSize = dbOom.queryConfig().getFetchSize(); - this.maxRows = dbOom.queryConfig().getMaxRows(); - } - - @SuppressWarnings("unchecked") - protected Q _this() { - return (Q) this; - } - - - // ---------------------------------------------------------------- query states - - /** - * Query states. - */ - public enum State { - CREATED, INITIALIZED, CLOSED - } - protected State queryState = CREATED; - - /** - * Returns query state. - */ - public State getQueryState() { - return queryState; - } - - /** - * Checks if query is not closed and throws an exception if it is. - */ - protected void checkNotClosed() { - if (queryState == CLOSED) { - throw new DbSqlException(this, "Query is closed. Operation may be performed only on active queries."); - } - } - - /** - * Checks if query is created (and not yet initialized or closed) and throws an exception if it is not. - */ - protected void checkCreated() { - if (queryState != CREATED) { - final String message = (queryState == INITIALIZED ? - "Query is already initialized." : "Query is closed."); - throw new DbSqlException(this, message + " Operation may be performed only on created queries."); - } - } - - /** - * Checks if query is initialized and throws an exception if it is not. - */ - protected void checkInitialized() { - if (queryState != INITIALIZED) { - final String message = (queryState == CREATED ? - "Query is created but not yet initialized." : "Query is closed."); - throw new DbSqlException(this, message + " Operation may be performed only on initialized queries."); - } - } - - - - /** - * Returns true if query is closed. - */ - public boolean isClosed() { - return queryState == CLOSED; - } - - /** - * Returns true if query is active: created and possibly initialized. - * Opened query may be not initialized. - */ - public boolean isActive() { - return queryState != CLOSED; - } - - /** - * Returns true if query is initialized. Initialized query is the one that has - * created JDBC statements. - */ - public boolean isInitialized() { - return queryState == INITIALIZED; - } - - // ---------------------------------------------------------------- input - - protected Connection connection; - protected DbSession session; - protected String sqlString; - - /** - * Returns used {@link DbSession}. - */ - public DbSession getSession() { - return session; - } - - // ---------------------------------------------------------------- statement - - protected Statement statement; - protected PreparedStatement preparedStatement; - protected CallableStatement callableStatement; - protected Set resultSets; - protected DbQueryParser query; - - /** - * Stores result set. - */ - protected void saveResultSet(final ResultSet rs) { - if (resultSets == null) { - resultSets = new HashSet<>(); - } - resultSets.add(rs); - } - - // ---------------------------------------------------------------- configuration - - /** - * If set to true all created statements will be prepared. - */ - protected boolean forcePreparedStatement; - - /** - * Forces creation of prepared statements. - */ - public Q forcePreparedStatement() { - checkCreated(); - forcePreparedStatement = true; - return _this(); - } - - // ---------------------------------------------------------------- initialization - - /** - * Initializes the query if not already initialized. - * Usually, user doesn't have to invoke it at all, since it will - * be called before all methods that deals directly with JDBC statement. - * Throws an exception if called on closed query. - */ - public final void init() { - checkNotClosed(); - if (queryState == INITIALIZED) { - return; - } - initializeJdbc(); - queryState = INITIALIZED; - prepareQuery(); - } - - /** - * Initializes session. When not specified (i.e. is null), - * session is fetched from session provider. - */ - protected void initSession(final DbSession session) { - if (session != null) { - this.session = session; - return; - } - - final DbSessionProvider dbSessionProvider = dbOom.sessionProvider(); - - this.session = dbSessionProvider.getDbSession(); - } - - /** - * Performs JDBC initialization of the query. Obtains connection, parses the SQL query string - * and creates statements. Initialization is performed only once, when switching to initialized state. - */ - @SuppressWarnings("MagicConstant") - protected void initializeJdbc() { - // connection - if (connection == null) { - initSession(session); - - connection = session.getConnection(); - } - - this.query = new DbQueryParser(sqlString); - - // callable statement - - if (query.callable) { - try { - if (debug) { - if (holdability != QueryHoldability.DEFAULT) { - callableStatement = new LoggableCallableStatement( - connection.prepareCall(query.sql, type.value(), concurrencyType.value(), holdability.value()), - query.sql - ); - } else { - callableStatement = new LoggableCallableStatement( - connection.prepareCall(query.sql, type.value(), concurrencyType.value()), - query.sql - ); - } - } - else { - if (holdability != QueryHoldability.DEFAULT) { - callableStatement = connection.prepareCall( - query.sql, type.value(), concurrencyType.value(), holdability.value()); - } else { - callableStatement = connection.prepareCall( - query.sql, type.value(), concurrencyType.value()); - } - } - } - catch (final SQLException sex) { - throw new DbSqlException(this, "Error creating callable statement", sex); - } - - preparedStatement = callableStatement; - statement = callableStatement; - - return; - } - - // prepared statement - - if (query.prepared || forcePreparedStatement) { - try { - if (debug) { - if (generatedColumns != null) { - if (generatedColumns.length == 0) { - preparedStatement = new LoggablePreparedStatement( - connection.prepareStatement(query.sql, Statement.RETURN_GENERATED_KEYS), - query.sql); - } else { - preparedStatement = new LoggablePreparedStatement( - connection.prepareStatement(query.sql, generatedColumns), - query.sql); - } - } else { - if (holdability != QueryHoldability.DEFAULT) { - preparedStatement = new LoggablePreparedStatement( - connection.prepareStatement(query.sql, type.value(), concurrencyType.value(), holdability.value()), - query.sql); - } else { - preparedStatement = new LoggablePreparedStatement( - connection.prepareStatement(query.sql, type.value(), concurrencyType.value()), - query.sql); - } - } - } else { - if (generatedColumns != null) { - if (generatedColumns.length == 0) { - preparedStatement = connection.prepareStatement(query.sql, Statement.RETURN_GENERATED_KEYS); - } else { - preparedStatement = connection.prepareStatement(query.sql, generatedColumns); - } - } else { - if (holdability != QueryHoldability.DEFAULT) { - preparedStatement = connection.prepareStatement( - query.sql, type.value(), concurrencyType.value(), holdability.value()); - } else { - preparedStatement = connection.prepareStatement( - query.sql, type.value(), concurrencyType.value()); - } - } - } - } - catch (final SQLException sex) { - throw new DbSqlException(this, "Error creating prepared statement", sex); - } - - statement = preparedStatement; - - return; - } - - // statement - - try { - if (holdability != QueryHoldability.DEFAULT) { - statement = connection.createStatement(type.value(), concurrencyType.value(), holdability.value()); - } else { - statement = connection.createStatement(type.value(), concurrencyType.value()); - } - } catch (final SQLException sex) { - throw new DbSqlException(this, "Error creating statement", sex); - } - } - - /** - * Prepares the query just after the initialization. - * Query is fully set and ready. - */ - protected void prepareQuery() { - if (fetchSize != 0) { - setFetchSize(fetchSize); - } - if (maxRows != 0) { - setMaxRows(maxRows); - } - } - - - // ---------------------------------------------------------------- close - - protected boolean autoClose; - - /** - * Defines that query should be automatically closed immediately after using. - * Should be called before actual statement execution. - */ - public Q autoClose() { - autoClose = true; - return _this(); - } - - /** - * Closes all result sets opened by this query. Query remains active. - * Returns SQLException (stacked with all exceptions) - * or null. - */ - private SQLException closeQueryResultSets() { - SQLException sqlException = null; - - if (resultSets != null) { - for (final ResultSet rs : resultSets) { - try { - rs.close(); - } catch (final SQLException sex) { - if (sqlException == null) { - sqlException = sex; - } else { - sqlException.setNextException(sex); - } - } finally { - totalOpenResultSetCount--; - } - } - resultSets.clear(); - resultSets = null; - } - return sqlException; - } - - /** - * Closes all result sets created by this query. Query remains active. - */ - public Q closeAllResultSets() { - final SQLException sex = closeQueryResultSets(); - if (sex != null) { - throw new DbSqlException("Close associated ResultSets error", sex); - } - return _this(); - } - - /** - * Closes all assigned result sets and then closes the query. Query becomes closed. - */ - protected SQLException closeQuery() { - SQLException sqlException = closeQueryResultSets(); - if (statement != null) { - try { - statement.close(); - } catch (final SQLException sex) { - if (sqlException == null) { - sqlException = sex; - } else { - sqlException.setNextException(sex); - } - } - statement = null; - } - query = null; - queryState = CLOSED; - return sqlException; - } - - /** - * Closes the query and all created results sets and detaches itself from the session. - */ - @Override - @SuppressWarnings({"ClassReferencesSubclass"}) - public void close() { - final SQLException sqlException = closeQuery(); - connection = null; - if (this.session != null) { - this.session.detachQuery(this); - } - if (sqlException != null) { - throw new DbSqlException("Close query error", sqlException); - } - } - - /** - * Closes single result set that was created by this query. It is not necessary to close result sets - * explicitly, since {@link DbQueryBase#close()} method closes all created result sets. - * Query remains active. - */ - public void closeResultSet(final ResultSet rs) { - if (rs == null) { - return; - } - if (!resultSets.remove(rs)) { - throw new DbSqlException(this, "ResultSet is not created by this query"); - } - try { - rs.close(); - } catch (final SQLException sex) { - throw new DbSqlException(this, "Close result set error", sex); - } finally { - totalOpenResultSetCount--; - } - } - - // ---------------------------------------------------------------- result set type - - protected QueryScrollType type; - - public QueryScrollType getType() { - return type; - } - - public Q setType(final QueryScrollType type) { - checkCreated(); - this.type = type; - return _this(); - } - public Q typeForwardOnly() { - setType(QueryScrollType.FORWARD_ONLY); - return _this(); - } - public Q typeScrollSensitive() { - setType(QueryScrollType.SCROLL_SENSITIVE); - return _this(); - } - public Q typeScrollInsensitive() { - setType(QueryScrollType.SCROLL_INSENSITIVE); - return _this(); - } - - // ---------------------------------------------------------------- concurrency - - protected QueryConcurrencyType concurrencyType; - - public QueryConcurrencyType getConcurrencyType() { - return concurrencyType; - } - - public Q setConcurrencyType(final QueryConcurrencyType concurrencyType) { - checkCreated(); - this.concurrencyType = concurrencyType; - return _this(); - } - public Q concurrentReadOnly() { - setConcurrencyType(QueryConcurrencyType.READ_ONLY); - return _this(); - } - public Q concurrentUpdatable() { - setConcurrencyType(QueryConcurrencyType.UPDATABLE); - return _this(); - } - - // ---------------------------------------------------------------- holdability - - protected QueryHoldability holdability; - - public QueryHoldability getHoldability() { - return holdability; - } - - public Q setHoldability(final QueryHoldability holdability) { - checkCreated(); - this.holdability = holdability; - return _this(); - } - - public Q holdCursorsOverCommit() { - setHoldability(QueryHoldability.HOLD_CURSORS_OVER_COMMIT); - return _this(); - } - - public Q closeCursorsAtCommit() { - setHoldability(QueryHoldability.CLOSE_CURSORS_AT_COMMIT); - return _this(); - } - - // ---------------------------------------------------------------- debug mode - - protected boolean debug; - - public boolean isInDebugMode() { - return debug; - } - - public Q setDebug(final boolean debug) { - checkCreated(); - this.debug = debug; - return _this(); - } - public Q setDebugMode() { - setDebug(true); - return _this(); - } - - - // ---------------------------------------------------------------- generated keys - - protected String[] generatedColumns; - - /** - * Returns generated column names. - */ - public String[] getGeneratedColumnNames() { - return generatedColumns; - } - - /** - * Specifies columns which values will be generated by database. - */ - public Q setGeneratedColumns(final String... columns) { - checkCreated(); - generatedColumns = columns; - return _this(); - } - - /** - * Specifies that database will generate some columns values, - * usually the single id. - */ - public Q setGeneratedKey() { - setGeneratedColumns(); - return _this(); - } - - /** - * Resets creating generated columns. - */ - public Q resetGeneratedColumns() { - checkCreated(); - generatedColumns = null; - return _this(); - } - - - // ---------------------------------------------------------------- performance hints - - protected int fetchSize; - - /** - * Returns fetch size. - * @see #setFetchSize(int) - */ - public int getFetchSize() { - return fetchSize; - } - - /** - * Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when - * more rows are needed. The number of rows specified affects only result sets created using this statement. - * If the value specified is zero, then the hint is ignored. The default value is zero. - * @see Statement#setFetchSize(int) - */ - public Q setFetchSize(final int rows) { - checkNotClosed(); - this.fetchSize = rows; - if (statement != null) { - try { - statement.setFetchSize(fetchSize); - } catch (final SQLException sex) { - throw new DbSqlException(this, "Unable to set fetch size: " + fetchSize, sex); - } - } - return _this(); - } - - protected int maxRows; - - /** - * Returns max rows. - * @see #setMaxRows(int) - */ - public int getMaxRows() { - return maxRows; - } - - /** - * Sets the limit for the maximum number of rows that any ResultSet object can contain to the given number. - * If the limit is exceeded, the excess rows are silently dropped. Zero means there is no limit. - * @see Statement#setMaxRows(int) - */ - public Q setMaxRows(final int maxRows) { - checkNotClosed(); - this.maxRows = maxRows; - if (statement != null) { - try { - statement.setMaxRows(maxRows); - } catch (final SQLException sex) { - throw new DbSqlException(this, "Unable to set max rows: " + maxRows, sex); - } - } - return _this(); - } - - // ---------------------------------------------------------------- execute - protected long start; - protected long elapsed = -1; - - /** - * Returns query execution elapsed time in milliseconds. - * Returns -1 if query is still not executed. - */ - public long getExecutionTime() { - return elapsed; - } - - /** - * Executes the query. If this method is invoked at least once, the query or - * all created ResultSets must be explicitly closed at the end of query usage. - * This can be done explicitly by calling {@link DbQueryBase#closeResultSet(ResultSet)} - * оr implicitly, during {@link DbQueryBase#close()}. - * @see Statement#execute(String) - */ - public ResultSet execute() { - start = System.currentTimeMillis(); - - init(); - ResultSet rs = null; - if (log.isDebugEnabled()) { - log.debug("Executing statement: " + getQueryString()); - } - try { - if (preparedStatement == null) { - rs = statement.executeQuery(query.sql); - } else { - rs = preparedStatement.executeQuery(); - } - rs.setFetchSize(fetchSize); - } catch (final SQLException sex) { - DbUtil.close(rs); - throw new DbSqlException(this, "Query execution failed", sex); - } - saveResultSet(rs); - totalOpenResultSetCount++; - - elapsed = System.currentTimeMillis() - start; - if (log.isDebugEnabled()) { - log.debug("execution time: " + elapsed + "ms"); - } - return rs; - } - - public DbCallResult executeCall() { - start = System.currentTimeMillis(); - - init(); - if (log.isDebugEnabled()) { - log.debug("Calling statement: " + getQueryString()); - } - try { - callableStatement.execute(); - } catch (final SQLException sex) { - DbUtil.close(callableStatement); - throw new DbSqlException(this, "Query execution failed", sex); - } - - elapsed = System.currentTimeMillis() - start; - if (log.isDebugEnabled()) { - log.debug("execution time: " + elapsed + "ms"); - } - return new DbCallResult(query, callableStatement); - } - - /** - * Executes UPDATE, INSERT or DELETE queries. Query is not closed afterwards - * unless {@link #autoClose() auto close mode} is set. - * @see Statement#executeUpdate(String) - */ - public int executeUpdate() { - return executeUpdate(autoClose); - } - - /** - * Executes UPDATE, INSERT or DELETE queries and optionally closes the query. - * @see Statement#executeUpdate(String) - */ - protected int executeUpdate(final boolean closeQuery) { - start = System.currentTimeMillis(); - - init(); - final int result; - if (log.isDebugEnabled()) { - log.debug("Executing update: " + getQueryString()); - } - try { - if (preparedStatement == null) { - if (generatedColumns != null) { - if (generatedColumns.length == 0) { - result = statement.executeUpdate(query.sql, Statement.RETURN_GENERATED_KEYS); - } else { - result = statement.executeUpdate(query.sql, generatedColumns); - } - } else { - result = statement.executeUpdate(query.sql); - } - } else { - result = preparedStatement.executeUpdate(); - } - } catch (final SQLException sex) { - throw new DbSqlException(this, "Query execution failed", sex); - } - if (closeQuery) { - close(); - } - - elapsed = System.currentTimeMillis() - start; - if (log.isDebugEnabled()) { - log.debug("execution time: " + elapsed + "ms"); - } - return result; - } - - /** - * Special execute() for 'select count(*)' queries. Query is not closed after the execution - * unless {@link #autoClose() auto-close mode} is set. - * Doesn't check if query is really a count query, so it would work for any - * query that has number in the first column of result. - * If result set returns zero rows (very unlikely), returns -1. - */ - public long executeCount() { - return executeCount(autoClose); - } - - /** - * Executes count queries and optionally closes query afterwards. - */ - protected long executeCount(final boolean close) { - start = System.currentTimeMillis(); - - init(); - ResultSet rs = null; - if (log.isDebugEnabled()) { - log.debug("Executing prepared count: " + getQueryString()); - } - try { - if (preparedStatement == null) { - rs = statement.executeQuery(query.sql); - } else { - rs = preparedStatement.executeQuery(); - } - - final long firstLong = DbUtil.getFirstLong(rs); - - elapsed = System.currentTimeMillis() - start; - if (log.isDebugEnabled()) { - log.debug("execution time: " + elapsed + "ms"); - } - - return firstLong; - } catch (final SQLException sex) { - throw new DbSqlException(this, "Count query failed", sex); - } finally { - DbUtil.close(rs); - if (close) { - close(); - } - } - } - - // ---------------------------------------------------------------- result set mapper - - /** - * {@link #execute() Executes} the query, iterates result set and - * {@link QueryMapper maps} each row. - */ - public List list(final QueryMapper queryMapper) { - final ResultSet resultSet = execute(); - - final List list = new ArrayList<>(); - - try { - while (resultSet.next()) { - final T t = queryMapper.process(resultSet); - if (t == null) { - break; - } - list.add(t); - } - } catch (final SQLException sex) { - throw new DbSqlException(sex); - } finally { - DbUtil.close(resultSet); - } - - return list; - } - - /** - * {@link #execute() Executes} the query and {@link QueryMapper maps} single result row. - */ - public T find(final QueryMapper queryMapper) { - final ResultSet resultSet = execute(); - - try { - if (resultSet.next()) { - return queryMapper.process(resultSet); - } - } catch (final SQLException sex) { - throw new DbSqlException(sex); - } finally { - DbUtil.close(resultSet); - } - return null; - } - - /** - * {@link #execute() Executes} the query, iterates all rows and - * {@link QueryMapper maps} them. - */ - public Set listSet(final QueryMapper queryMapper) { - final ResultSet resultSet = execute(); - - final Set set = new HashSet<>(); - - try { - while (resultSet.next()) { - final T t = queryMapper.process(resultSet); - if (t == null) { - break; - } - set.add(t); - } - } catch (final SQLException sex) { - throw new DbSqlException(sex); - } finally { - DbUtil.close(resultSet); - } - return set; - } - - // ---------------------------------------------------------------- generated keys - - /** - * Returns generated columns. - */ - public ResultSet getGeneratedColumns() { - checkInitialized(); - if (generatedColumns == null) { - throw new DbSqlException(this, "No column is specified as auto-generated"); - } - final ResultSet rs; - try { - rs = statement.getGeneratedKeys(); - } catch (final SQLException sex) { - throw new DbSqlException(this, "No generated keys", sex); - } - saveResultSet(rs); - totalOpenResultSetCount++; - return rs; - } - - /** - * Returns generated key i.e. first generated column as long. - */ - public long getGeneratedKey() { - checkInitialized(); - final ResultSet rs = getGeneratedColumns(); - try { - return DbUtil.getFirstLong(rs); - } catch (final SQLException sex) { - throw new DbSqlException(this, "No generated key as long", sex); - } finally { - DbUtil.close(rs); - resultSets.remove(rs); - totalOpenResultSetCount--; - } - } - - public Object getGeneratedKeyObject() { - checkInitialized(); - final ResultSet rs = getGeneratedColumns(); - try { - return DbUtil.getFirstObject(rs); - } catch (final SQLException sex) { - throw new DbSqlException(this, "No generated key as long", sex); - } finally { - DbUtil.close(rs); - resultSets.remove(rs); - totalOpenResultSetCount--; - } - } - - - // ---------------------------------------------------------------- query string - - /** - * Returns query SQL string. For prepared statements, returned sql string with quick-and-dirty replaced values. - */ - public String getQueryString() { - if (debug) { - if ((callableStatement != null)) { - if (preparedStatement instanceof LoggableCallableStatement) { - return ((LoggableCallableStatement) callableStatement).getQueryString(); - } - } - if (preparedStatement != null) { - if (preparedStatement instanceof LoggablePreparedStatement) { - return ((LoggablePreparedStatement) preparedStatement).getQueryString(); - } - } - } - if (query != null) { - return query.sql; - } - return sqlString; - } - - /** - * @see #getQueryString() - */ - @Override - public String toString() { - return getQueryString(); - } - - - - // ---------------------------------------------------------------- statistics - - - protected static int totalOpenResultSetCount; - - /** - * Returns total number of open result sets. - * @see #getOpenResultSetCount() - */ - public static int getTotalOpenResultSetCount() { - return totalOpenResultSetCount; - } - - /** - * Returns number of created result sets that are still not explicitly closed. - * @see #getTotalOpenResultSetCount() - */ - public int getOpenResultSetCount() { - return resultSets == null ? 0 : resultSets.size(); - } -} diff --git a/jodd-db/src/main/java/jodd/db/DbQueryConfig.java b/jodd-db/src/main/java/jodd/db/DbQueryConfig.java deleted file mode 100644 index 354d2cc71..000000000 --- a/jodd-db/src/main/java/jodd/db/DbQueryConfig.java +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -/** - * Db query default configuration. - */ -public class DbQueryConfig { - - /** - * Default debug mode. - */ - private boolean debug = false; - /** - * Enables creation of prepared statements for all queries. - */ - private boolean forcePreparedStatement = false; - /** - * Default type. - */ - private QueryScrollType type = QueryScrollType.FORWARD_ONLY; - /** - * Default concurrency type. - */ - private QueryConcurrencyType concurrencyType = QueryConcurrencyType.READ_ONLY; - /** - * Default holdability. - */ - private QueryHoldability holdability = QueryHoldability.DEFAULT; - /** - * Default value for fetch size. - */ - private int fetchSize = 0; - /** - * Default value for max rows. - */ - private int maxRows = 0; - - - public boolean isDebug() { - return debug; - } - - public void setDebug(final boolean debug) { - this.debug = debug; - } - - public boolean isForcePreparedStatement() { - return forcePreparedStatement; - } - - public void setForcePreparedStatement(final boolean forcePreparedStatement) { - this.forcePreparedStatement = forcePreparedStatement; - } - - public QueryScrollType getType() { - return type; - } - - public void setType(final QueryScrollType type) { - this.type = type; - } - - public QueryConcurrencyType getConcurrencyType() { - return concurrencyType; - } - - public void setConcurrencyType(final QueryConcurrencyType concurrencyType) { - this.concurrencyType = concurrencyType; - } - - public QueryHoldability getHoldability() { - return holdability; - } - - public void setHoldability(final QueryHoldability holdability) { - this.holdability = holdability; - } - - public int getFetchSize() { - return fetchSize; - } - - public void setFetchSize(final int fetchSize) { - this.fetchSize = fetchSize; - } - - public int getMaxRows() { - return maxRows; - } - - public void setMaxRows(final int maxRows) { - this.maxRows = maxRows; - } -} diff --git a/jodd-db/src/main/java/jodd/db/DbQueryNamedParameter.java b/jodd-db/src/main/java/jodd/db/DbQueryNamedParameter.java deleted file mode 100644 index 02669d6c4..000000000 --- a/jodd-db/src/main/java/jodd/db/DbQueryNamedParameter.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import java.util.Arrays; - -/** - * Storage for named parameters. - */ -class DbQueryNamedParameter { - /** - * Name. - */ - public final String name; - /** - * Indices. - */ - public int[] indices; - public DbQueryNamedParameter next; - - DbQueryNamedParameter(final String name) { - this.name = name; - } - - public boolean equalsName(final String name) { - return this.name.equals(name); - } - - public void add(final int index) { - indices = Arrays.copyOf(indices, indices.length + 1); - indices[indices.length - 1] = index; - } -} diff --git a/jodd-db/src/main/java/jodd/db/DbQueryParser.java b/jodd-db/src/main/java/jodd/db/DbQueryParser.java deleted file mode 100644 index be3c76e94..000000000 --- a/jodd-db/src/main/java/jodd/db/DbQueryParser.java +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.util.CharUtil; -import jodd.util.StringUtil; - -import java.util.HashMap; -import java.util.Map; -import java.util.function.Consumer; - -/** - * SQL parameters parser that recognizes named and ordinal parameters. - */ -class DbQueryParser { - - public static final String SQL_SEPARATORS = " \n\r\f\t,()=<>&|+-=/*'^![]#~\\"; - - boolean prepared; - boolean callable; - String sql; - - // ---------------------------------------------------------------- ctors - - DbQueryParser(final String sql) { - parseSql(sql); - } - - // ---------------------------------------------------------------- parameters - - private DbQueryNamedParameter rootNP; - - void storeNamedParameter(final String name, final int position) { - DbQueryNamedParameter p = lookupNamedParameter(name); - if (p == null) { - p = new DbQueryNamedParameter(name); - p.indices = new int[] {position}; - p.next = rootNP; - rootNP = p; - } - else { - p.add(position); - } - } - - /** - * Lookup for named parameter. - */ - DbQueryNamedParameter lookupNamedParameter(final String name) { - DbQueryNamedParameter p = rootNP; - while (p != null) { - if (p.equalsName(name)) { - return p; - } - p = p.next; - } - return null; - } - - int[] getNamedParameterIndices(final String name) { - final DbQueryNamedParameter p = lookupNamedParameter(name); - if (p == null) { - throw new DbSqlException("Named parameter not found: " + name + "\nQuery: " + sql); - } - return p.indices; - } - - void forEachNamedParameter(final Consumer consumer) { - DbQueryNamedParameter p = rootNP; - while (p != null) { - consumer.accept(p); - p = p.next; - } - } - - // ---------------------------------------------------------------- batch - - private Map batchParams; - - private void saveBatchParameter(final String name, final int size) { - if (batchParams == null) { - batchParams = new HashMap<>(); - } - batchParams.put(name, Integer.valueOf(size)); - } - - /** - * Returns the size of batch parameter. Returns 0 - * if parameter does not exist. - */ - protected int getBatchParameterSize(final String name) { - if (batchParams == null) { - return 0; - } - Integer size = batchParams.get(name); - if (size == null) { - return 0; - } - return size.intValue(); - } - - // ---------------------------------------------------------------- parser - - void parseSql(final String sqlString) { - rootNP = null; - final int stringLength = sqlString.length(); - final StringBuilder pureSql = new StringBuilder(stringLength); - boolean inQuote = false; - int index = 0; - int paramCount = 0; - - while (index < stringLength) { - char c = sqlString.charAt(index); - if (inQuote) { - if (c == '\'') { - inQuote = false; - } - } - else if (c == '\'') { - inQuote = true; - } - else if (c == ':' && index + 1 < stringLength - && sqlString.charAt(index + 1) == ':') { - // don't treat '::foo' sequence as named parameter; skip this - // chunk - int right = StringUtil.indexOfChars(sqlString, - SQL_SEPARATORS, index + 2); - if (right < 0) { - right = stringLength; - } - pureSql.append(sqlString.substring(index, right)); - index = right; - continue; - } - else if (c == ':') { - int right = StringUtil.indexOfChars(sqlString, SQL_SEPARATORS, index + 1); - boolean batch = false; - - if (right < 0) { - right = stringLength; - } else { - if (sqlString.charAt(right) == '!') { - batch = true; - } - } - - String param = sqlString.substring(index + 1, right); - - if (!batch) { - paramCount++; - storeNamedParameter(param, paramCount); - pureSql.append('?'); - } - else { - // read batch size - right++; - int numStart = right; - - while (right < stringLength) { - if (!CharUtil.isDigit(sqlString.charAt(right))) { - break; - } - right++; - } - - String numberValue = sqlString.substring(numStart, right); - int batchSize; - try { - batchSize = Integer.parseInt(numberValue); - } catch (NumberFormatException nfex) { - throw new DbSqlException("Batch size is not an integer: " + numberValue, nfex); - } - - saveBatchParameter(param, batchSize); - - // create batch parameters - for (int i = 1; i <= batchSize; i++) { - if (i != 1) { - pureSql.append(','); - } - paramCount++; - storeNamedParameter(param + '.' + i, paramCount); - pureSql.append('?'); - } - } - - index = right; - continue; - } - else if (c == '?') { // either an ordinal or positional parameter - if ((index < stringLength - 1) && (Character.isDigit(sqlString.charAt(index + 1)))) { // positional parameter - int right = StringUtil.indexOfChars(sqlString, SQL_SEPARATORS, index + 1); - if (right < 0) { - right = stringLength; - } - String param = sqlString.substring(index + 1, right); - try { - Integer.parseInt(param); - } catch (NumberFormatException nfex) { - throw new DbSqlException("Positional parameter is not an integer: " + param, nfex); - } - paramCount++; - storeNamedParameter(param, paramCount); - pureSql.append('?'); - index = right; - continue; - } - paramCount++; // ordinal param - } - pureSql.append(c); - index++; - } - this.prepared = (paramCount != 0); - this.sql = pureSql.toString(); - - if (this.sql.startsWith("{")) { - this.callable = true; - } - } -} diff --git a/jodd-db/src/main/java/jodd/db/DbSession.java b/jodd-db/src/main/java/jodd/db/DbSession.java deleted file mode 100644 index b1e75758a..000000000 --- a/jodd-db/src/main/java/jodd/db/DbSession.java +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.db.connection.ConnectionProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.Connection; -import java.sql.SQLException; -import java.util.HashSet; -import java.util.Set; - -/** - * Encapsulates db connection. Initially works in auto-commit mode. - * May start and work with transactions, after committing/rolling back - * DbSession goes back to auto-commit mode. - *

- * All invoked queries are stored within one session and closed implicitly - * on session closing. - *

- * For managed transaction see DbJtxTransactionManager from jodd-tx. - */ -public class DbSession implements AutoCloseable { - - private static final Logger log = LoggerFactory.getLogger(DbSession.class); - - // ---------------------------------------------------------------- init & close - - protected final ConnectionProvider connectionProvider; - protected Connection connection; - - /** - * Creates new database session with default transaction mode and in autocommit mode. - */ - public DbSession(ConnectionProvider connectionProvider) { - log.debug("Creating new db session"); - - if (connectionProvider == null) { - connectionProvider = DbOom.get().connectionProvider(); - - if (connectionProvider == null) { - throw new DbSqlException("Connection provider is not available"); - } - } - - this.connectionProvider = connectionProvider; - this.txActive = false; - this.txMode = DbTransactionMode.READ_ONLY_TX; - this.queries = new HashSet<>(); - } - - - /** - * Closes current session and all allocated resources. - * All attached queries are closed. If a transaction is still active, exception occurs. - * Database connection is returned to the {@link ConnectionProvider}. - * Closed session is no longer available for usage. - */ - public void closeSession() { - log.debug("Closing db session"); - - SQLException sqlException = null; - - if (queries != null) { - for (final DbQueryBase query : queries) { - final SQLException sex = query.closeQuery(); - if (sex != null) { - if (sqlException == null) { - sqlException = sex; - } else { - sqlException.setNextException(sex); - } - } - } - } - if (connection != null) { - if (txActive) { - throw new DbSqlException("TX was not closed before closing the session"); - } - connectionProvider.closeConnection(connection); - connection = null; - } - queries = null; - if (sqlException != null) { - throw new DbSqlException("Closing DbSession failed", sqlException); - } - } - - @Override - public void close() { - closeSession(); - } - - /** - * Indicates whether a session is closed. - */ - public boolean isSessionClosed() { - return queries == null; - } - - /** - * Returns true if session is open. - */ - public boolean isSessionOpen() { - return queries != null; - } - - - // ---------------------------------------------------------------- query - - /** - * Bag of all queries attached to this session. Explicitly closed queries - * remains in the set. If null, session is closed. - * If not null, but empty, session is still considered as open. - */ - protected Set queries; - - /** - * Returns total number of queries assigned to this session. - */ - public int getTotalQueries() { - if (queries == null) { - return 0; - } - return queries.size(); - } - - /** - * Returns current connection. - */ - public Connection getConnection() { - return connection; - } - - - /** - * Attaches a new {@link DbQuery}. May be invoked both inside and outside of transaction. - */ - protected void attachQuery(final DbQueryBase query) { - assertSessionIsOpen(); - openConnectionForQuery(); - queries.add(query); - } - - /** - * Detach used {@link DbQuery}. Usually invoked by {@link jodd.db.DbQuery#close()}. - */ - protected void detachQuery(final DbQueryBase query) { - queries.remove(query); - } - - - /** - * Opens connection in auto-commit mode, if already not opened. - */ - protected void openConnectionForQuery() { - if (connection == null) { - connection = connectionProvider.getConnection(); - txActive = false; // txAction should already be false - try { - connection.setAutoCommit(true); - } catch (final SQLException sex) { - throw new DbSqlException("Failed to open non-TX connection", sex); - } - } - } - - // ---------------------------------------------------------------- transaction - - protected boolean txActive; - - protected DbTransactionMode txMode; - - /** - * Indicate whether a transaction is in progress. - */ - public boolean isTransactionActive() { - return txActive; - } - - - /** - * Opens a transaction. - */ - protected void openTx() { - if (connection == null) { - connection = connectionProvider.getConnection(); - } - txActive = true; - try { - connection.setAutoCommit(false); - if (txMode.getIsolation() != DbTransactionMode.ISOLATION_DEFAULT) { - connection.setTransactionIsolation(txMode.getIsolation()); - } - connection.setReadOnly(txMode.isReadOnly()); - } catch (final SQLException sex) { - throw new DbSqlException("Open TX failed", sex); - } - } - - /** - * Closes current transaction. - */ - protected void closeTx() { - txActive = false; - try { - connection.setAutoCommit(true); - } catch (final SQLException sex) { - throw new DbSqlException("Close TX failed", sex); - } - } - - - /** - * Starts a transaction. - */ - public void beginTransaction(final DbTransactionMode mode) { - log.debug("Beginning transaction"); - - assertTxIsClosed(); - this.txMode = mode; - openTx(); - } - - /** - * Commit the current transaction, writing any unflushed changes to the database. - * Transaction mode is closed. - */ - public void commitTransaction() { - log.debug("Committing transaction"); - - assertTxIsActive(); - try { - connection.commit(); - } catch (final SQLException sex) { - throw new DbSqlException("Commit TX failed", sex); - } finally { - closeTx(); - } - } - - /** - * Roll back the current transaction. Transaction mode is closed. - */ - public void rollbackTransaction() { - log.debug("Rolling-back transaction"); - - assertTxIsActive(); - - try { - connection.rollback(); - } catch (final SQLException sex) { - throw new DbSqlException("Rollback TX failed", sex); - } finally { - closeTx(); - } - } - - - // ---------------------------------------------------------------- checking - - protected void assertSessionIsOpen() { - if (queries == null) { - throw new DbSqlException("Session is closed"); - } - } - - protected void assertTxIsClosed() { - assertSessionIsOpen(); - if (txActive) { - throw new DbSqlException("TX already started for this session"); - } - } - - protected void assertTxIsActive() { - assertSessionIsOpen(); - if (!txActive) { - throw new DbSqlException("TX not available for this session"); - } - } -} diff --git a/jodd-db/src/main/java/jodd/db/DbSessionProvider.java b/jodd-db/src/main/java/jodd/db/DbSessionProvider.java deleted file mode 100644 index f85eaa11d..000000000 --- a/jodd-db/src/main/java/jodd/db/DbSessionProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -/** - * Provide {@link DbSession} when requested by {@link DbQuery}. - * Important: DbSessionProvider implementations - * should NOT create new db sessions! DbSession should - * be already created and somehow assigned to DbSessionProvider - * implementation. User must control session opening and closing, - * and not DbSessionProvider, as we can not figure - * weather connection should be closed after closing a query; - * or still hold on open for the next query. - */ -@FunctionalInterface -public interface DbSessionProvider { - - /** - * Returns {@link DbSession}. May throws an exception - * if session can not be provided. - */ - DbSession getDbSession(); - -} diff --git a/jodd-db/src/main/java/jodd/db/DbSqlException.java b/jodd-db/src/main/java/jodd/db/DbSqlException.java deleted file mode 100644 index ea5425cfd..000000000 --- a/jodd-db/src/main/java/jodd/db/DbSqlException.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.exception.UncheckedException; - -/** - * Unchecked SQL exception. - */ -public class DbSqlException extends UncheckedException { - - public DbSqlException(final Throwable t) { - super(t); - } - - public DbSqlException(final String message) { - super(message); - } - - public DbSqlException(final DbQueryBase dbQuery, final String message) { - super(message + "\nQuery: " + dbQuery.getQueryString()); - } - - public DbSqlException(final String message, final Throwable t) { - super(message, t); - } - - public DbSqlException(final DbQueryBase dbQuery, final String message, final Throwable t) { - super(message + "\nQuery: " + dbQuery.getQueryString(), t); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/DbThreadSession.java b/jodd-db/src/main/java/jodd/db/DbThreadSession.java deleted file mode 100644 index 8f52b5bfe..000000000 --- a/jodd-db/src/main/java/jodd/db/DbThreadSession.java +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.db.connection.ConnectionProvider; - -/** - * Thread assigned {@link jodd.db.DbSession}. Upon creation, it assigns - * the session to current thread. Useful when only one session (i.e. connection) - * is used per thread, through service layers. - *

- * {@link jodd.db.DbThreadSession} uses {@link jodd.db.ThreadDbSessionHolder} for storing - * created sessions in the thread storage. Note that holder may be manipulated from outside - * of this class. - */ -public class DbThreadSession extends DbSession { - - /** - * Creates new db session and assigns it to the current thread. - * Closes already assigned session, if any exist. - * @param connectionProvider connection provider - */ - public DbThreadSession(final ConnectionProvider connectionProvider) { - super(connectionProvider); - - final DbSession session = ThreadDbSessionHolder.get(); - if (session != null) { - session.closeSession(); - } - ThreadDbSessionHolder.set(this); - } - - /** - * Creates new db session and assigns it to the current thread, using - * default connection provider. - */ - public DbThreadSession() { - this(null); - } - - - /** - * Closes current session and remove the association from current thread. - * @see jodd.db.DbSession#closeSession() - */ - @Override - public void closeSession() { - ThreadDbSessionHolder.remove(); - super.closeSession(); - } - - // ---------------------------------------------------------------- static stuff - - /** - * Returns current thread session or null if no session is assigned - * to a thread. - */ - public static DbSession getCurrentSession() { - return ThreadDbSessionHolder.get(); - } - - /** - * Returns existing thread session, or new one if already not exist. If session doesn't exist, it will be created - * using default connection provider. - */ - public static DbThreadSession getThreadSession() { - DbThreadSession session = (DbThreadSession) ThreadDbSessionHolder.get(); - if (session == null) { - session = new DbThreadSession(); - } - return session; - } - - /** - * Closes thread session. - */ - public static void closeThreadSession() { - DbThreadSession session = (DbThreadSession) ThreadDbSessionHolder.get(); - if (session != null) { - session.closeSession(); - } - } - -} diff --git a/jodd-db/src/main/java/jodd/db/DbTransactionMode.java b/jodd-db/src/main/java/jodd/db/DbTransactionMode.java deleted file mode 100644 index b034563d2..000000000 --- a/jodd-db/src/main/java/jodd/db/DbTransactionMode.java +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import java.sql.Connection; -import java.util.Objects; - -/** - * Native SQL transaction mode for {@link DbSession} transactions. - */ -public class DbTransactionMode { - - // ---------------------------------------------------------------- isolation - - /** - * Default isolation. - */ - public static final int ISOLATION_DEFAULT = -1; - /** - * @see Connection#TRANSACTION_NONE - */ - public static final int ISOLATION_NONE = Connection.TRANSACTION_NONE; - /** - * @see Connection#TRANSACTION_READ_UNCOMMITTED - */ - public static final int ISOLATION_READ_UNCOMMITTED = Connection.TRANSACTION_READ_UNCOMMITTED; - /** - * @see Connection#TRANSACTION_READ_COMMITTED - */ - public static final int ISOLATION_READ_COMMITTED = Connection.TRANSACTION_READ_COMMITTED; - /** - * @see Connection#TRANSACTION_REPEATABLE_READ - */ - public static final int ISOLATION_REPEATABLE_READ = Connection.TRANSACTION_REPEATABLE_READ; - /** - * @see Connection#TRANSACTION_SERIALIZABLE - */ - public static final int ISOLATION_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE; - - private final int isolation; - - /** - * Returns isolation level. - */ - public int getIsolation() { - return isolation; - } - - // ---------------------------------------------------------------- read-only - - public static final boolean READ_ONLY = true; - public static final boolean READ_WRITE = false; - - private final boolean readOnlyMode; - - /** - * Returns {@code true} if transaction is read-only. - */ - public boolean isReadOnly() { - return readOnlyMode; - } - - - // ---------------------------------------------------------------- ctor - - public static final DbTransactionMode READ_ONLY_TX = new DbTransactionMode(ISOLATION_DEFAULT, READ_ONLY); - public static final DbTransactionMode READ_WRITE_TX = new DbTransactionMode(ISOLATION_DEFAULT, READ_WRITE); - - public DbTransactionMode(final int isolation, boolean readOnlyMode) { - this.isolation = isolation; - this.readOnlyMode = readOnlyMode; - } - - // ---------------------------------------------------------------- equals & hashCode - - @Override - public boolean equals(final Object object) { - if (this == object) { - return true; - } - if (this.getClass() != object.getClass()) { - return false; - } - DbTransactionMode mode = (DbTransactionMode) object; - return (mode.getIsolation() == this.isolation) && - (mode.isReadOnly() == this.readOnlyMode); - } - - @Override - public int hashCode() { - return Objects.hash(readOnlyMode, isolation); - } - - -} diff --git a/jodd-db/src/main/java/jodd/db/DbUtil.java b/jodd-db/src/main/java/jodd/db/DbUtil.java deleted file mode 100644 index e310c67b2..000000000 --- a/jodd-db/src/main/java/jodd/db/DbUtil.java +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import jodd.db.type.SqlType; -import jodd.typeconverter.Converter; -import jodd.typeconverter.TypeConverterManager; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.sql.Types; - -/** - * Various DB utilities. - */ -public class DbUtil { - - /** - * Closes statement safely without throwing an exception. - */ - public static void close(final Statement statement) { - if (statement == null) { - return; - } - - try { - statement.close(); - } catch (SQLException sex) { - // ignore - } - } - - /** - * Closes result set safely without throwing an exception. - */ - public static void close(final ResultSet resultSet) { - if (resultSet == null) { - return; - } - try { - resultSet.close(); - } catch (SQLException sex) { - // ignore - } - } - - /** - * Returns long value of very first column in result set. - */ - public static long getFirstLong(final ResultSet resultSet) throws SQLException { - if (resultSet.next()) { - return resultSet.getLong(1); - } - return -1; - } - - /** - * Returns int value of very first column in result set. - */ - public static int getFirstInt(final ResultSet resultSet) throws SQLException { - if (resultSet.next()) { - return resultSet.getInt(1); - } - return -1; - } - - public static Object getFirstObject(final ResultSet resultSet) throws SQLException { - if (resultSet.next()) { - return resultSet.getObject(1); - } - return null; - } - - /** - * Sets prepared statement object using target SQL type. - * Here Jodd makes conversion and not JDBC driver. - * See: http://www.tutorialspoint.com/jdbc/jdbc-data-types.htm - */ - public static void setPreparedStatementObject(final PreparedStatement preparedStatement, final int index, final Object value, final int targetSqlType) throws SQLException { - if (value == null) { - preparedStatement.setNull(index, Types.NULL); - return; - } - - switch (targetSqlType) { - case Types.VARCHAR: - case Types.LONGVARCHAR: - case Types.CHAR: - preparedStatement.setString(index, Converter.get().toString(value)); - break; - - case Types.INTEGER: - case Types.SMALLINT: - case Types.TINYINT: - preparedStatement.setInt(index, Converter.get().toIntValue(value)); - break; - - case Types.BIGINT: - preparedStatement.setLong(index, Converter.get().toLongValue(value)); - break; - - case Types.BOOLEAN: - case Types.BIT: - preparedStatement.setBoolean(index, Converter.get().toBooleanValue(value)); - break; - - case Types.DATE: - preparedStatement.setDate(index, TypeConverterManager.get().convertType(value, java.sql.Date.class)); - break; - - case Types.NUMERIC: - case Types.DECIMAL: - preparedStatement.setBigDecimal(index, Converter.get().toBigDecimal(value)); - break; - - case Types.DOUBLE: - preparedStatement.setDouble(index, Converter.get().toDoubleValue(value)); - break; - - case Types.REAL: - case Types.FLOAT: - preparedStatement.setFloat(index, Converter.get().toFloatValue(value)); - break; - - case Types.TIME: - preparedStatement.setTime(index, TypeConverterManager.get().convertType(value, java.sql.Time.class)); - break; - - case Types.TIMESTAMP: - preparedStatement.setTimestamp(index, TypeConverterManager.get().convertType(value, Timestamp.class)); - break; - - case Types.BINARY: - case Types.VARBINARY: - preparedStatement.setBytes(index, TypeConverterManager.get().convertType(value, byte[].class)); - break; - - default: - if (targetSqlType != SqlType.DB_SQLTYPE_NOT_AVAILABLE) { - preparedStatement.setObject(index, value, targetSqlType); - } else { - preparedStatement.setObject(index, value); - } - } - - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/QueryConcurrencyType.java b/jodd-db/src/main/java/jodd/db/QueryConcurrencyType.java deleted file mode 100644 index 75740914d..000000000 --- a/jodd-db/src/main/java/jodd/db/QueryConcurrencyType.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import java.sql.ResultSet; - -/** - * Query concurrency type. - */ -public enum QueryConcurrencyType { - - READ_ONLY(ResultSet.CONCUR_READ_ONLY), - UPDATABLE(ResultSet.CONCUR_UPDATABLE); - - private final int type; - - QueryConcurrencyType(final int type) { - this.type = type; - } - - public int value() { - return type; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/QueryHoldability.java b/jodd-db/src/main/java/jodd/db/QueryHoldability.java deleted file mode 100644 index cbffd6eb2..000000000 --- a/jodd-db/src/main/java/jodd/db/QueryHoldability.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import java.sql.ResultSet; - -/** - * Query holdability. - */ -public enum QueryHoldability { - /** - * Default holdability. JDBC specification does not specifies default value for holdability. - */ - DEFAULT(-1), - CLOSE_CURSORS_AT_COMMIT(ResultSet.CLOSE_CURSORS_AT_COMMIT), - HOLD_CURSORS_OVER_COMMIT(ResultSet.HOLD_CURSORS_OVER_COMMIT); - - private final int type; - - QueryHoldability(final int type) { - this.type = type; - } - - public int value() { - return type; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/QueryMapper.java b/jodd-db/src/main/java/jodd/db/QueryMapper.java deleted file mode 100644 index f71497725..000000000 --- a/jodd-db/src/main/java/jodd/db/QueryMapper.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import java.sql.ResultSet; -import java.sql.SQLException; - -/** - * Process {@link jodd.db.DbQuery query} and map it execution result to a type. - */ -public interface QueryMapper { - - /** - * Processes single result sets row. - * Returns null to stop iterations. - */ - T process(ResultSet resultSet) throws SQLException; - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/QueryScrollType.java b/jodd-db/src/main/java/jodd/db/QueryScrollType.java deleted file mode 100644 index 94663e66e..000000000 --- a/jodd-db/src/main/java/jodd/db/QueryScrollType.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import java.sql.ResultSet; - -/** - * Query scroll type. - */ -public enum QueryScrollType { - /** - * @see ResultSet#TYPE_FORWARD_ONLY - */ - FORWARD_ONLY(ResultSet.TYPE_FORWARD_ONLY), - /** - * @see ResultSet#TYPE_SCROLL_SENSITIVE - */ - SCROLL_SENSITIVE(ResultSet.TYPE_SCROLL_SENSITIVE), - /** - * @see ResultSet#TYPE_SCROLL_INSENSITIVE - */ - SCROLL_INSENSITIVE(ResultSet.TYPE_SCROLL_INSENSITIVE); - - private final int type; - - QueryScrollType(final int type) { - this.type = type; - } - - public int value() { - return type; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/ThreadDbSessionHolder.java b/jodd-db/src/main/java/jodd/db/ThreadDbSessionHolder.java deleted file mode 100644 index 634828434..000000000 --- a/jodd-db/src/main/java/jodd/db/ThreadDbSessionHolder.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -/** - * {@link DbSession} thread storage. - */ -public class ThreadDbSessionHolder { - - private static final ThreadLocal DB_SESSION_THREAD_LOCAL = new ThreadLocal<>(); - - /** - * Returns current thread db session. - */ - public static DbSession get() { - return DB_SESSION_THREAD_LOCAL.get(); - } - - /** - * Sets current db session. - */ - public static void set(final DbSession dbSession) { - DB_SESSION_THREAD_LOCAL.set(dbSession); - } - - /** - * Removes current db session from the thread and returns it. - */ - public static void remove() { - DB_SESSION_THREAD_LOCAL.set(null); - } -} diff --git a/jodd-db/src/main/java/jodd/db/ThreadDbSessionProvider.java b/jodd-db/src/main/java/jodd/db/ThreadDbSessionProvider.java deleted file mode 100644 index 52e358df1..000000000 --- a/jodd-db/src/main/java/jodd/db/ThreadDbSessionProvider.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Returns {@link DbSession} assigned to current thread. - * @see DbThreadSession - * @see ThreadDbSessionHolder - */ -public class ThreadDbSessionProvider implements DbSessionProvider { - - private static final Logger log = LoggerFactory.getLogger(ThreadDbSessionProvider.class); - - /** - * {@inheritDoc} - */ - @Override - public DbSession getDbSession() { - log.debug("Requesting thread session"); - - final DbSession session = ThreadDbSessionHolder.get(); - - if (session == null) { - throw new DbSqlException( - "No DbSession associated with current thread. " + - "It seems that ThreadDbSessionHolder is not used."); - } - return session; - } - - -} diff --git a/jodd-db/src/main/java/jodd/db/connection/ConnectionPoolDataSourceConnectionProvider.java b/jodd-db/src/main/java/jodd/db/connection/ConnectionPoolDataSourceConnectionProvider.java deleted file mode 100644 index 6909e10ae..000000000 --- a/jodd-db/src/main/java/jodd/db/connection/ConnectionPoolDataSourceConnectionProvider.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.connection; - -import jodd.db.DbSqlException; - -import javax.sql.ConnectionPoolDataSource; -import javax.sql.PooledConnection; -import java.sql.Connection; -import java.sql.SQLException; - -/** - * Connection pool data source {@link jodd.db.connection.ConnectionProvider} - */ -public class ConnectionPoolDataSourceConnectionProvider implements ConnectionProvider { - // ---------------------------------------------------------------- properties - - private ConnectionPoolDataSource cpds; - - public ConnectionPoolDataSourceConnectionProvider(final ConnectionPoolDataSource cpds) { - this.cpds = cpds; - } - - // ---------------------------------------------------------------- init/close - - @Override - public void init() { - } - - @Override - public void close() { - cpds = null; - } - - // ---------------------------------------------------------------- get/free - - @Override - public Connection getConnection() { - PooledConnection pconn; - try { - pconn = cpds.getPooledConnection(); - } catch (SQLException sex) { - throw new DbSqlException("Invalid pooled connection", sex); - } - try { - return pconn.getConnection(); - } catch (SQLException sex) { - throw new DbSqlException("Invalid pooled connection", sex); - } - } - - @Override - public void closeConnection(final Connection connection) { - try { - if (connection != null) { - connection.close(); - } - } catch (SQLException sex) { - // ignore - } - } -} diff --git a/jodd-db/src/main/java/jodd/db/connection/ConnectionProvider.java b/jodd-db/src/main/java/jodd/db/connection/ConnectionProvider.java deleted file mode 100644 index 92402175c..000000000 --- a/jodd-db/src/main/java/jodd/db/connection/ConnectionProvider.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.connection; - -import java.sql.Connection; - -/** - * A generic strategy for obtaining JDBC connections. - *

- * Implementors might also implement connection pooling. - *

- * Implementations should provide a public default constructor. - */ -public interface ConnectionProvider extends AutoCloseable { - - /** - * Initialize the connection provider. May be called more then once; - * does not have any effect if pool is already initialized. - */ - void init(); - - /** - * Returns a connection from connection pool. - */ - Connection getConnection(); - - /** - * Dispose of a used {@link #getConnection() connection}. - */ - void closeConnection(Connection connection); - - /** - * Closes a provider and releases all its resources. - */ - @Override - void close(); - -} diff --git a/jodd-db/src/main/java/jodd/db/connection/DataSourceConnectionProvider.java b/jodd-db/src/main/java/jodd/db/connection/DataSourceConnectionProvider.java deleted file mode 100644 index e885f8f6d..000000000 --- a/jodd-db/src/main/java/jodd/db/connection/DataSourceConnectionProvider.java +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.connection; - -import jodd.db.DbSqlException; - -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; -import java.sql.Connection; -import java.sql.SQLException; - -/** - * DataSource connection provider. Note that data source implementation might - * not support dataSource.getConnection(username, password). - */ -public class DataSourceConnectionProvider implements ConnectionProvider { - - private final DataSource dataSource; - private final String username; - private final String password; - - public DataSourceConnectionProvider(final String jndiName) { - this(jndiName, null, null); - } - - public DataSourceConnectionProvider(final String jndiName, final String user, final String pass) { - try { - InitialContext initialContext = new InitialContext(); - - this.dataSource = (DataSource) initialContext.lookup(jndiName); - } catch (NamingException nex) { - throw new DbSqlException("Invalid JNDI datasource name: " + jndiName, nex); - } - this.username = user; - this.password = pass; - } - - public DataSourceConnectionProvider(final DataSource dataSource) { - this.dataSource = dataSource; - username = password = null; - } - - public DataSourceConnectionProvider(final DataSource dataSource, final String user, final String pass) { - this.dataSource = dataSource; - this.username = user; - this.password = pass; - } - - @Override - public void init() {} - - @Override - public Connection getConnection() { - try { - if (username != null || password != null) { - return dataSource.getConnection(username, password); - } else { - return dataSource.getConnection(); - } - } catch (SQLException sex) { - throw new DbSqlException("Invalid datasource connection", sex); - } - } - - @Override - public void closeConnection(final Connection connection) { - try { - connection.close(); - } catch (SQLException sex) { - // ignore - } - } - - @Override - public void close() {} -} diff --git a/jodd-db/src/main/java/jodd/db/connection/DriverManagerConnectionProvider.java b/jodd-db/src/main/java/jodd/db/connection/DriverManagerConnectionProvider.java deleted file mode 100644 index 9a3c5329c..000000000 --- a/jodd-db/src/main/java/jodd/db/connection/DriverManagerConnectionProvider.java +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.connection; - -import jodd.db.DbSqlException; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -/** - * Driver manager connection provider; - */ -public class DriverManagerConnectionProvider implements ConnectionProvider { - - // ---------------------------------------------------------------- properties - - private String url; - private String username; - private String password; - private String driverClass; - private Integer isolation; - private Boolean autoCommit; - - public void setUrl(final String url) { - this.url = url; - } - - public void setUsername(final String username) { - this.username = username; - } - - public void setPassword(final String password) { - this.password = password; - } - - public void setDriverClass(final String driverClass) { - this.driverClass = driverClass; - } - - public void setIsolation(final Integer isolation) { - this.isolation = isolation; - } - - public void setAutoCommit(final Boolean autoCommit) { - this.autoCommit = autoCommit; - } - - // ---------------------------------------------------------------- ctors - - public DriverManagerConnectionProvider(final String driverClass, final String url, final String username, final String password) { - this.driverClass = driverClass; - this.password = password; - this.username = username; - this.url = url; - } - public DriverManagerConnectionProvider(final String driverClass, final String url) { - this.driverClass = driverClass; - this.url = url; - } - - // ---------------------------------------------------------------- provider - - @Override - public synchronized void init() { - try { - Class.forName(driverClass); - } catch (ClassNotFoundException cnfex) { - throw new DbSqlException("JDBC driver not found: " + driverClass, cnfex); - } - } - - @Override - public Connection getConnection() { - Connection conn; - try { - if (username != null) { - conn = DriverManager.getConnection(url, username, password); - } else { - conn = DriverManager.getConnection(url); - } - if (isolation != null) { - conn.setTransactionIsolation(isolation.intValue()); - } - if (autoCommit != null) { - conn.setAutoCommit(autoCommit.booleanValue()); - } - } - catch (SQLException sex) { - throw new DbSqlException("Connection not found", sex); - } - return conn; - } - - @Override - public void closeConnection(final Connection connection) { - try { - connection.close(); - } catch (SQLException sex) { - // ignore - } - } - - @Override - public void close() { - } -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/connection/XADataSourceConnectionProvider.java b/jodd-db/src/main/java/jodd/db/connection/XADataSourceConnectionProvider.java deleted file mode 100644 index ac55a58be..000000000 --- a/jodd-db/src/main/java/jodd/db/connection/XADataSourceConnectionProvider.java +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.connection; - -import jodd.db.DbSqlException; - -import javax.sql.XAConnection; -import javax.sql.XADataSource; -import java.sql.Connection; -import java.sql.SQLException; - -/** - * XA-DataSource connection provider. - */ -public class XADataSourceConnectionProvider implements ConnectionProvider { - - private final XADataSource xaDataSource; - private final String username; - private final String password; - - public XADataSourceConnectionProvider(final XADataSource dataSource) { - this.xaDataSource = dataSource; - this.username = this.password = null; - } - public XADataSourceConnectionProvider(final XADataSource dataSource, final String user, final String pass) { - this.xaDataSource = dataSource; - this.username = user; - this.password = pass; - } - - @Override - public void init() {} - - @Override - public Connection getConnection() { - try { - XAConnection xaConnection; - if (username != null) { - xaConnection = xaDataSource.getXAConnection(username, password); - } else { - xaConnection = xaDataSource.getXAConnection(); - } - return xaConnection.getConnection(); - } catch (SQLException sex) { - throw new DbSqlException("Unable to get connection from XA datasource", sex); - } - } - - @Override - public void closeConnection(final Connection connection) { - try { - connection.close(); - } catch (SQLException sex) { - // ignore - } - } - - @Override - public void close() {} -} diff --git a/jodd-db/src/main/java/jodd/db/connection/package-info.java b/jodd-db/src/main/java/jodd/db/connection/package-info.java deleted file mode 100644 index 3f7607524..000000000 --- a/jodd-db/src/main/java/jodd/db/connection/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Various database connection providers. - */ -package jodd.db.connection; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/debug/BaseLoggableStatement.java b/jodd-db/src/main/java/jodd/db/debug/BaseLoggableStatement.java deleted file mode 100644 index e407f7846..000000000 --- a/jodd-db/src/main/java/jodd/db/debug/BaseLoggableStatement.java +++ /dev/null @@ -1,348 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.debug; - -import jodd.typeconverter.Converter; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.SQLWarning; -import java.sql.Statement; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.util.ArrayList; -import java.util.Date; -import java.util.StringTokenizer; - -public abstract class BaseLoggableStatement implements Statement { - - protected final S wrappedStatement; - protected final String sqlTemplate; - - public BaseLoggableStatement(final S wrappedStatement, final String sqlTemplate) { - this.wrappedStatement = wrappedStatement; - this.sqlTemplate = sqlTemplate; - } - - // ---------------------------------------------------------------- query - - protected ArrayList parameterValues; - - /** - * Returns the query string. - */ - public String getQueryString() { - if (sqlTemplate == null) { - return toString(); - } - if (parameterValues == null) { - return sqlTemplate; - } - - final StringBuilder sb = new StringBuilder(); - - int qMarkCount = 0; - final StringTokenizer tok = new StringTokenizer(sqlTemplate + ' ', "?"); - - while (tok.hasMoreTokens()) { - final String oneChunk = tok.nextToken(); - sb.append(oneChunk); - try { - Object value = null; - if (parameterValues.size() > 1 + qMarkCount) { - value = parameterValues.get(1 + qMarkCount); - qMarkCount++; - } else { - if (!tok.hasMoreTokens()) { - value = ""; - } - } - if (value == null) { - value = "?"; - } - sb.append(value); - } catch (Throwable th) { - sb.append("--- Building query failed: ").append(th.toString()); - } - } - return sb.toString().trim(); - } - - /** - * Saves the parameter value obj for the specified - * position for use in logging output. - * - * @param position position (starting at 1) of the parameter to save - * @param obj java.lang.Object the parameter value to save - */ - protected void saveQueryParamValue(final int position, final Object obj) { - final String strValue; - if (obj instanceof String || obj instanceof Date) { - strValue = "'" + obj + '\''; // if we have a String or Date, include '' in the saved value - } else if (obj instanceof LocalDateTime || obj instanceof LocalDate || obj instanceof LocalTime) { - strValue = "'" + Converter.get().toString(obj) + '\''; // time as string with ' - } else if (obj == null) { - strValue = ""; // convert null to the string null - } else { - strValue = Converter.get().toString(obj); // all other objects (includes all Numbers, arrays, etc) - } - - // if we are setting a position larger than current size of parameterValues, - // first make it larger - if (parameterValues == null) { - parameterValues = new ArrayList<>(); - } - - while (position >= parameterValues.size()) { - parameterValues.add(null); - } - parameterValues.set(position, strValue); - } - - // ---------------------------------------------------------------- statement - - @Override - public ResultSet executeQuery(String sql) throws SQLException { - return wrappedStatement.executeQuery(sql); - } - - @Override - public int executeUpdate(String sql) throws SQLException { - return wrappedStatement.executeUpdate(sql); - } - - @Override - public void close() throws SQLException { - wrappedStatement.close(); - } - - @Override - public int getMaxFieldSize() throws SQLException { - return wrappedStatement.getMaxFieldSize(); - } - - @Override - public void setMaxFieldSize(int max) throws SQLException { - wrappedStatement.setMaxFieldSize(max); - } - - @Override - public int getMaxRows() throws SQLException { - return wrappedStatement.getMaxRows(); - } - - @Override - public void setMaxRows(int max) throws SQLException { - wrappedStatement.setMaxRows(max); - } - - @Override - public void setEscapeProcessing(boolean enable) throws SQLException { - wrappedStatement.setEscapeProcessing(enable); - } - - @Override - public int getQueryTimeout() throws SQLException { - return wrappedStatement.getQueryTimeout(); - } - - @Override - public void setQueryTimeout(int seconds) throws SQLException { - wrappedStatement.setQueryTimeout(seconds); - } - - @Override - public void cancel() throws SQLException { - wrappedStatement.cancel(); - } - - @Override - public SQLWarning getWarnings() throws SQLException { - return wrappedStatement.getWarnings(); - } - - @Override - public void clearWarnings() throws SQLException { - wrappedStatement.clearWarnings(); - } - - @Override - public void setCursorName(String name) throws SQLException { - wrappedStatement.setCursorName(name); - } - - @Override - public boolean execute(String sql) throws SQLException { - return wrappedStatement.execute(sql); - } - - @Override - public ResultSet getResultSet() throws SQLException { - return wrappedStatement.getResultSet(); - } - - @Override - public int getUpdateCount() throws SQLException { - return wrappedStatement.getUpdateCount(); - } - - @Override - public boolean getMoreResults() throws SQLException { - return wrappedStatement.getMoreResults(); - } - - @Override - public void setFetchDirection(int direction) throws SQLException { - wrappedStatement.setFetchDirection(direction); - } - - @Override - public int getFetchDirection() throws SQLException { - return wrappedStatement.getFetchDirection(); - } - - @Override - public void setFetchSize(int rows) throws SQLException { - wrappedStatement.setFetchDirection(rows); - } - - @Override - public int getFetchSize() throws SQLException { - return wrappedStatement.getFetchSize(); - } - - @Override - public int getResultSetConcurrency() throws SQLException { - return wrappedStatement.getResultSetConcurrency(); - } - - @Override - public int getResultSetType() throws SQLException { - return wrappedStatement.getResultSetType(); - } - - @Override - public void addBatch(String sql) throws SQLException { - wrappedStatement.addBatch(sql); - } - - @Override - public void clearBatch() throws SQLException { - wrappedStatement.clearBatch(); - } - - @Override - public int[] executeBatch() throws SQLException { - return wrappedStatement.executeBatch(); - } - - @Override - public Connection getConnection() throws SQLException { - return wrappedStatement.getConnection(); - } - - @Override - public boolean getMoreResults(int current) throws SQLException { - return wrappedStatement.getMoreResults(current); - } - - @Override - public ResultSet getGeneratedKeys() throws SQLException { - return wrappedStatement.getGeneratedKeys(); - } - - @Override - public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { - return wrappedStatement.executeUpdate(sql, autoGeneratedKeys); - } - - @Override - public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { - return wrappedStatement.executeUpdate(sql, columnIndexes); - } - - @Override - public int executeUpdate(String sql, String[] columnNames) throws SQLException { - return wrappedStatement.executeUpdate(sql, columnNames); - } - - @Override - public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { - return wrappedStatement.execute(sql, autoGeneratedKeys); - } - - @Override - public boolean execute(String sql, int[] columnIndexes) throws SQLException { - return wrappedStatement.execute(sql, columnIndexes); - } - - @Override - public boolean execute(String sql, String[] columnNames) throws SQLException { - return wrappedStatement.execute(sql, columnNames); - } - - @Override - public int getResultSetHoldability() throws SQLException { - return wrappedStatement.getResultSetHoldability(); - } - - @Override - public boolean isClosed() throws SQLException { - return wrappedStatement.isClosed(); - } - - @Override - public void setPoolable(boolean poolable) throws SQLException { - wrappedStatement.setPoolable(poolable); - } - - @Override - public boolean isPoolable() throws SQLException { - return wrappedStatement.isPoolable(); - } - - @Override - public void closeOnCompletion() throws SQLException { - wrappedStatement.closeOnCompletion(); - } - - @Override - public boolean isCloseOnCompletion() throws SQLException { - return wrappedStatement.isCloseOnCompletion(); - } - - @Override - public T unwrap(Class iface) throws SQLException { - return wrappedStatement.unwrap(iface); - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return wrappedStatement.isWrapperFor(iface); - } -} diff --git a/jodd-db/src/main/java/jodd/db/debug/LoggableCallableStatement.java b/jodd-db/src/main/java/jodd/db/debug/LoggableCallableStatement.java deleted file mode 100644 index d00fba877..000000000 --- a/jodd-db/src/main/java/jodd/db/debug/LoggableCallableStatement.java +++ /dev/null @@ -1,622 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.debug; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.net.URL; -import java.sql.Array; -import java.sql.Blob; -import java.sql.CallableStatement; -import java.sql.Clob; -import java.sql.Date; -import java.sql.NClob; -import java.sql.Ref; -import java.sql.RowId; -import java.sql.SQLException; -import java.sql.SQLXML; -import java.sql.Time; -import java.sql.Timestamp; -import java.util.Calendar; -import java.util.Map; - -public class LoggableCallableStatement extends LoggablePreparedStatement implements CallableStatement { - private CallableStatement callableStatement; - - public LoggableCallableStatement(final CallableStatement wrappedStatement, final String sqlTemplate) { - super(wrappedStatement, sqlTemplate); - this.callableStatement = wrappedStatement; - } - - @Override - public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { - callableStatement.registerOutParameter(parameterIndex, sqlType); - } - - @Override - public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { - callableStatement.registerOutParameter(parameterIndex, sqlType, scale); - } - - @Override - public boolean wasNull() throws SQLException { - return callableStatement.wasNull(); - } - - @Override - public String getString(int parameterIndex) throws SQLException { - return callableStatement.getString(parameterIndex); - } - - @Override - public boolean getBoolean(int parameterIndex) throws SQLException { - return callableStatement.getBoolean(parameterIndex); - } - - @Override - public byte getByte(int parameterIndex) throws SQLException { - return callableStatement.getByte(parameterIndex); - } - - @Override - public short getShort(int parameterIndex) throws SQLException { - return callableStatement.getShort(parameterIndex); - } - - @Override - public int getInt(int parameterIndex) throws SQLException { - return callableStatement.getInt(parameterIndex); - } - - @Override - public long getLong(int parameterIndex) throws SQLException { - return callableStatement.getLong(parameterIndex); - } - - @Override - public float getFloat(int parameterIndex) throws SQLException { - return callableStatement.getFloat(parameterIndex); - } - - @Override - public double getDouble(int parameterIndex) throws SQLException { - return callableStatement.getDouble(parameterIndex); - } - - @Override - @Deprecated - public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { - return callableStatement.getBigDecimal(parameterIndex, scale); - } - - @Override - public byte[] getBytes(int parameterIndex) throws SQLException { - return callableStatement.getBytes(parameterIndex); - } - - @Override - public Date getDate(int parameterIndex) throws SQLException { - return callableStatement.getDate(parameterIndex); - } - - @Override - public Time getTime(int parameterIndex) throws SQLException { - return callableStatement.getTime(parameterIndex); - } - - @Override - public Timestamp getTimestamp(int parameterIndex) throws SQLException { - return callableStatement.getTimestamp(parameterIndex); - } - - @Override - public Object getObject(int parameterIndex) throws SQLException { - return callableStatement.getObject(parameterIndex); - } - - @Override - public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { - return callableStatement.getBigDecimal(parameterIndex); - } - - @Override - public Object getObject(int parameterIndex, Map> map) throws SQLException { - return callableStatement.getObject(parameterIndex, map); - } - - @Override - public Ref getRef(int parameterIndex) throws SQLException { - return callableStatement.getRef(parameterIndex); - } - - @Override - public Blob getBlob(int parameterIndex) throws SQLException { - return callableStatement.getBlob(parameterIndex); - } - - @Override - public Clob getClob(int parameterIndex) throws SQLException { - return callableStatement.getClob(parameterIndex); - } - - @Override - public Array getArray(int parameterIndex) throws SQLException { - return callableStatement.getArray(parameterIndex); - } - - @Override - public Date getDate(int parameterIndex, Calendar cal) throws SQLException { - return callableStatement.getDate(parameterIndex, cal); - } - - @Override - public Time getTime(int parameterIndex, Calendar cal) throws SQLException { - return callableStatement.getTime(parameterIndex, cal); - } - - @Override - public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { - return callableStatement.getTimestamp(parameterIndex, cal); - } - - @Override - public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { - callableStatement.registerOutParameter(parameterIndex, sqlType, typeName); - } - - @Override - public void registerOutParameter(String parameterName, int sqlType) throws SQLException { - callableStatement.registerOutParameter(parameterName, sqlType); - } - - @Override - public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { - callableStatement.registerOutParameter(parameterName, sqlType, scale); - } - - @Override - public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { - callableStatement.registerOutParameter(parameterName, sqlType, typeName); - } - - @Override - public URL getURL(int parameterIndex) throws SQLException { - return callableStatement.getURL(parameterIndex); - } - - @Override - public void setURL(String parameterName, URL val) throws SQLException { - callableStatement.setURL(parameterName, val); - } - - @Override - public void setNull(String parameterName, int sqlType) throws SQLException { - callableStatement.setNull(parameterName, sqlType); - } - - @Override - public void setBoolean(String parameterName, boolean x) throws SQLException { - callableStatement.setBoolean(parameterName, x); - } - - @Override - public void setByte(String parameterName, byte x) throws SQLException { - callableStatement.setByte(parameterName, x); - } - - @Override - public void setShort(String parameterName, short x) throws SQLException { - callableStatement.setShort(parameterName, x); - } - - @Override - public void setInt(String parameterName, int x) throws SQLException { - callableStatement.setInt(parameterName, x); - } - - @Override - public void setLong(String parameterName, long x) throws SQLException { - callableStatement.setLong(parameterName, x); - } - - @Override - public void setFloat(String parameterName, float x) throws SQLException { - callableStatement.setFloat(parameterName, x); - } - - @Override - public void setDouble(String parameterName, double x) throws SQLException { - callableStatement.setDouble(parameterName, x); - } - - @Override - public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { - callableStatement.setBigDecimal(parameterName, x); - } - - @Override - public void setString(String parameterName, String x) throws SQLException { - callableStatement.setString(parameterName, x); - } - - @Override - public void setBytes(String parameterName, byte[] x) throws SQLException { - callableStatement.setBytes(parameterName, x); - } - - @Override - public void setDate(String parameterName, Date x) throws SQLException { - callableStatement.setDate(parameterName, x); - } - - @Override - public void setTime(String parameterName, Time x) throws SQLException { - callableStatement.setTime(parameterName, x); - } - - @Override - public void setTimestamp(String parameterName, Timestamp x) throws SQLException { - callableStatement.setTimestamp(parameterName, x); - } - - @Override - public void setAsciiStream(String parameterName, InputStream x, int length) throws SQLException { - callableStatement.setAsciiStream(parameterName, x, length); - } - - @Override - public void setBinaryStream(String parameterName, InputStream x, int length) throws SQLException { - callableStatement.setBinaryStream(parameterName, x, length); - } - - @Override - public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { - callableStatement.setObject(parameterName, x, targetSqlType, scale); - } - - @Override - public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { - callableStatement.setObject(parameterName, x, targetSqlType); - } - - @Override - public void setObject(String parameterName, Object x) throws SQLException { - callableStatement.setObject(parameterName, x); - } - - @Override - public void setCharacterStream(String parameterName, Reader reader, int length) throws SQLException { - callableStatement.setCharacterStream(parameterName, reader, length); - } - - @Override - public void setDate(String parameterName, Date x, Calendar cal) throws SQLException { - callableStatement.setDate(parameterName, x, cal); - } - - @Override - public void setTime(String parameterName, Time x, Calendar cal) throws SQLException { - callableStatement.setTime(parameterName, x, cal); - } - - @Override - public void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException { - callableStatement.setTimestamp(parameterName, x, cal); - } - - @Override - public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { - callableStatement.setNull(parameterName, sqlType, typeName); - } - - @Override - public String getString(String parameterName) throws SQLException { - return callableStatement.getString(parameterName); - } - - @Override - public boolean getBoolean(String parameterName) throws SQLException { - return callableStatement.getBoolean(parameterName); - } - - @Override - public byte getByte(String parameterName) throws SQLException { - return callableStatement.getByte(parameterName); - } - - @Override - public short getShort(String parameterName) throws SQLException { - return callableStatement.getShort(parameterName); - } - - @Override - public int getInt(String parameterName) throws SQLException { - return callableStatement.getInt(parameterName); - } - - @Override - public long getLong(String parameterName) throws SQLException { - return callableStatement.getLong(parameterName); - } - - @Override - public float getFloat(String parameterName) throws SQLException { - return callableStatement.getFloat(parameterName); - } - - @Override - public double getDouble(String parameterName) throws SQLException { - return callableStatement.getDouble(parameterName); - } - - @Override - public byte[] getBytes(String parameterName) throws SQLException { - return callableStatement.getBytes(parameterName); - } - - @Override - public Date getDate(String parameterName) throws SQLException { - return callableStatement.getDate(parameterName); - } - - @Override - public Time getTime(String parameterName) throws SQLException { - return callableStatement.getTime(parameterName); - } - - @Override - public Timestamp getTimestamp(String parameterName) throws SQLException { - return callableStatement.getTimestamp(parameterName); - } - - @Override - public Object getObject(String parameterName) throws SQLException { - return callableStatement.getObject(parameterName); - } - - @Override - public BigDecimal getBigDecimal(String parameterName) throws SQLException { - return callableStatement.getBigDecimal(parameterName); - } - - @Override - public Object getObject(String parameterName, Map> map) throws SQLException { - return callableStatement.getObject(parameterName, map); - } - - @Override - public Ref getRef(String parameterName) throws SQLException { - return callableStatement.getRef(parameterName); - } - - @Override - public Blob getBlob(String parameterName) throws SQLException { - return callableStatement.getBlob(parameterName); - } - - @Override - public Clob getClob(String parameterName) throws SQLException { - return callableStatement.getClob(parameterName); - } - - @Override - public Array getArray(String parameterName) throws SQLException { - return callableStatement.getArray(parameterName); - } - - @Override - public Date getDate(String parameterName, Calendar cal) throws SQLException { - return callableStatement.getDate(parameterName, cal); - } - - @Override - public Time getTime(String parameterName, Calendar cal) throws SQLException { - return callableStatement.getTime(parameterName, cal); - } - - @Override - public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { - return callableStatement.getTimestamp(parameterName, cal); - } - - @Override - public URL getURL(String parameterName) throws SQLException { - return callableStatement.getURL(parameterName); - } - - @Override - public RowId getRowId(int parameterIndex) throws SQLException { - return callableStatement.getRowId(parameterIndex); - } - - @Override - public RowId getRowId(String parameterName) throws SQLException { - return callableStatement.getRowId(parameterName); - } - - @Override - public void setRowId(String parameterName, RowId x) throws SQLException { - callableStatement.setRowId(parameterName, x); - } - - @Override - public void setNString(String parameterName, String value) throws SQLException { - callableStatement.setNString(parameterName, value); - } - - @Override - public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { - callableStatement.setNCharacterStream(parameterName, value, length); - } - - @Override - public void setNClob(String parameterName, NClob value) throws SQLException { - callableStatement.setNClob(parameterName, value); - } - - @Override - public void setClob(String parameterName, Reader reader, long length) throws SQLException { - callableStatement.setClob(parameterName, reader, length); - } - - @Override - public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { - callableStatement.setBlob(parameterName, inputStream, length); - } - - @Override - public void setNClob(String parameterName, Reader reader, long length) throws SQLException { - callableStatement.setNClob(parameterName, reader, length); - } - - @Override - public NClob getNClob(int parameterIndex) throws SQLException { - return callableStatement.getNClob(parameterIndex); - } - - @Override - public NClob getNClob(String parameterName) throws SQLException { - return callableStatement.getNClob(parameterName); - } - - @Override - public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { - callableStatement.setSQLXML(parameterName, xmlObject); - } - - @Override - public SQLXML getSQLXML(int parameterIndex) throws SQLException { - return callableStatement.getSQLXML(parameterIndex); - } - - @Override - public SQLXML getSQLXML(String parameterName) throws SQLException { - return callableStatement.getSQLXML(parameterName); - } - - @Override - public String getNString(int parameterIndex) throws SQLException { - return callableStatement.getNString(parameterIndex); - } - - @Override - public String getNString(String parameterName) throws SQLException { - return callableStatement.getNString(parameterName); - } - - @Override - public Reader getNCharacterStream(int parameterIndex) throws SQLException { - return callableStatement.getNCharacterStream(parameterIndex); - } - - @Override - public Reader getNCharacterStream(String parameterName) throws SQLException { - return callableStatement.getNCharacterStream(parameterName); - } - - @Override - public Reader getCharacterStream(int parameterIndex) throws SQLException { - return callableStatement.getCharacterStream(parameterIndex); - } - - @Override - public Reader getCharacterStream(String parameterName) throws SQLException { - return callableStatement.getCharacterStream(parameterName); - } - - @Override - public void setBlob(String parameterName, Blob x) throws SQLException { - callableStatement.setBlob(parameterName, x); - } - - @Override - public void setClob(String parameterName, Clob x) throws SQLException { - callableStatement.setClob(parameterName, x); - } - - @Override - public void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException { - callableStatement.setAsciiStream(parameterName, x, length); - } - - @Override - public void setBinaryStream(String parameterName, InputStream x, long length) throws SQLException { - callableStatement.setBinaryStream(parameterName, x, length); - } - - @Override - public void setCharacterStream(String parameterName, Reader reader, long length) throws SQLException { - callableStatement.setCharacterStream(parameterName, reader, length); - } - - @Override - public void setAsciiStream(String parameterName, InputStream x) throws SQLException { - callableStatement.setAsciiStream(parameterName, x); - } - - @Override - public void setBinaryStream(String parameterName, InputStream x) throws SQLException { - callableStatement.setBinaryStream(parameterName, x); - } - - @Override - public void setCharacterStream(String parameterName, Reader reader) throws SQLException { - callableStatement.setCharacterStream(parameterName, reader); - } - - @Override - public void setNCharacterStream(String parameterName, Reader value) throws SQLException { - callableStatement.setNCharacterStream(parameterName, value); - } - - @Override - public void setClob(String parameterName, Reader reader) throws SQLException { - callableStatement.setClob(parameterName, reader); - } - - @Override - public void setBlob(String parameterName, InputStream inputStream) throws SQLException { - callableStatement.setBlob(parameterName, inputStream); - } - - @Override - public void setNClob(String parameterName, Reader reader) throws SQLException { - callableStatement.setNClob(parameterName, reader); - } - - @Override - public T getObject(int parameterIndex, Class type) throws SQLException { - return callableStatement.getObject(parameterIndex, type); - } - - @Override - public T getObject(String parameterName, Class type) throws SQLException { - return callableStatement.getObject(parameterName, type); - } -} - - diff --git a/jodd-db/src/main/java/jodd/db/debug/LoggablePreparedStatement.java b/jodd-db/src/main/java/jodd/db/debug/LoggablePreparedStatement.java deleted file mode 100644 index 992b07285..000000000 --- a/jodd-db/src/main/java/jodd/db/debug/LoggablePreparedStatement.java +++ /dev/null @@ -1,387 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.debug; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.net.URL; -import java.sql.Array; -import java.sql.Blob; -import java.sql.Clob; -import java.sql.Date; -import java.sql.NClob; -import java.sql.ParameterMetaData; -import java.sql.PreparedStatement; -import java.sql.Ref; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.RowId; -import java.sql.SQLException; -import java.sql.SQLXML; -import java.sql.Time; -import java.sql.Timestamp; -import java.util.Calendar; - -/** - * Factory for loggable prepared statements - a PreparedStatement with added logging capability. - *

- * In addition to the methods declared in PreparedStatement, - * LoggablePreparedStatement provides a method {@link #getQueryString} that can be used to get - * the query string in a format suitable for logging. - *

- * Should not be used in production! - */ -@SuppressWarnings("MagicConstant") -public class LoggablePreparedStatement extends BaseLoggableStatement implements PreparedStatement { - - public LoggablePreparedStatement(final PreparedStatement wrappedStatement, final String sqlTemplate) { - super(wrappedStatement, sqlTemplate); - } - - @Override - public ResultSet executeQuery() throws SQLException { - return wrappedStatement.executeQuery(); - } - - @Override - public int executeUpdate() throws SQLException { - return wrappedStatement.executeUpdate(); - } - - @Override - public void setNull(int parameterIndex, int sqlType) throws SQLException { - saveQueryParamValue(parameterIndex, null); - wrappedStatement.setNull(parameterIndex, sqlType); - } - - @Override - public void setBoolean(int parameterIndex, boolean x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBoolean(parameterIndex, x); - } - - @Override - public void setByte(int parameterIndex, byte x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setByte(parameterIndex, x); - } - - @Override - public void setShort(int parameterIndex, short x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setShort(parameterIndex, x); - } - - @Override - public void setInt(int parameterIndex, int x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setInt(parameterIndex, x); - } - - @Override - public void setLong(int parameterIndex, long x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setLong(parameterIndex, x); - } - - @Override - public void setFloat(int parameterIndex, float x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setFloat(parameterIndex, x); - } - - @Override - public void setDouble(int parameterIndex, double x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setDouble(parameterIndex, x); - } - - @Override - public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBigDecimal(parameterIndex, x); - } - - @Override - public void setString(int parameterIndex, String x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setString(parameterIndex, x); - } - - @Override - public void setBytes(int parameterIndex, byte[] x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBytes(parameterIndex, x); - } - - @Override - public void setDate(int parameterIndex, Date x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setDate(parameterIndex, x); - } - - @Override - public void setTime(int parameterIndex, Time x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setTime(parameterIndex, x); - } - - @Override - public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setTimestamp(parameterIndex, x); - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setAsciiStream(parameterIndex, x); - } - - @Override - @Deprecated - public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setUnicodeStream(parameterIndex, x, length); - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBinaryStream(parameterIndex, x, length); - } - - @Override - public void clearParameters() throws SQLException { - wrappedStatement.clearParameters(); - } - - @Override - public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setObject(parameterIndex, x, targetSqlType); - } - - @Override - public void setObject(int parameterIndex, Object x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setObject(parameterIndex, x); - } - - @Override - public boolean execute() throws SQLException { - return wrappedStatement.execute(); - } - - @Override - public void addBatch() throws SQLException { - wrappedStatement.addBatch(); - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setCharacterStream(parameterIndex, reader, length); - } - - @Override - public void setRef(int parameterIndex, Ref x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setRef(parameterIndex, x); - } - - @Override - public void setBlob(int parameterIndex, Blob x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBlob(parameterIndex, x); - } - - @Override - public void setClob(int parameterIndex, Clob x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setClob(parameterIndex, x); - } - - @Override - public void setArray(int parameterIndex, Array x) throws SQLException { - wrappedStatement.setArray(parameterIndex, x); - } - - @Override - public ResultSetMetaData getMetaData() throws SQLException { - return wrappedStatement.getMetaData(); - } - - @Override - public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setDate(parameterIndex, x, cal); - } - - @Override - public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setTime(parameterIndex, x, cal); - } - - @Override - public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setTimestamp(parameterIndex, x, cal); - } - - @Override - public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { - saveQueryParamValue(parameterIndex, null); - wrappedStatement.setNull(parameterIndex, sqlType, typeName); - } - - @Override - public void setURL(int parameterIndex, URL x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setURL(parameterIndex, x); - } - - @Override - public ParameterMetaData getParameterMetaData() throws SQLException { - return wrappedStatement.getParameterMetaData(); - } - - @Override - public void setRowId(int parameterIndex, RowId x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setRowId(parameterIndex, x); - } - - @Override - public void setNString(int parameterIndex, String value) throws SQLException { - saveQueryParamValue(parameterIndex, value); - wrappedStatement.setNString(parameterIndex, value); - } - - @Override - public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { - saveQueryParamValue(parameterIndex, value); - wrappedStatement.setNCharacterStream(parameterIndex, value, length); - } - - @Override - public void setNClob(int parameterIndex, NClob value) throws SQLException { - saveQueryParamValue(parameterIndex, value); - wrappedStatement.setNClob(parameterIndex, value); - } - - @Override - public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setClob(parameterIndex, reader, length); - } - - @Override - public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { - saveQueryParamValue(parameterIndex, inputStream); - wrappedStatement.setBlob(parameterIndex, inputStream, length); - } - - @Override - public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setNClob(parameterIndex, reader, length); - } - - @Override - public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { - saveQueryParamValue(parameterIndex, xmlObject); - wrappedStatement.setSQLXML(parameterIndex, xmlObject); - } - - @Override - public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setObject(parameterIndex, x, targetSqlType, scaleOrLength); - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setAsciiStream(parameterIndex, x, length); - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBinaryStream(parameterIndex, x, length); - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setCharacterStream(parameterIndex, reader, length); - } - - @Override - public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setAsciiStream(parameterIndex, x); - } - - @Override - public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { - saveQueryParamValue(parameterIndex, x); - wrappedStatement.setBinaryStream(parameterIndex, x); - } - - @Override - public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setCharacterStream(parameterIndex, reader); - } - - @Override - public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { - saveQueryParamValue(parameterIndex, value); - wrappedStatement.setNCharacterStream(parameterIndex, value); - } - - @Override - public void setClob(int parameterIndex, Reader reader) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setClob(parameterIndex, reader); - } - - @Override - public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { - saveQueryParamValue(parameterIndex, inputStream); - wrappedStatement.setBlob(parameterIndex, inputStream); - } - - @Override - public void setNClob(int parameterIndex, Reader reader) throws SQLException { - saveQueryParamValue(parameterIndex, reader); - wrappedStatement.setNClob(parameterIndex, reader); - } -} diff --git a/jodd-db/src/main/java/jodd/db/debug/package-info.java b/jodd-db/src/main/java/jodd/db/debug/package-info.java deleted file mode 100644 index 880542698..000000000 --- a/jodd-db/src/main/java/jodd/db/debug/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Various database debugging tools. Not for use in production. - */ -package jodd.db.debug; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/jtx/DbJtxResourceManager.java b/jodd-db/src/main/java/jodd/db/jtx/DbJtxResourceManager.java deleted file mode 100644 index 9b834356d..000000000 --- a/jodd-db/src/main/java/jodd/db/jtx/DbJtxResourceManager.java +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.jtx; - -import jodd.db.DbSession; -import jodd.db.connection.ConnectionProvider; -import jodd.jtx.JtxException; -import jodd.jtx.JtxResourceManager; -import jodd.jtx.JtxTransactionMode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Database {@link jodd.jtx.JtxResourceManager} manages life-cycle of {@link jodd.db.DbSession} resources. - * Also acts as an adapter of resource object (of any type) and JTX engine. - *

- * Transaction resources may be of any type. The only thing what is important is that resource must be - * aware of its transactional state - is it in no-transactional mode (i.e. auto-commit), or under the transaction. - */ -public class DbJtxResourceManager implements JtxResourceManager { - - private static final Logger log = LoggerFactory.getLogger(DbJtxResourceManager.class); - - protected final ConnectionProvider connectionProvider; - - /** - * Creates resource manager. - */ - public DbJtxResourceManager(final ConnectionProvider connectionProvider) { - this.connectionProvider = connectionProvider; - } - - /** - * {@inheritDoc} - */ - public Class getResourceType() { - return DbSession.class; - } - - // ---------------------------------------------------------------- resource manager - - /** - * {@inheritDoc} - */ - public DbSession beginTransaction(final JtxTransactionMode jtxMode, final boolean active) { - final DbSession session = new DbSession(connectionProvider); - if (active) { - log.debug("begin jtx"); - - session.beginTransaction(JtxDbUtil.convertToDbMode(jtxMode)); - } - return session; - } - - /** - * {@inheritDoc} - */ - public void commitTransaction(final DbSession resource) { - if (resource.isTransactionActive()) { - log.debug("commit jtx"); - - resource.commitTransaction(); - } - resource.closeSession(); - } - - /** - * {@inheritDoc} - */ - public void rollbackTransaction(final DbSession resource) { - try { - if (resource.isTransactionActive()) { - log.debug("rollback tx"); - - resource.rollbackTransaction(); - } - } catch (final Exception ex) { - throw new JtxException(ex); - } finally { - resource.closeSession(); - } - } - - /** - * {@inheritDoc} - */ - public void close() { - connectionProvider.close(); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/jtx/DbJtxSessionProvider.java b/jodd-db/src/main/java/jodd/db/jtx/DbJtxSessionProvider.java deleted file mode 100644 index a5a37fe77..000000000 --- a/jodd-db/src/main/java/jodd/db/jtx/DbJtxSessionProvider.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.jtx; - -import jodd.db.DbSession; -import jodd.db.DbSessionProvider; -import jodd.db.DbSqlException; -import jodd.jtx.JtxTransactionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Returns session from the db {@link JtxTransactionManager transaction manager}, - * like {@link DbJtxTransactionManager}. - */ -public class DbJtxSessionProvider implements DbSessionProvider { - - private static final Logger log = LoggerFactory.getLogger(DbJtxSessionProvider.class); - - protected final JtxTransactionManager jtxTxManager; - - /** - * Creates new JTX session provider. - */ - public DbJtxSessionProvider(final JtxTransactionManager txManager) { - this.jtxTxManager = txManager; - } - - /** - * Returns session from JTX transaction manager and started transaction. - */ - @Override - public DbSession getDbSession() { - log.debug("Requesting db TX manager session"); - - final DbJtxTransaction jtx = (DbJtxTransaction) jtxTxManager.getTransaction(); - - if (jtx == null) { - throw new DbSqlException( - "No transaction is in progress and DbSession can't be provided. " + - "It seems that transaction manager is not used to begin a transaction."); - } - - return jtx.requestResource(); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/jtx/DbJtxTransaction.java b/jodd-db/src/main/java/jodd/db/jtx/DbJtxTransaction.java deleted file mode 100644 index c0f0802bb..000000000 --- a/jodd-db/src/main/java/jodd/db/jtx/DbJtxTransaction.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.jtx; - -import jodd.db.DbSession; -import jodd.jtx.JtxTransaction; -import jodd.jtx.JtxTransactionManager; -import jodd.jtx.JtxTransactionMode; - -/** - * {@link JtxTransaction} extension that simplifies beginning of the transaction since - * related {@link DbJtxTransactionManager} allows only one resource type. - */ -public class DbJtxTransaction extends JtxTransaction { - - protected DbJtxTransaction(final JtxTransactionManager txManager, final JtxTransactionMode mode, final Object scope, final boolean active) { - super(txManager, mode, scope, active); - } - - public DbSession requestResource() { - return requestResource(DbSession.class); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/jtx/DbJtxTransactionManager.java b/jodd-db/src/main/java/jodd/db/jtx/DbJtxTransactionManager.java deleted file mode 100644 index bfa397e2b..000000000 --- a/jodd-db/src/main/java/jodd/db/jtx/DbJtxTransactionManager.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.jtx; - -import jodd.db.connection.ConnectionProvider; -import jodd.jtx.JtxTransaction; -import jodd.jtx.JtxTransactionManager; -import jodd.jtx.JtxTransactionMode; - -/** - * {@link jodd.jtx.JtxTransactionManager} that uses only one JTX db resource type. - * Usually, applications have only one transactional resource type - the database. - * This manager just simplifies the usage, nothing more. - * @see jodd.jtx.JtxTransactionManager - */ -public class DbJtxTransactionManager extends JtxTransactionManager { - - /** - * Creates db jtx manager and registers provided {@link DbJtxResourceManager}. - */ - public DbJtxTransactionManager(final DbJtxResourceManager resourceManager) { - setMaxResourcesPerTransaction(1); - setSingleResourceManager(true); - super.registerResourceManager(resourceManager); - - } - - /** - * Creates db jtx manager and registers new {@link DbJtxResourceManager}. - */ - public DbJtxTransactionManager(final ConnectionProvider connectionProvider) { - this(new DbJtxResourceManager(connectionProvider)); - } - - /** - * {@inheritDoc} - */ - @Override - public DbJtxTransaction requestTransaction(final JtxTransactionMode mode) { - return (DbJtxTransaction) super.requestTransaction(mode, null); - } - - /** - * {@inheritDoc} - */ - @Override - public DbJtxTransaction requestTransaction(final JtxTransactionMode mode, final Object scope) { - return (DbJtxTransaction) super.requestTransaction(mode, scope); - } - - /** - * Builds new transaction instance. - */ - @Override - protected JtxTransaction createNewTransaction(final JtxTransactionMode tm, final Object scope, final boolean active) { - return new DbJtxTransaction(this, tm, scope, active); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/jtx/JtxDbUtil.java b/jodd-db/src/main/java/jodd/db/jtx/JtxDbUtil.java deleted file mode 100644 index 0dd936a47..000000000 --- a/jodd-db/src/main/java/jodd/db/jtx/JtxDbUtil.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.jtx; - -import jodd.db.DbTransactionMode; -import jodd.jtx.JtxTransactionMode; - -/** - * Helpers for jtx db. - */ -public class JtxDbUtil { - - /** - * Converter JTX transaction mode to DB transaction mode. - */ - public static DbTransactionMode convertToDbMode(final JtxTransactionMode txMode) { - final int isolation; - switch (txMode.getIsolationLevel()) { - case ISOLATION_DEFAULT: isolation = DbTransactionMode.ISOLATION_DEFAULT; break; - case ISOLATION_NONE: isolation = DbTransactionMode.ISOLATION_NONE; break; - case ISOLATION_READ_COMMITTED: isolation = DbTransactionMode.ISOLATION_READ_COMMITTED; break; - case ISOLATION_READ_UNCOMMITTED: isolation = DbTransactionMode.ISOLATION_READ_UNCOMMITTED; break; - case ISOLATION_REPEATABLE_READ: isolation = DbTransactionMode.ISOLATION_REPEATABLE_READ; break; - case ISOLATION_SERIALIZABLE: isolation = DbTransactionMode.ISOLATION_SERIALIZABLE; break; - default: - throw new IllegalArgumentException(); - } - return new DbTransactionMode(isolation, txMode.isReadOnly()); - } -} diff --git a/jodd-db/src/main/java/jodd/db/jtx/package-info.java b/jodd-db/src/main/java/jodd/db/jtx/package-info.java deleted file mode 100644 index ba6691d2b..000000000 --- a/jodd-db/src/main/java/jodd/db/jtx/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Database extension for propagated transactions. - */ -package jodd.db.jtx; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/AutomagicDbOomConfigurator.java b/jodd-db/src/main/java/jodd/db/oom/AutomagicDbOomConfigurator.java deleted file mode 100644 index fff733e24..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/AutomagicDbOomConfigurator.java +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.oom.meta.DbTable; -import jodd.io.findfile.ClassScanner; -import jodd.util.Consumers; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.function.Consumer; - -/** - * Auto-magically scans classpath for domain objects annotated with DbOom annotations. - */ -public class AutomagicDbOomConfigurator { - - private static final Logger log = LoggerFactory.getLogger(AutomagicDbOomConfigurator.class); - - protected final static byte[] DB_TABLE_ANNOTATION_BYTES = ClassScanner.bytecodeSignatureOfType(DbTable.class); - protected final boolean registerAsEntities; - protected final DbEntityManager dbEntityManager; - private final Consumers classScannerConsumers = new Consumers<>(); - - public AutomagicDbOomConfigurator(final DbEntityManager dbEntityManager, final boolean registerAsEntities) { - this.dbEntityManager = dbEntityManager; - this.registerAsEntities = registerAsEntities; - } - - public AutomagicDbOomConfigurator withScanner(final Consumer scannerConsumer) { - classScannerConsumers.add(scannerConsumer); - return this; - } - - - /** - * Configures {@link DbEntityManager} with specified class path. - */ - public void configure() { - long elapsed = System.currentTimeMillis(); - - final ClassScanner classScanner = new ClassScanner(); - - classScanner.detectEntriesMode(true); - classScanner.scanDefaultClasspath(); - - classScannerConsumers.accept(classScanner); - - registerAsConsumer(classScanner); - - try { - classScanner.start(); - } catch (final Exception ex) { - throw new DbOomException("Scan classpath error", ex); - } - elapsed = System.currentTimeMillis() - elapsed; - if (log.isInfoEnabled()) { - log.info("DbEntityManager configured in " + elapsed + "ms. Total entities: " + dbEntityManager.getTotalNames()); - } - } - - /** - * Registers a class consumer that registers only those annotated with {@link DbTable}. - * Because of performance purposes, classes are not dynamically loaded; instead, their - * file content is examined. - */ - public void registerAsConsumer(final ClassScanner classScanner) { - classScanner.registerEntryConsumer(classPathEntry -> { - if (!classPathEntry.isTypeSignatureInUse(DB_TABLE_ANNOTATION_BYTES)) { - return; - } - - final Class beanClass; - try { - beanClass = classPathEntry.loadClass(); - } catch (final ClassNotFoundException cnfex) { - throw new DbOomException("Entry class not found: " + classPathEntry.name(), cnfex); - } - - if (beanClass == null) { - return; - } - - final DbTable dbTable = beanClass.getAnnotation(DbTable.class); - - if (dbTable == null) { - return; - } - - if (registerAsEntities) { - dbEntityManager.registerEntity(beanClass); - } else { - dbEntityManager.registerType(beanClass); - } - }); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/ColumnAliasType.java b/jodd-db/src/main/java/jodd/db/oom/ColumnAliasType.java deleted file mode 100644 index 653e1a7d0..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/ColumnAliasType.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -/** - * Various column alias types. Sometimes, when database JDBC driver does not - * support table names in ResultSet metadata, it might be useful to include - * table name or a reference in the column name, separated by some separator. - *

- * Using TABLE_NAME type might be dangerous, since most databases (including Oracle) - * has some maximum length for column names, so adding table name prefix might - * be too much;) - *

- * Column types are usually used internally by SQL generators (see: {@link DbSqlGenerator}). - */ -public enum ColumnAliasType { - - TABLE_NAME(1), // table_namecolumn_name - TABLE_REFERENCE(2), // table_referencecolumn_name - COLUMN_CODE(3); // col__ - - int value; - - ColumnAliasType(final int aliasType) { - this.value = aliasType; - } -} diff --git a/jodd-db/src/main/java/jodd/db/oom/ColumnData.java b/jodd-db/src/main/java/jodd/db/oom/ColumnData.java deleted file mode 100644 index 281d64f66..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/ColumnData.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -/** - * Column data. - */ -public class ColumnData { - - private final String tableName; - private final String columnName; - - public ColumnData(final String tableName) { - this.tableName = tableName; - this.columnName = null; - } - - public ColumnData(final String tableName, final String columnName) { - this.tableName = tableName; - this.columnName = columnName; - } - - /** - * Returns table name for this column. - */ - public String getTableName() { - return tableName; - } - - /** - * Returns column name for this column. - */ - public String getColumnName() { - return columnName; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbEntityColumnDescriptor.java b/jodd-db/src/main/java/jodd/db/oom/DbEntityColumnDescriptor.java deleted file mode 100644 index e1a437748..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbEntityColumnDescriptor.java +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.type.SqlType; -import jodd.util.StringUtil; - -/** - * Column descriptors. - */ -public class DbEntityColumnDescriptor implements Comparable { - - protected final DbEntityDescriptor dbEntityDescriptor; - protected final String columnName; - protected final String columnNameForQuery; - protected final String propertyName; - protected final Class propertyType; - protected final boolean isId; - protected final Class sqlTypeClass; - protected int dbSqlType = SqlType.DB_SQLTYPE_UNKNOWN; - - public DbEntityColumnDescriptor( - final DbEntityDescriptor ded, - final String columnName, - final String fieldName, - final Class fieldType, - final boolean isId, - final Class sqlTypeClass) { - - this.dbEntityDescriptor = ded; - this.propertyName = fieldName; - this.propertyType = fieldType; - this.isId = isId; - this.sqlTypeClass = sqlTypeClass; - - this.columnNameForQuery = columnName; - - if (StringUtil.detectQuoteChar(columnNameForQuery) != 0) { - this.columnName = StringUtil.substring(columnNameForQuery, 1, -1); - } - else { - this.columnName = columnNameForQuery; - } - } - - /** - * Returns {@link jodd.db.oom.DbEntityDescriptor} that this column description belongs to. - */ - public DbEntityDescriptor getDbEntityDescriptor() { - return dbEntityDescriptor; - } - - /** - * Returns column name. - */ - public String getColumnName() { - return columnName; - } - - /** - * Returns column name to be used in the generated sql. - */ - public String getColumnNameForQuery() { - return columnNameForQuery; - } - - /** - * Returns property name. - */ - public String getPropertyName() { - return propertyName; - } - - /** - * Returns property type. - */ - public Class getPropertyType() { - return propertyType; - } - - /** - * Returns true if column is ID column. - */ - public boolean isId() { - return isId; - } - - /** - * Returns SqlType or null for default type. - */ - public Class getSqlTypeClass() { - return sqlTypeClass; - } - - /** - * Returns db sql type. Important: available only after first saving of column value - * to database! - */ - public int getDbSqlType() { - return dbSqlType; - } - - /** - * Updates db sql type if not already set. - */ - public void updateDbSqlType(final int dbSqlType) { - if (this.dbSqlType == SqlType.DB_SQLTYPE_UNKNOWN) { - this.dbSqlType = dbSqlType; - } - } - - // ---------------------------------------------------------------- comparable - - /** - * Compares two column descriptors. Identity columns should be the first on the list. - * Each group then will be sorted by column name. - */ - @Override - public int compareTo(final Object o) { - DbEntityColumnDescriptor that = (DbEntityColumnDescriptor) o; - if (this.isId != that.isId) { - return this.isId ? -1 : 1; // IDs should be the first in the array - } - return this.columnName.compareTo(that.columnName); - } - - // ---------------------------------------------------------------- equals and hash - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (this.getClass() != o.getClass()) { - return false; - } - DbEntityColumnDescriptor that = (DbEntityColumnDescriptor) o; - return columnName.equals(that.columnName); - } - - @Override - public int hashCode() { - return columnName.hashCode(); - } - - // ---------------------------------------------------------------- to string - - - @Override - public String toString() { - return "DbEntityColumnDescriptor{" + - "columnName='" + columnName + '\'' + - ", propertyName='" + propertyName + '\'' + - ", isId=" + isId + - '}'; - } -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbEntityDescriptor.java b/jodd-db/src/main/java/jodd/db/oom/DbEntityDescriptor.java deleted file mode 100644 index 825b2b53a..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbEntityDescriptor.java +++ /dev/null @@ -1,341 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.bean.BeanUtil; -import jodd.db.oom.naming.ColumnNamingStrategy; -import jodd.db.oom.naming.TableNamingStrategy; -import jodd.introspector.ClassIntrospector; -import jodd.introspector.PropertyDescriptor; -import jodd.util.StringPool; -import jodd.util.StringUtil; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; - -/** - * Holds all information about some entity type, such as table name and {@link DbEntityColumnDescriptor columns data}. - */ -public class DbEntityDescriptor { - - public DbEntityDescriptor( - final Class type, - final String schemaName, - final TableNamingStrategy tableNamingStrategy, - final ColumnNamingStrategy columnNamingStrategy) { - - this.type = type; - this.entityName = type.getSimpleName(); - this.isAnnotated = DbMetaUtil.resolveIsAnnotated(type); - this.schemaName = DbMetaUtil.resolveSchemaName(type, schemaName); - this.columnNamingStrategy = columnNamingStrategy; - this.mappedTypes = DbMetaUtil.resolveMappedTypes(type); - - this.tableNameForQuery = DbMetaUtil.resolveTableName(type, tableNamingStrategy); - - if (StringUtil.detectQuoteChar(tableNameForQuery) != 0) { - this.tableName = StringUtil.substring(tableNameForQuery, 1, -1); - } else { - this.tableName = tableNameForQuery; - } - } - - // ---------------------------------------------------------------- type and table - - private final Class type; - private final String entityName; - private final boolean isAnnotated; - private final String tableName; - private final String tableNameForQuery; - private final String schemaName; - private final ColumnNamingStrategy columnNamingStrategy; - private final Class[] mappedTypes; - - /** - * Returns entity type. - */ - public Class getType() { - return type; - } - - /** - * Returns true if type is annotated with {@link jodd.db.oom.meta.DbTable}. - */ - public boolean isAnnotated() { - return isAnnotated; - } - - /** - * Returns table name to which the entity is mapped. - */ - public String getTableName() { - return tableName; - } - - /** - * Returns table name to be used when generating queries. - */ - public String getTableNameForQuery() { - return tableNameForQuery; - } - - /** - * Returns type name. - */ - public String getEntityName() { - return entityName; - } - - /** - * Returns schema name or null if not available. - */ - public String getSchemaName() { - return schemaName; - } - - /** - * Returns mapped types. - */ - public Class[] getMappedTypes() { - return mappedTypes; - } - - // ---------------------------------------------------------------- columns and fields - - private DbEntityColumnDescriptor[] columnDescriptors; - private DbEntityColumnDescriptor[] idColumnDescriptors; - - /** - * Returns the array of column descriptors. - */ - public DbEntityColumnDescriptor[] getColumnDescriptors() { - init(); - return columnDescriptors; - } - - // ---------------------------------------------------------------- initialization - - /** - * Lazy initialization of descriptor. - */ - protected void init() { - if (columnDescriptors == null) { - resolveColumnsAndProperties(type); - } - } - - /** - * Resolves list of all columns and properties. - */ - private void resolveColumnsAndProperties(final Class type) { - final PropertyDescriptor[] allProperties = ClassIntrospector.get().lookup(type).getAllPropertyDescriptors(); - final List decList = new ArrayList<>(allProperties.length); - int idcount = 0; - - final HashSet names = new HashSet<>(allProperties.length); - - for (final PropertyDescriptor propertyDescriptor : allProperties) { - - final DbEntityColumnDescriptor dec = - DbMetaUtil.resolveColumnDescriptors(this, propertyDescriptor, isAnnotated, columnNamingStrategy); - - if (dec != null) { - if (!names.add(dec.getColumnName())) { - throw new DbOomException("Duplicate column name: " + dec.getColumnName()); - } - - decList.add(dec); - - if (dec.isId) { - idcount++; - } - } - } - if (decList.isEmpty()) { - throw new DbOomException("No column mappings in entity: " + type); - } - columnDescriptors = decList.toArray(new DbEntityColumnDescriptor[0]); - Arrays.sort(columnDescriptors); - - // extract ids from sorted list - if (idcount > 0) { - idColumnDescriptors = new DbEntityColumnDescriptor[idcount]; - idcount = 0; - for (final DbEntityColumnDescriptor dec : columnDescriptors) { - if (dec.isId) { - idColumnDescriptors[idcount++] = dec; - } - } - } - } - - // ---------------------------------------------------------------- finders - - /** - * Finds column descriptor by column name. Case is ignored. - */ - public DbEntityColumnDescriptor findByColumnName(final String columnName) { - if (columnName == null) { - return null; - } - init(); - for (final DbEntityColumnDescriptor columnDescriptor : columnDescriptors) { - if (columnDescriptor.columnName.equalsIgnoreCase(columnName)) { - return columnDescriptor; - } - } - return null; - } - /** - * Finds column descriptor by property name. - */ - public DbEntityColumnDescriptor findByPropertyName(final String propertyName) { - if (propertyName == null) { - return null; - } - init(); - for (final DbEntityColumnDescriptor columnDescriptor : columnDescriptors) { - if (columnDescriptor.propertyName.equals(propertyName)) { - return columnDescriptor; - } - } - return null; - } - - - /** - * Returns property name for specified column name. - */ - public String getPropertyName(final String columnName) { - final DbEntityColumnDescriptor dec = findByColumnName(columnName); - return dec == null ? null : dec.propertyName; - } - - /** - * Returns column name for specified property name.. - */ - public String getColumnName(final String propertyName) { - final DbEntityColumnDescriptor dec = findByPropertyName(propertyName); - return dec == null ? null : dec.columnName; - } - - // ---------------------------------------------------------------- column work - - /** - * Returns total number of columns. - */ - public int getColumnsCount() { - init(); - return columnDescriptors.length; - } - - /** - * Returns total number of identity columns. - */ - public int getIdColumnsCount() { - init(); - return idColumnDescriptors == null ? 0 : idColumnDescriptors.length; - } - - /** - * Returns true if entity has one ID column. - */ - public boolean hasIdColumn() { - return getIdColumnsCount() == 1; - } - - private void ensureSingleIdColumn() { - init(); - if (idColumnDescriptors == null) { - throw new DbOomException("No identity column in entity: " + entityName); - } else if (idColumnDescriptors.length > 1) { - throw new DbOomException("More then one identity column in entity: " + entityName); - } - } - - /** - * Returns the identity column name of column marked as identity. - * Throws an exception if table has composite primary key. - */ - public String getIdColumnName() { - ensureSingleIdColumn(); - return idColumnDescriptors[0].getColumnName(); - } - - /** - * Returns the first property name of column marked as identity. - * Throws an exception if table has composite primary key. - */ - public String getIdPropertyName() { - ensureSingleIdColumn(); - return idColumnDescriptors[0].getPropertyName(); - } - - /** - * Returns ID value for given entity instance. - */ - public Object getIdValue(final E object) { - final String propertyName = getIdPropertyName(); - return BeanUtil.declared.getProperty(object, propertyName); - } - - /** - * Sets ID value for given entity. - */ - public void setIdValue(final E object, final Object value) { - final String propertyName = getIdPropertyName(); - BeanUtil.declared.setProperty(object, propertyName, value); - } - - /** - * Returns unique key for this entity. Returned key - * is built from entity class and id value. - */ - public String getKeyValue(final E object) { - final Object idValue = getIdValue(object); - - final String idValueString = idValue == null ? StringPool.NULL : idValue.toString(); - - return type.getName().concat(StringPool.COLON).concat(idValueString); - } - - // ---------------------------------------------------------------- toString - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("DbEntity: "); - if (schemaName != null) { - sb.append(schemaName); - sb.append('.'); - } - sb.append(tableName); - return sb.toString(); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbEntityManager.java b/jodd-db/src/main/java/jodd/db/oom/DbEntityManager.java deleted file mode 100644 index 50a9a5afb..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbEntityManager.java +++ /dev/null @@ -1,247 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.oom.naming.ColumnNamingStrategy; -import jodd.db.oom.naming.TableNamingStrategy; -import jodd.util.ClassUtil; -import jodd.util.StringUtil; -import jodd.util.TypeCache; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.Map; -import java.util.function.Consumer; - -/** - * DbOom Entity manager. - *

- * Important: configure settings before entity registration! - *

- * Mapping definitions are used only by a result set mapper (such as {@link jodd.db.oom.mapper.ResultSetMapper}) - * to lookup for an entity from table name. Table names are read from result-set meta data, for example. - * It is not needed to use mappings at all: in that case just provide entity types during the conversion of - * result set to objects. - */ -public class DbEntityManager { - - private static final Logger log = LoggerFactory.getLogger(DbEntityManager.class); - - private final DbOomConfig dbOomConfig; - - public DbEntityManager(final DbOomConfig dbOomConfig) { - this.dbOomConfig = dbOomConfig; - } - - // ---------------------------------------------------------------- registration - - protected String[] primitiveEntitiesPrefixes = new String[] { - "java.lang.", - "jodd.mutable.", - int.class.getName(), - long.class.getName(), - float.class.getName(), - double.class.getName(), - short.class.getName(), - boolean.class.getName(), - byte.class.getName()}; - - public String[] getPrimitiveEntitiesPrefixes() { - return primitiveEntitiesPrefixes; - } - - /** - * Specifies array of class name prefixes that will be mapped directly to column. - */ - public void setPrimitiveEntitiesPrefixes(final String... primitiveEntitiesPrefixes) { - this.primitiveEntitiesPrefixes = primitiveEntitiesPrefixes; - } - - protected TypeCache descriptorsMap = TypeCache.createDefault(); - protected Map entityNamesMap = new HashMap<>(); - protected Map tableNamesMap = new NamedValuesHashMap<>(); - - /** - * Lookups {@link DbEntityDescriptor} for some type and registers the type if is new. - *

- * Returns null for core classes from java run-time packages! - * Some types are not entities, i.e. domain objects. Instead, primitive entities - * are simply mapped to one column. - */ - public DbEntityDescriptor lookupType(final Class type) { - final String typeName = type.getName(); - if (StringUtil.startsWithOne(typeName, primitiveEntitiesPrefixes) != -1) { - return null; - } - DbEntityDescriptor ded = descriptorsMap.get(type); - if (ded == null) { - ded = registerType(type); - } - return ded; - } - - - /** - * Lookups for {@link jodd.db.oom.DbEntityDescriptor} that was registered with this manager. - * Returns null if name not found. - */ - public DbEntityDescriptor lookupName(final String typeName) { - return entityNamesMap.get(typeName); - } - - /** - * Lookups for {@link jodd.db.oom.DbEntityDescriptor} that was registered with this manager. - * Returns null if table name not found. Lookup is case-insensitive. - */ - public DbEntityDescriptor lookupTableName(final String tableName) { - return tableNamesMap.get(tableName); - } - - /** - * Registers just type and entity names. Enough for most usages. - */ - public DbEntityDescriptor registerType(final Class type) { - final DbEntityDescriptor ded = createDbEntityDescriptor(type); - DbEntityDescriptor existing = descriptorsMap.put(type, ded); - - if (log.isDebugEnabled()) { - log.debug("Register " + type.getName() + " as " + ded.getTableName()); - } - - if (existing != null) { - if (ded.getType() == type) { - return ded; - } - throw new DbOomException("Type already registered: " + existing.getType()); - } - - existing = entityNamesMap.put(ded.getEntityName(), ded); - - if (existing != null) { - throw new DbOomException("Name '" + ded.getEntityName() + "' already mapped to an entity: " + existing.getType()); - } - return ded; - } - - /** - * Registers entity. {@link #registerType(Class) Registers types} and table names. - */ - public DbEntityDescriptor registerEntity(final Class type) { - final DbEntityDescriptor ded = registerType(type); - final DbEntityDescriptor existing = tableNamesMap.put(ded.getTableName(), ded); - - if (existing != null) { - if (ded.getType() == type) { - return ded; - } - throw new DbOomException("Entity registration failed! Table '" + ded.getTableName() + "' already mapped to an entity: " + existing.getType()); - } - return ded; - } - - /** - * Registers entity. Existing entity will be removed if exist, so no exception will be thrown. - */ - public DbEntityDescriptor registerEntity(final Class type, final boolean force) { - if (force) { - removeEntity(type); - } - return registerEntity(type); - } - - /** - * Removes entity and returns removed descriptor. - */ - public DbEntityDescriptor removeEntity(final Class type) { - DbEntityDescriptor ded = descriptorsMap.remove(type); - if (ded == null) { - ded = createDbEntityDescriptor(type); - } - entityNamesMap.remove(ded.getEntityName()); - tableNamesMap.remove(ded.getTableName()); - return ded; - } - - /** - * Creates {@link DbEntityDescriptor}. - */ - protected DbEntityDescriptor createDbEntityDescriptor(final Class type) { - final String schemaName = dbOomConfig.getSchemaName(); - final TableNamingStrategy tableNames = dbOomConfig.getTableNames(); - final ColumnNamingStrategy columnNames = dbOomConfig.getColumnNames(); - - return new DbEntityDescriptor<>(type, schemaName, tableNames, columnNames); - } - - // ---------------------------------------------------------------- stats - - /** - * Returns total number of registered entity names. - */ - public int getTotalNames() { - return entityNamesMap.size(); - } - - /** - * Returns total number of registered table names. - */ - public int getTotalTableNames() { - return tableNamesMap.size(); - } - - /** - * Returns total number of registered types. - */ - public int getTotalTypes() { - return descriptorsMap.size(); - } - - /** - * Resets the manager and clears descriptors maps. - */ - public void reset() { - descriptorsMap.clear(); - entityNamesMap.clear(); - tableNamesMap.clear(); - } - - /** - * Creates new entity instances. - */ - public E createEntityInstance(final Class type) { - try { - return ClassUtil.newInstance(type); - } catch (final Exception ex) { - throw new DbOomException(ex); - } - } - - public void forEachEntity(final Consumer consumer) { - descriptorsMap.forEachValue(consumer); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbListIterator.java b/jodd-db/src/main/java/jodd/db/oom/DbListIterator.java deleted file mode 100644 index b006d1408..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbListIterator.java +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.oom.mapper.ResultSetMapper; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - * Internal result set iterator. - */ -class DbListIterator implements Iterator { - - protected final DbOomQuery query; - protected final boolean entityAwareMode; - protected final ResultSetMapper resultSetMapper; - protected final Class[] types; - protected final boolean closeOnEnd; - - // ---------------------------------------------------------------- ctors - - DbListIterator(final DbOomQuery query, final Class[] types, final boolean closeOnEnd) { - this.query = query; - this.resultSetMapper = query.executeAndBuildResultSetMapper(); - this.entityAwareMode = query.entityAwareMode; - this.types = (types == null ? resultSetMapper.resolveTables() : types); - this.closeOnEnd = closeOnEnd; - } - - DbListIterator(final DbOomQuery query, final Class[] types, final ResultSetMapper resultSetMapper, final boolean closeOnEnd) { - this.query = query; - this.resultSetMapper = resultSetMapper; - this.entityAwareMode = query.entityAwareMode; - this.types = (types == null ? resultSetMapper.resolveTables() : types); - this.closeOnEnd = closeOnEnd; - } - - // ---------------------------------------------------------------- iterate - - protected T previousElement; - protected T newElement; - protected int count; - protected boolean last; - protected Boolean hasNext; - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - /** - * Returns true if there is {@link #next() next} parsed object - * available. - */ - @Override - public boolean hasNext() { - if (hasNext == null) { - hasNext = Boolean.valueOf(moveToNext()); - } - return hasNext.booleanValue(); - } - - /** - * Returns next mapped object. - */ - @Override - public T next() { - if (hasNext == null) { - hasNext = Boolean.valueOf(moveToNext()); - } - if (hasNext == false) { - throw new NoSuchElementException(); - } - - if (!entityAwareMode) { - hasNext = null; - return newElement; - } - - count++; - - T result = previousElement; - - previousElement = newElement; - - hasNext = null; - return result; - } - - - /** - * Moves to next element. - */ - private boolean moveToNext() { - if (last) { - // last has been set to true, so no more rows to iterate - close everything - - if (closeOnEnd) { - query.close(); - } else { - query.closeResultSet(resultSetMapper.getResultSet()); - } - - return false; - } - - while (true) { - - if (!resultSetMapper.next()) { - // no more rows, no more parsing, previousElement is the last one to iterate - last = true; - return entityAwareMode; - } - - // parse row - - Object[] objects = resultSetMapper.parseObjects(types); - - Object row = query.resolveRowResults(objects); - - newElement = (T) row; - - if (entityAwareMode) { - - if (count == 0 && previousElement == null) { - previousElement = newElement; - - continue; - } - - if (previousElement != null && newElement != null) { - boolean equals; - - if (newElement.getClass().isArray()) { - equals = Arrays.equals((Object[]) previousElement, (Object[]) newElement); - } else { - equals = previousElement.equals(newElement); - } - - if (equals) { - continue; - } - } - } - - break; - } - - return true; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbMetaUtil.java b/jodd-db/src/main/java/jodd/db/oom/DbMetaUtil.java deleted file mode 100644 index 053d750aa..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbMetaUtil.java +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.oom.meta.DbColumn; -import jodd.db.oom.meta.DbId; -import jodd.db.oom.meta.DbMapTo; -import jodd.db.oom.meta.DbTable; -import jodd.db.oom.naming.ColumnNamingStrategy; -import jodd.db.oom.naming.TableNamingStrategy; -import jodd.db.type.SqlType; -import jodd.introspector.PropertyDescriptor; -import jodd.util.StringUtil; - -/** - * Meta-data resolving utils. - */ -public class DbMetaUtil { - - /** - * Resolves table name from a type. If type is annotated, table name - * will be read from annotation value. If this value is empty or if - * type is not annotated, table name will be set to wildcard pattern '*' - * (to match all tables). - */ - public static String resolveTableName(final Class type, final TableNamingStrategy tableNamingStrategy) { - String tableName = null; - final DbTable dbTable = type.getAnnotation(DbTable.class); - if (dbTable != null) { - tableName = dbTable.value().trim(); - } - if ((tableName == null) || (tableName.length() == 0)) { - tableName = tableNamingStrategy.convertEntityNameToTableName(type); - } else { - if (!tableNamingStrategy.isStrictAnnotationNames()) { - tableName = tableNamingStrategy.applyToTableName(tableName); - } - } - - return quoteIfRequired(tableName, tableNamingStrategy.isAlwaysQuoteNames(), tableNamingStrategy.getQuoteChar()); - } - - /** - * Resolves schema name from a type. Uses default schema name if not specified. - */ - public static String resolveSchemaName(final Class type, final String defaultSchemaName) { - String schemaName = null; - final DbTable dbTable = type.getAnnotation(DbTable.class); - if (dbTable != null) { - schemaName = dbTable.schema().trim(); - } - if ((schemaName == null) || (schemaName.length() == 0)) { - schemaName = defaultSchemaName; - } - return schemaName; - } - - /** - * Returns true if class is annotated with DbTable annotation. - */ - public static boolean resolveIsAnnotated(final Class type) { - final DbTable dbTable = type.getAnnotation(DbTable.class); - return dbTable != null; - } - - /** - * Resolves column descriptor from property. If property is annotated value will be read - * from annotation. If property is not annotated, then property will be ignored - * if entity is annotated. Otherwise, column name is generated from the property name. - */ - public static DbEntityColumnDescriptor resolveColumnDescriptors( - final DbEntityDescriptor dbEntityDescriptor, - final PropertyDescriptor property, - final boolean isAnnotated, - final ColumnNamingStrategy columnNamingStrategy) { - - String columnName = null; - boolean isId = false; - Class sqlTypeClass = null; - - // read ID annotation - - DbId dbId = null; - - if (property.getFieldDescriptor() != null) { - dbId = property.getFieldDescriptor().getField().getAnnotation(DbId.class); - } - if (dbId == null && property.getReadMethodDescriptor() != null) { - dbId = property.getReadMethodDescriptor().getMethod().getAnnotation(DbId.class); - } - if (dbId == null && property.getWriteMethodDescriptor() != null) { - dbId = property.getWriteMethodDescriptor().getMethod().getAnnotation(DbId.class); - } - - if (dbId != null) { - columnName = dbId.value().trim(); - sqlTypeClass = dbId.sqlType(); - isId = true; - } else { - DbColumn dbColumn = null; - - if (property.getFieldDescriptor() != null) { - dbColumn = property.getFieldDescriptor().getField().getAnnotation(DbColumn.class); - } - if (dbColumn == null && property.getReadMethodDescriptor() != null) { - dbColumn = property.getReadMethodDescriptor().getMethod().getAnnotation(DbColumn.class); - } - if (dbColumn == null && property.getWriteMethodDescriptor() != null) { - dbColumn = property.getWriteMethodDescriptor().getMethod().getAnnotation(DbColumn.class); - } - - if (dbColumn != null) { - columnName = dbColumn.value().trim(); - sqlTypeClass = dbColumn.sqlType(); - } else { - if (isAnnotated) { - return null; - } - } - } - - if (StringUtil.isEmpty(columnName)) { - // default annotation value - columnName = columnNamingStrategy.convertPropertyNameToColumnName(property.getName()); - } else { - if (!columnNamingStrategy.isStrictAnnotationNames()) { - columnName = columnNamingStrategy.applyToColumnName(columnName); - } - } - if (sqlTypeClass == SqlType.class) { - sqlTypeClass = null; - } - - return new DbEntityColumnDescriptor( - dbEntityDescriptor, - quoteIfRequired(columnName, columnNamingStrategy.isAlwaysQuoteNames(), columnNamingStrategy.getQuoteChar()), - property.getName(), - property.getType(), - isId, - sqlTypeClass); - } - - /** - * Resolves mapped types from {@link jodd.db.oom.meta.DbMapTo} annotation. - */ - public static Class[] resolveMappedTypes(final Class type) { - final DbMapTo dbMapTo = (DbMapTo) type.getAnnotation(DbMapTo.class); - if (dbMapTo == null) { - return null; - } - return dbMapTo.value(); - } - - // ---------------------------------------------------------------- privates - - private static String quoteIfRequired(final String name, final boolean alwaysQuoteNames, final char quoteChar) { - if (StringUtil.detectQuoteChar(name) != 0) { - return name; // already quoted - } - if (alwaysQuoteNames && quoteChar != 0) { - return quoteChar + name + quoteChar; - } - return name; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbOomConfig.java b/jodd-db/src/main/java/jodd/db/oom/DbOomConfig.java deleted file mode 100644 index e5e93ec5c..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbOomConfig.java +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.oom.naming.ColumnNamingStrategy; -import jodd.db.oom.naming.TableNamingStrategy; - -/** - * DBOOM configuration for names and SQL generation. - */ -public class DbOomConfig { - - /** - * Specifies separator for column aliases that divides table reference and column name. - * Separator should contains of characters that are not used in table names, such as: - * '$' or '__'. - */ - private String columnAliasSeparator = "$"; - /** - * Default column alias type. - */ - private ColumnAliasType defaultColumnAliasType; - /** - * Optional schema name. - */ - private String schemaName; - /** - * Table name strategy. - */ - private TableNamingStrategy tableNames = new TableNamingStrategy(); - /** - * Column name strategy. - */ - private ColumnNamingStrategy columnNames = new ColumnNamingStrategy(); - - /** - * {@code true} if SQL syntax allow usage of table alias in the update query. - */ - private boolean updateAcceptsTableAlias = true; - - /** - * {@code true} if database supports update of the primary key. - */ - private boolean updateablePrimaryKey = true; - - /** - * Defines entity-aware mode, when resulting collections does not have duplicates. - * It make sense to enable it if {@link #cacheEntitiesInResultSet cache} is set. - */ - private boolean entityAwareMode = false; - - /** - * Defines if entities have to be cached in result set. - * When cached, more memory is consumed during the existence of - * {@link jodd.db.oom.mapper.ResultSetMapper}. - */ - private boolean cacheEntitiesInResultSet = false; - - /** - * Specifies how primary keys are generated by database. - */ - protected boolean keysGeneratedByDatabase = true; - - // ---------------------------------------------------------------- r/o - - public TableNamingStrategy getTableNames() { - return tableNames; - } - - public ColumnNamingStrategy getColumnNames() { - return columnNames; - } - - - // ---------------------------------------------------------------- access - - public String getColumnAliasSeparator() { - return columnAliasSeparator; - } - - public void setColumnAliasSeparator(final String separator) { - this.columnAliasSeparator = separator; - } - - - public ColumnAliasType getDefaultColumnAliasType() { - return defaultColumnAliasType; - } - - public void setDefaultColumnAliasType(final ColumnAliasType defaultColumnAliasType) { - this.defaultColumnAliasType = defaultColumnAliasType; - } - - public String getSchemaName() { - return schemaName; - } - - public void setSchemaName(final String schemaName) { - this.schemaName = schemaName; - } - - public boolean isUpdateAcceptsTableAlias() { - return updateAcceptsTableAlias; - } - - public void setUpdateAcceptsTableAlias(final boolean updateAcceptsTableAlias) { - this.updateAcceptsTableAlias = updateAcceptsTableAlias; - } - - public boolean isUpdateablePrimaryKey() { - return updateablePrimaryKey; - } - - public void setUpdateablePrimaryKey(final boolean updateablePrimaryKey) { - this.updateablePrimaryKey = updateablePrimaryKey; - } - - public boolean isEntityAwareMode() { - return entityAwareMode; - } - - public void setEntityAwareMode(final boolean entityAwareMode) { - this.entityAwareMode = entityAwareMode; - } - - public boolean isCacheEntitiesInResultSet() { - return cacheEntitiesInResultSet; - } - - public void setCacheEntitiesInResultSet(final boolean cacheEntitiesInResultSet) { - this.cacheEntitiesInResultSet = cacheEntitiesInResultSet; - } - - public boolean isKeysGeneratedByDatabase() { - return keysGeneratedByDatabase; - } - - public void setKeysGeneratedByDatabase(final boolean keysGeneratedByDatabase) { - this.keysGeneratedByDatabase = keysGeneratedByDatabase; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbOomException.java b/jodd-db/src/main/java/jodd/db/oom/DbOomException.java deleted file mode 100644 index 759ce71f8..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbOomException.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.DbQuery; -import jodd.db.DbSqlException; - -/** - * DbOom exceptions. - */ -public class DbOomException extends DbSqlException { - - public DbOomException(final Throwable t) { - super(t); - } - - public DbOomException(final String message) { - super(message); - } - - public DbOomException(final DbQuery dbQuery, final String message) { - super(dbQuery, message); - } - - public DbOomException(final String message, final Throwable t) { - super(message, t); - } - - public DbOomException(final DbQuery dbQuery, final String message, final Throwable t) { - super(dbQuery, message, t); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/DbOomQuery.java b/jodd-db/src/main/java/jodd/db/oom/DbOomQuery.java deleted file mode 100644 index 64f4dbb6b..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbOomQuery.java +++ /dev/null @@ -1,563 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.bean.BeanUtil; -import jodd.db.DbOom; -import jodd.db.DbQuery; -import jodd.db.DbSession; -import jodd.db.DbUtil; -import jodd.db.oom.mapper.DefaultResultSetMapper; -import jodd.db.oom.mapper.ResultSetMapper; -import jodd.db.oom.sqlgen.ParameterValue; -import jodd.db.type.SqlType; -import jodd.util.CharUtil; -import jodd.util.StringUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * A simple ORM extension for {@link DbQuery}. - *

- * OOM extension may map results to objects in two ways: - *

- */ -public class DbOomQuery extends DbQuery { - - private static final Logger log = LoggerFactory.getLogger(DbOomQuery.class); - - // ---------------------------------------------------------------- default ctors - - public DbOomQuery(final DbOom dbOom, final Connection conn, final String sqlString) { - super(dbOom, conn, sqlString); - this.sqlgen = null; - init(dbOom); - } - - public static DbOomQuery query(final Connection conn, final String sqlString) { - return new DbOomQuery(DbOom.get(), conn, sqlString); - } - - public DbOomQuery(final DbOom dbOom, final DbSession session, final String sqlString) { - super(dbOom, session, sqlString); - this.sqlgen = null; - init(dbOom); - } - - public static DbOomQuery query(final DbSession session, final String sqlString) { - return new DbOomQuery(DbOom.get(), session, sqlString); - } - - public DbOomQuery(final DbOom dbOom, final String sqlString) { - super(dbOom, sqlString); - this.sqlgen = null; - init(dbOom); - } - - public static DbOomQuery query(final String sqlString) { - return new DbOomQuery(DbOom.get(), sqlString); - } - - // ---------------------------------------------------------------- sqlgen ctors - - protected final DbSqlGenerator sqlgen; - - public DbOomQuery(final DbOom dbOom, final Connection conn, final DbSqlGenerator sqlgen) { - super(dbOom, conn, sqlgen.generateQuery()); - this.sqlgen = sqlgen; - init(dbOom); - } - public static DbOomQuery query(final Connection conn, final DbSqlGenerator sqlgen) { - return new DbOomQuery(DbOom.get(), conn, sqlgen); - } - - public DbOomQuery(final DbOom dbOom, final DbSession session, final DbSqlGenerator sqlgen) { - super(dbOom, session, sqlgen.generateQuery()); - this.sqlgen = sqlgen; - init(dbOom); - } - public static DbOomQuery query(final DbSession session, final DbSqlGenerator sqlgen) { - return new DbOomQuery(DbOom.get(), session, sqlgen); - } - - public DbOomQuery(final DbOom dbOom, final DbSqlGenerator sqlgen) { - super(dbOom, sqlgen.generateQuery()); - this.sqlgen = sqlgen; - init(dbOom); - } - public static DbOomQuery query(final DbSqlGenerator sqlgen) { - return new DbOomQuery(DbOom.get(), sqlgen); - } - - protected void init(final DbOom dbOom) { - this.sqlString = preprocessSql(sqlString); - this.cacheEntities = dbOom.config().isCacheEntitiesInResultSet(); - this.entityAwareMode = dbOom.config().isEntityAwareMode(); - } - - // ---------------------------------------------------------------- initialization - - /** - * Prepares the query after initialization. Besides default work, it checks if sql generator - * is used, and if so, generator hints and query parameters will be used for this query. - * Note regarding hints: since hints can be added manually, generators hints will be ignored - * if there exists some manually set hints. - */ - @Override - protected void prepareQuery() { - super.prepareQuery(); - if (sqlgen == null) { - return; - } - if (hints == null) { - final String[] joinHints = sqlgen.getJoinHints(); - if (joinHints != null) { - withHints(joinHints); - } - } - // insert parameters - final Map parameters = sqlgen.getQueryParameters(); - if (parameters == null) { - return; - } - for (final Map.Entry entry : parameters.entrySet()) { - final String paramName = entry.getKey(); - final ParameterValue param = entry.getValue(); - final DbEntityColumnDescriptor dec = param.getColumnDescriptor(); - if (dec == null) { - setObject(paramName, param.getValue()); - } else { - resolveColumnDbSqlType(connection, dec); - setObject(paramName, param.getValue(), dec.getSqlTypeClass(), dec.getDbSqlType()); - } - } - } - - /** - * Resolves column db sql type and populates it in column descriptor if missing. - */ - protected void resolveColumnDbSqlType(final Connection connection, final DbEntityColumnDescriptor dec) { - if (dec.dbSqlType != SqlType.DB_SQLTYPE_UNKNOWN) { - return; - } - ResultSet rs = null; - final DbEntityDescriptor ded = dec.getDbEntityDescriptor(); - try { - final DatabaseMetaData dmd = connection.getMetaData(); - rs = dmd.getColumns(null, ded.getSchemaName(), ded.getTableName(), dec.getColumnName()); - if (rs.next()) { - dec.dbSqlType = rs.getInt("DATA_TYPE"); - } else { - dec.dbSqlType = SqlType.DB_SQLTYPE_NOT_AVAILABLE; - if (log.isWarnEnabled()) { - log.warn("Column SQL type not available: " + ded.toString() + '.' + dec.getColumnName()); - } - } - } catch (final SQLException sex) { - dec.dbSqlType = SqlType.DB_SQLTYPE_NOT_AVAILABLE; - if (log.isWarnEnabled()) { - log.warn("Column SQL type not resolved: " + ded.toString() + '.' + dec.getColumnName(), sex); - } - } finally { - DbUtil.close(rs); - } - } - - /** - * Pre-process SQL before using it. If string starts with a non-ascii char - * or it has no spaces, it will be loaded from the query map. - */ - protected String preprocessSql(String sqlString) { - // detects callable statement - if (sqlString.charAt(0) == '{') { - return sqlString; - } - - // quickly detect if SQL string is a key - if (!CharUtil.isAlpha(sqlString.charAt(0))) { - sqlString = sqlString.substring(1); - } - else if (sqlString.indexOf(' ') != -1) { - return sqlString; - } - - final String sqlFromMap = dbOom.queryMap().getQuery(sqlString); - - if (sqlFromMap != null) { - sqlString = sqlFromMap.trim(); - } - - return sqlString; - } - - - - // ---------------------------------------------------------------- join hints - - protected JoinHintResolver hintResolver; - - protected String[] hints; - - /** - * Specifies hints for the query. Provided string is - * split on ',' separator. - */ - public DbOomQuery withHints(final String hint) { - this.hints = StringUtil.splitc(hint, ','); - return this; - } - - /** - * Specifies multiple hints for the query. - */ - public DbOomQuery withHints(final String... hints) { - this.hints = hints; - return this; - } - - /** - * Prepares a row (array of rows mapped object) using hints. - * Returns either single object or objects array. - */ - protected Object resolveRowResults(Object[] row) { - if (hintResolver == null) { - hintResolver = new JoinHintResolver(); - } - row = hintResolver.join(row, hints); - return row.length == 1 ? row[0] : row; - } - - // ---------------------------------------------------------------- result set - - protected boolean cacheEntities; - - /** - * Defines if entities should be cached in {@link ResultSetMapper}. - * Overrides default value in {@link DbEntityManager}. - */ - public DbOomQuery cacheEntities(final boolean cacheEntities) { - this.cacheEntities = cacheEntities; - return this; - } - - /** - * Executes the query and returns {@link #createResultSetMapper(java.sql.ResultSet) builded ResultSet mapper}. - */ - protected ResultSetMapper executeAndBuildResultSetMapper() { - final ResultSet resultSet = execute(); - - return createResultSetMapper(resultSet); - } - - /** - * Factory for result sets mapper. - */ - protected ResultSetMapper createResultSetMapper(final ResultSet resultSet) { - final Map columnAliases = sqlgen != null ? sqlgen.getColumnData() : null; - - return new DefaultResultSetMapper(dbOom, resultSet, columnAliases, cacheEntities, this); - } - - // ---------------------------------------------------------------- db list - - protected boolean entityAwareMode; - - /** - * Defines entity-aware mode for entities tracking in result collection. - */ - public DbOomQuery entityAwareMode(final boolean entityAware) { - if (entityAware) { - this.cacheEntities = true; - } - this.entityAwareMode = entityAware; - return this; - } - - // ---------------------------------------------------------------- iterator - - public Iterator iterate(final Class... types) { - return iterate(types, autoClose); - } - public Iterator iterate() { - return iterate(null, autoClose); - } - protected Iterator iterate(final Class[] types, final boolean close) { - return new DbListIterator<>(this, types, close); - } - - // ---------------------------------------------------------------- list - - public List list(final Class... types) { - return list(types, -1, autoClose); - } - public List list() { - return list(null, -1, autoClose); - } - public List list(final int max, final Class... types) { - return list(types, max, autoClose); - } - public List list(final int max) { - return list(null, max, autoClose); - } - /** - * Iterates result set, maps rows to classes and populates resulting array list. - * @param types mapping types - * @param max max number of rows to collect, -1 for all - * @param close true if query is closed at the end, otherwise false. - * @return list of mapped entities or array of entities - */ - @SuppressWarnings({"unchecked"}) - protected List list(Class[] types, final int max, final boolean close) { - final List result = new ArrayList<>(initialCollectionSize(max)); - - final ResultSetMapper rsm = executeAndBuildResultSetMapper(); - if (types == null) { - types = rsm.resolveTables(); - } - - Object previousElement = null; - - while (rsm.next()) { - final Object[] objects = rsm.parseObjects(types); - final Object row = resolveRowResults(objects); - - final int size = result.size(); - - final T newElement = (T) row; - - if (entityAwareMode && size > 0) { - if (previousElement != null && newElement != null) { - final boolean equals; - - if (newElement.getClass().isArray()) { - equals = Arrays.equals((Object[]) previousElement, (Object[]) newElement); - } else { - equals = previousElement.equals(newElement); - } - - if (equals) { - continue; - } - } - } - - if (size == max) { - break; - } - - result.add(newElement); - previousElement = newElement; - } - - close(rsm, close); - return result; - } - - /** - * Returns initial collections size when max - * value is provided. - */ - private static int initialCollectionSize(final int max) { - return max > 0 ? max : 10; - } - - - // ---------------------------------------------------------------- set - - public Set listSet(final Class... types) { - return listSet(types, -1, autoClose); - } - public Set listSet() { - return listSet(null, -1, autoClose); - } - public Set listSet(final int max, final Class... types) { - return listSet(types, max, autoClose); - } - public Set listSet(final int max) { - return listSet(null, max, autoClose); - } - @SuppressWarnings({"unchecked"}) - protected Set listSet(Class[] types, final int max, final boolean close) { - final Set result = new LinkedHashSet<>(initialCollectionSize(max)); - - final ResultSetMapper rsm = executeAndBuildResultSetMapper(); - if (types == null) { - types = rsm.resolveTables(); - } - - Object previousElement = null; - - while (rsm.next()) { - final Object[] objects = rsm.parseObjects(types); - final Object row = resolveRowResults(objects); - - final int size = result.size(); - - final T newElement = (T) row; - - if (entityAwareMode && size > 0) { - if (previousElement != null && newElement != null) { - final boolean equals; - - if (newElement.getClass().isArray()) { - equals = Arrays.equals((Object[]) previousElement, (Object[]) newElement); - } else { - equals = previousElement.equals(newElement); - } - - if (equals) { - continue; - } - } - } - - if (size == max) { - break; - } - - result.add(newElement); - previousElement = newElement; - } - - close(rsm, close); - return result; - } - - // ---------------------------------------------------------------- find - - public T find(final Class... types) { - return find(types, autoClose, null); - } - public T find() { - return find(null, autoClose, null); - } - protected T find(final Class[] types, final boolean close, ResultSet resultSet) { - if (resultSet == null) { - resultSet = execute(); - } - final ResultSetMapper rsm = createResultSetMapper(resultSet); - - final Iterator iterator = new DbListIterator<>(this, types, rsm, false); - - T result = null; - - if (iterator.hasNext()) { - result = iterator.next(); - } - - close(rsm, close); - return result; - } - - // ---------------------------------------------------------------- generated columns - - /** - * Finds generated key column of given type. - */ - public T findGeneratedKey(final Class type) { - return find(new Class[] {type}, false, getGeneratedColumns()); - } - - /** - * Finds generated columns. - */ - public Object findGeneratedColumns(final Class... types) { - return find(types, false, getGeneratedColumns()); - } - - - /** - * Populates entity with generated column values from executed query. - */ - public void populateGeneratedKeys(final Object entity) { - - final String[] generatedColumns = getGeneratedColumnNames(); - if (generatedColumns == null) { - return; - } - final DbEntityDescriptor ded = dbOom.entityManager().lookupType(entity.getClass()); - - // prepare key types - final Class[] keyTypes = new Class[generatedColumns.length]; - final String[] properties = new String[generatedColumns.length]; - for (int i = 0; i < generatedColumns.length; i++) { - final String column = generatedColumns[i]; - final DbEntityColumnDescriptor decd = ded.findByColumnName(column); - if (decd != null) { - keyTypes[i] = decd.getPropertyType(); - properties[i] = decd.getPropertyName(); - } - } - - final Object keyValues = findGeneratedColumns(keyTypes); - if (!keyValues.getClass().isArray()) { - BeanUtil.declared.setProperty(entity, properties[0], keyValues); - } else { - for (int i = 0; i < properties.length; i++) { - BeanUtil.declared.setProperty(entity, properties[i], ((Object[]) keyValues)[i]); - } - } - } - - - // ---------------------------------------------------------------- util - - /** - * {@inheritDoc} - */ - @Override - public DbOomQuery autoClose() { - super.autoClose(); - return this; - } - - /** - * Closes results set or whole query. - */ - protected void close(final ResultSetMapper rsm, final boolean closeQuery) { - if (closeQuery) { - close(); - } else { - closeResultSet(rsm.getResultSet()); - } - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/DbSqlGenerator.java b/jodd-db/src/main/java/jodd/db/oom/DbSqlGenerator.java deleted file mode 100644 index e746abc85..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/DbSqlGenerator.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.db.oom.sqlgen.ParameterValue; - -import java.util.Map; - -/** - * Generates SQL queries. - */ -public interface DbSqlGenerator { - - /** - * Generates SQL query. May be called multiple times. - */ - String generateQuery(); - - /** - * Returns a map of SQL parameters used by generated query. - * Must be invoked only after the {@link #generateQuery()}. - * May be null - */ - Map getQueryParameters(); - - /** - * Returns an optional map of table and column names, used by {@link jodd.db.oom.mapper.ResultSetMapper}. - * May be null. - */ - Map getColumnData(); - - /** - * Returns join hints. May be null. - */ - String[] getJoinHints(); - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/JoinHintResolver.java b/jodd-db/src/main/java/jodd/db/oom/JoinHintResolver.java deleted file mode 100644 index ad9c5762a..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/JoinHintResolver.java +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import jodd.bean.BeanUtil; -import jodd.introspector.ClassDescriptor; -import jodd.introspector.ClassIntrospector; -import jodd.util.ArraysUtil; -import jodd.util.ClassUtil; -import jodd.util.StringUtil; - -import java.lang.reflect.Array; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Joins an array of objects using provided hints. - * If hint is not available, methods returns the very same object array instance. - */ -public class JoinHintResolver { - - public Object[] join(final Object[] data, final String hints) { - if (hints == null) { - return data; - } - return join(data, StringUtil.splitc(hints, ',')); - } - - /** - * Joins entity array using provided string hints. - */ - public Object[] join(final Object[] data, final String[] hints) { - if (hints == null) { - return data; - } - // build context - Map context = new HashMap<>(hints.length); - for (int i = 0; i < hints.length; i++) { - hints[i] = hints[i].trim(); - String hint = hints[i]; - if (hint.indexOf('.') == -1) { - context.put(hint, data[i]); - } - } - - // no joining hints found - if (context.size() == data.length) { - return data; - } - - // joining - Object[] result = new Object[context.size()]; - int count = 0; - for (int i = 0; i < hints.length; i++) { - - String hint = hints[i]; - int ndx = hint.indexOf('.'); - if (ndx != -1) { - String key = hint.substring(0, ndx); - Object value = context.get(key); - if (value == null) { - throw new DbOomException("Hint value missing: " + key); - } - - // don't merge nulls - if (data[i] == null) { - continue; - } - - String hintPropertyName = hint.substring(ndx + 1); - Class hintPropertyType = BeanUtil.pojo.getPropertyType(value, hintPropertyName); - - if (hintPropertyType != null) { - ClassDescriptor cd = ClassIntrospector.get().lookup(hintPropertyType); - - if (cd.isCollection()) { - // add element to collection - try { - Collection collection = BeanUtil.declared.getProperty(value, hintPropertyName); - - if (collection == null) { - collection = (Collection) ClassUtil.newInstance(hintPropertyType); - BeanUtil.declaredSilent.setProperty(value, hintPropertyName, collection); - } - - collection.add(data[i]); - } catch (Exception ex) { - throw new DbOomException(ex); - } - } else if (cd.isArray()) { - // add element to array - try { - Object[] array = BeanUtil.declared.getProperty(value, hintPropertyName); - - if (array == null) { - array = (Object[]) Array.newInstance(hintPropertyType.getComponentType(), 1); - - BeanUtil.declaredSilent.setProperty(value, hintPropertyName, array); - - array[0] = data[i]; - } else { - Object[] newArray = ArraysUtil.append(array, data[i]); - - if (newArray != array) { - BeanUtil.declaredSilent.setProperty(value, hintPropertyName, newArray); - } - } - } catch (Exception ex) { - throw new DbOomException(ex); - } - } else { - // set value - BeanUtil.declaredSilent.setProperty(value, hintPropertyName, data[i]); - } - } - else { - // special case - the property probably contains the collection in the way - - int lastNdx = hintPropertyName.lastIndexOf('.'); - - String name = hintPropertyName.substring(0, lastNdx); - - Object target = resolveValueInSpecialCase(value, name); - - if (target != null) { - String targetSimpleName = hintPropertyName.substring(lastNdx + 1); - - BeanUtil.declaredForcedSilent.setProperty(target, targetSimpleName, data[i]); - } - } - - } else { - result[count] = data[i]; - count++; - } - } - return result; - } - - protected Object resolveValueInSpecialCase(Object value, final String name) { - String[] elements = StringUtil.splitc(name, '.'); - - for (String element : elements) { - value = BeanUtil.declaredSilent.getProperty(value, element); - - if (value instanceof List) { - List list = (List) value; - - value = list.get(list.size() - 1); - } - } - - return value; - } -} diff --git a/jodd-db/src/main/java/jodd/db/oom/NamedValuesHashMap.java b/jodd-db/src/main/java/jodd/db/oom/NamedValuesHashMap.java deleted file mode 100644 index f10f99134..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/NamedValuesHashMap.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom; - -import java.util.HashMap; - -/** - * HashMap with String keys that are case-insensitive. - */ -public class NamedValuesHashMap extends HashMap { - - @Override - public V put(String key, final V value) { - key = key.toUpperCase(); - return super.put(key, value); - } - - @Override - public V get(Object key) { - key = ((String)key).toUpperCase(); - return super.get(key); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/dao/GenericDao.java b/jodd-db/src/main/java/jodd/db/oom/dao/GenericDao.java deleted file mode 100644 index 73d0108e2..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/dao/GenericDao.java +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.dao; - -import jodd.bean.BeanUtil; -import jodd.db.DbOom; -import jodd.db.DbQuery; -import jodd.db.oom.DbEntityDescriptor; -import jodd.db.oom.DbOomException; - -import java.util.List; - -import static jodd.db.oom.DbOomQuery.query; - -/** - * Generic DAO. Contains many convenient wrappers. - */ -public class GenericDao { - - private final DbOom dbOom; - - public GenericDao(final DbOom dbOom) { - this.dbOom = dbOom; - } - - // ---------------------------------------------------------------- store - - /** - * Returns true if entity is persistent. - */ - protected boolean isPersistent(final DbEntityDescriptor ded, final E entity) { - final Object key = ded.getIdValue(entity); - - if (key == null) { - return false; - } - if (key instanceof Number) { - final long value = ((Number)key).longValue(); - - if (value == 0) { - return false; - } - } - return true; - } - - /** - * Sets new ID value for entity. - */ - protected void setEntityId(final DbEntityDescriptor ded, final E entity, final ID newIdValue) { - ded.setIdValue(entity, newIdValue); - } - - /** - * Generates next id for given type. - */ - protected ID generateNextId(final DbEntityDescriptor dbEntityDescriptor) { - throw new UnsupportedOperationException("Use Joy"); - } - - /** - * Saves or updates entity. If ID is not null, entity will be updated. - * Otherwise, entity will be inserted into the database. - */ - public E store(final E entity) { - final Class type = entity.getClass(); - final DbEntityDescriptor ded = dbOom.entityManager().lookupType(type); - - if (ded == null) { - throw new DbOomException("Not an entity: " + type); - } - if (!isPersistent(ded, entity)) { - final DbQuery q; - if (dbOom.config().isKeysGeneratedByDatabase()) { - q = query(dbOom.entities().insert(entity)); - q.setGeneratedKey(); - q.executeUpdate(); - final Object nextId = q.getGeneratedKey(); - setEntityId(ded, entity, nextId); - } - else { - final Object nextId = generateNextId(ded); - setEntityId(ded, entity, nextId); - q = query(dbOom.entities().insert(entity)); - q.executeUpdate(); - } - q.close(); - } - else { - query(dbOom.entities().updateAll(entity)).autoClose().executeUpdate(); - } - return entity; - } - - /** - * Simply inserts object into the database. - */ - public void save(final Object entity) { - final DbQuery q = query(dbOom.entities().insert(entity)); - q.autoClose().executeUpdate(); - } - - /** - * Inserts bunch of objects into the database. - * @see #save(Object) - */ - public void saveAll(final Iterable entities) { - for (final Object entity: entities) { - save(entity); - } - } - - // ---------------------------------------------------------------- update - - /** - * Updates single entity. - */ - public void update(final Object entity) { - query(dbOom.entities().updateAll(entity)).autoClose().executeUpdate(); - } - - /** - * Updates all entities. - * @see #update(Object) - */ - public void updateAll(final Iterable entities) { - for (final Object entity : entities) { - update(entity); - } - } - - /** - * Updates single property in database and in the bean. - */ - public E updateProperty(final E entity, final String name, final Object newValue) { - query(dbOom.entities().updateColumn(entity, name, newValue)).autoClose().executeUpdate(); - BeanUtil.declared.setProperty(entity, name, newValue); - return entity; - } - - /** - * Updates property in the database by storing the current property value. - */ - public E updateProperty(final E entity, final String name) { - Object value = BeanUtil.declared.getProperty(entity, name); - query(dbOom.entities().updateColumn(entity, name, value)).autoClose().executeUpdate(); - return entity; - } - - // ---------------------------------------------------------------- find - - /** - * Finds single entity by its id. - */ - public E findById(final Class entityType, final ID id) { - return query(dbOom.entities().findById(entityType, id)).autoClose().find(entityType); - } - - /** - * Finds single entity by matching property. - */ - public E findOneByProperty(final Class entityType, final String name, final Object value) { - return query(dbOom.entities().findByColumn(entityType, name, value)).autoClose().find(entityType); - } - - /** - * Finds one entity for given criteria. - */ - @SuppressWarnings({"unchecked"}) - public E findOne(final Object criteria) { - return (E) query(dbOom.entities().find(criteria)).autoClose().find(criteria.getClass()); - } - - /** - * Finds list of entities matching given criteria. - */ - @SuppressWarnings({"unchecked"}) - public List find(final Object criteria) { - return query(dbOom.entities().find(criteria)).autoClose().list(criteria.getClass()); - } - - /** - * Finds list of entities matching given criteria. - */ - public List find(final Class entityType, final Object criteria) { - return query(dbOom.entities().find(entityType, criteria)).autoClose().list(entityType); - } - - // ---------------------------------------------------------------- delete - - /** - * Deleted single entity by its id. - */ - public void deleteById(final Class entityType, final ID id) { - query(dbOom.entities().deleteById(entityType, id)).autoClose().executeUpdate(); - } - - /** - * Delete single object by its id. Resets ID value. - */ - public void deleteById(final Object entity) { - if (entity != null) { - int result = query(dbOom.entities().deleteById(entity)).autoClose().executeUpdate(); - - if (result != 0) { - // now reset the ID value - Class type = entity.getClass(); - DbEntityDescriptor ded = dbOom.entityManager().lookupType(type); - - setEntityId(ded, entity, 0); - } - } - } - - /** - * Deletes all objects by their ids. - */ - public void deleteAllById(final Iterable objects) { - for (final Object entity : objects) { - deleteById(entity); - } - } - - // ---------------------------------------------------------------- count - - /** - * Counts number of all entities. - */ - public long count(final Class entityType) { - return query(dbOom.entities().count(entityType)).autoClose().executeCount(); - } - - - // ---------------------------------------------------------------- increase - - /** - * Increases a property. - */ - public void increaseProperty(final Class entityType, final ID id, final String name, final Number delta) { - query(dbOom.entities().increaseColumn(entityType, id, name, delta, true)).autoClose().executeUpdate(); - } - - /** - * Decreases a property. - */ - public void decreaseProperty(final Class entityType, final ID id, final String name, final Number delta) { - query(dbOom.entities().increaseColumn(entityType, id, name, delta, false)).autoClose().executeUpdate(); - } - - // ---------------------------------------------------------------- related - - /** - * Finds related entity. - */ - public List findRelated(final Class target, final Object source) { - return query(dbOom.entities().findForeign(target, source)).autoClose().list(target); - } - - // ---------------------------------------------------------------- list - - /** - * List all entities. - */ - public List listAll(final Class target) { - return query(dbOom.entities().from(target)).autoClose().list(target); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/dao/package-info.java b/jodd-db/src/main/java/jodd/db/oom/dao/package-info.java deleted file mode 100644 index 712fa88d2..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/dao/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Generic DAO. - */ -package jodd.db.oom.dao; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/mapper/BaseResultSetMapper.java b/jodd-db/src/main/java/jodd/db/oom/mapper/BaseResultSetMapper.java deleted file mode 100644 index 3210436da..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/mapper/BaseResultSetMapper.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.mapper; - -import jodd.db.oom.DbOomException; - -import java.sql.ResultSet; -import java.sql.SQLException; - -/** - * Common {@link ResultSetMapper} implementation. - */ -public abstract class BaseResultSetMapper implements ResultSetMapper { - - protected final ResultSet resultSet; - - protected BaseResultSetMapper(final ResultSet resultSet) { - this.resultSet = resultSet; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean next() { - try { - return resultSet.next(); - } catch (SQLException sex) { - throw new DbOomException(sex); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void close() { - try { - resultSet.close(); - } catch (SQLException sex) { - // ignore - } - } - - /** - * {@inheritDoc} - */ - @Override - public ResultSet getResultSet() { - return resultSet; - } - - - /** - * {@inheritDoc} - */ - @Override - public Object parseOneObject(final Class... types) { - return parseObjects(types)[0]; - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/mapper/DefaultResultSetMapper.java b/jodd-db/src/main/java/jodd/db/oom/mapper/DefaultResultSetMapper.java deleted file mode 100644 index cc9fb8d9a..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/mapper/DefaultResultSetMapper.java +++ /dev/null @@ -1,524 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.mapper; - -import jodd.bean.BeanUtil; -import jodd.db.DbOom; -import jodd.db.oom.ColumnData; -import jodd.db.oom.DbEntityColumnDescriptor; -import jodd.db.oom.DbEntityDescriptor; -import jodd.db.oom.DbEntityManager; -import jodd.db.oom.DbOomException; -import jodd.db.oom.DbOomQuery; -import jodd.db.type.SqlType; -import jodd.db.type.SqlTypeManager; -import jodd.typeconverter.TypeConverterManager; - -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Maps all columns of database result set (RS) row to objects. - * It does it in two steps: preparation (reading table and column names) - * and parsing (parsing one result set row to resulting objects). - *

- * Preparation
- * Default mapper reads RS column and table names from RS meta-data and external maps, if provided. - * Since column name is always available in RS meta-data, it may be used to hold table name information. - * Column names may contain table code separator that - * divides column name to table reference and column name. Here, table reference may be either table name or - * table alias. When it is table alias, external alias-to-name map must be provided. - * Hence, this defines the table name, and there is no need to read it from RS meta-data. - *

- * When column name doesn't contain a separator, it may be either an actual column name, or a column code. - * For column codes, both table and column name is lookup-ed from external map. If column name is an actual column name, - * table information is read from the RS meta data. Unfortunately, some DBs (such Oracle) doesn't implements - * this simple JDBC feature. Therefore, it must be expected that column table name is not available. - *

- * Table name is also not available for columns which are not directly table columns: - * e.g. some calculations, counts etc. - *

- * Parsing
- * Parser takes types array and tries to populate their instances in best possible way. It assumes that provided - * types list matches selected columns. That is very important, and yet very easy and natural to follow. - * So, parser will try to inject columns value into the one result instance. Now, there are two types of instances: - * simple types (numbers and strings) and entities (pojo objects). Simple types are always mapped to - * one and only one column. Entities will be mapped to all possible columns that can be matched starting from - * current column. So, simple types are not column-hungry, entity types are column-hungry:) - * - *

- * A column can be injected in one entities property only once. If one column is already mapped to current result, - * RS mapper will assume that current result is finished with mapping and will proceed to the next one. - * Similarly, if property name is not found for a column, RS mapper will proceed to the next result. - * Therefore, entity types are column precise and hungry;) - all listed columns must be mapped somewhere. - * - *

- * Results that are not used during parsing will be set to null. - *

- */ -public class DefaultResultSetMapper extends BaseResultSetMapper { - - protected final DbOomQuery dbOomQuery; - protected final boolean cacheEntities; - protected final int totalColumns; // total number of columns - protected final String[] columnNames; // list of all column names - protected final int[] columnDbSqlTypes; // list of all column db types - protected final String[] tableNames; // list of table names for each column, table name may be null - - private final Set resultColumns; // internal columns per entity cache - private final DbEntityManager dbEntityManager; - - // ---------------------------------------------------------------- ctor - - /** - * Reads ResultSet meta-data for column and table names. - * @param resultSet JDBC result set - * @param columnAliases alias names for columns, if exist - * @param cacheEntities flag if entities should be cached - * @param dbOomQuery query that created this mapper. - */ - public DefaultResultSetMapper( - final DbOom dbOom, - final ResultSet resultSet, - final Map columnAliases, - final boolean cacheEntities, - final DbOomQuery dbOomQuery) { - super(resultSet); - - this.dbEntityManager = dbOom.entityManager(); - this.dbOomQuery = dbOomQuery; - this.cacheEntities = cacheEntities; - - //this.resultColumns = new HashSet(); - try { - ResultSetMetaData rsMetaData = resultSet.getMetaData(); - if (rsMetaData == null) { - throw new DbOomException("No ResultSet meta-data"); - } - - totalColumns = rsMetaData.getColumnCount(); - - this.resultColumns = new HashSet<>(totalColumns); - columnNames = new String[totalColumns]; - columnDbSqlTypes = new int[totalColumns]; - tableNames = new String[totalColumns]; - - for (int i = 0; i < totalColumns; i++) { - String columnName = rsMetaData.getColumnLabel(i + 1); - - if (columnName == null) { - columnName = rsMetaData.getColumnName(i + 1); - } - - String tableName = null; - - // resolve column and table name - int sepNdx = columnName.indexOf(dbOom.config().getColumnAliasSeparator()); - if (sepNdx != -1) { - // column alias exist, result set is ignored and columnAliases contains table data - tableName = columnName.substring(0, sepNdx); - if (columnAliases != null) { - ColumnData columnData = columnAliases.get(tableName); - if (columnData != null) { - tableName = columnData.getTableName(); - } - } - columnName = columnName.substring(sepNdx + 1); - } else { - // column alias does not exist, table name is read from columnAliases and result set (if available) - if (columnAliases != null) { - ColumnData columnData = columnAliases.get(columnName); - if (columnData != null) { - tableName = columnData.getTableName(); - columnName = columnData.getColumnName(); - } - } - if (tableName == null) { - try { - tableName = rsMetaData.getTableName(i + 1); - } catch (SQLException sex) { - // ignore - } - if ((tableName != null) && (tableName.length() == 0)) { - tableName = null; - } - } - } - - columnName = columnName.trim(); - if (columnName.length() == 0) { - columnName = null; - } - - if (columnName != null) { - columnName = columnName.trim(); - columnName = columnName.toUpperCase(); - } - columnNames[i] = columnName; - - if (tableName != null) { - tableName = tableName.trim(); - tableName = tableName.toUpperCase(); - } - tableNames[i] = tableName; - columnDbSqlTypes[i] = rsMetaData.getColumnType(i + 1); - } - } catch (SQLException sex) { - throw new DbOomException(dbOomQuery, "Reading ResultSet meta-data failed", sex); - } - } - - // ---------------------------------------------------------------- delegates - - /** - * {@inheritDoc} - */ - @Override - public Class[] resolveTables() { - List classes = new ArrayList<>(tableNames.length); - String lastTableName = null; - resultColumns.clear(); - - for (int i = 0; i < tableNames.length; i++) { - String tableName = tableNames[i]; - String columnName = columnNames[i]; - - if (tableName == null) { - // maybe JDBC driver does not support it - throw new DbOomException(dbOomQuery, "Table name missing in meta-data"); - } - - if ((!tableName.equals(lastTableName)) || (resultColumns.contains(columnName))) { - resultColumns.clear(); - lastTableName = tableName; - - DbEntityDescriptor ded = dbEntityManager.lookupTableName(tableName); - if (ded == null) { - throw new DbOomException(dbOomQuery, "Table name not registered: " + tableName); - } - - classes.add(ded.getType()); - } - resultColumns.add(columnName); - } - return classes.toArray(new Class[0]); - } - - // ---------------------------------------------------------------- cache - - protected DbEntityDescriptor[] cachedDbEntityDescriptors; - protected Class[] cachedUsedTypes; - protected String[] cachedTypesTableNames; - protected String[][] cachedMappedNames; - - /** - * Resolves {@link jodd.db.oom.DbEntityDescriptor} for all given types, - * so not to repeat every time. - */ - protected DbEntityDescriptor[] resolveDbEntityDescriptors(final Class[] types) { - if (cachedDbEntityDescriptors == null) { - DbEntityDescriptor[] descs = new DbEntityDescriptor[types.length]; - for (int i = 0; i < types.length; i++) { - Class type = types[i]; - if (type != null) { - descs[i] = dbEntityManager.lookupType(type); - } - } - cachedDbEntityDescriptors = descs; - } - return cachedDbEntityDescriptors; - } - - /** - * Creates table names for all specified types. - * Since this is usually done once per result set, these names are cached. - * Type name will be null for simple names, i.e. for all those - * types that returns null when used by {@link DbEntityManager#lookupType(Class)}. - */ - protected String[] resolveTypesTableNames(final Class[] types) { - if (types != cachedUsedTypes) { - cachedTypesTableNames = createTypesTableNames(types); - cachedUsedTypes = types; - } - return cachedTypesTableNames; - } - - /** - * Resolved mapped type names for each type. - */ - protected String[][] resolveMappedTypesTableNames(final Class[] types) { - if (cachedMappedNames == null) { - String[][] names = new String[types.length][]; - for (int i = 0; i < types.length; i++) { - Class type = types[i]; - if (type != null) { - DbEntityDescriptor ded = cachedDbEntityDescriptors[i]; - if (ded != null) { - Class[] mappedTypes = ded.getMappedTypes(); - if (mappedTypes != null) { - names[i] = createTypesTableNames(mappedTypes); - } - } - } - } - cachedMappedNames = names; - } - return cachedMappedNames; - } - - /** - * Creates table names for given types. - */ - protected String[] createTypesTableNames(final Class[] types) { - String[] names = new String[types.length]; - for (int i = 0; i < types.length; i++) { - if (types[i] == null) { - names[i] = null; - continue; - } - DbEntityDescriptor ded = dbEntityManager.lookupType(types[i]); - if (ded != null) { - String tableName = ded.getTableName(); - tableName = tableName.toUpperCase(); - names[i] = tableName; - } - } - return names; - } - - protected int cachedColumnNdx; - protected Object cachedColumnValue; - - // ---------------------------------------------------------------- parse object - - /** - * Reads column value from result set. Since this method may be called more then once for - * the same column, it caches column values. - */ - @SuppressWarnings({"unchecked"}) - protected Object readColumnValue(final int colNdx, final Class destinationType, final Class sqlTypeClass, final int columnDbSqlType) { - if (colNdx != cachedColumnNdx) { - try { - SqlType sqlType; - if (sqlTypeClass != null) { - sqlType = SqlTypeManager.get().lookupSqlType(sqlTypeClass); - } else { - sqlType = SqlTypeManager.get().lookup(destinationType); - } - if (sqlType != null) { - cachedColumnValue = sqlType.readValue(resultSet, colNdx + 1, destinationType, columnDbSqlType); - } else { - cachedColumnValue = resultSet.getObject(colNdx + 1); - cachedColumnValue = TypeConverterManager.get().convertType(cachedColumnValue, destinationType); - } - } catch (SQLException sex) { - throw new DbOomException(dbOomQuery, "Invalid value for column #" + (colNdx + 1), sex); - } - cachedColumnNdx = colNdx; - } - return cachedColumnValue; - } - - /** - * {@inheritDoc} - */ - @Override - public Object[] parseObjects(final Class... types) { - resultColumns.clear(); - - int totalTypes = types.length; - Object[] result = new Object[totalTypes]; - boolean[] resultUsage = new boolean[totalTypes]; - DbEntityDescriptor[] dbEntityDescriptors = resolveDbEntityDescriptors(types); - String[] typesTableNames = resolveTypesTableNames(types); - String[][] mappedNames = resolveMappedTypesTableNames(types); - - int currentResult = 0; - cachedColumnNdx = -1; - int colNdx = 0; - while (colNdx < totalColumns) { - - // no more types for mapping? - if (currentResult >= totalTypes) { - break; - } - - // skip columns that doesn't map - Class currentType = types[currentResult]; - if (currentType == null) { - colNdx++; - currentResult++; - resultColumns.clear(); - continue; - } - - String columnName = columnNames[colNdx]; - int columnDbSqlType = columnDbSqlTypes[colNdx]; - String tableName = tableNames[colNdx]; - String resultTableName = typesTableNames[currentResult]; - - if (resultTableName == null) { - // match: simple type - result[currentResult] = readColumnValue(colNdx, currentType, null, columnDbSqlType); - resultUsage[currentResult] = true; - colNdx++; - currentResult++; resultColumns.clear(); - continue; - } - - // match table - boolean tableMatched = false; - - if (tableName == null) { - tableMatched = true; - } else if (resultTableName.equals(tableName)) { - tableMatched = true; - } else { - String[] mapped = mappedNames[currentResult]; - if (mapped != null) { - for (String m : mapped) { - if (m.equals(tableName)) { - tableMatched = true; - break; - } - } - } - } - - if (tableMatched) { - if (!resultColumns.contains(columnName)) { - //DbEntityDescriptor ded = dbEntityManager.lookupType(currentType); - DbEntityDescriptor ded = dbEntityDescriptors[currentResult]; - - DbEntityColumnDescriptor dec = ded.findByColumnName(columnName); - String propertyName = (dec == null ? null : dec.getPropertyName()); - - // check if a property that matches column name exist - if (propertyName != null) { - - // if current entity instance does not exist (i.e. we are at the first column - // of some entity), create the instance and store it - if (result[currentResult] == null) { - result[currentResult] = dbEntityManager.createEntityInstance(currentType); - } -/* - boolean success = value != null ? - BeanUtil.setDeclaredPropertySilent(result[currentResult], propertyName, value) : - BeanUtil.hasDeclaredProperty(result[currentResult], propertyName); -*/ - Class type = BeanUtil.declared.getPropertyType(result[currentResult], propertyName); - if (type != null) { - // match: entity - dec.updateDbSqlType(columnDbSqlType); // updates column db sql type information for the entity!!! - Class sqlTypeClass = dec.getSqlTypeClass(); - Object value = readColumnValue(colNdx, type, sqlTypeClass, columnDbSqlType); - - if (value != null) { - // inject column value into existing entity - BeanUtil.declared.setProperty(result[currentResult], propertyName, value); - resultUsage[currentResult] = true; - } - colNdx++; - resultColumns.add(columnName); - continue; - } - } - } - } - // go to next type, i.e. result - currentResult++; - resultColumns.clear(); - } - - resultColumns.clear(); - for (int i = 0; i < resultUsage.length; i++) { - if (!resultUsage[i]) { - result[i] = null; - } - } - - if (cacheEntities) { - cacheResultSetEntities(result); - } - - return result; - } - - - // ---------------------------------------------------------------- cache - - protected HashMap entitiesCache; - - /** - * Caches returned entities. Replaces new instances with existing ones. - */ - protected void cacheResultSetEntities(final Object[] result) { - if (entitiesCache == null) { - entitiesCache = new HashMap<>(); - } - - for (int i = 0; i < result.length; i++) { - Object object = result[i]; - - if (object == null) { - continue; - } - - DbEntityDescriptor ded = cachedDbEntityDescriptors[i]; - - if (ded == null) { // not a type, continue - continue; - } - - // calculate key - Object key; - if (ded.hasIdColumn()) { - //noinspection unchecked - key = ded.getKeyValue(object); - } else { - key = object; - } - - Object cachedObject = entitiesCache.get(key); - - if (cachedObject == null) { - // object is not in the cache, add it - entitiesCache.put(key, object); - } else { - // object is in the cache, replace it - result[i] = cachedObject; - } - } - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/mapper/ResultSetMapper.java b/jodd-db/src/main/java/jodd/db/oom/mapper/ResultSetMapper.java deleted file mode 100644 index a42868481..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/mapper/ResultSetMapper.java +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.mapper; - -import jodd.db.oom.DbEntityManager; - -import java.sql.ResultSet; - -/** - * ResultSet mapper which implementations parse objects from one result set row. - * There are two ways of mapping. The basic way is mapping against provided - * entity types. The second, extended, way is auto-mapping, where no types - * are provided. Instead, they are mapped by {@link DbEntityManager} or - * similar external class. - *

- * There should be only one instance of ResultSetMapper per ResultSet. - */ -public interface ResultSetMapper { - - // ---------------------------------------------------------------- moving - - /** - * Moves the cursor down one row from its current position. - */ - boolean next(); - - /** - * Releases this ResultSet object's database and JDBC resources immediately instead of - * waiting for this to happen when it is automatically closed. - */ - void close(); - - /** - * Return JDBC result set. - */ - ResultSet getResultSet(); - - - // ---------------------------------------------------------------- parse types - - /** - * Resolves table names into the list of entity types. - * Resolving is used when query is executed without specified types. - */ - Class[] resolveTables(); - - /** - * Parse objects from one result set row to specified types. - */ - Object[] parseObjects(Class... types); - - /** - * Parse single object from result set row to specified type. - * @see #parseObjects(Class[]) - */ - Object parseOneObject(Class... types); - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/mapper/package-info.java b/jodd-db/src/main/java/jodd/db/oom/mapper/package-info.java deleted file mode 100644 index 17325a729..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/mapper/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * ResultSet to objects mappers. - */ -package jodd.db.oom.mapper; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/meta/DbColumn.java b/jodd-db/src/main/java/jodd/db/oom/meta/DbColumn.java deleted file mode 100644 index 7254c2307..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/meta/DbColumn.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.meta; - -import jodd.db.type.SqlType; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Fields marker for mapped columns. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface DbColumn { - - /** - * Column name. - */ - String value() default ""; - - /** - * SqlType class. - */ - Class sqlType() default SqlType.class; - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/meta/DbId.java b/jodd-db/src/main/java/jodd/db/oom/meta/DbId.java deleted file mode 100644 index 85a498322..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/meta/DbId.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.meta; - -import jodd.db.type.SqlType; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Field marker for ID columns, not necessary to use, but might be helpful. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface DbId { - - /** - * ID column name. - */ - String value() default ""; - - /** - * SqlType class. - */ - Class sqlType() default SqlType.class; - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/meta/DbMapTo.java b/jodd-db/src/main/java/jodd/db/oom/meta/DbMapTo.java deleted file mode 100644 index 6b7fe39b3..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/meta/DbMapTo.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.meta; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Marker for 'composed' entities. They are mapped to more then one - * resulting table. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface DbMapTo { - - /** - * List of entities object is composed of. - */ - Class[] value(); - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/meta/DbTable.java b/jodd-db/src/main/java/jodd/db/oom/meta/DbTable.java deleted file mode 100644 index c14dbfa42..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/meta/DbTable.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.meta; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Class marker for entity mapped to a table or a view. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface DbTable { - - /** - * Table or view name. - */ - String value() default ""; - - /** - * Schema name. - */ - String schema() default ""; - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/meta/package-info.java b/jodd-db/src/main/java/jodd/db/oom/meta/package-info.java deleted file mode 100644 index 4be519b94..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/meta/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * DbOom annotations. - */ -package jodd.db.oom.meta; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/naming/BaseNamingStrategy.java b/jodd-db/src/main/java/jodd/db/oom/naming/BaseNamingStrategy.java deleted file mode 100644 index fa32a7eac..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/naming/BaseNamingStrategy.java +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.naming; - -/** - * Common stuff for both naming strategies. - */ -abstract class BaseNamingStrategy { - - // ---------------------------------------------------------------- common properties - - protected boolean splitCamelCase = true; - protected char separatorChar = '_'; - protected boolean changeCase = true; - protected boolean uppercase = true; - protected boolean strictAnnotationNames = true; - protected boolean alwaysQuoteNames = false; - protected char quoteChar = 0; - - public boolean isSplitCamelCase() { - return splitCamelCase; - } - - /** - * Specifies if camel case name has to be split. - * If set to false, then name is passed unchanged. - */ - public void setSplitCamelCase(final boolean splitCamelCase) { - this.splitCamelCase = splitCamelCase; - } - - public char getSeparatorChar() { - return separatorChar; - } - - /** - * Separator character, when camel case names - * are {@link #setSplitCamelCase(boolean) split}. - */ - public void setSeparatorChar(final char separatorChar) { - this.separatorChar = separatorChar; - } - - public boolean isChangeCase() { - return changeCase; - } - - /** - * Specifies if database names should be convert to - * uppercase or lowercase. - */ - public void setChangeCase(final boolean changeCase) { - this.changeCase = changeCase; - } - - public boolean isUppercase() { - return uppercase; - } - - /** - * Specifies if table name should be converted to uppercase. - * Table names includes prefix and suffix. Otherwise, table name - * will be converted to lowercase. - */ - public void setUppercase(final boolean uppercase) { - this.uppercase = uppercase; - } - - public boolean isLowercase() { - return !uppercase; - } - - /** - * Alternative property to {@link #setUppercase(boolean)}. - * Does just the opposite. - */ - public void setLowercase(final boolean lowercase) { - this.uppercase = !lowercase; - } - - public boolean isStrictAnnotationNames() { - return strictAnnotationNames; - } - - /** - * Defines if annotation names are strict, or if all the naming - * rules should apply on them, too. - */ - public void setStrictAnnotationNames(final boolean strictAnnotationNames) { - this.strictAnnotationNames = strictAnnotationNames; - } - - public boolean isAlwaysQuoteNames() { - return alwaysQuoteNames; - } - - /** - * Defines if all table and column names should be quoted. - */ - public void setAlwaysQuoteNames(final boolean alwaysQuoteNames) { - this.alwaysQuoteNames = alwaysQuoteNames; - } - - public char getQuoteChar() { - return quoteChar; - } - - /** - * Defines quote char. - */ - public void setQuoteChar(final char quoteChar) { - this.quoteChar = quoteChar; - } - - // ---------------------------------------------------------------- util methods - - protected static StringBuilder toUppercase(final StringBuilder string) { - final int strLen = string.length(); - - for (int i = 0; i < strLen; i++) { - char c = string.charAt(i); - - char uppercaseChar = Character.toUpperCase(c); - if (c != uppercaseChar) { - string.setCharAt(i, uppercaseChar); - } - } - return string; - } - - protected static StringBuilder toLowercase(final StringBuilder string) { - final int strLen = string.length(); - - for (int i = 0; i < strLen; i++) { - char c = string.charAt(i); - - char lowercaseChar = Character.toLowerCase(c); - if (c != lowercaseChar) { - string.setCharAt(i, lowercaseChar); - } - } - return string; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/naming/ColumnNamingStrategy.java b/jodd-db/src/main/java/jodd/db/oom/naming/ColumnNamingStrategy.java deleted file mode 100644 index 0f06f08bf..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/naming/ColumnNamingStrategy.java +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.naming; - -import jodd.util.StringUtil; - -/** - * Naming strategy for converting property names - * to database column names. - */ -public class ColumnNamingStrategy extends BaseNamingStrategy { - - // ---------------------------------------------------------------- methods - - /** - * Converts property name to column name. - */ - public String convertPropertyNameToColumnName(final String propertyName) { - final StringBuilder tableName = new StringBuilder(propertyName.length() * 2); - - if (splitCamelCase) { - final String convertedTableName = StringUtil.fromCamelCase(propertyName, separatorChar); - tableName.append(convertedTableName); - } else { - tableName.append(propertyName); - } - - if (!changeCase) { - return tableName.toString(); - } - return uppercase ? - toUppercase(tableName).toString() : - toLowercase(tableName).toString(); - - } - - /** - * Converts column name to property name. - */ - public String convertColumnNameToPropertyName(final String columnName) { - final StringBuilder propertyName = new StringBuilder(columnName.length()); - final int len = columnName.length(); - - if (splitCamelCase) { - boolean toUpper = false; - for (int i = 0; i < len; i++) { - final char c = columnName.charAt(i); - if (c == separatorChar) { - toUpper = true; - continue; - } - if (toUpper) { - propertyName.append(Character.toUpperCase(c)); - toUpper = false; - } else { - propertyName.append(Character.toLowerCase(c)); - } - } - return propertyName.toString(); - } - return columnName; - } - - /** - * Applies column naming strategy to given column name hint. - * Returns full column name. - */ - public String applyToColumnName(final String columnName) { - final String propertyName = convertColumnNameToPropertyName(columnName); - - return convertPropertyNameToColumnName(propertyName); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/naming/TableNamingStrategy.java b/jodd-db/src/main/java/jodd/db/oom/naming/TableNamingStrategy.java deleted file mode 100644 index 904ac37e9..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/naming/TableNamingStrategy.java +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.naming; - -import jodd.util.StringPool; -import jodd.util.StringUtil; - -/** - * Naming strategy for converting entity names - * (i.e. class names) to database table names. - */ -public class TableNamingStrategy extends BaseNamingStrategy { - - // ---------------------------------------------------------------- properties - - protected String prefix = StringPool.EMPTY; - protected String suffix = StringPool.EMPTY; - protected char entityNameTerminator = '$'; - - public String getPrefix() { - return prefix; - } - - /** - * Table prefix, may be null. - */ - public void setPrefix(final String prefix) { - this.prefix = prefix; - } - - public String getSuffix() { - return suffix; - } - - /** - * Table suffix, may be null. - */ - public void setSuffix(final String suffix) { - this.suffix = suffix; - } - - public char getEntityNameTerminator() { - return entityNameTerminator; - } - - /** - * Specifies the terminator character for entity names. - * When some type is proxified, new class name usually contains - * some special character, like '$'. - */ - public void setEntityNameTerminator(final char entityNameTerminator) { - this.entityNameTerminator = entityNameTerminator; - } - - // ---------------------------------------------------------------- methods - - /** - * Converts entity name to table name. - * @see #convertEntityNameToTableName(String) - */ - public String convertEntityNameToTableName(final Class type) { - return convertEntityNameToTableName(type.getSimpleName()); - } - - /** - * Converts entity (type) name to table name. - */ - public String convertEntityNameToTableName(String entityName) { - final int ndx = entityName.indexOf(entityNameTerminator); - if (ndx != -1) { - entityName = entityName.substring(0, ndx); - } - - final StringBuilder tableName = new StringBuilder(entityName.length() * 2); - - if (prefix != null) { - tableName.append(prefix); - } - - if (splitCamelCase) { - final String convertedTableName = StringUtil.fromCamelCase(entityName, separatorChar); - tableName.append(convertedTableName); - } else { - tableName.append(entityName); - } - - if (suffix != null) { - tableName.append(suffix); - } - - if (!changeCase) { - return tableName.toString(); - } - return uppercase ? - toUppercase(tableName).toString() : - toLowercase(tableName).toString(); - - } - - /** - * Converts table name to entity (type) name. - */ - public String convertTableNameToEntityName(final String tableName) { - final StringBuilder className = new StringBuilder(tableName.length()); - int len = tableName.length(); - - int i = 0; - if (prefix != null) { - if (tableName.startsWith(prefix)) { - i = prefix.length(); - } - } - if (suffix != null) { - if (tableName.endsWith(suffix)) { - len -= suffix.length(); - } - } - - if (splitCamelCase) { - boolean toUpper = true; - for (; i < len; i++) { - final char c = tableName.charAt(i); - if (c == separatorChar) { - toUpper = true; - continue; - } - if (toUpper) { - className.append(Character.toUpperCase(c)); - toUpper = false; - } else { - className.append(Character.toLowerCase(c)); - } - } - return className.toString(); - } - - return tableName.substring(i, len); - } - - /** - * Applies table naming strategy to given table name hint. - * Returns full table name. - */ - public String applyToTableName(final String tableName) { - final String entityName = convertTableNameToEntityName(tableName); - - return convertEntityNameToTableName(entityName); - } -} diff --git a/jodd-db/src/main/java/jodd/db/oom/naming/package-info.java b/jodd-db/src/main/java/jodd/db/oom/naming/package-info.java deleted file mode 100644 index bd33729d6..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/naming/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * DB OOM naming convention strategies. - */ -package jodd.db.oom.naming; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/package-info.java b/jodd-db/src/main/java/jodd/db/oom/package-info.java deleted file mode 100644 index 8b73c2d6d..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * DB OOM suite. - */ -package jodd.db.oom; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/DbEntitySql.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/DbEntitySql.java deleted file mode 100644 index 5f3db7b8c..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/DbEntitySql.java +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen; - -import jodd.bean.BeanUtil; -import jodd.db.DbOom; -import jodd.db.oom.DbEntityDescriptor; -import jodd.db.oom.DbEntityManager; -import jodd.db.oom.DbOomConfig; -import jodd.util.StringPool; - -import static jodd.db.oom.sqlgen.DbSqlBuilder.sql; -import static jodd.util.StringPool.EQUALS; -import static jodd.util.StringPool.SPACE; -import static jodd.util.StringUtil.capitalize; -import static jodd.util.StringUtil.uncapitalize; - -/** - * Useful {@link DbSqlBuilder} generators. - */ -public class DbEntitySql { - - private static final String DELETE_FROM = "delete from "; - private static final String WHERE = " where "; - private static final String UPDATE = "update "; - private static final String SELECT = "select "; - private static final String FROM = " from "; - private static final String SET = " set "; - private static final String SELECT_COUNT_1_FROM = "select count(*) from "; - - private final DbEntityManager entityManager; - private final DbOomConfig dbOomConfig; - - public DbEntitySql(final DbOom dbOom) { - this.entityManager = dbOom.entityManager(); - this.dbOomConfig = dbOom.config(); - } - - public DbEntitySql() { - this(DbOom.get()); - } - - // ---------------------------------------------------------------- insert - - /** - * Creates INSERT query for the entity. - */ - public DbSqlBuilder insert(final Object entity) { - return sql().insert(entity); - } - - // ---------------------------------------------------------------- truncate - - /** - * Creates DELETE query that truncates all table data. - */ - public DbSqlBuilder truncate(final Object entity) { - return sql().$(DELETE_FROM).table(entity, null); - } - - // ---------------------------------------------------------------- update - - /** - * Creates UPDATE query that updates all non-null values of an entity that is matched by id. - */ - public DbSqlBuilder update(final Object entity) { - String tableRef = createTableRefName(entity); - - if (!dbOomConfig.isUpdateAcceptsTableAlias()) { - tableRef = null; - } - - return sql().$(UPDATE).table(entity, tableRef).set(tableRef, entity).$(WHERE).matchIds(tableRef, entity); - } - - /** - * Creates UPDATE query that updates all values of an entity that is matched by id. - */ - public DbSqlBuilder updateAll(final Object entity) { - String tableRef = createTableRefName(entity); - - if (!dbOomConfig.isUpdateAcceptsTableAlias()) { - tableRef = null; - } - - return sql().$(UPDATE).table(entity, tableRef).setAll(tableRef, entity).$(WHERE).matchIds(tableRef, entity); - } - - /** - * Creates UPDATE query for single column of an entity that is matched by id. - */ - public DbSqlBuilder updateColumn(final Object entity, final String columnRef, final Object value) { - String tableRef = createTableRefName(entity); - - if (!dbOomConfig.isUpdateAcceptsTableAlias()) { - tableRef = null; - } - - return sql().$(UPDATE).table(entity, tableRef).$(SET).ref(null, columnRef).$(EQUALS).columnValue(value).$(WHERE).matchIds(tableRef, entity); - } - - /** - * Reads property value and updates the DB. - */ - public DbSqlBuilder updateColumn(final Object entity, final String columnRef) { - final Object value = BeanUtil.pojo.getProperty(entity, columnRef); - return updateColumn(entity, columnRef, value); - } - - // ---------------------------------------------------------------- delete - - /** - * Creates DELETE query that deletes entity matched by non-null values. - */ - public DbSqlBuilder delete(final Object entity) { - final String tableRef = createTableRefName(entity); - return sql().$(DELETE_FROM).table(entity, null, tableRef).$(WHERE).match(tableRef, entity); - } - - /** - * Creates DELETE query that deletes entity matched by all values. - */ - public DbSqlBuilder deleteByAll(final Object entity) { - final String tableRef = createTableRefName(entity); - return sql().$(DELETE_FROM).table(entity, null, tableRef).$(WHERE).matchAll(tableRef, entity); - } - - // ---------------------------------------------------------------- delete by id - - /** - * Creates DELETE query that deletes entity by ID. - */ - public DbSqlBuilder deleteById(final Object entity) { - final String tableRef = createTableRefName(entity); - return sql().$(DELETE_FROM).table(entity, null, tableRef).$(WHERE).matchIds(tableRef, entity); - } - - /** - * Creates DELETE query that deletes entity by ID. - */ - public DbSqlBuilder deleteById(final Object entityType, final Object id) { - final String tableRef = createTableRefName(entityType); - return sql(). - $(DELETE_FROM).table(entityType, null, tableRef). - $(WHERE).refId(tableRef).$(EQUALS).columnValue(id); - } - - // ---------------------------------------------------------------- from - - /** - * Creates 'SELECT all FROM entity' part of the SQL query that can be easily extended. - * Entity is referred with its simple class name. - */ - public DbSqlBuilder from(final Object entity) { - return from(entity, createTableRefName(entity)); - } - - public DbSqlBuilder from(final Object entity, final String tableRef) { - return sql().$(SELECT).column(tableRef).$(FROM).table(entity, tableRef).$(SPACE); - } - - public DbSqlBuilder from(final Class entityType) { - return from(entityType, createTableRefName(entityType)); - } - - public DbSqlBuilder from(final Class entityType, final String tableRef) { - return sql().$(SELECT).column(tableRef).$(FROM).table(entityType, tableRef).$(SPACE); - } - - // ---------------------------------------------------------------- find - - /** - * Creates SELECT criteria for the entity matched by non-null values. - */ - public DbSqlBuilder find(final Class target, final Object matchEntity) { - final String tableRef = createTableRefName(target); - return sql().$(SELECT).column(tableRef).$(FROM).table(target, tableRef).$(WHERE).match(tableRef, matchEntity); - } - - /** - * Creates SELECT criteria for the entity matched by non-null values. - */ - public DbSqlBuilder find(final Object entity) { - final String tableRef = createTableRefName(entity); - return sql().$(SELECT).column(tableRef).$(FROM).table(entity, tableRef).$(WHERE).match(tableRef, entity); - } - - /** - * Creates SELECT criteria for the entity matched by all values. - */ - public DbSqlBuilder findByAll(final Object entity) { - final String tableRef = createTableRefName(entity); - return sql().$(SELECT).column(tableRef).$(FROM).table(entity, tableRef).$(WHERE).matchAll(tableRef, entity); - } - - /** - * Creates SELECT criteria for the entity matched by column name - */ - public DbSqlBuilder findByColumn(final Class entity, final String column, final Object value) { - final String tableRef = createTableRefName(entity); - return sql().$(SELECT).column(tableRef).$(FROM).table(entity, tableRef).$(WHERE).ref(tableRef, column).$(EQUALS).columnValue(value); - } - - /** - * Creates SELECT criteria for the entity matched by foreign key. - * Foreign key is created by concatenating foreign table name and column name. - */ - public DbSqlBuilder findForeign(final Class entity, final Object value) { - final String tableRef = createTableRefName(entity); - - final DbEntityDescriptor dedFk = entityManager.lookupType(value.getClass()); - - final String tableName = dbOomConfig.getTableNames().convertTableNameToEntityName(dedFk.getTableName()); - final String columnName = dbOomConfig.getColumnNames().convertColumnNameToPropertyName(dedFk.getIdColumnName()); - - final String fkColumn = uncapitalize(tableName) + capitalize(columnName); - final Object idValue = BeanUtil.pojo.getProperty(value, dedFk.getIdPropertyName()); - return sql().$(SELECT).column(tableRef).$(FROM).table(entity, tableRef).$(WHERE).ref(tableRef, fkColumn).$(EQUALS).columnValue(idValue); - } - - // ---------------------------------------------------------------- ALL - - /** - * Returns all records for given type. - */ - public DbSqlBuilder findAll(final Object entity) { - final String tableRef = createTableRefName(entity); - return sql().$(SELECT).column(tableRef).$(FROM).table(entity, tableRef); - } - - - // ---------------------------------------------------------------- find by Id - - /** - * Creates SELECT criteria for the entity matched by id. - */ - public DbSqlBuilder findById(final Object entity) { - final String tableRef = createTableRefName(entity); - return sql().$(SELECT).column(tableRef).$(FROM).table(entity, tableRef).$(WHERE).matchIds(tableRef, entity); - } - - /** - * Creates SELECT criteria for the entity matched by id. - */ - public DbSqlBuilder findById(final Object entityType, final Object id) { - final String tableRef = createTableRefName(entityType); - return sql().$(SELECT).column(tableRef).$(FROM).table(entityType, tableRef) - .$(WHERE).refId(tableRef).$(EQUALS).columnValue(id); - } - - // ---------------------------------------------------------------- count - - /** - * Creates SELECT COUNT criteria for the entity matched by non-null values. - */ - public DbSqlBuilder count(final Object entity) { - final String tableRef = createTableRefName(entity); - return sql().$(SELECT_COUNT_1_FROM).table(entity, tableRef).$(WHERE).match(tableRef, entity); - } - - /** - * Creates SELECT COUNT all query. - */ - public DbSqlBuilder count(final Class entityType) { - final String tableRef = createTableRefName(entityType); - return sql().$(SELECT_COUNT_1_FROM).table(entityType, tableRef); - } - - - /** - * Creates SELECT COUNT criteria for the entity matched by all values. - */ - public DbSqlBuilder countAll(final Object entity) { - final String tableRef = createTableRefName(entity); - return sql().$(SELECT_COUNT_1_FROM).table(entity, tableRef).$(WHERE).matchAll(tableRef, entity); - } - - // ---------------------------------------------------------------- increase - - /** - * Creates UPDATE that increases/decreases column by some delta value. - */ - public DbSqlBuilder increaseColumn(final Class entity, final Object id, final String columnRef, final Number delta, final boolean increase) { - final String tableRef = createTableRefName(entity); - - return sql().$(UPDATE).table(entity, null, tableRef).$(SET) - .ref(null, columnRef).$(EQUALS).ref(null, columnRef) - .$(increase ? StringPool.PLUS : StringPool.DASH) - .columnValue(delta).$(WHERE).refId(tableRef).$(EQUALS).columnValue(id); - } - - - // ---------------------------------------------------------------- resolve tableRef - - /** - * Creates table reference name from entity type. - * Always appends an underscore to reference name in order - * to circumvent SQL compatibility issues when entity class name - * equals to a reserved word. - */ - protected static String createTableRefName(final Object entity) { - Class type = entity.getClass(); - type = (type == Class.class ? (Class) entity : type); - return (type.getSimpleName() + '_'); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/DbSqlBuilder.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/DbSqlBuilder.java deleted file mode 100644 index 35996d9fa..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/DbSqlBuilder.java +++ /dev/null @@ -1,429 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen; - -import jodd.db.DbOom; -import jodd.db.DbSession; -import jodd.db.oom.ColumnAliasType; -import jodd.db.oom.ColumnData; -import jodd.db.oom.DbOomQuery; -import jodd.db.oom.DbSqlGenerator; -import jodd.db.oom.sqlgen.chunks.ColumnValueChunk; -import jodd.db.oom.sqlgen.chunks.ColumnsSelectChunk; -import jodd.db.oom.sqlgen.chunks.InsertChunk; -import jodd.db.oom.sqlgen.chunks.MatchChunk; -import jodd.db.oom.sqlgen.chunks.RawSqlChunk; -import jodd.db.oom.sqlgen.chunks.ReferenceChunk; -import jodd.db.oom.sqlgen.chunks.SqlChunk; -import jodd.db.oom.sqlgen.chunks.TableChunk; -import jodd.db.oom.sqlgen.chunks.UpdateSetChunk; -import jodd.db.oom.sqlgen.chunks.ValueChunk; -import jodd.util.StringPool; - -import java.util.Map; - -/** - * Nice SQL query generator that provides some automatic query generation. - *

- * Query is built by appending 'chunks' - parts of the query. These chunks may be - * very simple, as a simple string. However, the main reason of existence of this class are - * chunks that auto-generate part of the query based on provided domain object. They can be - * used to easily create some most common queries in an efficient way. - *

- * Although it is not necessary, use of {@link jodd.db.oom.meta.DbId} annotation boost the functionality - * of this query builder. - *

- * Some chunks deals with relations between tables, so they must be aware of foreign key names. Here the - * naming convention is used, and even users might have their own foreign key naming convention. - *

- * Furthermore, if all queries are generated using just sql builder, it is possible to use dialects for various - * database types. - */ -public class DbSqlBuilder extends TemplateData implements DbSqlGenerator { - - private final DbOom dbOom; - - /** - * Creates new SQL builder. - */ - public DbSqlBuilder() { - this(DbOom.get()); - } - - public DbSqlBuilder(final String template) { - this(DbOom.get(), template); - } - - public DbSqlBuilder(final DbOom dbOom) { - super(dbOom); - this.dbOom = dbOom; - } - - public DbSqlBuilder(final DbOom dbOom, final String template) { - super(dbOom); - this.dbOom = dbOom; - append(template); - } - - /** - * Template static constructor. - */ - public static DbSqlBuilder sql() { - return new DbSqlBuilder(); - } - - /** - * Template static constructor. - */ - public static DbSqlBuilder sql(final String template) { - return new DbSqlBuilder().append(template); - } - - /** - * Resets the builder (soft reset), so it can be used again. - * Configuration is preserved. - * @see TemplateData#resetSoft() - */ - public DbSqlBuilder reset() { - resetSoft(); - return this; - } - - /** - * Hard reset of the builder, all configuration is reset. - * @see TemplateData#resetHard() - */ - public DbSqlBuilder resetAll() { - resetHard(); - return this; - } - - /** - * Builds the query and returns parsed data. - * Returned value can be cached or stored as a constant value - * to prevent further parsing of the same code. - */ - public ParsedSql parse() { - return new ParsedSql(this); - } - - - // ---------------------------------------------------------------- settings - - /** - * Specifies column alias type. May be null when column aliases are not used. - */ - public DbSqlBuilder aliasColumnsAs(final ColumnAliasType aliasesType) { - this.columnAliasType = aliasesType; - return this; - } - - /** - * Defines object reference and an object. - */ - public DbSqlBuilder use(final String name, final Object value) { - setObjectReference(name, value); - return this; - } - - - // ---------------------------------------------------------------- chunks - - protected SqlChunk firstChunk; - protected SqlChunk lastChunk; - protected int totalChunks; - protected static final TemplateParser templateParser = new TemplateParser(); - - /** - * Appends chunk to the list. Chunks must be added using this method. - */ - public DbSqlBuilder addChunk(final SqlChunk chunk) { - if (lastChunk == null) { - lastChunk = firstChunk = chunk; - } else { - chunk.insertChunkAfter(lastChunk); - lastChunk = chunk; - } - totalChunks++; - return this; - } - - // ---------------------------------------------------------------- template - - /** - * Parses provided text into the list of chunks and appends them to the list. - */ - public DbSqlBuilder append(final String text) { - templateParser.parse(this, text); - return this; - } - - /** - * Simply adds text without parsing to the query. - */ - public DbSqlBuilder appendRaw(final String text) { - addChunk(new RawSqlChunk(entityManager, text)); - return this; - } - - /** - * User-friendly {@link #append(String)}. - */ - public DbSqlBuilder $(final String text) { - return append(text); - } - - /** - * Single space shortcut. - */ - public DbSqlBuilder $() { - return appendRaw(StringPool.SPACE); - } - - public DbSqlBuilder $(final SqlChunk chunk) { - return addChunk(chunk); - } - - // ---------------------------------------------------------------- interface - - protected String generatedQuery; - - /** - * {@inheritDoc} - */ - @Override - public String generateQuery() { - reset(); - - // initialization - SqlChunk chunk = firstChunk; - while (chunk != null) { - chunk.init(this); - chunk = chunk.getNextChunk(); - } - - // process - StringBuilder query = new StringBuilder(); - chunk = firstChunk; - try { - while (chunk != null) { - chunk.process(query); - chunk = chunk.getNextChunk(); - } - } catch (DbSqlBuilderException dsbex) { - dsbex.setQueryString(query.toString()); - throw dsbex; - } - - generatedQuery = query.toString(); - - return generatedQuery; - } - - /** - * {@inheritDoc} - */ - @Override - public Map getColumnData() { - return columnData; - } - - @Override - public Map getQueryParameters() { - return parameters; - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getJoinHints() { - if (hints == null) { - return null; - } - return hints.toArray(new String[0]); - } - - // ---------------------------------------------------------------- table - - public DbSqlBuilder table(final String entityName) { - return addChunk(new TableChunk(entityManager, entityName)); - } - - public DbSqlBuilder table(final String entityName, final String alias) { - return addChunk(new TableChunk(entityManager, entityName, alias)); - } - - public DbSqlBuilder table(final Object entity, final String alias) { - return addChunk(new TableChunk(entityManager, entity, alias)); - } - - public DbSqlBuilder table(final Object entity, final String alias, final String tableReference) { - return addChunk(new TableChunk(entityManager, entity, alias, tableReference)); - } - - public DbSqlBuilder table(final Object entity) { - return addChunk(new TableChunk(entityManager, entity)); - } - - // ---------------------------------------------------------------- columns - - public DbSqlBuilder column(final String reference) { - return addChunk(new ColumnsSelectChunk(entityManager, dbOom.config().getColumnAliasSeparator(), reference)); - } - - public DbSqlBuilder column(final String tableRef, final String columnRef) { - return addChunk(new ColumnsSelectChunk(entityManager, dbOom.config().getColumnAliasSeparator(), tableRef, columnRef)); - } - - public DbSqlBuilder columnsAll(final String tableRef) { - return addChunk(new ColumnsSelectChunk(entityManager, dbOom.config().getColumnAliasSeparator(), tableRef, true)); - } - - public DbSqlBuilder columnsIds(final String tableRef) { - return addChunk(new ColumnsSelectChunk(entityManager, dbOom.config().getColumnAliasSeparator(), tableRef, false)); - } - - - // ---------------------------------------------------------------- reference - - public DbSqlBuilder ref(final String columnRef) { - return addChunk(new ReferenceChunk(entityManager, columnRef)); - } - - public DbSqlBuilder ref(final String tableRef, final String columnRef) { - return addChunk(new ReferenceChunk(entityManager, tableRef, columnRef, false)); - } - - public DbSqlBuilder refId(final String tableRef) { - return addChunk(new ReferenceChunk(entityManager, tableRef, null, true)); - } - - - // ---------------------------------------------------------------- match - - /** - * Creates condition part of the query only for existing columns. - */ - public DbSqlBuilder match(final String tableRef, final Object value) { - return addChunk(new MatchChunk(entityManager, tableRef, value, SqlChunk.COLS_ONLY_EXISTING)); - } - - public DbSqlBuilder match(final String tableRef, final String objectRef) { - return addChunk(new MatchChunk(entityManager, tableRef, objectRef, SqlChunk.COLS_ONLY_EXISTING)); - } - - /** - * Creates condition part of the query for id columns - */ - public DbSqlBuilder matchIds(final String tableRef, final Object value) { - return addChunk(new MatchChunk(entityManager, tableRef, value, SqlChunk.COLS_ONLY_IDS)); - } - - public DbSqlBuilder matchIds(final String tableRef, final String objectRef) { - return addChunk(new MatchChunk(entityManager, tableRef, objectRef, SqlChunk.COLS_ONLY_IDS)); - } - - /** - * Creates condition part of the query for all columns, including the null values. - */ - public DbSqlBuilder matchAll(final String tableRef, final Object value) { - return addChunk(new MatchChunk(entityManager, tableRef, value, SqlChunk.COLS_ALL)); - } - - public DbSqlBuilder matchAll(final String tableRef, final String objectRef) { - return addChunk(new MatchChunk(entityManager, tableRef, objectRef, SqlChunk.COLS_ALL)); - } - - public DbSqlBuilder match(final String expression) { - return addChunk(new MatchChunk(entityManager, expression)); - } - - - // ---------------------------------------------------------------- values - - public DbSqlBuilder value(final String name, final Object value) { - return addChunk(new ValueChunk(entityManager, name, value)); - } - - public DbSqlBuilder value(final Object value) { - return addChunk(new ValueChunk(entityManager, null, value)); - } - - public DbSqlBuilder valueRef(final String objectReference) { - return addChunk(new ValueChunk(entityManager, objectReference)); - } - - public DbSqlBuilder columnValue(final String name, final Object value) { - return addChunk(new ColumnValueChunk(entityManager, name, value)); - } - - public DbSqlBuilder columnValue(final Object value) { - return addChunk(new ColumnValueChunk(entityManager, null, value)); - } - - public DbSqlBuilder columnValueRef(final String objectReference) { - return addChunk(new ColumnValueChunk(entityManager, objectReference)); - } - - // ---------------------------------------------------------------- insert - - public DbSqlBuilder insert(final String entityName, final Object values) { - return addChunk(new InsertChunk(entityManager, dbOom.config().isUpdateablePrimaryKey(), entityName, values)); - } - - public DbSqlBuilder insert(final Class entity, final Object values) { - return addChunk(new InsertChunk(entityManager, dbOom.config().isUpdateablePrimaryKey(), entity, values)); - } - - public DbSqlBuilder insert(final Object values) { - return addChunk(new InsertChunk(entityManager, dbOom.config().isUpdateablePrimaryKey(), values.getClass(), values)); - } - - // ---------------------------------------------------------------- update set - - public DbSqlBuilder set(final String tableRef, final Object values) { - return addChunk(new UpdateSetChunk(dbOom, tableRef, values, SqlChunk.COLS_ONLY_EXISTING)); - } - - public DbSqlBuilder setAll(final String tableRef, final Object values) { - return addChunk(new UpdateSetChunk(dbOom, tableRef, values, SqlChunk.COLS_ALL)); - } - - // ---------------------------------------------------------------- query factories - - /** - * Returns {@link jodd.db.oom.DbOomQuery} instance for more fluent interface. - */ - public DbOomQuery query() { - return new DbOomQuery(dbOom, this); - } - - public DbOomQuery query(final DbSession session) { - return new DbOomQuery(dbOom, session, this); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/DbSqlBuilderException.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/DbSqlBuilderException.java deleted file mode 100644 index 6bb131c85..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/DbSqlBuilderException.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen; - -import jodd.db.oom.DbOomException; - -public class DbSqlBuilderException extends DbOomException { - - public DbSqlBuilderException(final String message) { - super(message); - } - - protected String queryString; - - public void setQueryString(final String queryString) { - this.queryString = queryString; - } - - @Override - public String getMessage() { - String message = super.getMessage(); - if (queryString != null) { - message += " Generated query: " + queryString; - } - return message; - } -} diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/ParameterValue.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/ParameterValue.java deleted file mode 100644 index f26075451..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/ParameterValue.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen; - -import jodd.db.oom.DbEntityColumnDescriptor; - -/** - * {@link TemplateData Template parameter} value. - */ -public class ParameterValue { - protected final Object value; - protected final DbEntityColumnDescriptor dec; - - public ParameterValue(final Object value, final DbEntityColumnDescriptor dec) { - this.value = value; - this.dec = dec; - } - - public Object getValue() { - return value; - } - - public DbEntityColumnDescriptor getColumnDescriptor() { - return dec; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/ParsedSql.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/ParsedSql.java deleted file mode 100644 index 498b4445e..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/ParsedSql.java +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen; - -import jodd.db.oom.ColumnData; -import jodd.db.oom.DbSqlGenerator; - -import java.util.Map; - -/** - * Simple holder of parsed SQL data. It occupies less memory and may be cached. - * @see DbSqlBuilder#parse() - */ -public class ParsedSql implements DbSqlGenerator { - - protected final String generatedQuery; - protected final Map queryParameters; - protected final Map columnData; - protected final String[] joinHints; - - public ParsedSql(final DbSqlGenerator dbSqlGenerator) { - generatedQuery = dbSqlGenerator.generateQuery(); - queryParameters = dbSqlGenerator.getQueryParameters(); - columnData = dbSqlGenerator.getColumnData(); - joinHints = dbSqlGenerator.getJoinHints(); - } - - @Override - public String generateQuery() { - return generatedQuery; - } - - @Override - public Map getQueryParameters() { - return queryParameters; - } - - @Override - public Map getColumnData() { - return columnData; - } - - @Override - public String[] getJoinHints() { - return joinHints; - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/TemplateData.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/TemplateData.java deleted file mode 100644 index b85e34ba5..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/TemplateData.java +++ /dev/null @@ -1,338 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen; - -import jodd.db.DbOom; -import jodd.db.oom.ColumnAliasType; -import jodd.db.oom.ColumnData; -import jodd.db.oom.DbEntityColumnDescriptor; -import jodd.db.oom.DbEntityDescriptor; -import jodd.db.oom.DbEntityManager; -import jodd.db.oom.NamedValuesHashMap; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Template common data used during template parsing. - * Extracted to super class for better visibility. - */ -public abstract class TemplateData { - - private static final String COL_CODE_PREFIX = "col_"; - protected final DbEntityManager entityManager; - protected final ColumnAliasType defaultColumnAliasType; - - protected TemplateData(final DbOom dbOom) { - this.entityManager = dbOom.entityManager(); - this.columnAliasType = defaultColumnAliasType = dbOom.config().getDefaultColumnAliasType(); - } - - /** - * Resets the builder so it can be used again. Not everything is reset: - * object references and column alias type is not. - */ - protected void resetSoft() { - columnCount = 0; - paramCount = 0; - hintCount = 0; - - if (tableRefs != null) { - tableRefs.clear(); - } -// objectRefs = null; - if (columnData != null) { - columnData.clear(); - } - if (parameters != null) { - parameters.clear(); - } - if (hints != null) { - hints.clear(); - } - //columnAliasType = defaultColumnAliasType; - } - - protected void resetHard() { - resetSoft(); - objectRefs = null; - columnAliasType = defaultColumnAliasType; - } - - - // ---------------------------------------------------------------- object refs - - protected Map objectRefs; // used object references - - /** - * Saves object reference. - */ - public void setObjectReference(final String name, final Object object) { - if (objectRefs == null) { - objectRefs = new HashMap<>(); - } - objectRefs.put(name, object); - } - - /** - * Returns object reference. - */ - public Object getObjectReference(final String name) { - if (objectRefs == null) { - return null; - } - return objectRefs.get(name); - } - - /** - * Lookups for object reference and throws an exception if reference doesn't exist. - */ - public Object lookupObject(final String ref) { - Object value = getObjectReference(ref); - if (value == null) { - throw new DbSqlBuilderException("Invalid object reference: " + ref); - } - return value; - } - - // ---------------------------------------------------------------- tables - - private static final class TableRefData { - final String alias; - final DbEntityDescriptor desc; - - private TableRefData(final DbEntityDescriptor desc, final String alias) { - this.alias = alias; - this.desc = desc; - } - } - - protected Map tableRefs; - - /** - * Returns entity descriptor for provided table reference. - */ - public DbEntityDescriptor getTableDescriptor(final String tableRef) { - if (tableRefs == null) { - return null; - } - TableRefData t = tableRefs.get(tableRef); - return t == null ? null : t.desc; - } - - /** - * Finds entity descriptor of a table that contains provided column reference. - */ - public DbEntityDescriptor findTableDescriptorByColumnRef(final String columnRef) { - for (Map.Entry entry : tableRefs.entrySet()) { - DbEntityDescriptor ded = entry.getValue().desc; - - if (ded.findByPropertyName(columnRef) != null) { - return ded; - } - } - return null; - } - - /** - * Returns table alias for provided table reference. - */ - public String getTableAlias(final String tableRef) { - if (tableRefs == null) { - return null; - } - TableRefData t = tableRefs.get(tableRef); - return t == null ? null : t.alias; - } - - /** - * Registers table reference for provided entity. - */ - public void registerTableReference(final String tableReference, final DbEntityDescriptor ded, final String tableAlias) { - if (tableRefs == null) { - tableRefs = new HashMap<>(); - } - TableRefData t = new TableRefData(ded, tableAlias); - if (tableRefs.put(tableReference, t) != null) { - throw new DbSqlBuilderException("Duplicated table reference: " + tableReference); - } - } - - // ---------------------------------------------------------------- column data - - /** - * Column or table aliases. - */ - protected Map columnData; - - /** - * Column counter for COLUMN_CODE column alias type. - */ - protected int columnCount; - - - /** - * Specifies column alias type. May be null when column aliases are not used. - */ - protected ColumnAliasType columnAliasType; - - /** - * Returns column alias type. - */ - public ColumnAliasType getColumnAliasType() { - return columnAliasType; - } - - - public void registerColumnDataForTableRef(final String tableRef, final String tableName) { - if (columnData == null) { - columnData = new NamedValuesHashMap<>(); - } - columnData.put(tableRef, new ColumnData(tableName)); - } - - public String registerColumnDataForColumnCode(final String tableName, final String column) { - if (columnData == null) { - columnData = new NamedValuesHashMap<>(); - } - String columnCode = COL_CODE_PREFIX + Integer.toString(columnCount++) + '_'; - columnData.put(columnCode, new ColumnData(tableName, column)); - return columnCode; - } - - - // ---------------------------------------------------------------- parameters - - protected Map parameters; - - protected int paramCount; - - /** - * Returns the next auto-generated parameter name. - */ - public String getNextParameterName() { - return "p" + (paramCount++); - } - - /** - * Adds query parameter. - */ - public void addParameter(final String name, final Object value, final DbEntityColumnDescriptor dec) { - if (parameters == null) { - parameters = new HashMap<>(); - } - parameters.put(name, new ParameterValue(value, dec)); - } - - - // ---------------------------------------------------------------- lookup - - - /** - * Lookups for entity name and throws exception if entity name not found. - */ - protected DbEntityDescriptor lookupName(final String entityName) { - DbEntityDescriptor ded = entityManager.lookupName(entityName); - if (ded == null) { - throw new DbSqlBuilderException("Entity name not registered: " + entityName); - } - return ded; - } - - /** - * Lookups for entity name and throws an exception if entity type is invalid. - */ - protected DbEntityDescriptor lookupType(final Class entity) { - DbEntityDescriptor ded = entityManager.lookupType(entity); - if (ded == null) { - throw new DbSqlBuilderException("Invalid or not-persistent entity type: " + entity.getName()); - } - return ded; - } - - /** - * Lookups for table reference and throws an exception if table reference not found. - */ - protected DbEntityDescriptor lookupTableRef(final String tableRef) { - DbEntityDescriptor ded = getTableDescriptor(tableRef); - if (ded == null) { - throw new DbSqlBuilderException("Table reference not used in this query: " + tableRef); - } - return ded; - } - - // ---------------------------------------------------------------- misc - - /** - * Defines parameter with name and its value. - */ - protected void defineParameter(final StringBuilder query, String name, final Object value) { - if (name == null) { - name = getNextParameterName(); - } - query.append(':').append(name); - addParameter(name, value, null); - } - - - // ---------------------------------------------------------------- hints - - protected int hintCount; - - protected List hints; - - /** - * Registers a hint. - */ - public void registerHint(final String hint) { - if (hints == null) { - hints = new ArrayList<>(hintCount); - } - hints.add(hint); - } - - /** - * Increments hints count. - */ - public void incrementHintsCount() { - hintCount++; - } - - /** - * Returns true if there are hints. - */ - public boolean hasHints() { - return hintCount > 0; - } - - - // ---------------------------------------------------------------- last column - - public DbEntityColumnDescriptor lastColumnDec; - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/TemplateParser.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/TemplateParser.java deleted file mode 100644 index 4303bac94..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/TemplateParser.java +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen; - -import jodd.util.StringPool; -import jodd.util.StringUtil; - -import static jodd.util.CharUtil.isAlpha; -import static jodd.util.CharUtil.isDigit; - -/** - * Internal template parser. - */ -class TemplateParser { - - // ---------------------------------------------------------------- parsing - - protected static final char ESCAPE_CHARACTER = '\\'; - protected static final String MACRO_TABLE = "$T{"; - protected static final String MACRO_COLUMN = "$C{"; - protected static final String MACRO_MATCH = "$M{"; - protected static final String MACRO_VALUE = "$V{"; - - /** - * Parses template and returns generated sql builder. - */ - public void parse(final DbSqlBuilder sqlBuilder, final String template) { - int length = template.length(); - int last = 0; - while (true) { - int mark = template.indexOf('$', last); - if (mark == -1) { - if (last < length) { - sqlBuilder.appendRaw(template.substring(last)); - } - break; - } - - int escapesCount = countEscapes(template, mark); // check if escaped - if (escapesCount > 0) { - boolean isEscaped = escapesCount % 2 != 0; - int escapesToAdd = escapesCount >> 1; - sqlBuilder.appendRaw(template.substring(last, mark - escapesCount + escapesToAdd) + '$'); - if (isEscaped) { - last = mark + 1; - continue; - } - } else { - sqlBuilder.appendRaw(template.substring(last, mark)); - } - - int end; - - if (template.startsWith(MACRO_TABLE, mark)) { - mark += MACRO_TABLE.length(); - end = findMacroEnd(template, mark); - onTable(sqlBuilder, template.substring(mark, end)); - } else if (template.startsWith(MACRO_COLUMN, mark)) { - mark += MACRO_COLUMN.length(); - end = findMacroEnd(template, mark); - onColumn(sqlBuilder, template.substring(mark, end)); - } else if (template.startsWith(MACRO_MATCH, mark)) { - mark += MACRO_MATCH.length(); - end = findMacroEnd(template, mark); - onMatch(sqlBuilder, template.substring(mark, end)); - } else if (template.startsWith(MACRO_VALUE, mark)) { - mark += MACRO_VALUE.length(); - end = findMacroEnd(template, mark); - onValue(sqlBuilder, template.substring(mark, end)); - } else { - mark++; // reference found - end = mark; // find macro end - while (end < length) { - if (!isReferenceChar(template, end)) { - break; - } - end++; - } - onReference(sqlBuilder, template.substring(mark, end)); - end--; - } - end++; - last = end; - } - } - - protected static boolean isReferenceChar(final String template, final int index) { - char c = template.charAt(index); - if ((c == '+') && (template.charAt(index - 1) == '.')) { - return true; - } - return isDigit(c) || isAlpha(c) || (c == '_') || (c == '.'); - } - - - - /** - * Finds macros end. - */ - protected int findMacroEnd(final String template, final int fromIndex) { - int endIndex = template.indexOf('}', fromIndex); - if (endIndex == -1) { - throw new DbSqlBuilderException("Template syntax error, some macros are not closed. Error at: '..." + template.substring(fromIndex)); - } - return endIndex; - } - - /** - * Count escapes to the left. - */ - protected int countEscapes(final String template, int macroIndex) { - macroIndex--; - int escapeCount = 0; - while (macroIndex >= 0) { - if (template.charAt(macroIndex) != ESCAPE_CHARACTER) { - break; - } - escapeCount++; - macroIndex--; - } - return escapeCount; - } - - // ---------------------------------------------------------------- handlers - - protected void onTable(final DbSqlBuilder sqlBuilder, final String allTables) { - String[] tables = StringUtil.split(allTables, StringPool.COMMA); - for (String table : tables) { - sqlBuilder.table(table); - } - } - - protected void onColumn(final DbSqlBuilder sqlBuilder, final String allColumns) { - int len = allColumns.length(); - int lastNdx = 0; - - for (int i = 0; i < len; i++) { - char c = allColumns.charAt(i); - - if (c == ',') { - sqlBuilder.column(allColumns.substring(lastNdx, i)); - lastNdx = i + 1; - continue; - } - - if (c == '[') { - i = allColumns.indexOf(']', i) + 1; - if (i == 0) { - i = len; - } - } - } - - sqlBuilder.column(allColumns.substring(lastNdx)); - } - - protected void onReference(final DbSqlBuilder sqlBuilder, final String reference) { - sqlBuilder.ref(reference); - } - - protected void onMatch(final DbSqlBuilder sqlBuilder, final String expression) { - sqlBuilder.match(expression); - } - - protected void onValue(final DbSqlBuilder sqlBuilder, final String expression) { - sqlBuilder.columnValue(expression); - } - - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/ColumnValueChunk.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/ColumnValueChunk.java deleted file mode 100644 index 9805d33a1..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/ColumnValueChunk.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen.chunks; - -import jodd.db.oom.DbEntityColumnDescriptor; -import jodd.db.oom.DbEntityManager; - -/** - * {@link ValueChunk Value} for the last column. - */ -public class ColumnValueChunk extends ValueChunk { - - public ColumnValueChunk(final DbEntityManager dbEntityManager, final String name, final Object value) { - this(dbEntityManager, name, value, null); - } - - public ColumnValueChunk(final DbEntityManager dbEntityManager, final String objReference) { - this(dbEntityManager, null, null, objReference); - } - - private ColumnValueChunk(final DbEntityManager dbEntityManager, final String name, final Object value, final String objReference) { - super(dbEntityManager, name, value, objReference); - } - - // ---------------------------------------------------------------- define - @Override - protected void defineParameter(final StringBuilder query, final String name, final Object value, DbEntityColumnDescriptor dec) { - if (dec == null) { - dec = templateData.lastColumnDec; - } - super.defineParameter(query, name, value, dec); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/ColumnsSelectChunk.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/ColumnsSelectChunk.java deleted file mode 100644 index e7ecc427a..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/ColumnsSelectChunk.java +++ /dev/null @@ -1,312 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen.chunks; - -import jodd.db.oom.ColumnAliasType; -import jodd.db.oom.DbEntityColumnDescriptor; -import jodd.db.oom.DbEntityDescriptor; -import jodd.db.oom.DbEntityManager; -import jodd.db.oom.sqlgen.DbSqlBuilderException; -import jodd.db.oom.sqlgen.TemplateData; -import jodd.util.ArraysUtil; -import jodd.util.StringPool; -import jodd.util.StringUtil; - -/** - * Columns select chunk resolves entity column(s) from column references. Should be used for SELECT queries. - *

- * Column reference is specified as: {@link TableChunk tableReference}.propertyName where property name is - * a property of the entity references by table reference. Result is rendered as: - * tableName.column or alias.column (if table has an alias). - *

- * There are some special values for propertyName - *

    - *
  • wildcard (*), all table columns will be listed
  • - *
  • id sign (+), all table id columns will be listed
  • - *
- *

- * If previous chunk is also a column chunk, comma separator will be added in between. - *

- * Note that column alias are appended to the column name (using 'as' construct). - *

- * Macro rules: - *

    - *
  • $C{tableRef} is rendered as FOO.col1, FOO.col2,...
  • - *
  • $C{tableRef.*} is equal to above, renders all entity columns
  • - *
  • $C{tableRef.+} renders to only identity columns
  • - *
  • $C{tableRef.%} renders all but identity columns
  • - *
  • $C{tableRef.colRef} is rendered as FOO.column
  • - *
  • $C{tableRef.[colRef1,colRef2|...]} is rendered as FOO.column1, FOO.column2,..., support id sign (+)
  • - *
  • $C{entityRef.colRef} renders to FOO$column
  • - *
  • $C{hint.entityRef...} defines a hint
  • - *
  • $C{hint:entityRef...} defines a hint with custom name
  • - *
  • $C{.columName} renders as column name
  • - *
  • $C{hint:.columName} renders as column name and defines its hint
  • - *
- */ -public class ColumnsSelectChunk extends SqlChunk { - - private static final String AS = " as "; - private static final char SPLIT = ','; - - protected final String tableRef; - protected final String columnRef; - protected final String[] columnRefArr; - protected final int includeColumns; - protected final String hint; - protected final String columnAliasSeparator; - - private ColumnsSelectChunk( - final DbEntityManager dbEntityManager, - final String columnAliasSeparator, - final String tableRef, - final String columnRef, - final String[] columnRefArr, - final int includeColumns, - final String hint) { - super(dbEntityManager, CHUNK_SELECT_COLUMNS); - this.columnAliasSeparator = columnAliasSeparator; - this.tableRef = tableRef; - this.columnRef = columnRef; - this.columnRefArr = columnRefArr; - this.includeColumns = includeColumns; - this.hint = hint; - } - - public ColumnsSelectChunk(final DbEntityManager dbEntityManager, final String columnAliasSeparator, final String tableRef, final String columnRef) { - this(dbEntityManager, columnAliasSeparator, tableRef, columnRef, null, COLS_NA, null); - } - - public ColumnsSelectChunk(final DbEntityManager dbEntityManager, final String columnAliasSeparator, final String tableRef, final String... columnRefArr) { - this(dbEntityManager, columnAliasSeparator, tableRef, null, columnRefArr, COLS_NA_MULTI, null); - } - - public ColumnsSelectChunk(final DbEntityManager dbEntityManager, final String columnAliasSeparator, final String tableRef, final boolean includeAll) { - this(dbEntityManager, columnAliasSeparator, tableRef, null, null, includeAll ? COLS_ALL : COLS_ONLY_IDS, null); - } - - public ColumnsSelectChunk(final DbEntityManager dbEntityManager, final String columnAliasSeparator, String reference) { - super(dbEntityManager, CHUNK_SELECT_COLUMNS); - reference = reference.trim(); - int dotNdx = reference.lastIndexOf('.'); - if (dotNdx == -1) { - this.tableRef = reference; - this.columnRef = null; - this.columnRefArr = null; - this.includeColumns = COLS_ALL; - this.hint = null; - } else { - - final String tref = reference.substring(0, dotNdx); - reference = reference.substring(dotNdx + 1); - - // table - dotNdx = tref.lastIndexOf('.'); - if (dotNdx == -1) { - this.tableRef = tref; - this.hint = null; - } else { - final int doubleColumnNdx = tref.indexOf(':'); - if (doubleColumnNdx == -1) { - // no special hint - this.tableRef = tref.substring(dotNdx + 1); - this.hint = tref; - } else { - // hint is different - this.tableRef = tref.substring(doubleColumnNdx + 1); - this.hint = tref.substring(0, doubleColumnNdx); - } - } - - // column - if (reference.equals(StringPool.STAR)) { - this.columnRef = null; - this.columnRefArr = null; - this.includeColumns = COLS_ALL; - } else if (reference.equals(StringPool.PLUS)) { - this.columnRef = null; - this.columnRefArr = null; - this.includeColumns = COLS_ONLY_IDS; - } else if (reference.equals(StringPool.PERCENT)) { - this.columnRef = null; - this.columnRefArr = null; - this.includeColumns = COLS_ALL_BUT_ID; - } else if ( - reference.length() != 0 - && reference.charAt(0) == '[' - && reference.charAt(reference.length() - 1) == ']') { - - this.columnRef = null; - this.columnRefArr = StringUtil.splitc(reference.substring(1, reference.length() - 1), SPLIT); - StringUtil.trimAll(this.columnRefArr); - this.includeColumns = COLS_NA_MULTI; - } else { - this.columnRef = reference; - this.columnRefArr = null; - this.includeColumns = COLS_NA; - } - } - this.columnAliasSeparator = columnAliasSeparator; - } - - // ---------------------------------------------------------------- process - - - /** - * Counts actual real hints. - */ - @Override - public void init(final TemplateData templateData) { - super.init(templateData); - if (hint != null) { - templateData.incrementHintsCount(); - } - } - - @Override - public void process(final StringBuilder out) { - // hints - if (templateData.hasHints()) { - templateData.registerHint(hint == null ? tableRef : hint); - } - - // columns - separateByCommaOrSpace(out); - - // special case, only column name, no table ref/name - if (tableRef.length() == 0) { - out.append(columnRef); - return; - } - - boolean useTableReference = true; - DbEntityDescriptor ded = lookupTableRef(tableRef, false); - if (ded == null) { - useTableReference = false; - ded = lookupName(tableRef); - } - - if (columnRef == null) { - final DbEntityColumnDescriptor[] decList = ded.getColumnDescriptors(); - int count = 0; - final boolean withIds = (columnRefArr != null) && ArraysUtil.contains(columnRefArr, StringPool.PLUS); - for (final DbEntityColumnDescriptor dec : decList) { - if ((includeColumns == COLS_ONLY_IDS) && (!dec.isId())) { - continue; - } - if ((includeColumns == COLS_ALL_BUT_ID) && (dec.isId())) { - continue; - } - if ((includeColumns == COLS_NA_MULTI) - && (!withIds || (!dec.isId())) - && (!ArraysUtil.contains(columnRefArr, dec.getPropertyName()))) { - continue; - } - if (count > 0) { - out.append(',').append(' '); - } - templateData.lastColumnDec = dec; - - if (useTableReference) { - appendColumnName(out, ded, dec); - } else { - appendAlias(out, ded, dec); - } - count++; - } - } else { - final DbEntityColumnDescriptor dec = ded.findByPropertyName(columnRef); - if (dec == null) { - throw new DbSqlBuilderException("Invalid column reference: [" + tableRef + '.' + columnRef + "]"); - } - - templateData.lastColumnDec = dec; - if (useTableReference) { - appendColumnName(out, ded, dec); - } else { - appendAlias(out, ded, dec); - } - } - } - - /** - * Appends alias. - */ - protected void appendAlias(final StringBuilder query, final DbEntityDescriptor ded, final DbEntityColumnDescriptor dec) { - final ColumnAliasType columnAliasType = templateData.getColumnAliasType(); - - if (columnAliasType == null || columnAliasType == ColumnAliasType.TABLE_REFERENCE) { - final String tableName = ded.getTableName(); - final String columnName = dec.getColumnNameForQuery(); - templateData.registerColumnDataForTableRef(tableRef, tableName); - query.append(tableRef).append(columnAliasSeparator).append(columnName); - } else - if (columnAliasType == ColumnAliasType.COLUMN_CODE) { - final String tableName = ded.getTableName(); - final String columnName = dec.getColumnName(); - final String code = templateData.registerColumnDataForColumnCode(tableName, columnName); - query.append(code); - } else - if (columnAliasType == ColumnAliasType.TABLE_NAME) { - final String tableName = ded.getTableNameForQuery(); - final String columnName = dec.getColumnNameForQuery(); - query.append(tableName).append(columnAliasSeparator).append(columnName); - } - } - - /** - * Simply appends column name with optional table reference and alias. - */ - protected void appendColumnName(final StringBuilder query, final DbEntityDescriptor ded, final DbEntityColumnDescriptor dec) { - query.append(resolveTable(tableRef, ded)).append('.').append(dec.getColumnName()); - - if (templateData.getColumnAliasType() != null) { // create column aliases - - query.append(AS); - - switch (templateData.getColumnAliasType()) { - case TABLE_NAME: { - final String tableName = ded.getTableNameForQuery(); - query.append(tableName).append(columnAliasSeparator).append(dec.getColumnNameForQuery()); - break; - } - case TABLE_REFERENCE: { - final String tableName = ded.getTableName(); - templateData.registerColumnDataForTableRef(tableRef, tableName); - query.append(tableRef).append(columnAliasSeparator).append(dec.getColumnNameForQuery()); - break; - } - case COLUMN_CODE: { - final String tableName = ded.getTableName(); - final String code = templateData.registerColumnDataForColumnCode(tableName, dec.getColumnName()); - query.append(code); - break; - } - } - } - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/InsertChunk.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/InsertChunk.java deleted file mode 100644 index 94b301033..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/InsertChunk.java +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen.chunks; - -import jodd.bean.BeanUtil; -import jodd.db.oom.DbEntityColumnDescriptor; -import jodd.db.oom.DbEntityDescriptor; -import jodd.db.oom.DbEntityManager; -import jodd.util.StringUtil; - -/** - * Renders complete INSERT statement. This chunk is a bit different than others since it renders a complete SQL - * query for inserting. - */ -public class InsertChunk extends SqlChunk { - - protected final String entityName; - protected final Class entityType; - protected final Object data; - protected final boolean defaultIsUpdateablePrimaryKey; - - public InsertChunk( - final DbEntityManager dbEntityManager, - final boolean isUpdateablePrimaryKey, - final String entityName, - final Object data) { - this(dbEntityManager, isUpdateablePrimaryKey, entityName, null, data); - } - - public InsertChunk( - final DbEntityManager dbEntityManager, - final boolean isUpdateablePrimaryKey, - final Class entityType, - final Object data) { - this(dbEntityManager, isUpdateablePrimaryKey, null, entityType, data); - } - - private InsertChunk( - final DbEntityManager dbEntityManager, - final boolean isUpdateablePrimaryKey, - final String entityName, - final Class entityType, - final Object data) { - super(dbEntityManager, CHUNK_INSERT); - this.defaultIsUpdateablePrimaryKey = isUpdateablePrimaryKey; - this.entityName = entityName; - this.entityType = entityType; - this.data = data; - } - - @Override - public void process(final StringBuilder out) { - final DbEntityDescriptor ded = entityName != null ? lookupName(entityName) : lookupType(entityType); - final StringBuilder col = new StringBuilder(); - final StringBuilder val = new StringBuilder(); - - final DbEntityColumnDescriptor[] decList = ded.getColumnDescriptors(); - final String typeName = StringUtil.uncapitalize(ded.getEntityName()); - - int size = 0; - for (final DbEntityColumnDescriptor dec : decList) { - if (dec.isId() && !defaultIsUpdateablePrimaryKey) { - continue; - } - - final String property = dec.getPropertyName(); - final Object value = BeanUtil.declared.getProperty(data, property); - if (value == null) { - continue; - } - - if (size > 0) { - col.append(',').append(' '); - val.append(',').append(' '); - } - size++; - col.append(dec.getColumnNameForQuery()); - - final String propertyName = typeName + '.' + property; - defineParameter(val, propertyName, value, dec); - } - - out.append("insert into ").append(ded.getTableNameForQuery()).append(" (") - .append(col).append(") values (").append(val).append(')'); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/MatchChunk.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/MatchChunk.java deleted file mode 100644 index 6cffdfb3f..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/MatchChunk.java +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen.chunks; - -import jodd.bean.BeanUtil; -import jodd.db.oom.DbEntityColumnDescriptor; -import jodd.db.oom.DbEntityDescriptor; -import jodd.db.oom.DbEntityManager; -import jodd.db.oom.sqlgen.DbSqlBuilderException; -import jodd.util.StringUtil; - -/** - * Renders condition part of the sql query based on values in provided entity object. - * Conditions are defined by following expression: tableRef = objectRef. - * Matching may be done for existing columns (non-null), all columns (including nulls) - * and just for the identity columns. - */ -public class MatchChunk extends SqlChunk { - - private static final String AND = " and "; - private static final String DEFAULT = "1=1"; - private static final String DOT_STAR = ".*"; - private static final String DOT_PLUS = ".+"; - - protected Object data; - protected final String tableRef; - protected final String objectRef; - protected final int includeColumns; - - public MatchChunk(final DbEntityManager dbEntityManager, final String tableRef, final Object data, final int includeColumns) { - this(dbEntityManager, tableRef, null, data, includeColumns); - } - - public MatchChunk(final DbEntityManager dbEntityManager, final String tableRef, final String objectRef, final int includeColumns) { - this(dbEntityManager, tableRef, objectRef, null, includeColumns); - } - - private MatchChunk( - final DbEntityManager dbEntityManager, - final String tableRef, - final String objectRef, - final Object data, - final int includeColumns) { - super(dbEntityManager, CHUNK_MATCH); - this.tableRef = tableRef; - this.objectRef = objectRef; - this.data = data; - this.includeColumns = includeColumns; - } - - public MatchChunk(final DbEntityManager dbEntityManager, String expression) { - super(dbEntityManager, CHUNK_MATCH); - expression = expression.trim(); - int lastNdx = expression.length(); - if (expression.endsWith(DOT_STAR)) { - lastNdx -= 2; - includeColumns = COLS_ALL; - } else if (expression.endsWith(DOT_PLUS)) { - lastNdx -= 2; - includeColumns = COLS_ONLY_IDS; - } else { - includeColumns = COLS_ONLY_EXISTING; - } - final int eq = expression.indexOf('='); - if (eq == -1) { - throw new DbSqlBuilderException("Syntax error, expected 'match' equality: {tableRef=objectRef}."); - } - tableRef = expression.substring(0, eq).trim(); - objectRef = expression.substring(eq + 1, lastNdx).trim(); - } - - @Override - public void process(final StringBuilder out) { - if (objectRef != null) { - data = templateData.lookupObject(objectRef); - } - - final DbEntityDescriptor ded = tableRef != null ? - lookupTableRef(tableRef) : - lookupType(resolveClass(data)); - - final String table = resolveTable(tableRef, ded); - final DbEntityColumnDescriptor[] decList = ded.getColumnDescriptors(); - final String typeName = StringUtil.uncapitalize(ded.getEntityName()); - - int count = 0; - out.append('('); - for (final DbEntityColumnDescriptor dec : decList) { - if ((includeColumns == COLS_ONLY_IDS) && (!dec.isId())) { - continue; - } - final String property = dec.getPropertyName(); - - final Object value = BeanUtil.declaredSilent.getProperty(data, property); - - if ((includeColumns == COLS_ONLY_EXISTING) && (value == null)) { - continue; - } - - if (includeColumns == COLS_ONLY_EXISTING) { - if (isEmptyColumnValue(dec, value)) { - continue; - } - } - if (count > 0) { - out.append(AND); - } - count++; - out.append(table).append('.').append(dec.getColumnNameForQuery()).append('='); - - String propertyName = objectRef != null ? objectRef : typeName; - propertyName += '.' + property; - defineParameter(out, propertyName, value, dec); - } - if (count == 0) { - out.append(DEFAULT); - } - out.append(')'); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/RawSqlChunk.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/RawSqlChunk.java deleted file mode 100644 index 5621960e4..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/RawSqlChunk.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen.chunks; - -import jodd.db.oom.DbEntityManager; - -/** - * Simply holds hard-coded SQL string that will be appended to the result. - */ -public class RawSqlChunk extends SqlChunk { - - protected final String sql; - - public RawSqlChunk(final DbEntityManager dbEntityManager, final String sql) { - super(dbEntityManager, CHUNK_RAW); - this.sql = sql; - } - - @Override - public void process(final StringBuilder out) { - out.append(sql); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/ReferenceChunk.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/ReferenceChunk.java deleted file mode 100644 index 756d403a4..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/ReferenceChunk.java +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen.chunks; - -import jodd.db.oom.DbEntityColumnDescriptor; -import jodd.db.oom.DbEntityDescriptor; -import jodd.db.oom.DbEntityManager; -import jodd.db.oom.sqlgen.DbSqlBuilderException; -import jodd.util.StringPool; - -/** - * Resolves column and table references. Reference is given in format: tableRef.propertyName. - * The propertyName may be '+' (e.g. tableRef.+), indicating the identity columns. - * If property name is omitted (e.g. tableRef), only table name will be rendered. - * If table reference is omitted (e.g. .propertyName), only property i.e. column name - * will be rendered. - */ -public class ReferenceChunk extends SqlChunk { - - protected final String tableRef; - protected final String columnRef; - protected final boolean onlyId; - - public ReferenceChunk(final DbEntityManager dbEntityManager, final String tableRef, final String columnRef) { - this(dbEntityManager, tableRef, columnRef, false); - } - - public ReferenceChunk(final DbEntityManager dbEntityManager, final String tableRef, final String columnRef, final boolean onlyId) { - super(dbEntityManager, CHUNK_REFERENCE); - this.tableRef = tableRef; - this.columnRef = columnRef; - this.onlyId = onlyId; - } - - public ReferenceChunk(final DbEntityManager dbEntityManager, final String reference) { - super(dbEntityManager, CHUNK_REFERENCE); - - final int dotNdx = reference.indexOf('.'); - - if (dotNdx == -1) { - this.tableRef = reference; - this.columnRef = null; - this.onlyId = false; - } else { - String ref = reference.substring(0, dotNdx); - if (ref.length() == 0) { - ref = null; - } - this.tableRef = ref; - - ref = reference.substring(dotNdx + 1); - if (ref.length() == 0) { - ref = null; - } - this.columnRef = ref; - onlyId = columnRef != null && columnRef.equals(StringPool.PLUS); - } - } - - // ---------------------------------------------------------------- process - - @Override - public void process(final StringBuilder out) { - - final DbEntityDescriptor ded; - - if (tableRef != null) { - ded = lookupTableRef(tableRef); - - final String tableName = resolveTable(tableRef, ded); - - out.append(tableName); - } else { - ded = findColumnRef(columnRef); - } - - - if (onlyId) { - if (tableRef != null) { - out.append('.'); - } - out.append(ded.getIdColumnName()); - } else if (columnRef != null) { - final DbEntityColumnDescriptor dec = ded.findByPropertyName(columnRef); - templateData.lastColumnDec = dec; - - if (dec == null) { - throw new DbSqlBuilderException("Invalid column reference: [" + tableRef + '.' + columnRef + "]"); - } - - if (tableRef != null) { - out.append('.'); - } - out.append(dec.getColumnNameForQuery()); - } - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/SqlChunk.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/SqlChunk.java deleted file mode 100644 index e2941b3af..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/SqlChunk.java +++ /dev/null @@ -1,311 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen.chunks; - -import jodd.db.oom.DbEntityColumnDescriptor; -import jodd.db.oom.DbEntityDescriptor; -import jodd.db.oom.DbEntityManager; -import jodd.db.oom.sqlgen.DbSqlBuilderException; -import jodd.db.oom.sqlgen.TemplateData; -import jodd.util.CharUtil; -import jodd.util.StringUtil; - -/** - * SQL chunk defines part of the SQL query that can be processed. - */ -public abstract class SqlChunk { - - public static final int COLS_NA = 0; // using explicit reference. - public static final int COLS_ONLY_EXISTING = 1; // using only existing columns i.e. that are not-null - public static final int COLS_ONLY_IDS = 2; // using only identity columns - public static final int COLS_ALL = 3; // using all available columns - public static final int COLS_ALL_BUT_ID = 4; // using all available columns except the identity column - public static final int COLS_NA_MULTI = 0; // using explicit reference. - - public static final int CHUNK_RAW = -1; - public static final int CHUNK_SELECT_COLUMNS = 1; - public static final int CHUNK_TABLE = 2; - public static final int CHUNK_REFERENCE = 3; - public static final int CHUNK_MATCH = 4; - public static final int CHUNK_VALUE = 5; - public static final int CHUNK_INSERT = 5; - public static final int CHUNK_UPDATE = 6; - - private final int chunkType; - private final DbEntityManager dbEntityManager; - - protected SqlChunk(final DbEntityManager dbEntityManager, final int chunkType) { - this.dbEntityManager = dbEntityManager; - this.chunkType = chunkType; - } - - // ---------------------------------------------------------------- linked list - - protected SqlChunk previousChunk; - - /** - * Returns previous chunk. - */ - public SqlChunk getPreviousChunk() { - return previousChunk; - } - - protected SqlChunk nextChunk; - - /** - * Returns next chunk. - */ - public SqlChunk getNextChunk() { - return nextChunk; - } - - /** - * Appends chunk to previous one and maintains the double-linked list of the previous chunk. - * Current surrounding connections of this chunk will be cut-off. - */ - public void insertChunkAfter(final SqlChunk previous) { - final SqlChunk next = previous.nextChunk; - previous.nextChunk = this; - this.previousChunk = previous; - if (next != null) { - next.previousChunk = this; - this.nextChunk = next; - } - } - - /** - * Returns true if previous chunk is of provided type. - */ - public boolean isPreviousChunkOfType(final int type) { - if (previousChunk == null) { - return false; - } - return previousChunk.chunkType == type; - } - - /** - * Returns true if previous chunk is of the same type. - */ - public boolean isPreviousChunkOfSameType() { - if (previousChunk == null) { - return false; - } - return previousChunk.chunkType == chunkType; - } - - /** - * Returns true if previous chunk is not raw. - */ - public boolean isPreviousMacroChunk() { - if (previousChunk == null) { - return false; - } - return previousChunk.chunkType != CHUNK_RAW; - } - - public boolean isPreviousRawChunk() { - if (previousChunk == null) { - return false; - } - return previousChunk.chunkType == CHUNK_RAW; - } - - - // ---------------------------------------------------------------- process - - protected TemplateData templateData; // working template context - - /** - * Initializes chunk. Assigns {@link jodd.db.oom.sqlgen.TemplateData} to chunk. - * If chunk needs some pre-processing, they should be done here. - */ - public void init(final TemplateData templateData) { - this.templateData = templateData; - } - - /** - * Process the chunk and appends data to the output. - */ - public abstract void process(StringBuilder out); - - - // ---------------------------------------------------------------- lookup - - /** - * Lookups for entity name and throws exception if entity name not found. - */ - protected DbEntityDescriptor lookupName(final String entityName) { - final DbEntityDescriptor ded = dbEntityManager.lookupName(entityName); - if (ded == null) { - throw new DbSqlBuilderException("Entity name not registered: " + entityName); - } - return ded; - } - - /** - * Lookups for entity name and throws an exception if entity type is invalid. - */ - protected DbEntityDescriptor lookupType(final Class entity) { - final DbEntityDescriptor ded = dbEntityManager.lookupType(entity); - if (ded == null) { - throw new DbSqlBuilderException("Invalid or not-persistent entity: " + entity.getName()); - } - return ded; - } - - /** - * Lookups for table reference and throws an exception if table reference not found. - */ - protected DbEntityDescriptor lookupTableRef(final String tableRef) { - return lookupTableRef(tableRef, true); - } - - /** - * Lookups for table reference and optionally throws an exception if table reference not found. - */ - protected DbEntityDescriptor lookupTableRef(final String tableRef, final boolean throwExceptionIfNotFound) { - final DbEntityDescriptor ded = templateData.getTableDescriptor(tableRef); - if (ded == null) { - if (throwExceptionIfNotFound) { - throw new DbSqlBuilderException("Invalid table reference: " + tableRef); - } - } - return ded; - } - - /** - * Finds a table that contains given column. - */ - protected DbEntityDescriptor findColumnRef(final String columnRef) { - final DbEntityDescriptor ded = templateData.findTableDescriptorByColumnRef(columnRef); - if (ded == null) { - throw new DbSqlBuilderException("Invalid column reference: [" + columnRef + "]"); - } - return ded; - } - - // ---------------------------------------------------------------- misc - - /** - * Resolves table name or alias that will be used in the query. - */ - protected String resolveTable(final String tableRef, final DbEntityDescriptor ded) { - final String tableAlias = templateData.getTableAlias(tableRef); - if (tableAlias != null) { - return tableAlias; - } - return ded.getTableNameForQuery(); - } - - /** - * Defines parameter with name and its value. - */ - protected void defineParameter(final StringBuilder query, String name, final Object value, final DbEntityColumnDescriptor dec) { - if (name == null) { - name = templateData.getNextParameterName(); - } - query.append(':').append(name); - templateData.addParameter(name, value, dec); - } - - /** - * Resolves object to a class. - */ - protected static Class resolveClass(final Object object) { - final Class type = object.getClass(); - return type == Class.class ? (Class) object : type; - } - - /** - * Returns true if a value is considered empty i.e. not existing. - */ - protected boolean isEmptyColumnValue(final DbEntityColumnDescriptor dec, final Object value) { - if (value == null) { - return true; - } - - // special case for ID column - if (dec.isId() && value instanceof Number) { - final double d = ((Number) value).doubleValue(); - if (d == 0.0d) { - return true; - } - } - - // special case for primitives - if (dec.getPropertyType().isPrimitive()) { - if (char.class == dec.getPropertyType()) { - final Character c = ((Character) value); - if ('\u0000' == c.charValue()) { - return true; - } - } else { - final double d = ((Number) value).doubleValue(); - if (d == 0) { - return true; - } - } - } - - // special case for strings - if (value instanceof CharSequence) { - if (StringUtil.isBlank((CharSequence) value)) { - return true; - } - } - - return false; - } - - - // ---------------------------------------------------------------- separation - - /** - * Appends missing space if the output doesn't end with whitespace. - */ - protected void appendMissingSpace(final StringBuilder out) { - int len = out.length(); - if (len == 0) { - return; - } - len--; - if (!CharUtil.isWhitespace(out.charAt(len))) { - out.append(' '); - } - } - - /** - * Separates from previous chunk by comma if is of the same type. - */ - protected void separateByCommaOrSpace(final StringBuilder out) { - if (isPreviousChunkOfSameType()) { - out.append(',').append(' '); - } else { - appendMissingSpace(out); - } - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/TableChunk.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/TableChunk.java deleted file mode 100644 index 13d7ea2ba..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/TableChunk.java +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen.chunks; - -import jodd.db.oom.DbEntityDescriptor; -import jodd.db.oom.DbEntityManager; -import jodd.db.oom.sqlgen.TemplateData; - -/** - * Table chunk resolves table name, optional table alias and defines table references. - *

- * If previous chunk is also a table, comma separator will be added between two table definitions, otherwise, - * regular space will be added if needed to separate from previous chunk. - *

- * Tables must be processed first, before all other chunks processing, since other chunks depends on it. - */ -public class TableChunk extends SqlChunk { - - protected final Class entity; - protected final String entityName; - protected final String tableAlias; - protected final String tableReference; - - public TableChunk(final DbEntityManager dbEntityManager, final Object entity) { - super(dbEntityManager, CHUNK_TABLE); - this.entity = resolveClass(entity); - this.entityName = null; - this.tableAlias = this.entity.getSimpleName(); - this.tableReference = null; - } - - public TableChunk(final DbEntityManager dbEntityManager, final Object entity, final String alias) { - super(dbEntityManager, CHUNK_TABLE); - this.entity = resolveClass(entity); - this.entityName = null; - this.tableAlias = alias; - this.tableReference = null; - } - - public TableChunk(final DbEntityManager dbEntityManager, final Object entity, final String alias, final String tableReference) { - super(dbEntityManager, CHUNK_TABLE); - this.entity = resolveClass(entity); - this.entityName = null; - this.tableAlias = alias; - this.tableReference = tableReference; - } - - public TableChunk(final DbEntityManager dbEntityManager, final String entityName, final String alias) { - this(dbEntityManager, null, entityName, alias, null); - } - - private TableChunk(final DbEntityManager dbEntityManager, final Class entity, final String entityName, final String tableAlias, final String tableReference) { - super(dbEntityManager, CHUNK_TABLE); - this.entity = entity; - this.entityName = entityName; - this.tableAlias = tableAlias; - this.tableReference = tableReference; - } - - public TableChunk(final DbEntityManager dbEntityManager, String tableRef) { - super(dbEntityManager, CHUNK_TABLE); - tableRef = tableRef.trim(); - int spaceNdx = tableRef.indexOf(' '); - this.entity = null; - if (spaceNdx != -1) { - this.entityName = tableRef.substring(0, spaceNdx); - String alias = tableRef.substring(spaceNdx + 1).trim(); - tableAlias = alias.length() == 0 ? null : alias; - } else { - this.entityName = tableRef; - this.tableAlias = null; - } - this.tableReference = null; - } - - // ---------------------------------------------------------------- process - - protected DbEntityDescriptor ded; - - /** - * Resolves and registers table references. - */ - @Override - public void init(final TemplateData templateData) { - super.init(templateData); - if (entity != null) { - ded = lookupType(entity); - } else { - Object object = templateData.getObjectReference(entityName); - if (object != null) { - ded = lookupType(resolveClass(object)); - } else { - ded = lookupName(entityName); - } - } - String tableReference = this.tableReference; - - if (tableReference == null) { - tableReference = tableAlias; - } - if (tableReference == null) { - tableReference = entityName; - } - if (tableReference == null) { - tableReference = ded.getEntityName(); - } - templateData.registerTableReference(tableReference, ded, tableAlias); - } - - @Override - public void process(final StringBuilder out) { - separateByCommaOrSpace(out); - out.append(ded.getTableNameForQuery()); - if (tableAlias != null) { - out.append(' ').append(tableAlias); - } - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/UpdateSetChunk.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/UpdateSetChunk.java deleted file mode 100644 index 169dd465c..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/UpdateSetChunk.java +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen.chunks; - -import jodd.bean.BeanUtil; -import jodd.db.DbOom; -import jodd.db.oom.DbEntityColumnDescriptor; -import jodd.db.oom.DbEntityDescriptor; -import jodd.util.StringUtil; - -/** - * Generates the SET part of the UPDATE statement. - * It may contains only non-null values, or all. - */ -public class UpdateSetChunk extends SqlChunk { - - private static final String SET = "set "; - - protected final Object data; - protected final String tableRef; - protected final int includeColumns; - protected final boolean isUpdateablePrimaryKey; - - public UpdateSetChunk(final DbOom dbOom, final String tableRef, final Object data, final int includeColumns) { - super(dbOom.entityManager(), CHUNK_UPDATE); - this.tableRef = tableRef; - this.data = data; - this.includeColumns = includeColumns; - this.isUpdateablePrimaryKey = dbOom.config().isUpdateablePrimaryKey(); - } - - @Override - public void process(final StringBuilder out) { - if (isPreviousChunkOfType(CHUNK_TABLE)) { - appendMissingSpace(out); - } - - final DbEntityDescriptor ded = tableRef != null ? - lookupTableRef(tableRef) : - lookupType(resolveClass(data)); - - out.append(SET); - - final DbEntityColumnDescriptor[] decList = ded.getColumnDescriptors(); - final String typeName = StringUtil.uncapitalize(ded.getEntityName()); - //String table = resolveTable(tableRef, ded); - - int size = 0; - for (final DbEntityColumnDescriptor dec : decList) { - if (dec.isId() && !isUpdateablePrimaryKey) { - continue; - } - - final String property = dec.getPropertyName(); - final Object value = BeanUtil.declared.getProperty(data, property); - - if (includeColumns == COLS_ONLY_EXISTING) { - if (isEmptyColumnValue(dec, value)) { - continue; - } - } - - if (size > 0) { - out.append(',').append(' '); - } - - size++; - - - // do not add table reference in set - // as only one table can be updated - // also, Postgress database does not allow it (see #JODD-21) - - //out.append(table).append('.'); - - out.append(dec.getColumnNameForQuery()).append('='); - - final String propertyName = typeName + '.' + property; - defineParameter(out, propertyName, value, dec); - } - if (size > 0) { - out.append(' '); - } - } - -} diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/ValueChunk.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/ValueChunk.java deleted file mode 100644 index 01cfdc1a4..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/ValueChunk.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.oom.sqlgen.chunks; - -import jodd.db.oom.DbEntityManager; - -import java.util.Collection; - -/** - * Defines SQL parameter and its value. Name may be null and will be - * automatically generated. Collections are recognized and will be rendered into - * the list of values. - *

- * For the last value use {@link ColumnValueChunk}! - */ -public class ValueChunk extends SqlChunk { - - protected final String name; - protected Object value; - protected final String objReference; - - public ValueChunk(final DbEntityManager dbEntityManager, final String name, final Object value) { - this(dbEntityManager, name, value, null); - } - - public ValueChunk(final DbEntityManager dbEntityManager, final String objReference) { - this(dbEntityManager, null, null, objReference); - } - - protected ValueChunk(final DbEntityManager dbEntityManager, final String name, final Object value, final String objReference) { - super(dbEntityManager, CHUNK_VALUE); - this.name = name; - this.value = value; - this.objReference = objReference; - } - - @Override - public void process(final StringBuilder out) { - if (objReference != null) { - value = templateData.lookupObject(objReference); - } - if (value != null) { - if (value instanceof Collection) { - Collection collection = (Collection) value; - int counter = 0; - for (Object obj : collection) { - if (counter > 0) { - out.append(',').append(' '); - } - defineParameter(out, name + counter, obj, null); - counter++; - } - return; - } - } - defineParameter(out, name, value, null); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/package-info.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/package-info.java deleted file mode 100644 index 91604a7b3..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * DbSqlBuilder query chunks. - */ -package jodd.db.oom.sqlgen.chunks; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/oom/sqlgen/package-info.java b/jodd-db/src/main/java/jodd/db/oom/sqlgen/package-info.java deleted file mode 100644 index fa5bbde3f..000000000 --- a/jodd-db/src/main/java/jodd/db/oom/sqlgen/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Various query generators. - */ -package jodd.db.oom.sqlgen; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/package-info.java b/jodd-db/src/main/java/jodd/db/package-info.java deleted file mode 100644 index 77364293d..000000000 --- a/jodd-db/src/main/java/jodd/db/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Simple and safe database access. - */ -package jodd.db; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/pool/CoreConnectionPool.java b/jodd-db/src/main/java/jodd/db/pool/CoreConnectionPool.java deleted file mode 100644 index 67022ec67..000000000 --- a/jodd-db/src/main/java/jodd/db/pool/CoreConnectionPool.java +++ /dev/null @@ -1,483 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.pool; - -import jodd.db.DbSqlException; -import jodd.db.connection.ConnectionProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; - -/** - * A class for pre-allocating, recycling, and managing JDBC connections. - *

- * It uses threads for opening a new connection. When no connection - * available it will wait until a connection is released. - */ -public class CoreConnectionPool implements Runnable, ConnectionProvider { - - private static final Logger log = LoggerFactory.getLogger(CoreConnectionPool.class); - - // ---------------------------------------------------------------- properties - - private static final String DEFAULT_VALIDATION_QUERY = "select 1"; - - private String driver; - private String url; - private String user; - private String password; - private int maxConnections = 10; - private int minConnections = 5; - private boolean waitIfBusy; - private boolean validateConnection = true; - private long validationTimeout = 18000000L; // 5 hours - private String validationQuery; - - public String getDriver() { - return driver; - } - - /** - * Specifies driver class name. - */ - public void setDriver(final String driver) { - this.driver = driver; - } - - public String getUrl() { - return url; - } - - /** - * Specifies JDBC url. - */ - public void setUrl(final String url) { - this.url = url; - } - - public String getUser() { - return user; - } - - /** - * Specifies db username. - */ - public void setUser(final String user) { - this.user = user; - } - - public String getPassword() { - return password; - } - - /** - * Specifies db password. - */ - public void setPassword(final String password) { - this.password = password; - } - - public int getMaxConnections() { - return maxConnections; - } - - /** - * Sets max number of connections. - */ - public void setMaxConnections(final int maxConnections) { - this.maxConnections = maxConnections; - } - - public int getMinConnections() { - return minConnections; - } - - /** - * Sets minimum number of open connections. - */ - public void setMinConnections(final int minConnections) { - this.minConnections = minConnections; - } - - public boolean isWaitIfBusy() { - return waitIfBusy; - } - - /** - * Sets if pool should wait for connection to be freed when none - * is available. If wait for busy is false - * exception will be thrown when max connection is reached. - */ - public void setWaitIfBusy(final boolean waitIfBusy) { - this.waitIfBusy = waitIfBusy; - } - - public long getValidationTimeout() { - return validationTimeout; - } - - /** - * Specifies number of milliseconds from connection creation - * when connection is considered as opened and valid. - */ - public void setValidationTimeout(final long validationTimeout) { - this.validationTimeout = validationTimeout; - } - - public String getValidationQuery() { - return validationQuery; - } - - /** - * Specifies query to be used for validating connections. - * If set to null validation will be performed - * by invoking Connection#isClosed method. - */ - public void setValidationQuery(final String validationQuery) { - this.validationQuery = validationQuery; - } - - /** - * Sets default validation query (select 1); - */ - public void setDefaultValidationQuery() { - this.validationQuery = DEFAULT_VALIDATION_QUERY; - } - - public boolean isValidateConnection() { - return validateConnection; - } - - /** - * Specifies if connections should be validated before returned. - */ - public void setValidateConnection(final boolean validateConnection) { - this.validateConnection = validateConnection; - } - - // ---------------------------------------------------------------- init - - private ArrayList availableConnections, busyConnections; - private boolean connectionPending; - private boolean initialised; - - /** - * {@inheritDoc} - */ - @Override - public synchronized void init() { - if (initialised) { - return; - } - if (log.isInfoEnabled()) { - log.info("Core connection pool initialization"); - } - try { - Class.forName(driver); - } - catch (final ClassNotFoundException cnfex) { - throw new DbSqlException("Database driver not found: " + driver, cnfex); - } - - if (minConnections > maxConnections) { - minConnections = maxConnections; - } - availableConnections = new ArrayList<>(maxConnections); - busyConnections = new ArrayList<>(maxConnections); - - for (int i = 0; i < minConnections; i++) { - try { - final Connection conn = DriverManager.getConnection(url, user, password); - availableConnections.add(new ConnectionData(conn)); - } catch (final SQLException sex) { - throw new DbSqlException("No database connection", sex); - } - } - initialised = true; - } - - // ---------------------------------------------------------------- get/close - - /** - * {@inheritDoc} - */ - @Override - public synchronized Connection getConnection() { - if (availableConnections == null) { - throw new DbSqlException("Connection pool is not initialized"); - } - if (!availableConnections.isEmpty()) { - final int lastIndex = availableConnections.size() - 1; - final ConnectionData existingConnection = availableConnections.get(lastIndex); - availableConnections.remove(lastIndex); - - // If conn on available list is closed (e.g., it timed out), then remove it from available list - // and repeat the process of obtaining a conn. Also wake up threads that were waiting for a - // conn because maxConnection limit was reached. - final long now = System.currentTimeMillis(); - final boolean isValid = isConnectionValid(existingConnection, now); - if (!isValid) { - if (log.isDebugEnabled()) { - log.debug("Pooled connection not valid, resetting"); - } - - notifyAll(); // freed up a spot for anybody waiting - return getConnection(); - } else { - if (log.isDebugEnabled()) { - log.debug("Returning valid pooled connection"); - } - - busyConnections.add(existingConnection); - existingConnection.lastUsed = now; - return existingConnection.connection; - } - } - if (log.isDebugEnabled()) { - log.debug("No more available connections"); - } - - // no available connections - if (((availableConnections.size() + busyConnections.size()) < maxConnections) && !connectionPending) { - makeBackgroundConnection(); - } else if (!waitIfBusy) { - throw new DbSqlException("Connection limit reached: " + maxConnections); - } - // wait for either a new conn to be established (if you called makeBackgroundConnection) or for - // an existing conn to be freed up. - try { - wait(); - } catch (final InterruptedException ie) { - // ignore - } - // someone freed up a conn, so try again. - return getConnection(); - } - - /** - * Checks if existing connection is valid and available. It may happens - * that if connection is not used for a while it becomes inactive, - * although not technically closed. - */ - private boolean isConnectionValid(final ConnectionData connectionData, final long now) { - if (!validateConnection) { - return true; - } - - if (now < connectionData.lastUsed + validationTimeout) { - return true; - } - - final Connection conn = connectionData.connection; - - if (validationQuery == null) { - try { - return !conn.isClosed(); - } catch (final SQLException sex) { - return false; - } - } - - boolean valid = true; - Statement st = null; - try { - st = conn.createStatement(); - st.execute(validationQuery); - } catch (final SQLException sex) { - valid = false; - } finally { - if (st != null) { - try { - st.close(); - } catch (final SQLException ignore) { - } - } - } - return valid; - } - - /** - * You can't just make a new conn in the foreground when none are - * available, since this can take several seconds with a slow network - * conn. Instead, start a thread that establishes a new conn, - * then wait. You get woken up either when the new conn is established - * or if someone finishes with an existing conn. - */ - private void makeBackgroundConnection() { - connectionPending = true; - final Thread connectThread = new Thread(this); - connectThread.start(); - } - - @Override - public void run() { - try { - final Connection connection = DriverManager.getConnection(url, user, password); - synchronized(this) { - availableConnections.add(new ConnectionData(connection)); - connectionPending = false; - notifyAll(); - } - } catch (final Exception ex) { - // give up on new conn and wait for existing one to free up. - } - } - - @Override - public synchronized void closeConnection(final Connection connection) { - final ConnectionData connectionData = new ConnectionData(connection); - busyConnections.remove(connectionData); - availableConnections.add(connectionData); - notifyAll(); // wake up threads that are waiting for a conn - } - - - // ---------------------------------------------------------------- close - - /** - * Close all the connections. Use with caution: be sure no connections are in - * use before calling. Note that you are not required to call this - * when done with a ConnectionPool, since connections are guaranteed to be - * closed when garbage collected. But this method gives more control - * regarding when the connections are closed. - */ - @Override - public synchronized void close() { - if (log.isInfoEnabled()) { - log.info("Core connection pool shutdown"); - } - closeConnections(availableConnections); - availableConnections = new ArrayList<>(maxConnections); - closeConnections(busyConnections); - busyConnections = new ArrayList<>(maxConnections); - } - - private void closeConnections(final ArrayList connections) { - if (connections == null) { - return; - } - try { - for (final ConnectionData connectionData : connections) { - final Connection connection = connectionData.connection; - if (!connection.isClosed()) { - connection.close(); - } - } - } catch (final SQLException ignore) { - // Ignore errors; garbage collect anyhow - } - } - - // ---------------------------------------------------------------- conn data - - /** - * Connection data with last used timestamp. - */ - class ConnectionData { - final Connection connection; - long lastUsed; - - ConnectionData(final Connection connection) { - this.connection = connection; - this.lastUsed = System.currentTimeMillis(); - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - final ConnectionData that = (ConnectionData) o; - return connection.equals(that.connection); - } - - @Override - public int hashCode() { - return connection.hashCode(); - } - } - - // ---------------------------------------------------------------- stats - - /** - * Returns connection stats. - */ - public synchronized SizeSnapshot getConnectionsCount() { - return new SizeSnapshot(availableConnections.size(), busyConnections.size()); - } - - /** - * Just a statistic class. - */ - public static class SizeSnapshot { - final int totalCount; - final int availableCount; - final int busyCount; - - SizeSnapshot(final int availableCount, final int busyCount) { - this.totalCount = availableCount + busyCount; - this.availableCount = availableCount; - this.busyCount = busyCount; - } - - /** - * Returns total number of connections. - */ - public int getTotalCount() { - return totalCount; - } - - /** - * Returns number of available connections. - */ - public int getAvailableCount() { - return availableCount; - } - - /** - * Returns number of busy connections. - */ - public int getBusyCount() { - return busyCount; - } - - @Override - public String toString() { - return "Connections count: {total=" + totalCount + - ", available=" + availableCount + - ", busy=" + busyCount + '}'; - } - } - -} diff --git a/jodd-db/src/main/java/jodd/db/pool/package-info.java b/jodd-db/src/main/java/jodd/db/pool/package-info.java deleted file mode 100644 index 9dcc3ce12..000000000 --- a/jodd-db/src/main/java/jodd/db/pool/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Various custom database pool implementations. - */ -package jodd.db.pool; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/querymap/DbPropsQueryMap.java b/jodd-db/src/main/java/jodd/db/querymap/DbPropsQueryMap.java deleted file mode 100644 index 47ee33487..000000000 --- a/jodd-db/src/main/java/jodd/db/querymap/DbPropsQueryMap.java +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.querymap; - -import jodd.core.JoddCore; -import jodd.exception.UncheckedException; -import jodd.io.findfile.ClassScanner; -import jodd.props.Props; -import jodd.util.StringUtil; - -import java.nio.charset.StandardCharsets; - -/** - * {@link jodd.db.querymap.QueryMap} implementation based on - * {@link jodd.props.Props} properties files. - * Scans for "*.sql.props" and "*.oom.props" - * properties on class path. - */ -public class DbPropsQueryMap implements QueryMap { - - protected final String[] patterns; - protected Props props; - - public DbPropsQueryMap(final String... patterns) { - this.patterns = patterns; - reload(); - } - - public DbPropsQueryMap() { - this("*.sql.props", "*.oom.props", "*.sql.properties", "*.oom.properties"); - } - - /** - * Returns Props. - */ - public Props props() { - return props; - } - - @Override - public void reload() { - props = new Props(); - loadFromClasspath(props, patterns); - } - - @Override - public int size() { - return props.countTotalProperties(); - } - - // ---------------------------------------------------------------- sql - - /** - * Returns query for given key. - * In debug mode, props are reloaded every time before the lookup. - */ - @Override - public String getQuery(final String key) { - return props.getValue(key); - } - - private void loadFromClasspath(final Props props, final String... patterns) { - ClassScanner.create() - .registerEntryConsumer(entryData -> { - String usedEncoding = JoddCore.encoding; - if (StringUtil.endsWithIgnoreCase(entryData.name(), ".properties")) { - usedEncoding = StandardCharsets.ISO_8859_1.name(); - } - - final String encoding = usedEncoding; - UncheckedException.runAndWrapException(() -> props.load(entryData.openInputStream(), encoding)); - }) - .includeResources(true) - .ignoreException(true) - .excludeCommonJars() - .excludeAllEntries(true) - .includeEntries(patterns) - .scanDefaultClasspath() - .start(); - } -} diff --git a/jodd-db/src/main/java/jodd/db/querymap/EmptyQueryMap.java b/jodd-db/src/main/java/jodd/db/querymap/EmptyQueryMap.java deleted file mode 100644 index 8c009c36b..000000000 --- a/jodd-db/src/main/java/jodd/db/querymap/EmptyQueryMap.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.querymap; - -/** - * Void implementation of a query map. - */ -public class EmptyQueryMap implements QueryMap { - - @Override - public void reload() { - } - - @Override - public String getQuery(final String key) { - return null; - } - - @Override - public int size() { - return 0; - } - -} diff --git a/jodd-db/src/main/java/jodd/db/querymap/QueryMap.java b/jodd-db/src/main/java/jodd/db/querymap/QueryMap.java deleted file mode 100644 index 41758d59e..000000000 --- a/jodd-db/src/main/java/jodd/db/querymap/QueryMap.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.querymap; - -/** - * Storage of SQL queries. - */ -public interface QueryMap { - - /** - * Optionally reloads the query map, if implementation allows it. - */ - void reload(); - - /** - * Returns query for given key. Returns null if query not found. - */ - String getQuery(String key); - - /** - * Returns total number of queries. - */ - int size(); -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/querymap/package-info.java b/jodd-db/src/main/java/jodd/db/querymap/package-info.java deleted file mode 100644 index e52eeb6b7..000000000 --- a/jodd-db/src/main/java/jodd/db/querymap/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Storage for queries. - */ -package jodd.db.querymap; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/servers/Db2DbServer.java b/jodd-db/src/main/java/jodd/db/servers/Db2DbServer.java deleted file mode 100644 index 2283d9b94..000000000 --- a/jodd-db/src/main/java/jodd/db/servers/Db2DbServer.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.servers; - -import jodd.db.oom.DbOomConfig; - -/** - * DB2. - */ -public class Db2DbServer implements DbServer { - - private final String version; - - public Db2DbServer() { - this.version = "(N/A)"; - } - - public Db2DbServer(final String version) { - this.version = version; - } - - @Override - public void accept(final DbOomConfig dbOomConfig) { - // quote character - dbOomConfig.getColumnNames().setQuoteChar('\"'); - } - - @Override - public String toString() { - return "DbServer: DB2 v" + version; - } -} diff --git a/jodd-db/src/main/java/jodd/db/servers/DbServer.java b/jodd-db/src/main/java/jodd/db/servers/DbServer.java deleted file mode 100644 index ee13fccb4..000000000 --- a/jodd-db/src/main/java/jodd/db/servers/DbServer.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.servers; - -import jodd.db.oom.DbOomConfig; - -import java.util.function.Consumer; - -public interface DbServer extends Consumer { - - @Override - void accept(DbOomConfig dbOomConfig); - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/servers/DerbyDbServer.java b/jodd-db/src/main/java/jodd/db/servers/DerbyDbServer.java deleted file mode 100644 index 68165aef0..000000000 --- a/jodd-db/src/main/java/jodd/db/servers/DerbyDbServer.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.servers; - -import jodd.db.oom.DbOomConfig; - -/** - * Apache Derby. - */ -public class DerbyDbServer implements DbServer { - - private final String version; - - public DerbyDbServer(final String version) { - this.version = version; - } - - @Override - public void accept(final DbOomConfig dbOomConfig) { - // quote character - dbOomConfig.getColumnNames().setQuoteChar('\"'); - } - - @Override - public String toString() { - return "DbServer: Apache Derby v" + version; - } -} diff --git a/jodd-db/src/main/java/jodd/db/servers/GenericDbServer.java b/jodd-db/src/main/java/jodd/db/servers/GenericDbServer.java deleted file mode 100644 index 0cf3da787..000000000 --- a/jodd-db/src/main/java/jodd/db/servers/GenericDbServer.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.servers; - -import jodd.db.oom.DbOomConfig; - -/** - * Generic database server, for any database that is not recognized. - */ -public class GenericDbServer implements DbServer { - - private final String name; - private final String version; - - public GenericDbServer() { - this(null, null); - } - - public GenericDbServer(String name, String version) { - if (name == null) { - name = "unknown server"; - } - if (version == null) { - version = "(N/A)"; - } - this.name = name; - this.version = version; - } - - @Override - public void accept(final DbOomConfig dbOomConfig) { - } - - @Override - public String toString() { - return "DbServer - Generic: " + name + " v" + version; - } -} diff --git a/jodd-db/src/main/java/jodd/db/servers/HsqlDbServer.java b/jodd-db/src/main/java/jodd/db/servers/HsqlDbServer.java deleted file mode 100644 index 8db7919a2..000000000 --- a/jodd-db/src/main/java/jodd/db/servers/HsqlDbServer.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.servers; - -import jodd.db.oom.DbOomConfig; - -/** - * HSQLDB. - */ -public class HsqlDbServer implements DbServer { - - private final String version; - - public HsqlDbServer(final String version) { - this.version = version; - } - - @Override - public void accept(final DbOomConfig dbOomConfig) { - - // When a database object is created with one of the CREATE statements or renamed with the ALTER statement, - // if the name is enclosed in double quotes, the exact name is used as the case-normal form. But if it is - // not enclosed in double quotes, the name is converted to uppercase and this uppercase version is stored - // in the database as the case-normal form. - dbOomConfig.getTableNames().setUppercase(true); - dbOomConfig.getColumnNames().setUppercase(true); - - // quote character - dbOomConfig.getColumnNames().setQuoteChar('\"'); - } - - @Override - public String toString() { - return "DbServer: HSQLDB v" + version; - } -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/servers/InformixDbServer.java b/jodd-db/src/main/java/jodd/db/servers/InformixDbServer.java deleted file mode 100644 index 41ceaccfe..000000000 --- a/jodd-db/src/main/java/jodd/db/servers/InformixDbServer.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.servers; - -import jodd.db.oom.DbOomConfig; - -/** - * Informix. - */ -public class InformixDbServer implements DbServer { - - private final String version; - - public InformixDbServer(final String version) { - this.version = version; - } - - @Override - public void accept(final DbOomConfig dbOomConfig) { - } - - @Override - public String toString() { - return "DbServer: Informix v" + version; - } -} diff --git a/jodd-db/src/main/java/jodd/db/servers/MySqlDbServer.java b/jodd-db/src/main/java/jodd/db/servers/MySqlDbServer.java deleted file mode 100644 index bf19383ae..000000000 --- a/jodd-db/src/main/java/jodd/db/servers/MySqlDbServer.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.servers; - -import jodd.db.oom.DbOomConfig; - -/** - * MySQL. - */ -public class MySqlDbServer implements DbServer { - - private final String version; - - public MySqlDbServer(final String version) { - this.version = version; - } - - @Override - public void accept(final DbOomConfig dbOomConfig) { - // Database and table names are not case sensitive in Windows, - // and case sensitive in most varieties of Unix. One notable exception is Mac OS X, - // which is Unix-based but uses a default file system type (HFS+) that is not case sensitive. - dbOomConfig.getTableNames().setLowercase(true); - - // Column and index names are not case sensitive on any platform, nor are column aliases. - dbOomConfig.getColumnNames().setLowercase(true); - - // quote character - dbOomConfig.getColumnNames().setQuoteChar('`'); - } - - @Override - public String toString() { - return "DbServer: MySQL v" + version; - } -} diff --git a/jodd-db/src/main/java/jodd/db/servers/OracleDbServer.java b/jodd-db/src/main/java/jodd/db/servers/OracleDbServer.java deleted file mode 100644 index 11927f72a..000000000 --- a/jodd-db/src/main/java/jodd/db/servers/OracleDbServer.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.servers; - -import jodd.db.oom.DbOomConfig; - -/** - * Oracle. - */ -public class OracleDbServer implements DbServer { - - private final String version; - - public OracleDbServer(final String version) { - this.version = version; - } - - @Override - public void accept(final DbOomConfig dbOomConfig) { - // quote character - dbOomConfig.getColumnNames().setQuoteChar('\"'); - } - - @Override - public String toString() { - return "DbServer: Oracle v" + version; - } -} - diff --git a/jodd-db/src/main/java/jodd/db/servers/PostgreSqlDbServer.java b/jodd-db/src/main/java/jodd/db/servers/PostgreSqlDbServer.java deleted file mode 100644 index 8646b6db1..000000000 --- a/jodd-db/src/main/java/jodd/db/servers/PostgreSqlDbServer.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.servers; - -import jodd.db.oom.DbOomConfig; - -/** - * Postgres. - */ -public class PostgreSqlDbServer implements DbServer { - - private final String version; - - public PostgreSqlDbServer(final String version) { - this.version = version; - } - - @Override - public void accept(final DbOomConfig dbOomConfig) { - // However, the standard says that unquoted identifiers should be - // folded to uppercase but PostgreSQL folds them to lower case - // (probably for historic reasons) - dbOomConfig.getTableNames().setLowercase(true); - dbOomConfig.getColumnNames().setLowercase(true); - - // quote character - dbOomConfig.getColumnNames().setQuoteChar('\"'); - } - - @Override - public String toString() { - return "DbServer: Postgres v" + version; - } -} - diff --git a/jodd-db/src/main/java/jodd/db/servers/SQLiteDbServer.java b/jodd-db/src/main/java/jodd/db/servers/SQLiteDbServer.java deleted file mode 100644 index 1dd37b5fe..000000000 --- a/jodd-db/src/main/java/jodd/db/servers/SQLiteDbServer.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.servers; - -import jodd.db.oom.DbOomConfig; - -/** - * SQLite. - */ -public class SQLiteDbServer implements DbServer { - - private final String version; - - public SQLiteDbServer(final String version) { - this.version = version; - } - - @Override - public void accept(final DbOomConfig dbOomConfig) { - dbOomConfig.setUpdateAcceptsTableAlias(false); - - // quote character - dbOomConfig.getColumnNames().setQuoteChar('\"'); - } - - @Override - public String toString() { - return "DbServer: SQLite v" + version; - } -} - diff --git a/jodd-db/src/main/java/jodd/db/servers/SqlServerDbServer.java b/jodd-db/src/main/java/jodd/db/servers/SqlServerDbServer.java deleted file mode 100644 index 61cd8102e..000000000 --- a/jodd-db/src/main/java/jodd/db/servers/SqlServerDbServer.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.servers; - -import jodd.db.oom.DbOomConfig; - -/** - * SQL Server. - */ -public class SqlServerDbServer implements DbServer { - - private final String version; - - public SqlServerDbServer(final String version) { - this.version = version; - } - - @Override - public void accept(final DbOomConfig dbOomConfig) { - dbOomConfig.setUpdateAcceptsTableAlias(false); - dbOomConfig.setUpdateablePrimaryKey(false); - - // quote character - dbOomConfig.getColumnNames().setQuoteChar('\"'); - } - - @Override - public String toString() { - return "DbServer: SQL Server v" + version; - } -} diff --git a/jodd-db/src/main/java/jodd/db/servers/SybaseDbServer.java b/jodd-db/src/main/java/jodd/db/servers/SybaseDbServer.java deleted file mode 100644 index 1bb35dd94..000000000 --- a/jodd-db/src/main/java/jodd/db/servers/SybaseDbServer.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.servers; - -import jodd.db.oom.DbOomConfig; - -/** - * Sybase. - */ -public class SybaseDbServer implements DbServer { - - private final String version; - - public SybaseDbServer(final String version) { - this.version = version; - } - - @Override - public void accept(final DbOomConfig dbOomConfig) { - // quote character - dbOomConfig.getColumnNames().setQuoteChar('\"'); - } - - @Override - public String toString() { - return "DbServer: Sybase v" + version; - } -} - diff --git a/jodd-db/src/main/java/jodd/db/servers/package-info.java b/jodd-db/src/main/java/jodd/db/servers/package-info.java deleted file mode 100644 index 6688a073d..000000000 --- a/jodd-db/src/main/java/jodd/db/servers/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Detected database servers. - */ -package jodd.db.servers; \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/type/BigDecimalSqlType.java b/jodd-db/src/main/java/jodd/db/type/BigDecimalSqlType.java deleted file mode 100644 index dd0f09a3d..000000000 --- a/jodd-db/src/main/java/jodd/db/type/BigDecimalSqlType.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.math.BigDecimal; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.PreparedStatement; - -public class BigDecimalSqlType extends SqlType { - /** - * {@inheritDoc} - */ - @Override - public BigDecimal get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return rs.getBigDecimal(index); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final BigDecimal value, final int dbSqlType) throws SQLException { - st.setBigDecimal(index, value); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/type/BigIntegerSqlType.java b/jodd-db/src/main/java/jodd/db/type/BigIntegerSqlType.java deleted file mode 100644 index 3ec349836..000000000 --- a/jodd-db/src/main/java/jodd/db/type/BigIntegerSqlType.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.math.BigInteger; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.PreparedStatement; - -public class BigIntegerSqlType extends SqlType { - /** - * {@inheritDoc} - */ - @Override - public BigInteger get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return BigInteger.valueOf(rs.getLong(index)); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final BigInteger value, final int dbSqlType) throws SQLException { - st.setLong(index, value.longValue()); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/type/BlobSqlType.java b/jodd-db/src/main/java/jodd/db/type/BlobSqlType.java deleted file mode 100644 index 23d203ee6..000000000 --- a/jodd-db/src/main/java/jodd/db/type/BlobSqlType.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.PreparedStatement; -import java.sql.Blob; - -public class BlobSqlType extends SqlType { - - /** - * {@inheritDoc} - */ - @Override - public Blob get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return rs.getBlob(index); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Blob value, final int dbSqlType) throws SQLException { - st.setBlob(index, value); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/type/BooleanSqlType.java b/jodd-db/src/main/java/jodd/db/type/BooleanSqlType.java deleted file mode 100644 index a0bcb3e89..000000000 --- a/jodd-db/src/main/java/jodd/db/type/BooleanSqlType.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.PreparedStatement; - -public class BooleanSqlType extends NullAwareSqlType { - - /** - * {@inheritDoc} - */ - @Override - public Boolean get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return Boolean.valueOf(rs.getBoolean(index)); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Boolean value, final int dbSqlType) throws SQLException { - st.setBoolean(index, value.booleanValue()); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/type/ByteArraySqlType.java b/jodd-db/src/main/java/jodd/db/type/ByteArraySqlType.java deleted file mode 100644 index 3f197b614..000000000 --- a/jodd-db/src/main/java/jodd/db/type/ByteArraySqlType.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class ByteArraySqlType extends SqlType { - /** - * {@inheritDoc} - */ - @Override - public byte[] get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return rs.getBytes(index); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final byte[] value, final int dbSqlType) throws SQLException { - st.setBytes(index, value); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/type/ByteSqlType.java b/jodd-db/src/main/java/jodd/db/type/ByteSqlType.java deleted file mode 100644 index b7207f572..000000000 --- a/jodd-db/src/main/java/jodd/db/type/ByteSqlType.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.PreparedStatement; - -public class ByteSqlType extends NullAwareSqlType { - - /** - * {@inheritDoc} - */ - @Override - public Byte get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return Byte.valueOf(rs.getByte(index)); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Byte value, final int dbSqlType) throws SQLException { - st.setByte(index, value.byteValue()); - } -} diff --git a/jodd-db/src/main/java/jodd/db/type/CharacterSqlType.java b/jodd-db/src/main/java/jodd/db/type/CharacterSqlType.java deleted file mode 100644 index 654a72346..000000000 --- a/jodd-db/src/main/java/jodd/db/type/CharacterSqlType.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import jodd.db.DbSqlException; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -/** - * Char SQL type. - */ -public class CharacterSqlType extends NullAwareSqlType { - - /** - * {@inheritDoc} - */ - @Override - public Character get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - if (TypesUtil.isIntegerType(dbSqlType)) { - return Character.valueOf((char) rs.getInt(index)); - } - String s = rs.getString(index); - if (s == null) { - return null; - } - if (s.length() > 1) { - throw new DbSqlException("Char column size too long, should be 1"); - } - return Character.valueOf(s.charAt(0)); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Character value, final int dbSqlType) throws SQLException { - if (TypesUtil.isIntegerType(dbSqlType)) { - st.setInt(index, value.charValue()); - return; - } - st.setString(index, value.toString()); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/type/ClobSqlType.java b/jodd-db/src/main/java/jodd/db/type/ClobSqlType.java deleted file mode 100644 index 0712d2085..000000000 --- a/jodd-db/src/main/java/jodd/db/type/ClobSqlType.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.Clob; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class ClobSqlType extends SqlType { - - /** - * {@inheritDoc} - */ - @Override - public Clob get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return rs.getClob(index); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Clob value, final int dbSqlType) throws SQLException { - st.setClob(index, value); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/type/DateSqlType.java b/jodd-db/src/main/java/jodd/db/type/DateSqlType.java deleted file mode 100644 index ea780fa3b..000000000 --- a/jodd-db/src/main/java/jodd/db/type/DateSqlType.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.Date; - -public class DateSqlType extends SqlType { - - /** - * {@inheritDoc} - */ - @Override - public Date get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return rs.getDate(index); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Date value, final int dbSqlType) throws SQLException { - st.setTimestamp(index, new Timestamp(value.getTime())); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/type/DoubleSqlType.java b/jodd-db/src/main/java/jodd/db/type/DoubleSqlType.java deleted file mode 100644 index 9e9dfeb19..000000000 --- a/jodd-db/src/main/java/jodd/db/type/DoubleSqlType.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class DoubleSqlType extends NullAwareSqlType { - - /** - * {@inheritDoc} - */ - @Override - public Double get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return Double.valueOf(rs.getDouble(index)); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Double value, final int dbSqlType) throws SQLException { - st.setDouble(index, value.doubleValue()); - } -} diff --git a/jodd-db/src/main/java/jodd/db/type/FloatSqlType.java b/jodd-db/src/main/java/jodd/db/type/FloatSqlType.java deleted file mode 100644 index e9adef72a..000000000 --- a/jodd-db/src/main/java/jodd/db/type/FloatSqlType.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.PreparedStatement; - -public class FloatSqlType extends NullAwareSqlType { - - /** - * {@inheritDoc} - */ - @Override - public Float get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return Float.valueOf(rs.getFloat(index)); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Float value, final int dbSqlType) throws SQLException { - st.setFloat(index, value.floatValue()); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/type/IntegerSqlType.java b/jodd-db/src/main/java/jodd/db/type/IntegerSqlType.java deleted file mode 100644 index 9f6b53f28..000000000 --- a/jodd-db/src/main/java/jodd/db/type/IntegerSqlType.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class IntegerSqlType extends NullAwareSqlType { - - /** - * {@inheritDoc} - */ - @Override - public Integer get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return Integer.valueOf(rs.getInt(index)); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Integer value, final int dbSqlType) throws SQLException { - st.setInt(index, value.intValue()); - } -} diff --git a/jodd-db/src/main/java/jodd/db/type/JulianDateSqlType.java b/jodd-db/src/main/java/jodd/db/type/JulianDateSqlType.java deleted file mode 100644 index cdd1bd77a..000000000 --- a/jodd-db/src/main/java/jodd/db/type/JulianDateSqlType.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import jodd.time.JulianDate; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.sql.Types; - -/** - * JulianDate sql type stores JulianDate data as number of milliseconds passed from 1970. - */ -public class JulianDateSqlType extends SqlType { - - @Override - public void set(final PreparedStatement st, final int index, final JulianDate value, final int dbSqlType) throws SQLException { - if (value == null) { - st.setNull(index, dbSqlType); - return; - } - if (dbSqlType == Types.TIMESTAMP) { - st.setTimestamp(index, new Timestamp(value.toMilliseconds())); - return; - } - st.setLong(index, value.toMilliseconds()); - } - - @Override - public JulianDate get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - if (dbSqlType == Types.TIMESTAMP) { - final Timestamp timestamp = rs.getTimestamp(index); - if (timestamp == null) { - return null; - } - return JulianDate.of(timestamp.getTime()); - } - final long time = rs.getLong(index); - - if (time == 0 && rs.wasNull()) { - return null; - } - return new JulianDate(time); - } -} diff --git a/jodd-db/src/main/java/jodd/db/type/LocalDateSqlType.java b/jodd-db/src/main/java/jodd/db/type/LocalDateSqlType.java deleted file mode 100644 index c25f03913..000000000 --- a/jodd-db/src/main/java/jodd/db/type/LocalDateSqlType.java +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import jodd.time.TimeUtil; - -import java.sql.Date; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.sql.Types; -import java.time.LocalDate; - -public class LocalDateSqlType extends SqlType { - - @Override - public void set(final PreparedStatement st, final int index, final LocalDate value, final int dbSqlType) throws SQLException { - if (value == null) { - st.setNull(index, dbSqlType); - return; - } - if (dbSqlType == Types.TIMESTAMP) { - st.setTimestamp(index, new Timestamp(TimeUtil.toMilliseconds(value))); - return; - } - if (dbSqlType == Types.VARCHAR) { - st.setString(index, value.toString()); - return; - } - if (dbSqlType == Types.INTEGER) { - st.setLong(index, TimeUtil.toMilliseconds(value)); - } - - st.setObject(index, value); - } - - @Override - public LocalDate get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - if (dbSqlType == Types.TIMESTAMP) { - Timestamp timestamp = rs.getTimestamp(index); - if (timestamp == null) { - return null; - } - return TimeUtil.fromMilliseconds(timestamp.getTime()).toLocalDate(); - } - if (dbSqlType == Types.VARCHAR) { - String string = rs.getString(index); - if (string == null) { - return null; - } - return LocalDate.parse(string); - } - if (dbSqlType == Types.INTEGER) { - long time = rs.getLong(index); - - if (time == 0 && rs.wasNull()) { - return null; - } - return TimeUtil.fromMilliseconds(time).toLocalDate(); - } - - Date date = (Date) rs.getObject(index); - - return TimeUtil.fromMilliseconds(date.getTime()).toLocalDate(); - } -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/type/LocalDateTimeSqlType.java b/jodd-db/src/main/java/jodd/db/type/LocalDateTimeSqlType.java deleted file mode 100644 index 19157ce32..000000000 --- a/jodd-db/src/main/java/jodd/db/type/LocalDateTimeSqlType.java +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import jodd.time.TimeUtil; - -import java.sql.Date; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.sql.Types; -import java.time.LocalDateTime; - -public class LocalDateTimeSqlType extends SqlType { - - @Override - public void set(final PreparedStatement st, final int index, final LocalDateTime value, final int dbSqlType) throws SQLException { - if (value == null) { - st.setNull(index, dbSqlType); - return; - } - if (dbSqlType == Types.TIMESTAMP) { - st.setTimestamp(index, new Timestamp(TimeUtil.toMilliseconds(value))); - return; - } - if (dbSqlType == Types.VARCHAR) { - st.setString(index, value.toString()); - return; - } - if (dbSqlType == Types.INTEGER) { - st.setLong(index, TimeUtil.toMilliseconds(value)); - } - - st.setObject(index, value); - } - - @Override - public LocalDateTime get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - if (dbSqlType == Types.TIMESTAMP) { - Timestamp timestamp = rs.getTimestamp(index); - if (timestamp == null) { - return null; - } - return TimeUtil.fromMilliseconds(timestamp.getTime()); - } - if (dbSqlType == Types.VARCHAR) { - String string = rs.getString(index); - if (string == null) { - return null; - } - return LocalDateTime.parse(string); - } - if (dbSqlType == Types.INTEGER) { - long time = rs.getLong(index); - - if (time == 0 && rs.wasNull()) { - return null; - } - return TimeUtil.fromMilliseconds(time); - } - - Date date = (Date) rs.getObject(index); - - return TimeUtil.fromMilliseconds(date.getTime()); - } -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/type/LocalTimeSqlType.java b/jodd-db/src/main/java/jodd/db/type/LocalTimeSqlType.java deleted file mode 100644 index 0e72c497a..000000000 --- a/jodd-db/src/main/java/jodd/db/type/LocalTimeSqlType.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import java.time.LocalTime; - -public class LocalTimeSqlType extends SqlType { - - @Override - public void set(final PreparedStatement st, final int index, final LocalTime value, final int dbSqlType) throws SQLException { - if (value == null) { - st.setNull(index, dbSqlType); - return; - } - if (dbSqlType == Types.VARCHAR) { - st.setString(index, value.toString()); - return; - } - st.setLong(index, value.toSecondOfDay()); - } - - @Override - public LocalTime get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - if (dbSqlType == Types.VARCHAR) { - String string = rs.getString(index); - if (string == null) { - return null; - } - return LocalTime.parse(string); - } - - long time = rs.getLong(index); - - if (time == 0 && rs.wasNull()) { - return null; - } - return LocalTime.ofSecondOfDay(time); - } -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/type/LongSqlType.java b/jodd-db/src/main/java/jodd/db/type/LongSqlType.java deleted file mode 100644 index c2c17672f..000000000 --- a/jodd-db/src/main/java/jodd/db/type/LongSqlType.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class LongSqlType extends NullAwareSqlType { - - /** - * {@inheritDoc} - */ - @Override - public Long get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return Long.valueOf(rs.getLong(index)); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Long value, final int dbSqlType) throws SQLException { - st.setLong(index, value.longValue()); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/type/NullAwareSqlType.java b/jodd-db/src/main/java/jodd/db/type/NullAwareSqlType.java deleted file mode 100644 index 05be91db3..000000000 --- a/jodd-db/src/main/java/jodd/db/type/NullAwareSqlType.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -/** - * Null-aware {@link SqlType sql types}. - */ -public abstract class NullAwareSqlType extends SqlType { - - /** - * Detects if there was a null reading and returns null if it was. - * Result set returns default value (e.g. 0) for many getters, therefore it detects if it was - * a null reading or it is a real value. - */ - @Override - public E readValue(final ResultSet rs, final int index, final Class destinationType, final int dbSqlType) throws SQLException { - T t = get(rs, index, dbSqlType); - if ((t == null) || (rs.wasNull())) { - return null; - } - return prepareGetValue(t, destinationType); - } - - /** - * Detects null before storing the value into the database. - */ - @Override - public void storeValue(final PreparedStatement st, final int index, final Object value, final int dbSqlType) throws SQLException { - if (value == null) { - st.setNull(index, dbSqlType); - return; - } - super.storeValue(st, index, value, dbSqlType); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/type/ShortSqlType.java b/jodd-db/src/main/java/jodd/db/type/ShortSqlType.java deleted file mode 100644 index 93f137f44..000000000 --- a/jodd-db/src/main/java/jodd/db/type/ShortSqlType.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.PreparedStatement; - -public class ShortSqlType extends NullAwareSqlType { - - /** - * {@inheritDoc} - */ - @Override - public Short get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return Short.valueOf(rs.getShort(index)); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Short value, final int dbSqlType) throws SQLException { - st.setShort(index, value.shortValue()); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/type/SqlArraySqlType.java b/jodd-db/src/main/java/jodd/db/type/SqlArraySqlType.java deleted file mode 100644 index dc7f7978d..000000000 --- a/jodd-db/src/main/java/jodd/db/type/SqlArraySqlType.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.Array; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class SqlArraySqlType extends SqlType { - - /** - * {@inheritDoc} - */ - @Override - public Array get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return rs.getArray(index); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Array value, final int dbSqlType) throws SQLException { - st.setArray(index, value); - } - -} \ No newline at end of file diff --git a/jodd-db/src/main/java/jodd/db/type/SqlDateSqlType.java b/jodd-db/src/main/java/jodd/db/type/SqlDateSqlType.java deleted file mode 100644 index 9d0fdc5c7..000000000 --- a/jodd-db/src/main/java/jodd/db/type/SqlDateSqlType.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.Date; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class SqlDateSqlType extends SqlType{ - - /** - * {@inheritDoc} - */ - @Override - public Date get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return rs.getDate(index); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Date value, final int dbSqlType) throws SQLException { - st.setDate(index, value); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/type/SqlRefSqlType.java b/jodd-db/src/main/java/jodd/db/type/SqlRefSqlType.java deleted file mode 100644 index 150214550..000000000 --- a/jodd-db/src/main/java/jodd/db/type/SqlRefSqlType.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.PreparedStatement; -import java.sql.Ref; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class SqlRefSqlType extends SqlType { - - /** - * {@inheritDoc} - */ - @Override - public Ref get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return rs.getRef(index); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final Ref value, final int dbSqlType) throws SQLException { - st.setRef(index, value); - } -} diff --git a/jodd-db/src/main/java/jodd/db/type/SqlType.java b/jodd-db/src/main/java/jodd/db/type/SqlType.java deleted file mode 100644 index 5e40f52b9..000000000 --- a/jodd-db/src/main/java/jodd/db/type/SqlType.java +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import jodd.typeconverter.TypeConverterManager; -import jodd.util.ClassUtil; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -/** - * SQL type. - */ -public abstract class SqlType { - - /** - * Indicator for not yet resolved DB SQL type. - */ - public static final int DB_SQLTYPE_UNKNOWN = Integer.MAX_VALUE; - - /** - * Indicator for unavailable DB SQL type. Used usually when sql type is not - * available by JDBC meta data or when column can not be matched - * (due to case-mismatching). - */ - public static final int DB_SQLTYPE_NOT_AVAILABLE = Integer.MIN_VALUE; - - - protected Class sqlType; - - @SuppressWarnings({"unchecked"}) - protected SqlType() { - this.sqlType = ClassUtil.getGenericSupertype(this.getClass(), 0); - } - - /** - * Sets prepared statement value. - */ - public abstract void set(PreparedStatement st, int index, T value, int dbSqlType) throws SQLException; - - /** - * Returns value from result set. - * @param rs result set - * @param index column index - * @param dbSqlType java.sql.Types hint - */ - public abstract T get(ResultSet rs, int index, int dbSqlType) throws SQLException; - - - /** - * Stores value in database. Value is casted to sql type. - */ - public void storeValue(final PreparedStatement st, final int index, final Object value, final int dbSqlType) throws SQLException { - final T t = TypeConverterManager.get().convertType(value, sqlType); - set(st, index, t, dbSqlType); - } - - /** - * Reads value from database. Value is casted to destination type. - * @param rs result set - * @param index database column index - * @param destinationType property type - * @param dbSqlType hint for column sql type value - */ - public E readValue(final ResultSet rs, final int index, final Class destinationType, final int dbSqlType) throws SQLException { - final T t = get(rs, index, dbSqlType); - return prepareGetValue(t, destinationType); - } - - /** - * Once when value is read from result set, prepare it to match destination type. - * @param t get value - * @param destinationType destination type - */ - @SuppressWarnings({"unchecked"}) - protected E prepareGetValue(final T t, final Class destinationType) { - if (t == null) { - return null; - } - if (destinationType == null) { - return (E) t; - } - return TypeConverterManager.get().convertType(t, destinationType); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/type/SqlTypeManager.java b/jodd-db/src/main/java/jodd/db/type/SqlTypeManager.java deleted file mode 100644 index 2ee2d02c8..000000000 --- a/jodd-db/src/main/java/jodd/db/type/SqlTypeManager.java +++ /dev/null @@ -1,192 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import jodd.db.DbSqlException; -import jodd.mutable.MutableBoolean; -import jodd.mutable.MutableByte; -import jodd.mutable.MutableDouble; -import jodd.mutable.MutableFloat; -import jodd.mutable.MutableInteger; -import jodd.mutable.MutableLong; -import jodd.mutable.MutableShort; -import jodd.time.JulianDate; -import jodd.util.ClassUtil; -import jodd.util.TypeCache; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.net.URL; -import java.sql.Array; -import java.sql.Blob; -import java.sql.Clob; -import java.sql.Date; -import java.sql.Ref; -import java.sql.Time; -import java.sql.Timestamp; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; - -/** - * Provides dynamic object conversion to a type. - * Contains a map of registered converters. User may add new converter. - */ -public class SqlTypeManager { - - private static final SqlTypeManager SQL_TYPE_MANAGER = new SqlTypeManager(); - - /** - * Returns default implementation of the {@code SqlTypeManager}. - */ - public static SqlTypeManager get() { - return SQL_TYPE_MANAGER; - } - - private final TypeCache types = TypeCache.createDefault(); - private final TypeCache sqlTypes = TypeCache.createDefault(); - - public SqlTypeManager() { - registerDefaults(); - } - - /** - * Unregisters all converters. - */ - public void unregisterAll() { - types.clear(); - } - - /** - * Registers default set of SQL types. - */ - public void registerDefaults() { - register(Integer.class, IntegerSqlType.class); - register(int.class, IntegerSqlType.class); - register(MutableInteger.class, IntegerSqlType.class); - - register(Float.class, FloatSqlType.class); - register(float.class, FloatSqlType.class); - register(MutableFloat.class, FloatSqlType.class); - - register(Double.class, DoubleSqlType.class); - register(double.class, DoubleSqlType.class); - register(MutableDouble.class, DoubleSqlType.class); - - register(Byte.class, ByteSqlType.class); - register(byte.class, ByteSqlType.class); - register(MutableByte.class, ByteSqlType.class); - - register(Boolean.class, BooleanSqlType.class); - register(boolean.class, BooleanSqlType.class); - register(MutableBoolean.class, BooleanSqlType.class); - - register(Long.class, LongSqlType.class); - register(long.class, LongSqlType.class); - register(MutableLong.class, LongSqlType.class); - - register(Short.class, ShortSqlType.class); - register(short.class, ShortSqlType.class); - register(MutableShort.class, ShortSqlType.class); - - register(Character.class, CharacterSqlType.class); - register(char.class, CharacterSqlType.class); - - register(BigDecimal.class, BigDecimalSqlType.class); - register(BigInteger.class, BigIntegerSqlType.class); - - register(String.class, StringSqlType.class); - - register(LocalDateTime.class, LocalDateTimeSqlType.class); - register(LocalDate.class, LocalDateSqlType.class); - register(LocalTime.class, LocalTimeSqlType.class); - register(Date.class, SqlDateSqlType.class); - register(Timestamp.class, TimestampSqlType.class); - register(Time.class, TimeSqlType.class); - register(java.util.Date.class, DateSqlType.class); - register(JulianDate.class, JulianDateSqlType.class); - - register(byte[].class, ByteArraySqlType.class); - register(URL.class, URLSqlType.class); - - register(Blob.class, BlobSqlType.class); - register(Clob.class, ClobSqlType.class); - register(Array.class, SqlArraySqlType.class); - register(Ref.class, SqlRefSqlType.class); - } - - /** - * Registers sql type for provided type. - */ - public void register(final Class type, final Class sqlTypeClass) { - types.put(type, lookupSqlType(sqlTypeClass)); - } - - /** - * Unregisters some sql type. - */ - public void unregister(final Class type) { - types.remove(type); - } - - // ---------------------------------------------------------------- lookup - - /** - * Retrieves SQL type for provided type. All subclasses and interfaces are examined - * for matching sql type. - */ - public SqlType lookup(final Class clazz) { - SqlType sqlType; - for (Class x = clazz; x != null; x = x.getSuperclass()) { - sqlType = types.get(clazz); - if (sqlType != null) { - return sqlType; - } - final Class[] interfaces = x.getInterfaces(); - for (final Class i : interfaces) { - sqlType = types.get(i); - if (sqlType != null) { - return sqlType; - } - } - } - return null; - } - - /** - * Returns sql type instance. Instances are stored for better performances. - */ - public SqlType lookupSqlType(final Class sqlTypeClass) { - return sqlTypes.get(sqlTypeClass, t -> { - try { - return ClassUtil.newInstance(sqlTypeClass); - } catch (final Exception ex) { - throw new DbSqlException("SQL type not found: " + sqlTypeClass.getSimpleName(), ex); - } - }); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/type/StringSqlType.java b/jodd-db/src/main/java/jodd/db/type/StringSqlType.java deleted file mode 100644 index a2dfeb299..000000000 --- a/jodd-db/src/main/java/jodd/db/type/StringSqlType.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; - -public class StringSqlType extends SqlType { - - /** - * {@inheritDoc} - */ - @Override - public String get(final ResultSet rs, final int index, final int dbSqlType) throws SQLException { - return rs.getString(index); - } - - /** - * {@inheritDoc} - */ - @Override - public void set(final PreparedStatement st, final int index, final String value, final int dbSqlType) throws SQLException { - st.setString(index, value); - } - -} diff --git a/jodd-db/src/main/java/jodd/db/type/TimeSqlType.java b/jodd-db/src/main/java/jodd/db/type/TimeSqlType.java deleted file mode 100644 index 4ab2f918a..000000000 --- a/jodd-db/src/main/java/jodd/db/type/TimeSqlType.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.db.type; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.PreparedStatement; -import java.sql.Time; - -public class TimeSqlType extends SqlType

{@code
-	 * None -> T2 (same session, new tx)
-	 * T1 -> T1 (same session, join tx)
-	 * }
- */ - PROPAGATION_REQUIRED(1), - - /** - * Support a current transaction, execute non-transactionally if none exists. - *
{@code
-	 * None -> None (same session)
-	 * T1 -> T1 (same session, join tx)
-	 * }
- */ - PROPAGATION_SUPPORTS(2), - - /** - * Support a current transaction, throw an exception if none exists. - *
{@code
-	 * None -> Error
-	 * T1 -> T1 (same session, join tx)
-	 * }
- */ - PROPAGATION_MANDATORY(3), - - /** - * Create a new transaction, suspend the current transaction if one exists. - *
{@code
-	 * None -> T2 (same session, new tx)
-	 * T1 -> T2  (new session, new tx)
-	 * }
- */ - PROPAGATION_REQUIRES_NEW(4), - - /** - * Execute non-transactionally, suspend the current transaction if one exists. - *
{@code
-	 * None -> None (same session)
-	 * T1 -> None (new session, no tx)
-	 * }
- */ - PROPAGATION_NOT_SUPPORTED(5), - - /** - * Execute non-transactionally, throw an exception if a transaction exists. - *
{@code
-	 * None -> None (same session)
-	 * T1 -> Error
-	 * }
- */ - PROPAGATION_NEVER(6); - - private int value; - - JtxPropagationBehavior(final int value) { - this.value = value; - } - - public int value() { - return value; - } - - @Override - public String toString() { - switch(value) { - case 1: return "Required"; - case 2: return "Supports"; - case 3: return "Mandatory"; - case 4: return "Requires New"; - case 5: return "Not Supported"; - case 6: return "Never"; - default: return "Undefined"; - } - } -} diff --git a/jodd-jtx/src/main/java/jodd/jtx/JtxResource.java b/jodd-jtx/src/main/java/jodd/jtx/JtxResource.java deleted file mode 100644 index 3f1f7422d..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/JtxResource.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx; - -import jodd.util.ClassUtil; - -/** - * Stores resource object and its resource manager. - */ -final class JtxResource { - - final JtxTransaction transaction; - final JtxResourceManager resourceManager; - private final E resource; - - JtxResource(final JtxTransaction transaction, final JtxResourceManager resourceManager, final E resource) { - this.transaction = transaction; - this.resourceManager = resourceManager; - this.resource = resource; - } - - /** - * Returns true if resource is of provided resource type. - */ - public boolean isSameTypeAsResource(final Class type) { - return ClassUtil.isTypeOf(type, resource.getClass()); - } - - // ---------------------------------------------------------------- delegates - - /** - * Delegates to {@link jodd.jtx.JtxResourceManager#commitTransaction(Object)}. - */ - void commitTransaction() { - resourceManager.commitTransaction(resource); - } - - /** - * Delegates to {@link JtxResourceManager#rollbackTransaction(Object)}}. - */ - void rollbackTransaction() { - resourceManager.rollbackTransaction(resource); - } - - /** - * Returns resource instance. -s */ - public E getResource() { - return resource; - } -} diff --git a/jodd-jtx/src/main/java/jodd/jtx/JtxResourceManager.java b/jodd-jtx/src/main/java/jodd/jtx/JtxResourceManager.java deleted file mode 100644 index e46b40815..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/JtxResourceManager.java +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx; - -/** - * Responsible for managing transactions of the - * resources of the same type under the control of the {@link JtxTransaction transaction}. - * Resource manager has to be registered in the {@link JtxTransactionManager transaction manager}. - */ -public interface JtxResourceManager { - - /** - * Returns associated resource type. - */ - Class getResourceType(); - - /** - * Creates new resource and begins new transaction if specified so by - * active flag, usually determined by propagation behavior. - * Propagation behavior and timeout may be handled by the Jtx framework, - * leaving resource manager to handle isolation and read only flag. - */ - E beginTransaction(JtxTransactionMode jtxMode, boolean active); - - /** - * Commits resource and closes it if committing was successful. - */ - void commitTransaction(E resource); - - /** - * Rollback resource and closes it. Resource is closed no matter if rolling back fails. - */ - void rollbackTransaction(E resource); - - /** - * Closes manager and free its resources. - */ - void close(); -} diff --git a/jodd-jtx/src/main/java/jodd/jtx/JtxStatus.java b/jodd-jtx/src/main/java/jodd/jtx/JtxStatus.java deleted file mode 100644 index 8a6606247..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/JtxStatus.java +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx; - -/** - * Transaction statuses. - */ -public enum JtxStatus { - - /** - * A transaction is associated with the target object and it is in the active state. - */ - STATUS_ACTIVE(0), - - /** - * A transaction is associated with the target object and it has been marked for rollback, - * perhaps as a result of a setRollbackOnly operation. - */ - STATUS_MARKED_ROLLBACK(1), - - /** - * NOT IN USE IN JTX, since two-phase protocol is not supported. - */ - //STATUS_PREPARED(2), - - /** - * A transaction is associated with the target object and it has been committed. - */ - STATUS_COMMITTED(3), - - /** - * A transaction is associated with the target object and the outcome has been determined as rollback. - */ - STATUS_ROLLEDBACK(4), - - /** - * A transaction is associated with the target object but its status is unknown. - */ - STATUS_UNKNOWN(5), - - /** - * No transaction is currently associated with the target object. Indicates the auto-commit mode. - */ - STATUS_NO_TRANSACTION(6), - - /** - * NOT IN USE IN JTX, since two-phase protocol is not supported. - */ - //STATUS_PREPARING(7), - - /** - * A transaction is associated with the target object and it is in the process of committing. - */ - STATUS_COMMITTING(8), - - /** - * A transaction is associated with the target object and it is in the process of rolling back. - */ - STATUS_ROLLING_BACK(9); - - - private int value; - - JtxStatus(final int value) { - this.value = value; - } - - public int value() { - return value; - } - - @Override - public String toString() { - switch(value) { - case 0: return "Active"; - case 1: return "Marked for rollback"; - case 3: return "Committed"; - case 4: return "Rolled back"; - case 5: return "Unknown"; - case 6: return "No transaction"; - case 8: return "Committing"; - case 9: return "Rolling back"; - default: return "Undefined"; - } - } - -} diff --git a/jodd-jtx/src/main/java/jodd/jtx/JtxTransaction.java b/jodd-jtx/src/main/java/jodd/jtx/JtxTransaction.java deleted file mode 100644 index c25394974..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/JtxTransaction.java +++ /dev/null @@ -1,385 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import static jodd.jtx.JtxStatus.STATUS_ACTIVE; -import static jodd.jtx.JtxStatus.STATUS_COMMITTED; -import static jodd.jtx.JtxStatus.STATUS_COMMITTING; -import static jodd.jtx.JtxStatus.STATUS_MARKED_ROLLBACK; -import static jodd.jtx.JtxStatus.STATUS_NO_TRANSACTION; -import static jodd.jtx.JtxStatus.STATUS_ROLLEDBACK; -import static jodd.jtx.JtxStatus.STATUS_ROLLING_BACK; -import static jodd.jtx.JtxStatus.STATUS_UNKNOWN; -import static jodd.jtx.JtxTransactionMode.DEFAULT_TIMEOUT; - -/** - * Transaction is an unit of work that is performed by one or more resources. - * Created and controlled by {@link JtxTransactionManager transaction manager}. - *

- * Transaction is associated to a thread from where it was created. - * Transaction may have more than one resource attached. - *

- * Committing and rolling back transaction actually performs commit/rollback on - * all attached resources. Therefore, it may happens that committing of one resource - * fails, what actually breaks the atomicity of the transaction. If transaction is - * attached just to one resource, atomicity is saved. - *

- * Only one resource of some type may exists in the transaction. There is no way to have - * two resources of the same type in one transaction. - *

- * This class is responsible for transaction life-cycle. It can be consider that all - * work is scoped to associated thread. - */ -public class JtxTransaction { - - private static final Logger log = LoggerFactory.getLogger(JtxTransaction.class); - - // ---------------------------------------------------------------- init - - protected final JtxTransactionManager txManager; - protected final JtxTransactionMode mode; - protected final Set resources; - protected final Object scope; - protected final long deadline; - protected final boolean startAsActive; - protected Throwable rollbackCause; - protected JtxStatus status; - - /** - * Creates new transaction. Should be invoked by {@link jodd.jtx.JtxTransactionManager}. - * If transaction is set as active, it will be actually created, meaning - * that it is the first transaction on this connection i.e. in this session. - * If transaction is not active, transaction object will be created, - * but the real transaction not, and it is expected that one is already created before. - * - * @param txManager jtx manager - * @param mode transaction mode - * @param scope transaction live scope within the other transaction requests are ignored - * @param active if true it is an active transaction, otherwise it's not - */ - public JtxTransaction(final JtxTransactionManager txManager, final JtxTransactionMode mode, final Object scope, final boolean active) { - this.txManager = txManager; - this.mode = mode; - this.scope = scope; - this.resources = new HashSet<>(); - this.deadline = mode.getTransactionTimeout() == DEFAULT_TIMEOUT ? - DEFAULT_TIMEOUT : - System.currentTimeMillis() + (mode.getTransactionTimeout() * 1000L); - this.status = active ? STATUS_ACTIVE : STATUS_NO_TRANSACTION; - this.startAsActive = active; - txManager.associateTransaction(this); - if (log.isDebugEnabled()) { - log.debug("New JTX {status:" + this.status + ", mode:" + this.mode + '}'); - } - } - - /** - * Returns transaction mode. - */ - public JtxTransactionMode getTransactionMode() { - return mode; - } - - /** - * Returns transaction manager that owns this transaction. - */ - public JtxTransactionManager getTransactionManager() { - return txManager; - } - - /** - * Returns transaction scope if exist, or null. - */ - public Object getScope() { - return scope; - } - - // ---------------------------------------------------------------- status - - /** - * Returns current transaction status. - */ - public JtxStatus getStatus() { - return status; - } - - /** - * Returns true if transaction started as active one. - * This value is never changed, while {@link #getStatus() status} - * changes during the execution. - */ - public boolean isStartAsActive() { - return startAsActive; - } - - /** - * Returns true if transaction is active. - * This status changes during the transaction flow. - */ - public boolean isActive() { - return status == STATUS_ACTIVE; - } - - /** - * Returns true if transaction is explicitly forbidden, i.e. - * session is in auto-commit mode. - */ - public boolean isNoTransaction() { - return status == STATUS_NO_TRANSACTION; - } - - /** - * Returns true if transaction and all its resources are committed successfully. - */ - public boolean isCommitted() { - return status == STATUS_COMMITTED; - } - - /** - * Returns true if transaction and all its resources are rolled-back successfully. - */ - public boolean isRolledback() { - return status == STATUS_ROLLEDBACK; - } - - /** - * Returns true if transaction is either committed or rolled back. - */ - public boolean isCompleted() { - return status == STATUS_COMMITTED || status == STATUS_ROLLEDBACK; - } - - // ---------------------------------------------------------------- rollback - - /** - * Modify the transaction associated with the target object such that the only possible outcome - * of the transaction is to roll back the transaction. - */ - public void setRollbackOnly() { - setRollbackOnly(null); - } - - /** - * Modify the transaction associated with the target object such that the only possible outcome - * of the transaction is to roll back the transaction. - */ - public void setRollbackOnly(final Throwable th) { - if (!isNoTransaction()) { - if ((status != STATUS_MARKED_ROLLBACK) && (status != STATUS_ACTIVE)) { - throw new JtxException("TNo active TX that can be marked as rollback only"); - } - } - rollbackCause = th; - status = STATUS_MARKED_ROLLBACK; - } - - /** - * Returns true if transaction is marked as rollback only. - */ - public boolean isRollbackOnly() { - return status == STATUS_MARKED_ROLLBACK; - } - - // ---------------------------------------------------------------- timeout - - /** - * Sets the rollback-only if the deadline has been reached and throws an exception. - */ - protected void checkTimeout() { - if (deadline == DEFAULT_TIMEOUT) { - return; - } - if (this.deadline - System.currentTimeMillis() < 0) { - setRollbackOnly(); - throw new JtxException("TX timed out, marked as rollback only"); - } - } - - // ---------------------------------------------------------------- core - - /** - * Commit and completes current transaction. Transaction is committed on all attached resources. After, resources - * are detached from the transaction. When this method completes,transaction is no longer - * associated with current thread. - */ - public void commit() { - checkTimeout(); - commitOrRollback(true); - } - - /** - * Roll back and completes current transaction. Transaction is rolled back on all attached resources. - * Resource are then detached from the transaction. When this method completes, transaction is no - * longer associated with current thread. - */ - public void rollback() { - commitOrRollback(false); - } - - /** - * Performs either commit or rollback on all transaction resources. - */ - protected void commitOrRollback(boolean doCommit) { - if (log.isDebugEnabled()) { - if (doCommit) { - log.debug("Commit JTX"); - } else { - log.debug("Rollback JTX"); - } - } - boolean forcedRollback = false; - if (!isNoTransaction()) { - if (isRollbackOnly()) { - if (doCommit) { - doCommit = false; - forcedRollback = true; - } - } else if (!isActive()) { - if (isCompleted()) { - throw new JtxException("TX is already completed, commit or rollback should be called once per TX"); - } - throw new JtxException("No active TX to " + (doCommit ? "commit" : "rollback")); - } - } - if (doCommit) { - commitAllResources(); - } else { - rollbackAllResources(forcedRollback); - } - } - - // ---------------------------------------------------------------- resources - - /** - * Commits all attached resources. On successful commit, resource will be closed - * and detached from this transaction. On exception, resource remains attached - * to transaction. - *

- * All resources will be committed, even if commit fails on some in that process. - * If there was at least one failed commit, its exception will be re-thrown after finishing - * committing all resources, and transaction will be marked as rollback only. - */ - protected void commitAllResources() throws JtxException { - status = STATUS_COMMITTING; - Exception lastException = null; - final Iterator it = resources.iterator(); - while (it.hasNext()) { - final JtxResource resource = it.next(); - try { - resource.commitTransaction(); - it.remove(); - } catch (final Exception ex) { - lastException = ex; - } - } - if (lastException != null) { - setRollbackOnly(lastException); - throw new JtxException("Commit failed: one or more TX resources couldn't commit a TX", lastException); - } - txManager.removeTransaction(this); - status = STATUS_COMMITTED; - } - - /** - * Rollbacks all attached resources. Resource will be closed. and detached from this transaction. - * If exception occurs, it will be rethrown at the end. - */ - protected void rollbackAllResources(final boolean wasForced) { - status = STATUS_ROLLING_BACK; - Exception lastException = null; - final Iterator it = resources.iterator(); - while (it.hasNext()) { - final JtxResource resource = it.next(); - try { - resource.rollbackTransaction(); - } catch (final Exception ex) { - lastException = ex; - } finally { - it.remove(); - } - } - txManager.removeTransaction(this); - status = STATUS_ROLLEDBACK; - if (lastException != null) { - status = STATUS_UNKNOWN; - throw new JtxException("Rollback failed: one or more TX resources couldn't rollback a TX", lastException); - } - if (wasForced) { - throw new JtxException("TX rolled back because it has been marked as rollback-only", rollbackCause); - } - } - - - // ---------------------------------------------------------------- resources - - /** - * Requests a resource. If resource is not found, it will be created and new transaction will be started on it. - */ - public E requestResource(final Class resourceType) { - if (isCompleted()) { - throw new JtxException("TX is already completed, resource is not available after commit or rollback"); - } - if (isRollbackOnly()) { - throw new JtxException("TX is marked as rollback only, resource is not available", rollbackCause); - } - if (!isNoTransaction() && !isActive()) { - throw new JtxException("Resource is not available since TX is not active"); - } - checkTimeout(); - E resource = lookupResource(resourceType); - if (resource == null) { - final int maxResources = txManager.getMaxResourcesPerTransaction(); - if ((maxResources != -1) && (resources.size() >= maxResources)) { - throw new JtxException("TX already has attached max. number of resources"); - } - final JtxResourceManager resourceManager = txManager.lookupResourceManager(resourceType); - resource = resourceManager.beginTransaction(mode, isActive()); - resources.add(new JtxResource<>(this, resourceManager, resource)); - } - return resource; - } - - /** - * Lookups for open resource. Returns null if resource not found. - * Only open resources can be found. - */ - protected E lookupResource(final Class resourceType) { - for (final JtxResource jtxResource : resources) { - if (jtxResource.isSameTypeAsResource(resourceType)) { - //noinspection unchecked - return (E) jtxResource.getResource(); - } - } - return null; - } -} diff --git a/jodd-jtx/src/main/java/jodd/jtx/JtxTransactionManager.java b/jodd-jtx/src/main/java/jodd/jtx/JtxTransactionManager.java deleted file mode 100644 index 3e2044355..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/JtxTransactionManager.java +++ /dev/null @@ -1,469 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx; - -import jodd.util.TypeCache; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; - -import static jodd.jtx.JtxIsolationLevel.ISOLATION_DEFAULT; -import static jodd.jtx.JtxStatus.STATUS_ACTIVE; - -/** - * {@link JtxTransaction} manager is responsible for handling transaction - * propagation and resource managers. Holds various JTX configuration data. - *

- * Note that transactions are hold inside a thread-local transaction stack. - * Therefore, if one transaction is created after the other during the - * same thread, the second transaction will be aware that it is 'after' - * the first one. - */ -public class JtxTransactionManager { - - private static final Logger log = LoggerFactory.getLogger(JtxTransactionManager.class); - - protected int maxResourcesPerTransaction; - protected boolean oneResourceManager; - protected boolean validateExistingTransaction; - protected boolean ignoreScope; - protected TypeCache resourceManagers; - - protected final ThreadLocal> txStack = new ThreadLocal<>(); - - /** - * Creates new transaction manager. - */ - public JtxTransactionManager() { - this.maxResourcesPerTransaction = -1; - this.resourceManagers = TypeCache.createDefault(); - } - - // ---------------------------------------------------------------- config - - /** - * Returns max number of resources per transaction. - */ - public int getMaxResourcesPerTransaction() { - return maxResourcesPerTransaction; - } - - /** - * Sets max number of resources per transaction. - */ - public void setMaxResourcesPerTransaction(final int maxResourcesPerTransaction) { - this.maxResourcesPerTransaction = maxResourcesPerTransaction; - } - - /** - * Returns whether existing transactions should be validated before participating in them. - */ - public boolean isValidateExistingTransaction() { - return validateExistingTransaction; - } - - /** - * Sets whether existing transactions should be validated before participating - * in them. - *

When participating in an existing transaction (e.g. with - * PROPAGATION_REQUIRES or PROPAGATION_SUPPORTS encountering an existing - * transaction), this outer transaction's characteristics will apply even - * to the inner transaction scope. Validation will detect incompatible - * isolation level and read-only settings on the inner transaction definition - * and reject participation accordingly through throwing a corresponding exception. - */ - public void setValidateExistingTransaction(final boolean validateExistingTransaction) { - this.validateExistingTransaction = validateExistingTransaction; - } - - /** - * Returns true if this transaction manager works with just one resource. - */ - public boolean isSingleResourceManager() { - return oneResourceManager; - } - /** - * Specifies if transaction manager works with just one resource. - */ - public void setSingleResourceManager(final boolean oneResourceManager) { - this.oneResourceManager = oneResourceManager; - } - - /** - * Returns if transaction scope should be ignored. - */ - public boolean isIgnoreScope() { - return ignoreScope; - } - - /** - * Sets if transaction scope should be ignored. If ignored, - * there may be more then one transaction in one scope. - * Scopes may be ignored if set to null - */ - public void setIgnoreScope(final boolean ignoreScope) { - this.ignoreScope = ignoreScope; - } - - // ---------------------------------------------------------------- count - - /** - * Returns total number of transactions associated with current thread. - */ - public int totalThreadTransactions() { - final ArrayList txList = txStack.get(); - if (txList == null) { - return 0; - } - return txList.size(); - } - - /** - * Returns total number of transactions of the specified status associated with current thread. - */ - public int totalThreadTransactionsWithStatus(final JtxStatus status) { - final ArrayList txlist = txStack.get(); - if (txlist == null) { - return 0; - } - int count = 0; - for (final JtxTransaction tx : txlist) { - if (tx.getStatus() == status) { - count++; - } - } - return count; - } - - /** - * Returns total number of active transactions associated with current thread. - */ - public int totalActiveThreadTransactions() { - return totalThreadTransactionsWithStatus(STATUS_ACTIVE); - } - - /** - * Returns true if provided transaction - * is associated with current thread. - */ - public boolean isAssociatedWithThread(final JtxTransaction tx) { - final ArrayList txList = txStack.get(); - if (txList == null) { - return false; - } - return txList.contains(tx); - } - - // ---------------------------------------------------------------- thread work - - /** - * Removes transaction association with current thread. - * Transaction should be properly handled (committed or rolledback) - * before removing from current thread. - * Also removes thread list from this thread. - */ - protected boolean removeTransaction(final JtxTransaction tx) { - final ArrayList txList = txStack.get(); - if (txList == null) { - return false; - } - - final boolean removed = txList.remove(tx); - if (removed) { - totalTransactions--; - } - - if (txList.isEmpty()) { - txStack.remove(); - } - - return removed; - } - - - /** - * Returns last transaction associated with current thread or - * null when thread has no associated transactions created - * by this transaction manager. - */ - public JtxTransaction getTransaction() { - final ArrayList txlist = txStack.get(); - if (txlist == null) { - return null; - } - if (txlist.isEmpty()) { - return null; - } - return txlist.get(txlist.size() - 1); // get last - } - - /** - * Associate transaction to current thread. - */ - protected void associateTransaction(final JtxTransaction tx) { - totalTransactions++; - ArrayList txList = txStack.get(); - if (txList == null) { - txList = new ArrayList<>(); - txStack.set(txList); - } - txList.add(tx); // add last - } - - protected int totalTransactions; - - /** - * Returns total number of transactions issued by this transaction manager. - */ - public int totalTransactions() { - return totalTransactions; - } - - // ---------------------------------------------------------------- create - - /** - * Creates new {@link jodd.jtx.JtxTransaction} instance. - * Custom implementations of manager may override this method for - * creating custom transaction instances. - */ - protected JtxTransaction createNewTransaction(final JtxTransactionMode tm, final Object scope, final boolean active) { - return new JtxTransaction(this, tm, scope, active); - } - - - // ---------------------------------------------------------------- propagation - - public JtxTransaction requestTransaction(final JtxTransactionMode mode) { - return requestTransaction(mode, null); - } - - /** - * Requests transaction with specified {@link JtxTransactionMode mode}. - * Depending on propagation behavior, it will return either existing or new transaction. - * Only one transaction can be opened over one scope. - * The exception may be thrown indicating propagation mismatch. - */ - public JtxTransaction requestTransaction(final JtxTransactionMode mode, final Object scope) { - if (log.isDebugEnabled()) { - log.debug("Requesting TX " + mode.toString()); - } - final JtxTransaction currentTx = getTransaction(); - if (!isNewTxScope(currentTx, scope)) { - return currentTx; - } - switch (mode.getPropagationBehavior()) { - case PROPAGATION_REQUIRED: return propRequired(currentTx, mode, scope); - case PROPAGATION_SUPPORTS: return propSupports(currentTx, mode, scope); - case PROPAGATION_MANDATORY: return propMandatory(currentTx, mode, scope); - case PROPAGATION_REQUIRES_NEW: return propRequiresNew(currentTx, mode, scope); - case PROPAGATION_NOT_SUPPORTED: return propNotSupported(currentTx, mode, scope); - case PROPAGATION_NEVER: return propNever(currentTx, mode, scope); - } - throw new JtxException("Invalid TX propagation value: " + mode.getPropagationBehavior().value()); - } - - /** - * Returns true if scope is specified and it is different then of existing transaction. - */ - protected boolean isNewTxScope(final JtxTransaction currentTx, final Object destScope) { - if (ignoreScope) { - return true; - } - if (currentTx == null) { - return true; - } - if (destScope == null) { - return true; - } - if (currentTx.getScope() == null) { - return true; - } - return !destScope.equals(currentTx.getScope()); - } - - /** - * Check if propagation of a transaction is possible, due to source and destination transaction modes. - * @see #setValidateExistingTransaction(boolean) - */ - protected void continueTx(final JtxTransaction sourceTx, final JtxTransactionMode destMode) { - if (!validateExistingTransaction) { - return; - } - final JtxTransactionMode sourceMode = sourceTx.getTransactionMode(); - final JtxIsolationLevel destIsolationLevel = destMode.getIsolationLevel(); - if (destIsolationLevel != ISOLATION_DEFAULT) { - final JtxIsolationLevel currentIsolationLevel = sourceMode.getIsolationLevel(); - if (currentIsolationLevel != destIsolationLevel) { - throw new JtxException("Participating TX specifies isolation level: " + destIsolationLevel + - " which is incompatible with existing TX: " + currentIsolationLevel); - } - } - if ((!destMode.isReadOnly()) && (sourceMode.isReadOnly())) { - throw new JtxException("Participating TX is not marked as read-only, but existing TX is"); - } - } - - - /** - * Propagation: REQUIRED - *

{@code
-	 * None -> T2
-	 * T1   -> T1 (cont.)
-	 * }
- */ - protected JtxTransaction propRequired(JtxTransaction currentTx, final JtxTransactionMode mode, final Object scope) { - if ((currentTx == null) || (currentTx.isNoTransaction())) { - currentTx = createNewTransaction(mode, scope, true); - } else { - continueTx(currentTx, mode); - } - return currentTx; - } - - /** - * Propagation: REQUIRES_NEW - *
{@code
-	 * None -> T2
-	 * T1   -> T2
-	 * }
- */ - @SuppressWarnings({"UnusedDeclaration"}) - protected JtxTransaction propRequiresNew(final JtxTransaction currentTx, final JtxTransactionMode mode, final Object scope) { - return createNewTransaction(mode, scope, true); - } - - /** - * Propagation: SUPPORTS - *
{@code
-	 * None -> None
-	 * T1   -> T1 (cont.)
-	 * }
- */ - protected JtxTransaction propSupports(JtxTransaction currentTx, final JtxTransactionMode mode, final Object scope) { - if ((currentTx != null) && (!currentTx.isNoTransaction())) { - continueTx(currentTx, mode); - } - if (currentTx == null) { - currentTx = createNewTransaction(mode, scope, false); - } - return currentTx; - } - - /** - * Propagation: MANDATORY - *
{@code
-	 * None -> Error
-	 * T1   -> T1 (cont.)
-	 * }
- */ - @SuppressWarnings({"UnusedDeclaration"}) - protected JtxTransaction propMandatory(final JtxTransaction currentTx, final JtxTransactionMode mode, final Object scope) { - if ((currentTx == null) || (currentTx.isNoTransaction())) { - throw new JtxException("No existing TX found for TX marked with propagation 'mandatory'"); - } - continueTx(currentTx, mode); - return currentTx; - } - - /** - * Propagation: NOT_SUPPORTED - *
{@code
-	 * None -> None
-	 * T1   -> None
-	 * }
- */ - protected JtxTransaction propNotSupported(final JtxTransaction currentTx, final JtxTransactionMode mode, final Object scope) { - if (currentTx == null) { - return createNewTransaction(mode, scope, false); - } - if (currentTx.isNoTransaction()) { - return currentTx; - } - return createNewTransaction(mode, scope, false); - } - - /** - * Propagation: NEVER - *
{@code
-	 * None -> None
-	 * T1   -> Error
-	 * }
- */ - protected JtxTransaction propNever(JtxTransaction currentTx, final JtxTransactionMode mode, final Object scope) { - if ((currentTx != null) && (!currentTx.isNoTransaction())) { - throw new JtxException("Existing TX found for TX marked with propagation 'never'"); - } - if (currentTx == null) { - currentTx = createNewTransaction(mode, scope, false); - } - return currentTx; - } - - // ---------------------------------------------------------------- resources - - /** - * Registers new {@link JtxResourceManager resource manager}. - */ - public void registerResourceManager(final JtxResourceManager resourceManager) { - if ((oneResourceManager) && (!resourceManagers.isEmpty())) { - throw new JtxException("TX manager allows only one resource manager"); - } - this.resourceManagers.put(resourceManager.getResourceType(), resourceManager); - } - - /** - * Lookups resource manager for provided type. Throws an exception if provider doesn't exists. - */ - protected JtxResourceManager lookupResourceManager(final Class resourceType) { - //noinspection unchecked - final JtxResourceManager resourceManager = this.resourceManagers.get(resourceType); - if (resourceManager == null) { - throw new JtxException("No registered resource manager for resource type: " + resourceType.getSimpleName()); - } - return resourceManager; - } - - - // ---------------------------------------------------------------- close - - /** - * Closes transaction manager. All registered {@link JtxResourceManager} - * will be closed. - */ - public void close() { - this.resourceManagers.forEachValue(resourceManager -> { - try { - resourceManager.close(); - } catch (final Exception ex) { - // ignore - } - }); - resourceManagers.clear(); - } - -} - diff --git a/jodd-jtx/src/main/java/jodd/jtx/JtxTransactionMode.java b/jodd-jtx/src/main/java/jodd/jtx/JtxTransactionMode.java deleted file mode 100644 index 58445904d..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/JtxTransactionMode.java +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx; - -import java.util.Objects; - -import static jodd.jtx.JtxIsolationLevel.ISOLATION_DEFAULT; -import static jodd.jtx.JtxPropagationBehavior.PROPAGATION_SUPPORTS; - -/** - * Transaction mode is defined by {@link JtxPropagationBehavior propagation behavior}, - * {@link JtxIsolationLevel isolation level} and read-only flag. - */ -public class JtxTransactionMode { - - public JtxTransactionMode( - final JtxPropagationBehavior propagationBehavior, - final JtxIsolationLevel isolationLevel, - final boolean readOnly, - final int timeout) { - this.propagationBehavior = propagationBehavior; - this.isolationLevel = isolationLevel; - this.readOnlyMode = readOnly; - this.timeout = timeout; - } - public JtxTransactionMode( - final JtxPropagationBehavior propagationBehavior, - final boolean readOnly) { - this.propagationBehavior = propagationBehavior; - this.isolationLevel = JtxIsolationLevel.ISOLATION_DEFAULT; - this.readOnlyMode = readOnly; - this.timeout = DEFAULT_TIMEOUT; - } - - // ---------------------------------------------------------------- propagation behaviour - - protected final JtxPropagationBehavior propagationBehavior; - - public JtxPropagationBehavior getPropagationBehavior() { - return propagationBehavior; - } - - // ---------------------------------------------------------------- isolation - - private final JtxIsolationLevel isolationLevel; - - public JtxIsolationLevel getIsolationLevel() { - return isolationLevel; - } - - // ---------------------------------------------------------------- read-only - - public static final boolean READ_ONLY = true; - public static final boolean READ_WRITE = false; - - private final boolean readOnlyMode; - - public boolean isReadOnly() { - return readOnlyMode; - } - - // ---------------------------------------------------------------- time-out - - public static final int DEFAULT_TIMEOUT = -1; - - private final int timeout; - - /** - * Returns transaction timeout in seconds. - */ - public int getTransactionTimeout() { - return timeout; - } - - // ---------------------------------------------------------------- equals & hashCode - - @Override - public boolean equals(final Object object) { - if (this == object) { - return true; - } - if (this.getClass() != object.getClass()) { - return false; - } - JtxTransactionMode mode = (JtxTransactionMode) object; - return (mode.getPropagationBehavior() == this.propagationBehavior) && - (mode.getIsolationLevel() == this.isolationLevel) && - (mode.isReadOnly() == this.readOnlyMode) && - (mode.getTransactionTimeout() == this.timeout); - } - - @Override - public int hashCode() { - return Objects.hash(propagationBehavior, readOnlyMode, isolationLevel, timeout); - } - - // ---------------------------------------------------------------- defaults - - public static final JtxTransactionMode PROPAGATION_SUPPORTS_READ_ONLY = new JtxTransactionMode(PROPAGATION_SUPPORTS, ISOLATION_DEFAULT, READ_ONLY, DEFAULT_TIMEOUT); - - - // ---------------------------------------------------------------- to string - - /** - * Returns tx description for debugging purposes. - */ - @Override - public String toString() { - return "jtx{" + propagationBehavior + - ',' + (readOnlyMode ? "readonly" : "readwrite") + - ',' + isolationLevel.toString() + ',' + - timeout + '}'; - } -} diff --git a/jodd-jtx/src/main/java/jodd/jtx/meta/ReadOnlyTransaction.java b/jodd-jtx/src/main/java/jodd/jtx/meta/ReadOnlyTransaction.java deleted file mode 100644 index 7d6e460a8..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/meta/ReadOnlyTransaction.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.meta; - -import jodd.jtx.JtxIsolationLevel; -import jodd.jtx.JtxPropagationBehavior; -import jodd.jtx.JtxTransactionMode; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Read-only PROPAGATION_REQUIRED tx annotation marker. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -@Transaction(readOnly = true) -public @interface ReadOnlyTransaction { - - JtxPropagationBehavior propagation() default JtxPropagationBehavior.PROPAGATION_REQUIRED; - - JtxIsolationLevel isolation() default JtxIsolationLevel.ISOLATION_DEFAULT; - - int timeout() default JtxTransactionMode.DEFAULT_TIMEOUT; - -} diff --git a/jodd-jtx/src/main/java/jodd/jtx/meta/ReadWriteTransaction.java b/jodd-jtx/src/main/java/jodd/jtx/meta/ReadWriteTransaction.java deleted file mode 100644 index fa592ad36..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/meta/ReadWriteTransaction.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.meta; - -import jodd.jtx.JtxIsolationLevel; -import jodd.jtx.JtxPropagationBehavior; -import jodd.jtx.JtxTransactionMode; -import jodd.jtx.meta.Transaction; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Read-write PROPAGATION_REQUIRED tx annotation marker. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -@Transaction(readOnly = false) -public @interface ReadWriteTransaction { - - JtxPropagationBehavior propagation() default JtxPropagationBehavior.PROPAGATION_REQUIRED; - - JtxIsolationLevel isolation() default JtxIsolationLevel.ISOLATION_DEFAULT; - - int timeout() default JtxTransactionMode.DEFAULT_TIMEOUT; - -} diff --git a/jodd-jtx/src/main/java/jodd/jtx/meta/Transaction.java b/jodd-jtx/src/main/java/jodd/jtx/meta/Transaction.java deleted file mode 100644 index afddc53c2..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/meta/Transaction.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.meta; - -import jodd.jtx.JtxPropagationBehavior; -import jodd.jtx.JtxIsolationLevel; -import jodd.jtx.JtxTransactionMode; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.annotation.ElementType; - -/** - * Transaction method annotation for external use. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) -public @interface Transaction { - - /** - * Transaction propagation mode. Default value: PROPAGATION_SUPPORTS. - */ - JtxPropagationBehavior propagation() default JtxPropagationBehavior.PROPAGATION_SUPPORTS; - - /** - * Transaction isolation mode. Default value: ISOLATION_DEFAULT. - */ - JtxIsolationLevel isolation() default JtxIsolationLevel.ISOLATION_DEFAULT; - - /** - * Transaction read-only mode. Default value: true - */ - boolean readOnly() default true; - - /** - * Transaction time-out time in seconds. - */ - int timeout() default JtxTransactionMode.DEFAULT_TIMEOUT; - -} diff --git a/jodd-jtx/src/main/java/jodd/jtx/meta/TransactionAnnotationValues.java b/jodd-jtx/src/main/java/jodd/jtx/meta/TransactionAnnotationValues.java deleted file mode 100644 index 79f4e3a34..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/meta/TransactionAnnotationValues.java +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.meta; - -import jodd.jtx.JtxIsolationLevel; -import jodd.jtx.JtxPropagationBehavior; -import jodd.jtx.JtxTransactionMode; -import jodd.util.AnnotationParser; - -import java.lang.annotation.Annotation; -import java.lang.reflect.AnnotatedElement; - -public class TransactionAnnotationValues implements Transaction { - - /** - * Shortcut methods for given annotation class. - */ - public static AnnotationParser parserFor(final Class annotationClass) { - return new AnnotationParser(annotationClass, Transaction.class); - } - - /** - * Shortcut for checking the annotation on annotated element and returning either the values or {@code null}. - */ - public static TransactionAnnotationValues of(final AnnotationParser annotationParser, final AnnotatedElement annotatedElement) { - if (!annotationParser.hasAnnotationOn(annotatedElement)) { - return null; - } - return new TransactionAnnotationValues(annotationParser.of(annotatedElement)); - } - - protected final Class annotationType; - protected final JtxPropagationBehavior propagation; - protected final JtxIsolationLevel isolation; - protected final boolean readOnly; - protected final int timeout; - - private TransactionAnnotationValues(final AnnotationParser.Reader reader) { - this.annotationType = reader.annotationType(); - - this.propagation = (JtxPropagationBehavior) reader.readElement("propagation"); - - this.isolation = (JtxIsolationLevel) reader.readElement("isolation"); - - this.readOnly = reader.readBoolean("readOnly", false); - - this.timeout = reader.readInt("timeout", JtxTransactionMode.DEFAULT_TIMEOUT); - } - - - @Override - public JtxPropagationBehavior propagation() { - return propagation; - } - - @Override - public JtxIsolationLevel isolation() { - return isolation; - } - - @Override - public boolean readOnly() { - return readOnly; - } - - @Override - public int timeout() { - return timeout; - } - - @Override - public Class annotationType() { - return null; - } -} diff --git a/jodd-jtx/src/main/java/jodd/jtx/meta/package-info.java b/jodd-jtx/src/main/java/jodd/jtx/meta/package-info.java deleted file mode 100644 index 04dc7eb31..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/meta/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Transaction annotations. - */ -package jodd.jtx.meta; \ No newline at end of file diff --git a/jodd-jtx/src/main/java/jodd/jtx/package-info.java b/jodd-jtx/src/main/java/jodd/jtx/package-info.java deleted file mode 100644 index a68cc7fe2..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/package-info.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Quick and dirty Java transactions management. No JTA, no two-phase commit, no XA, no theory; - * but - pragmatic. - */ -package jodd.jtx; \ No newline at end of file diff --git a/jodd-jtx/src/main/java/jodd/jtx/proxy/AnnotationTxAdvice.java b/jodd-jtx/src/main/java/jodd/jtx/proxy/AnnotationTxAdvice.java deleted file mode 100644 index b68df2c3f..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/proxy/AnnotationTxAdvice.java +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.proxy; - -import jodd.proxetta.ProxyAdvice; - -import static jodd.proxetta.ProxyTarget.createArgumentsClassArray; -import static jodd.proxetta.ProxyTarget.targetClass; -import static jodd.proxetta.ProxyTarget.targetMethodDescription; -import static jodd.proxetta.ProxyTarget.targetMethodName; -import static jodd.proxetta.ProxyTarget.invoke; -import jodd.jtx.JtxTransactionMode; -import jodd.jtx.JtxTransaction; - -import static jodd.jtx.proxy.AnnotationTxAdviceSupport.manager; - -/** - * Advice that reads transaction annotations and manage transactions over method invocation. - */ -public class AnnotationTxAdvice implements ProxyAdvice { - - public Object execute() { - Class type = targetClass(); - String methodName = targetMethodName(); - Class[] methodArgsTypes = createArgumentsClassArray(); - String methodDescription = targetMethodDescription(); - - // read transaction mode from annotation - JtxTransactionMode txMode = manager.getTxMode(type, methodName, methodArgsTypes, methodDescription); - - // request transaction - JtxTransaction tx = null; - try { - String scope = manager.resolveScope(type, methodName); - tx = manager.getJtxWorker().maybeRequestTransaction(txMode, scope); - Object result = invoke(); - manager.getJtxWorker().maybeCommitTransaction(tx); - return result; - } catch (Exception ex) { - manager.getJtxWorker().markOrRollbackTransaction(tx, ex); - throw ex; - } - - } -} diff --git a/jodd-jtx/src/main/java/jodd/jtx/proxy/AnnotationTxAdviceManager.java b/jodd-jtx/src/main/java/jodd/jtx/proxy/AnnotationTxAdviceManager.java deleted file mode 100644 index 34528527d..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/proxy/AnnotationTxAdviceManager.java +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.proxy; - -import jodd.jtx.JtxTransactionMode; -import jodd.jtx.meta.ReadOnlyTransaction; -import jodd.jtx.meta.ReadWriteTransaction; -import jodd.jtx.meta.Transaction; -import jodd.jtx.meta.TransactionAnnotationValues; -import jodd.jtx.worker.LeanJtxWorker; -import jodd.proxetta.ProxettaException; -import jodd.util.AnnotationParser; -import jodd.util.StringUtil; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - -/** - * Manager for {@link jodd.jtx.proxy.AnnotationTxAdvice}. - */ -public class AnnotationTxAdviceManager { - - protected static final String JTXCTX_PATTERN_CLASS = "$class"; - protected static final String JTXCTX_PATTERN_METHOD = "$method"; - - protected final Map txmap = new HashMap<>(); - - protected final LeanJtxWorker jtxWorker; - - protected final JtxTransactionMode defaultTransactionMode; - - protected final String scopePattern; - - protected Class[] annotations; - protected AnnotationParser[] annotationParsers; - - // ---------------------------------------------------------------- ctors - - public AnnotationTxAdviceManager(final LeanJtxWorker jtxWorker) { - this(jtxWorker, JTXCTX_PATTERN_CLASS + '#' + JTXCTX_PATTERN_METHOD, null); - } - - public AnnotationTxAdviceManager(final LeanJtxWorker jtxWorker, final String scopePattern) { - this(jtxWorker, scopePattern, null); - } - - @SuppressWarnings( {"unchecked"}) - public AnnotationTxAdviceManager(final LeanJtxWorker jtxWorker, final String scopePattern, final JtxTransactionMode defaultTxMode) { - this.jtxWorker = jtxWorker; - this.defaultTransactionMode = defaultTxMode == null ? JtxTransactionMode.PROPAGATION_SUPPORTS_READ_ONLY : defaultTxMode; - this.scopePattern = scopePattern; - - registerAnnotations(new Class[] { - Transaction.class, ReadWriteTransaction.class, ReadOnlyTransaction.class - }); - } - - // ---------------------------------------------------------------- methods - - /** - * Returns tx worker. - */ - public LeanJtxWorker getJtxWorker() { - return jtxWorker; - } - - /** - * Returns default transaction mode. - */ - public JtxTransactionMode getDefaultTransactionMode() { - return defaultTransactionMode; - } - - /** - * Resolves tx scope from scope pattern. - */ - public String resolveScope(final Class type, final String methodName) { - if (scopePattern == null) { - return null; - } - String ctx = scopePattern; - ctx = StringUtil.replace(ctx, JTXCTX_PATTERN_CLASS, type.getName()); - ctx = StringUtil.replace(ctx, JTXCTX_PATTERN_METHOD, methodName); - return ctx; - } - - /** - * Reads transaction mode from method annotation. Annotations are cached for better performances. - * @param type target class - * @param methodName target method name over which the transaction should be wrapped - * @param methodArgTypes types of arguments, used to find the method - * @param unique unique method fingerprint that contains return and arguments type information - */ - public synchronized JtxTransactionMode getTxMode(final Class type, final String methodName, final Class[] methodArgTypes, final String unique) { - final String signature = type.getName() + '#' + methodName + '%' + unique; - JtxTransactionMode txMode = txmap.get(signature); - if (txMode == null) { - if (!txmap.containsKey(signature)) { - - final Method m; - try { - m = type.getMethod(methodName, methodArgTypes); - } catch (final NoSuchMethodException nsmex) { - throw new ProxettaException(nsmex); - } - - final TransactionAnnotationValues txAnn = readTransactionAnnotation(m); - if (txAnn != null) { - txMode = new JtxTransactionMode( - txAnn.propagation(), - txAnn.isolation(), - txAnn.readOnly(), - txAnn.timeout() - ); - } else { - txMode = defaultTransactionMode; - } - txmap.put(signature, txMode); - } - } - return txMode; - } - - // ---------------------------------------------------------------- tx annotations - - /** - * Returns current TX annotations. - */ - public Class[] getAnnotations() { - return annotations; - } - - /** - * Registers new TX annotations. - */ - @SuppressWarnings( {"unchecked"}) - public void registerAnnotations(final Class[] annotations) { - this.annotations = annotations; - - this.annotationParsers = new AnnotationParser[annotations.length]; - - for (int i = 0; i < annotations.length; i++) { - annotationParsers[i] = TransactionAnnotationValues.parserFor(annotations[i]); - } - } - - /** - * Finds TX annotation. - */ - protected TransactionAnnotationValues readTransactionAnnotation(final Method method) { - for (final AnnotationParser annotationParser : annotationParsers) { - final TransactionAnnotationValues tad = TransactionAnnotationValues.of(annotationParser, method); - if (tad != null) { - return tad; - } - } - return null; - } - -} diff --git a/jodd-jtx/src/main/java/jodd/jtx/proxy/AnnotationTxAdviceSupport.java b/jodd-jtx/src/main/java/jodd/jtx/proxy/AnnotationTxAdviceSupport.java deleted file mode 100644 index 8629ac334..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/proxy/AnnotationTxAdviceSupport.java +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.proxy; - -/** - * Support class for {@link jodd.jtx.proxy.AnnotationTxAdvice}. - * It represent a connection point from the advice's code and the rest of the application. - */ -public class AnnotationTxAdviceSupport { - - /** - * Manager that will be used by advice. - */ - public static AnnotationTxAdviceManager manager; - -} \ No newline at end of file diff --git a/jodd-jtx/src/main/java/jodd/jtx/proxy/package-info.java b/jodd-jtx/src/main/java/jodd/jtx/proxy/package-info.java deleted file mode 100644 index f6de12862..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/proxy/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Advices and managers for annotation managed transactions. - */ -package jodd.jtx.proxy; \ No newline at end of file diff --git a/jodd-jtx/src/main/java/jodd/jtx/worker/LeanJtxWorker.java b/jodd-jtx/src/main/java/jodd/jtx/worker/LeanJtxWorker.java deleted file mode 100644 index 2a3f04bf7..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/worker/LeanJtxWorker.java +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.worker; - -import jodd.jtx.JtxTransaction; -import jodd.jtx.JtxTransactionManager; -import jodd.jtx.JtxTransactionMode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Lean transaction worker helps dealing transactions when they were requested - * in several places, usually in separated methods. This worker knows when requested transaction is - * the same as current one, or completely new. It might be useful for aspects. - */ -public class LeanJtxWorker { - - private static final Logger log = LoggerFactory.getLogger(LeanJtxWorker.class); - - protected final JtxTransactionManager txManager; - - public LeanJtxWorker(final JtxTransactionManager txManager) { - this.txManager = txManager; - } - - /** - * Returns transaction manager. - */ - public JtxTransactionManager getTransactionManager() { - return txManager; - } - - - /** - * Returns current transaction or null if there is no transaction at the moment. - */ - public JtxTransaction getCurrentTransaction() { - return txManager.getTransaction(); - } - - /** - * Requests for transaction and returns non-null value only when new transaction - * is created! When null is returned, transaction may be get by - * {@link #getCurrentTransaction()}. - * - * @see jodd.jtx.JtxTransactionManager#requestTransaction(jodd.jtx.JtxTransactionMode) - */ - public JtxTransaction maybeRequestTransaction(final JtxTransactionMode txMode, final Object scope) { - if (txMode == null) { - return null; - } - final JtxTransaction currentTx = txManager.getTransaction(); - final JtxTransaction requestedTx = txManager.requestTransaction(txMode, scope); - if (currentTx == requestedTx) { - return null; - } - return requestedTx; - } - - - /** - * Commits transaction if created in the same level where this method is invoked. - * Returns true if transaction was actually committed or false - * if transaction was not created on this level. - */ - public boolean maybeCommitTransaction(final JtxTransaction tx) { - if (tx == null) { - return false; - } - log.debug("commit tx"); - - tx.commit(); - return true; - } - - /** - * Rollbacks transaction if created in the same scope where this method is invoked. - * If not, current transaction is marked for rollback. - * Returns true if transaction was actually roll backed. - */ - public boolean markOrRollbackTransaction(JtxTransaction tx, final Throwable cause) { - if (tx == null) { - tx = getCurrentTransaction(); - if (tx == null) { - return false; - } - log.debug("set rollback only tx"); - - tx.setRollbackOnly(cause); - return false; - } - log.debug("rollback tx"); - - tx.rollback(); - return true; - } -} diff --git a/jodd-jtx/src/main/java/jodd/jtx/worker/package-info.java b/jodd-jtx/src/main/java/jodd/jtx/worker/package-info.java deleted file mode 100644 index 0b1cd6605..000000000 --- a/jodd-jtx/src/main/java/jodd/jtx/worker/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Transaction workers utilizes usage of transactions in certain way. - */ -package jodd.jtx.worker; \ No newline at end of file diff --git a/jodd-jtx/src/main/resources/META-INF/LICENSE b/jodd-jtx/src/main/resources/META-INF/LICENSE deleted file mode 100644 index a040a3b95..000000000 --- a/jodd-jtx/src/main/resources/META-INF/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2003-present, Jodd Team (https://jodd.org) -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, -this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright -notice, this list of conditions and the following disclaimer in the -documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. diff --git a/jodd-jtx/src/test/java/jodd/jtx/JtxManagerTest.java b/jodd-jtx/src/test/java/jodd/jtx/JtxManagerTest.java deleted file mode 100644 index bbb86ec9d..000000000 --- a/jodd-jtx/src/test/java/jodd/jtx/JtxManagerTest.java +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx; - -import jodd.exception.UncheckedException; -import jodd.jtx.fixtures.WorkResourceManager; -import jodd.jtx.fixtures.WorkSession; -import jodd.jtx.worker.LeanJtxWorker; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -class JtxManagerTest { - - private JtxTransactionManager createManager() { - JtxTransactionManager jtxManager = new JtxTransactionManager(); - jtxManager.registerResourceManager(new WorkResourceManager()); - return jtxManager; - } - - private LeanJtxWorker createWorker() { - return new LeanJtxWorker(createManager()); - } - - // ---------------------------------------------------------------- ro - - @Test - void testReadOnly() { - JtxTransactionManager manager = createManager(); - JtxTransaction jtx = manager.requestTransaction(new JtxTransactionMode(JtxPropagationBehavior.PROPAGATION_REQUIRED, true)); - WorkSession work = jtx.requestResource(WorkSession.class); - - WorkSession work2 = jtx.requestResource(WorkSession.class); - assertSame(work2, work); - - try { - work.writeValue("new value"); - fail("error"); - } catch (UncheckedException ignored) { - } - - jtx.commit(); - manager.close(); - } - - // ---------------------------------------------------------------- rollback - - @Test - void testRollback() { - JtxTransactionManager manager = createManager(); - JtxTransaction jtx = manager.requestTransaction(new JtxTransactionMode(JtxPropagationBehavior.PROPAGATION_REQUIRED, false)); - WorkSession work = jtx.requestResource(WorkSession.class); - - work.writeValue("new value"); - jtx.rollback(); - assertFalse(work.readValue().equals("new value")); - - manager.close(); - - } - - - // ---------------------------------------------------------------- required - - @Test - void testPropagationRequired() { - - JtxTransactionManager manager = createManager(); - - JtxTransaction jtx1 = manager.requestTransaction(new JtxTransactionMode(JtxPropagationBehavior.PROPAGATION_REQUIRED, false)); - WorkSession work1 = jtx1.requestResource(WorkSession.class); - assertEquals(1, manager.totalTransactions()); - work1.writeValue("one"); - assertEquals("[1] one", work1.readValue()); - - JtxTransaction jtx2 = manager.requestTransaction(new JtxTransactionMode(JtxPropagationBehavior.PROPAGATION_REQUIRED, false)); - assertEquals(1, manager.totalTransactions()); - assertSame(jtx2, jtx1); - - WorkSession work2 = jtx2.requestResource(WorkSession.class); - assertSame(work2, work1); - work2.writeValue("two"); - assertEquals("[1] two", work2.readValue()); - //jtx2.commit(); - - work1.writeValue("three"); - assertEquals("[1] three", work1.readValue()); - - jtx1.commit(); - - assertTrue(jtx1.isCommitted()); - } - - @Test - void testPropagationRequiredWithWorker() { - - LeanJtxWorker worker = createWorker(); - - JtxTransaction jtx1 = worker.maybeRequestTransaction(new JtxTransactionMode(JtxPropagationBehavior.PROPAGATION_REQUIRED, false), null); - WorkSession work1 = jtx1.requestResource(WorkSession.class); - assertEquals(1, worker.getTransactionManager().totalTransactions()); - work1.writeValue("one"); - assertEquals("[1] one", work1.readValue()); - - JtxTransaction jtx2 = worker.maybeRequestTransaction(new JtxTransactionMode(JtxPropagationBehavior.PROPAGATION_REQUIRED, false), null); - assertEquals(1, worker.getTransactionManager().totalTransactions()); - assertNull(jtx2); - - WorkSession work2 = jtx1.requestResource(WorkSession.class); - assertSame(work2, work1); - work2.writeValue("two"); - assertEquals("[1] two", work2.readValue()); - assertFalse(worker.maybeCommitTransaction(jtx2)); - - work1.writeValue("three"); - assertEquals("[1] three", work1.readValue()); - assertTrue(worker.maybeCommitTransaction(jtx1)); - } - - // ---------------------------------------------------------------- supports - - @Test - void testPropagationSupports() { - - JtxTransactionManager manager = createManager(); - - JtxTransaction jtx1 = manager.requestTransaction(new JtxTransactionMode(JtxPropagationBehavior.PROPAGATION_SUPPORTS, false)); - WorkSession work1 = jtx1.requestResource(WorkSession.class); - assertEquals(1, manager.totalTransactions()); - work1.writeValue("one"); - assertEquals("one", work1.readValue()); - - jtx1.commit(); - - assertTrue(jtx1.isCommitted()); - } - - - // ---------------------------------------------------------------- required - - @Test - void testPropagationRequiresNew() { - - JtxTransactionManager manager = createManager(); - - JtxTransaction jtx1 = manager.requestTransaction(new JtxTransactionMode(JtxPropagationBehavior.PROPAGATION_REQUIRED, false)); - WorkSession work1 = jtx1.requestResource(WorkSession.class); - assertEquals(1, manager.totalTransactions()); - work1.writeValue("one"); - assertEquals("[1] one", work1.readValue()); - - JtxTransaction jtx2 = manager.requestTransaction(new JtxTransactionMode(JtxPropagationBehavior.PROPAGATION_REQUIRES_NEW, false)); - assertEquals(2, manager.totalTransactions()); - assertNotSame(jtx2, jtx1); - - WorkSession work2 = jtx2.requestResource(WorkSession.class); - assertNotSame(work2, work1); - work2.writeValue("two"); - assertEquals("[2] two", work2.readValue()); - jtx2.commit(); - - work1.writeValue("three"); - assertEquals("[1] three", work1.readValue()); - - jtx1.commit(); - - assertTrue(jtx1.isCommitted()); - - assertEquals("[1] three", WorkSession.getPersistedValue()); - } - - -} diff --git a/jodd-jtx/src/test/java/jodd/jtx/JtxResourceTest.java b/jodd-jtx/src/test/java/jodd/jtx/JtxResourceTest.java deleted file mode 100644 index 14faa52d8..000000000 --- a/jodd-jtx/src/test/java/jodd/jtx/JtxResourceTest.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx; - -import jodd.jtx.fixtures.Foo; -import jodd.jtx.fixtures.FooRes; -import jodd.jtx.fixtures.FooResourceManager; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class JtxResourceTest { - - private JtxTransactionManager createManager() { - final JtxTransactionManager jtxManager = new JtxTransactionManager(); - jtxManager.registerResourceManager(new FooResourceManager()); - return jtxManager; - } - - // ---------------------------------------------------------------- ro - - @Test - void isSameTypeAsResourceTest() { - final JtxTransactionManager manager = createManager(); - final JtxTransaction jtx = manager.requestTransaction(new JtxTransactionMode(JtxPropagationBehavior.PROPAGATION_REQUIRED, true)); - - final FooRes foo = jtx.requestResource(FooRes.class); - assertNotNull(foo); - assertTrue(foo instanceof Foo); - assertEquals("Foo", foo.value()); - } - -} diff --git a/jodd-jtx/src/test/java/jodd/jtx/JtxThreadTest.java b/jodd-jtx/src/test/java/jodd/jtx/JtxThreadTest.java deleted file mode 100644 index 955ffe8ef..000000000 --- a/jodd-jtx/src/test/java/jodd/jtx/JtxThreadTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package jodd.jtx; - -import jodd.jtx.fixtures.WorkResourceManager; -import jodd.jtx.fixtures.WorkSession; -import jodd.jtx.worker.LeanJtxWorker; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import static jodd.jtx.JtxPropagationBehavior.*; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class JtxThreadTest { - - public static final int COUNT = 2_000_000; - - @Test - void testMultithreadsAndJtx() throws InterruptedException { - JtxTransactionManager jtxManager = new JtxTransactionManager(); - WorkResourceManager workResourceManager = new WorkResourceManager(); - - jtxManager.registerResourceManager(workResourceManager); - LeanJtxWorker x = new LeanJtxWorker(jtxManager); - - ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(200); - CountDownLatch latch = new CountDownLatch(COUNT); - - for (int i = 0; i < COUNT; i++) { - executor.execute(() -> { - JtxTransaction jtx = askForTx(x); - WorkSession work = jtx.requestResource(WorkSession.class); - - JtxTransaction jtx2 = askForTx(x); - - work.writeValue("X"); - - byeTx(x, jtx2); - byeTx(x, jtx); - - latch.countDown(); - }); - } - - assertTrue(latch.await(5, TimeUnit.SECONDS)); - assertEquals(0, workResourceManager.txno.get()); - } - - private JtxTransaction askForTx(LeanJtxWorker w) { - return w.maybeRequestTransaction(new JtxTransactionMode(PROPAGATION_REQUIRED, false), this); - } - - private void byeTx(LeanJtxWorker w, JtxTransaction jtxTransaction) { - w.maybeCommitTransaction(jtxTransaction); - } -} diff --git a/jodd-jtx/src/test/java/jodd/jtx/JtxTimeoutTest.java b/jodd-jtx/src/test/java/jodd/jtx/JtxTimeoutTest.java deleted file mode 100644 index f2b1be501..000000000 --- a/jodd-jtx/src/test/java/jodd/jtx/JtxTimeoutTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package jodd.jtx; - -import jodd.jtx.fixtures.WorkResourceManager; -import jodd.jtx.fixtures.WorkSession; -import jodd.jtx.worker.LeanJtxWorker; -import jodd.util.ThreadUtil; -import org.junit.jupiter.api.Test; - -import static jodd.jtx.JtxIsolationLevel.ISOLATION_DEFAULT; -import static jodd.jtx.JtxPropagationBehavior.PROPAGATION_REQUIRED; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -class JtxTimeoutTest { - - @Test - void testTimeOutAndNewTx() { - final JtxTransactionManager jtxManager = new JtxTransactionManager(); - final WorkResourceManager workResourceManager = new WorkResourceManager(); - - jtxManager.registerResourceManager(workResourceManager); - final LeanJtxWorker x = new LeanJtxWorker(jtxManager); - - final JtxTransaction jtx = askForTx(x, 1); - final WorkSession work = jtx.requestResource(WorkSession.class); - - work.writeValue("X"); - ThreadUtil.sleep(1100); - - byeTx(x, jtx); - - // new transaction, the previous one should be cleared! - final JtxTransaction newJtx = askForTx(x, 1); - final WorkSession newWork = newJtx.requestResource(WorkSession.class); - assertNotNull(newJtx); - byeTx(x, newJtx); - - assertEquals(0, workResourceManager.txno.get()); - } - - private JtxTransaction askForTx(final LeanJtxWorker w, final int timeout) { - return w.maybeRequestTransaction(new JtxTransactionMode(PROPAGATION_REQUIRED, ISOLATION_DEFAULT, false, timeout), this); - } - - private void byeTx(final LeanJtxWorker w, final JtxTransaction jtxTransaction) { - try { - w.maybeCommitTransaction(jtxTransaction); - } - catch (final Exception cause) { - w.markOrRollbackTransaction(jtxTransaction, cause); - } - } -} diff --git a/jodd-jtx/src/test/java/jodd/jtx/fixtures/Foo.java b/jodd-jtx/src/test/java/jodd/jtx/fixtures/Foo.java deleted file mode 100644 index d16969dc8..000000000 --- a/jodd-jtx/src/test/java/jodd/jtx/fixtures/Foo.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.fixtures; - -public class Foo implements FooRes { - @Override - public String value() { - return this.getClass().getSimpleName(); - } -} diff --git a/jodd-jtx/src/test/java/jodd/jtx/fixtures/FooRes.java b/jodd-jtx/src/test/java/jodd/jtx/fixtures/FooRes.java deleted file mode 100644 index 02cd071ac..000000000 --- a/jodd-jtx/src/test/java/jodd/jtx/fixtures/FooRes.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.fixtures; - -public interface FooRes { - public String value(); -} diff --git a/jodd-jtx/src/test/java/jodd/jtx/fixtures/FooResourceManager.java b/jodd-jtx/src/test/java/jodd/jtx/fixtures/FooResourceManager.java deleted file mode 100644 index df738890e..000000000 --- a/jodd-jtx/src/test/java/jodd/jtx/fixtures/FooResourceManager.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.fixtures; - -import jodd.jtx.JtxResourceManager; -import jodd.jtx.JtxTransactionMode; - -public class FooResourceManager implements JtxResourceManager { - - @Override - public Class getResourceType() { - return FooRes.class; - } - - @Override - public FooRes beginTransaction(final JtxTransactionMode jtxMode, final boolean active) { - return new Foo(); - } - - @Override - public void commitTransaction(final FooRes resource) { - } - - @Override - public void rollbackTransaction(final FooRes resource) { - } - - @Override - public void close() { - } -} diff --git a/jodd-jtx/src/test/java/jodd/jtx/fixtures/WorkResourceManager.java b/jodd-jtx/src/test/java/jodd/jtx/fixtures/WorkResourceManager.java deleted file mode 100644 index 56108929c..000000000 --- a/jodd-jtx/src/test/java/jodd/jtx/fixtures/WorkResourceManager.java +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.fixtures; - -import jodd.jtx.JtxResourceManager; -import jodd.jtx.JtxTransactionMode; - -import java.util.concurrent.atomic.AtomicInteger; - -public class WorkResourceManager implements JtxResourceManager { - - public AtomicInteger txno = new AtomicInteger(); - - @Override - public Class getResourceType() { - return WorkSession.class; - } - - @Override - public WorkSession beginTransaction(final JtxTransactionMode jtxMode, final boolean active) { - if (!active) { - return new WorkSession(); - } - final WorkSession work = new WorkSession(txno.incrementAndGet()); - work.readOnly = jtxMode.isReadOnly(); - return work; - } - - @Override - public void commitTransaction(final WorkSession resource) { - resource.done(); - txno.decrementAndGet(); - } - - @Override - public void rollbackTransaction(final WorkSession resource) { - resource.back(); - txno.decrementAndGet(); - } - - @Override - public void close() { - } - -} diff --git a/jodd-jtx/src/test/java/jodd/jtx/fixtures/WorkSession.java b/jodd-jtx/src/test/java/jodd/jtx/fixtures/WorkSession.java deleted file mode 100644 index 8862c3afa..000000000 --- a/jodd-jtx/src/test/java/jodd/jtx/fixtures/WorkSession.java +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.fixtures; - -import jodd.exception.UncheckedException; - -/** - * Transactional resource, encapsulates working session. - */ -public class WorkSession { - - static String persistedValue = "The big bang theory"; - - public static String getPersistedValue() { - return persistedValue; - } - - public WorkSession() { - } - - public WorkSession(int txno) { - this.txno = txno; - } - - String sessionValue; - boolean readOnly; - public int txno; - - public void writeValue(String value) { - if (txno == 0) { // no transaction - persistedValue = value; - return; - } - // under transaction - if (readOnly) { - throw new UncheckedException(); - } - sessionValue = "[" + txno + "] " + value; - } - - public String readValue() { - if (sessionValue != null) { - return sessionValue; - } - return persistedValue; - } - - // aka commit - public void done() { - if (sessionValue != null) { - persistedValue = sessionValue; - } - sessionValue = null; - } - - // aka rollback - public void back() { - sessionValue = null; - } -} diff --git a/jodd-jtx/src/test/java/jodd/jtx/meta/CustomTransaction.java b/jodd-jtx/src/test/java/jodd/jtx/meta/CustomTransaction.java deleted file mode 100644 index aa0ee762c..000000000 --- a/jodd-jtx/src/test/java/jodd/jtx/meta/CustomTransaction.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.meta; - -import jodd.jtx.JtxIsolationLevel; -import jodd.jtx.JtxPropagationBehavior; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -@Transaction(readOnly = false) -public @interface CustomTransaction { - - JtxPropagationBehavior propagation() default JtxPropagationBehavior.PROPAGATION_REQUIRED; - - JtxIsolationLevel isolation() default JtxIsolationLevel.ISOLATION_DEFAULT; - -} \ No newline at end of file diff --git a/jodd-jtx/src/test/java/jodd/jtx/meta/TransactionAnnotationTest.java b/jodd-jtx/src/test/java/jodd/jtx/meta/TransactionAnnotationTest.java deleted file mode 100644 index 94e28fd0a..000000000 --- a/jodd-jtx/src/test/java/jodd/jtx/meta/TransactionAnnotationTest.java +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.jtx.meta; - -import jodd.util.AnnotationParser; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Method; - -import static jodd.jtx.JtxIsolationLevel.ISOLATION_DEFAULT; -import static jodd.jtx.JtxIsolationLevel.ISOLATION_SERIALIZABLE; -import static jodd.jtx.JtxPropagationBehavior.PROPAGATION_MANDATORY; -import static jodd.jtx.JtxPropagationBehavior.PROPAGATION_REQUIRED; -import static jodd.jtx.JtxPropagationBehavior.PROPAGATION_REQUIRES_NEW; -import static jodd.jtx.JtxPropagationBehavior.PROPAGATION_SUPPORTS; -import static org.junit.jupiter.api.Assertions.assertEquals; - -class TransactionAnnotationTest { - - @Transaction - public void hello() { - } - - @Transaction(readOnly = false, isolation = ISOLATION_SERIALIZABLE, propagation = PROPAGATION_REQUIRES_NEW, timeout = 1000) - public void hello2() { - } - - @CustomTransaction - public void hello3() { - } - - @CustomTransaction(propagation = PROPAGATION_MANDATORY) - public void hello4() { - } - - - @Test - void testTransactionAnnotationOnly() throws NoSuchMethodException { - final AnnotationParser annotationParser = TransactionAnnotationValues.parserFor(Transaction.class); - - Method method = this.getClass().getMethod("hello"); - TransactionAnnotationValues annotationData = TransactionAnnotationValues.of(annotationParser, method); - - assertEquals(ISOLATION_DEFAULT, annotationData.isolation); - assertEquals(PROPAGATION_SUPPORTS, annotationData.propagation); - assertEquals(true, annotationData.readOnly); - assertEquals(-1, annotationData.timeout); - - method = this.getClass().getMethod("hello2"); - annotationData = TransactionAnnotationValues.of(annotationParser, method); - - assertEquals(ISOLATION_SERIALIZABLE, annotationData.isolation); - assertEquals(PROPAGATION_REQUIRES_NEW, annotationData.propagation); - assertEquals(false, annotationData.readOnly); - assertEquals(1000, annotationData.timeout); - } - - @Test - void testCustomTransactionAnnotation() throws NoSuchMethodException { - final AnnotationParser annotationParser = TransactionAnnotationValues.parserFor(CustomTransaction.class); - - Method method = this.getClass().getMethod("hello3"); - TransactionAnnotationValues annotationData = TransactionAnnotationValues.of(annotationParser, method); - - assertEquals(ISOLATION_DEFAULT, annotationData.isolation); - assertEquals(PROPAGATION_REQUIRED, annotationData.propagation); - assertEquals(false, annotationData.readOnly); - assertEquals(-1, annotationData.timeout); - - method = this.getClass().getMethod("hello4"); - annotationData = TransactionAnnotationValues.of(annotationParser, method); - - assertEquals(ISOLATION_DEFAULT, annotationData.isolation); - assertEquals(PROPAGATION_MANDATORY, annotationData.propagation); - assertEquals(false, annotationData.readOnly); - assertEquals(-1, annotationData.timeout); - } - - -} diff --git a/jodd-madvoc/build.gradle b/jodd-madvoc/build.gradle index 3aa9c9337..41ff721f8 100644 --- a/jodd-madvoc/build.gradle +++ b/jodd-madvoc/build.gradle @@ -5,10 +5,10 @@ ext.moduleDescription = 'Jodd Madvoc is elegant web MVC framework that uses CoC dependencies { api project(':jodd-core') api project(':jodd-servlet') - api project(':jodd-petite') - api project(':jodd-proxetta') api 'org.jodd:jodd-json:6.0.2' api 'org.jodd:jodd-props:6.0.1' + api 'org.jodd:jodd-petite:6.0.0' + api 'org.jodd:jodd-proxetta:6.0.0' api 'org.slf4j:slf4j-api:1.7.30' provided lib.servlet diff --git a/jodd-madvoc/src/test/java/jodd/madvoc/action/ItemAction.java b/jodd-madvoc/src/test/java/jodd/madvoc/action/ItemAction.java deleted file mode 100644 index 7b3eb354b..000000000 --- a/jodd-madvoc/src/test/java/jodd/madvoc/action/ItemAction.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.madvoc.action; - -import jodd.madvoc.beans.GlobalService; -import jodd.madvoc.beans.SessionBean; -import jodd.madvoc.meta.Action; -import jodd.madvoc.meta.In; -import jodd.madvoc.meta.MadvocAction; -import jodd.madvoc.result.TextResult; -import jodd.petite.meta.PetiteInject; - -import javax.servlet.http.HttpSession; - -@MadvocAction -public class ItemAction { - - @PetiteInject - SessionBean sessionBean; - - @PetiteInject - GlobalService globalService; - - @In - HttpSession httpSession; - - @Action - public TextResult view() { - return TextResult.of(sessionBean.toString() + " sid:" + httpSession.getId()); - } - - @Action - public TextResult global() { - return TextResult.of(globalService.toString() + " " + globalService.getSessionBean().toString() + " sid:" + httpSession.getId()); - } -} \ No newline at end of file diff --git a/jodd-madvoc/src/test/java/jodd/madvoc/beans/GlobalService.java b/jodd-madvoc/src/test/java/jodd/madvoc/beans/GlobalService.java deleted file mode 100644 index df6a808aa..000000000 --- a/jodd-madvoc/src/test/java/jodd/madvoc/beans/GlobalService.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.madvoc.beans; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.meta.PetiteInject; - -@PetiteBean -public class GlobalService { - - @PetiteInject - SessionBean sessionBean; - - public SessionBean getSessionBean() { - return sessionBean; - } - - public void setSessionBean(SessionBean sessionBean) { - this.sessionBean = sessionBean; - } -} \ No newline at end of file diff --git a/jodd-madvoc/src/test/java/jodd/madvoc/beans/SessionBean.java b/jodd-madvoc/src/test/java/jodd/madvoc/beans/SessionBean.java deleted file mode 100644 index 00f952dde..000000000 --- a/jodd-madvoc/src/test/java/jodd/madvoc/beans/SessionBean.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.madvoc.beans; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.scope.SessionScope; - -import java.io.Serializable; - -@PetiteBean(scope = SessionScope.class) -public class SessionBean implements Serializable { - - -} \ No newline at end of file diff --git a/jodd-petite/build.gradle b/jodd-petite/build.gradle deleted file mode 100644 index b0dfd5e08..000000000 --- a/jodd-petite/build.gradle +++ /dev/null @@ -1,18 +0,0 @@ - -ext.moduleName = 'Jodd Petite' -ext.moduleDescription = 'Jodd Petite is slick and lightweight DI container that uses annotations and supports sufficient most of features offered by other containers.' - -dependencies { - api project(':jodd-core') - api project(':jodd-proxetta') - api project(':jodd-servlet'), optional - - api 'org.slf4j:slf4j-api:1.7.30' - api 'org.jodd:jodd-props:6.0.1' - - provided lib.servlet, optional - - testImplementation project(':jodd-core').sourceSets.test.output - testImplementation lib.junit5 - testImplementation lib.mockito -} diff --git a/jodd-petite/src/main/java/jodd/petite/AnnotationResolver.java b/jodd-petite/src/main/java/jodd/petite/AnnotationResolver.java deleted file mode 100644 index 16bec49e7..000000000 --- a/jodd-petite/src/main/java/jodd/petite/AnnotationResolver.java +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.scope.Scope; -import jodd.util.StringUtil; - -public class AnnotationResolver { - - /** - * Resolves bean's auto-wire flag from the annotation. Returns default auto-wire if annotation doesn't exist. - */ - public WiringMode resolveBeanWiringMode(final Class type) { - PetiteBean petiteBean = ((Class) type).getAnnotation(PetiteBean.class); - return petiteBean != null ? petiteBean.wiring() : WiringMode.DEFAULT; - } - - /** - * Resolves bean's scope type from the annotation. Returns null - * if annotation doesn't exist. - */ - public Class resolveBeanScopeType(final Class type) { - PetiteBean petiteBean = ((Class) type).getAnnotation(PetiteBean.class); - return petiteBean != null ? petiteBean.scope() : null; - } - - /** - * Resolves bean's name from bean annotation or type name. May be used for resolving bean name - * of base type during registration of bean subclass. - */ - public String resolveBeanName(final Class type, final boolean useLongTypeName) { - PetiteBean petiteBean = ((Class)type).getAnnotation(PetiteBean.class); - String name = null; - if (petiteBean != null) { - name = petiteBean.value().trim(); - } - if ((name == null) || (name.length() == 0)) { - if (useLongTypeName) { - name = type.getName(); - } else { - name = StringUtil.uncapitalize(type.getSimpleName()); - } - } - return name; - } - - /** - * Returns true if bean has name defined by Petite annotation. - */ - public boolean beanHasAnnotationName(final Class type) { - PetiteBean petiteBean = ((Class)type).getAnnotation(PetiteBean.class); - - if (petiteBean == null) { - return false; - } - - String name = petiteBean.value().trim(); - - return !name.isEmpty(); - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/AutomagicPetiteConfigurator.java b/jodd-petite/src/main/java/jodd/petite/AutomagicPetiteConfigurator.java deleted file mode 100644 index 92a95cc2f..000000000 --- a/jodd-petite/src/main/java/jodd/petite/AutomagicPetiteConfigurator.java +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.io.findfile.ClassScanner; -import jodd.petite.meta.PetiteBean; -import jodd.util.Consumers; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.function.Consumer; - -/** - * Auto-magically configures Petite container by analyzing the classpath. - *

- * Scans all classes on classpath and in jar files, and scans for {@link jodd.petite.meta.PetiteBean} - * annotation (not by loading the class!). If annotation is founded, class will be loaded and - * registered as Petite bean. - */ -public class AutomagicPetiteConfigurator { - - private static final Logger log = LoggerFactory.getLogger(AutomagicPetiteConfigurator.class); - private final static byte[] PETITE_BEAN_ANNOTATION_BYTES = ClassScanner.bytecodeSignatureOfType(PetiteBean.class); - private final PetiteContainer container; - private final Consumers classScannerConsumers = new Consumers<>(); - - public AutomagicPetiteConfigurator(final PetiteContainer petiteContainer) { - this.container = petiteContainer; - } - - public AutomagicPetiteConfigurator withScanner(final Consumer scannerConsumer) { - classScannerConsumers.add(scannerConsumer); - return this; - } - - /** - * Configures {@link jodd.petite.PetiteContainer} with specified class path. - */ - public void configure() { - long elapsed = System.currentTimeMillis(); - - final ClassScanner classScanner = new ClassScanner(); - - classScanner.detectEntriesMode(true); - classScanner.scanDefaultClasspath(); - classScannerConsumers.accept(classScanner); - - registerAsConsumer(classScanner); - - try { - classScanner.start(); - } catch (final Exception ex) { - throw new PetiteException("Scan classpath error", ex); - } - elapsed = System.currentTimeMillis() - elapsed; - log.info("Petite configured in " + elapsed + " ms. Total beans: " + container.beansCount()); - } - - /** - * Registers a class consumer that registers only those annotated with {@link jodd.petite.meta.PetiteBean}. - * Because of performance purposes, classes are not dynamically loaded; instead, their - * file content is examined. - */ - public void registerAsConsumer(final ClassScanner classScanner) { - classScanner.registerEntryConsumer(classPathEntry -> { - if (!classPathEntry.isTypeSignatureInUse(PETITE_BEAN_ANNOTATION_BYTES)) { - return; - } - - final Class beanClass; - - try { - beanClass = classPathEntry.loadClass(); - } catch (final ClassNotFoundException cnfex) { - throw new PetiteException("Unable to load class: " + cnfex, cnfex); - } - - if (beanClass == null) { - return; - } - - final PetiteBean petiteBean = beanClass.getAnnotation(PetiteBean.class); - - if (petiteBean == null) { - return; - } - container.registerPetiteBean(beanClass, null, null, null, false, null); - }); - } -} diff --git a/jodd-petite/src/main/java/jodd/petite/BeanData.java b/jodd-petite/src/main/java/jodd/petite/BeanData.java deleted file mode 100644 index 19e4aa04d..000000000 --- a/jodd-petite/src/main/java/jodd/petite/BeanData.java +++ /dev/null @@ -1,302 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.bean.BeanUtil; -import jodd.introspector.Setter; -import jodd.petite.def.BeanReferences; -import jodd.petite.def.CtorInjectionPoint; -import jodd.petite.def.DestroyMethodPoint; -import jodd.petite.def.InitMethodPoint; -import jodd.petite.def.MethodInjectionPoint; -import jodd.petite.def.PropertyInjectionPoint; -import jodd.petite.def.SetInjectionPoint; -import jodd.petite.def.ValueInjectionPoint; -import jodd.petite.meta.InitMethodInvocationStrategy; - -import java.util.Collection; - -/** - * Petite bean is defined by {@link jodd.petite.BeanDefinition bean definition} - * and it's bean instance. This is a internal bean. It holds data and - * performs all the operation on the pair of definition and the value. - */ -public class BeanData { - - private final PetiteContainer pc; - private final BeanDefinition beanDefinition; - private final T bean; - - public BeanData(final PetiteContainer petiteContainer, final BeanDefinition beanDefinition, final T bean) { - this.pc = petiteContainer; - this.beanDefinition = beanDefinition; - this.bean = bean; - } - - public BeanData(final PetiteContainer petiteContainer, final BeanDefinition beanDefinition) { - this.pc = petiteContainer; - this.beanDefinition = beanDefinition; - this.bean = (T) newBeanInstance(); - } - - /** - * Returns {@link BeanDefinition}. - */ - public BeanDefinition definition() { - return beanDefinition; - } - - /** - * Returns Petite bean instance. - */ - public T bean() { - return bean; - } - - // ---------------------------------------------------------------- scope - - /** - * Registers scope. - */ - public void scopeRegister() { - beanDefinition.scopeRegister(bean); - } - - // ---------------------------------------------------------------- invoke - - /** - * Invokes init methods. - */ - public void invokeInitMethods(final InitMethodInvocationStrategy invocationStrategy) { - for (final InitMethodPoint initMethod : beanDefinition.initMethodPoints()) { - if (invocationStrategy != initMethod.invocationStrategy) { - continue; - } - try { - initMethod.method.invoke(bean); - } catch (Exception ex) { - throw new PetiteException("Invalid init method: " + initMethod, ex); - } - } - } - - /** - * Calls destroy methods on given BeanData. Destroy methods are called - * without any order. - */ - public void callDestroyMethods() { - for (final DestroyMethodPoint destroyMethodPoint : beanDefinition.destroyMethodPoints()) { - try { - destroyMethodPoint.method.invoke(bean); - } catch (Exception ex) { - throw new PetiteException("Invalid destroy method: " + destroyMethodPoint.method, ex); - } - } - } - - public void invokeConsumerIfRegistered() { - if (beanDefinition.consumer() == null) { - return; - } - beanDefinition.consumer().accept(bean); - } - - // ---------------------------------------------------------------- new instance - - /** - * Creates a new instance. - */ - public Object newBeanInstance() { - if (beanDefinition.ctor == CtorInjectionPoint.EMPTY) { - throw new PetiteException("No constructor (annotated, single or default) founded as injection point for: " + beanDefinition.type.getName()); - } - - int paramNo = beanDefinition.ctor.references.length; - Object[] args = new Object[paramNo]; - - // wiring - if (beanDefinition.wiringMode != WiringMode.NONE) { - for (int i = 0; i < paramNo; i++) { - args[i] = pc.getBean(beanDefinition.ctor.references[i]); - if (args[i] == null) { - if ((beanDefinition.wiringMode == WiringMode.STRICT)) { - throw new PetiteException( - "Wiring constructor failed. References '" + beanDefinition.ctor.references[i] + - "' not found for constructor: " + beanDefinition.ctor.constructor); - } - } - } - } - - // create instance - final Object bean; - try { - bean = beanDefinition.ctor.constructor.newInstance(args); - } catch (Exception ex) { - throw new PetiteException("Failed to create new bean instance '" + beanDefinition.type.getName() + "' using constructor: " + beanDefinition.ctor.constructor, ex); - } - - return bean; - } - - // ---------------------------------------------------------------- params - - /** - * Injects all parameters. - */ - public void injectParams(final ParamManager paramManager, final boolean implicitParamInjection) { - if (beanDefinition.name == null) { - return; - } - - if (implicitParamInjection) { - // implicit - final int len = beanDefinition.name.length() + 1; - for (final String param : beanDefinition.params) { - final Object value = paramManager.get(param); - final String destination = param.substring(len); - try { - BeanUtil.declared.setProperty(bean, destination, value); - } catch (Exception ex) { - throw new PetiteException("Unable to set parameter: '" + param + "' to bean: " + beanDefinition.name, ex); - } - } - } - - // explicit - for (final ValueInjectionPoint pip : beanDefinition.values) { - final String value = paramManager.parseKeyTemplate(pip.valueTemplate); - - try { - BeanUtil.declared.setProperty(bean, pip.property, value); - } catch (Exception ex) { - throw new PetiteException("Unable to set value for: '" + pip.valueTemplate + "' to bean: " + beanDefinition.name, ex); - } - } - } - - // ---------------------------------------------------------------- wire - - /** - * Wires beans. - */ - public void wireBean() { - if (definition().wiringMode == WiringMode.NONE) { - return; - } - wireProperties(); - wireSets(); - wireMethods(); - } - - protected void wireProperties() { - for (PropertyInjectionPoint pip : beanDefinition.properties) { - final BeanReferences refNames = pip.references; - - final Object value = pc.lookupMixingScopedBean(this.definition(), refNames); - - if (value == null) { - if ((beanDefinition.wiringMode == WiringMode.STRICT)) { - throw new PetiteException("Wiring failed. Beans references: '" + - refNames + "' not found for property: " + beanDefinition.type.getName() + - '#' + pip.propertyDescriptor.getName()); - } - continue; - } - - // BeanUtil.setDeclaredProperty(bean, pip.propertyDescriptor.getName(), value); - - final Setter setter = pip.propertyDescriptor.getSetter(true); - try { - setter.invokeSetter(bean, value); - } catch (Exception ex) { - throw new PetiteException("Wiring failed", ex); - } - } - } - - protected void wireSets() { - for (final SetInjectionPoint sip : definition().sets) { - - String[] beanNames = pc.resolveBeanNamesForType(sip.targetClass); - - Collection beans = sip.createSet(beanNames.length); - - for (String beanName : beanNames) { - if (!beanName.equals(definition().name)) { - Object value = pc.getBean(beanName); - beans.add(value); - } - } - - //BeanUtil.setDeclaredProperty(bean, sip.field.getName(), beans); - - final Setter setter = sip.propertyDescriptor.getSetter(true); - try { - setter.invokeSetter(bean, beans); - } - catch (Exception ex) { - throw new PetiteException("Wiring failed", ex); - } - } - } - - /** - * Invokes single method injection point on given bean with given bean definition. - */ - protected void wireMethods() { - for (final MethodInjectionPoint methodRef : definition().methods) { - invokeMethodInjectionPoint(methodRef); - } - } - - public Object invokeMethodInjectionPoint(final MethodInjectionPoint methodRef) { - - final BeanReferences[] refNames = methodRef.references; - final Object[] args = new Object[refNames.length]; - - for (int i = 0; i < refNames.length; i++) { - final BeanReferences refName = refNames[i]; - - final Object value = pc.lookupMixingScopedBean(beanDefinition, refName); - - args[i] = value; - if (value == null) { - if ((beanDefinition.wiringMode == WiringMode.STRICT)) { - throw new PetiteException("Wiring failed. Beans references: '" + - refName + "' not found for method: " + beanDefinition.type.getName() + '#' + methodRef.method.getName()); - } - } - } - - try { - return methodRef.method.invoke(bean, args); - } catch (Exception ex) { - throw new PetiteException(ex); - } - } - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/BeanDefinition.java b/jodd-petite/src/main/java/jodd/petite/BeanDefinition.java deleted file mode 100644 index 25f195085..000000000 --- a/jodd-petite/src/main/java/jodd/petite/BeanDefinition.java +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.def.CtorInjectionPoint; -import jodd.petite.def.DestroyMethodPoint; -import jodd.petite.def.InitMethodPoint; -import jodd.petite.def.MethodInjectionPoint; -import jodd.petite.def.PropertyInjectionPoint; -import jodd.petite.def.SetInjectionPoint; -import jodd.petite.def.ValueInjectionPoint; -import jodd.petite.scope.Scope; -import jodd.util.ArraysUtil; - -import java.util.function.Consumer; - -/** - * Petite bean definition and cache. Consist of bean data that defines a bean - * and cache, that might not be initialized (if null). - * To initialize cache, get the bean instance from container. - */ -public class BeanDefinition { - - public BeanDefinition(final String name, final Class type, final Scope scope, final WiringMode wiringMode, final Consumer beanInitConsumer) { - this.name = name; - this.type = type; - this.scope = scope; - this.wiringMode = wiringMode; - this.consumer = beanInitConsumer; - } - - // finals - protected final String name; // bean name - protected final Class type; // bean type - protected final Scope scope; // bean scope, may be null for beans that are not stored in scope but just wired - protected final WiringMode wiringMode; // wiring mode - protected final Consumer consumer; // bean consumer, may be null - - // cache - protected CtorInjectionPoint ctor; - protected PropertyInjectionPoint[] properties; - protected SetInjectionPoint[] sets; - protected MethodInjectionPoint[] methods; - protected InitMethodPoint[] initMethods; - protected DestroyMethodPoint[] destroyMethods; - protected String[] params; - protected ValueInjectionPoint[] values; - - // ---------------------------------------------------------------- definition getters - - /** - * Returns bean name. - */ - public String name() { - return name; - } - - /** - * Returns bean type. - */ - public Class type() { - return type; - } - - /** - * Returns beans scope type. - */ - public Class scope() { - if (scope == null) { - return null; - } - return scope.getClass(); - } - - /** - * Returns wiring mode. - */ - public WiringMode wiringMode() { - return wiringMode; - } - - /** - * Returns an optional consumer. - */ - public Consumer consumer() { - return consumer; - } - - // ---------------------------------------------------------------- cache getters - - /** - * Returns constructor injection point. - */ - public CtorInjectionPoint ctorInjectionPoint() { - return ctor; - } - - /** - * Returns property injection points. - */ - public PropertyInjectionPoint[] propertyInjectionPoints() { - return properties; - } - - /** - * Returns set injection points. - */ - public SetInjectionPoint[] setterInjectionPoints() { - return sets; - } - - /** - * Returns method injection points. - */ - public MethodInjectionPoint[] methodInjectionPoints() { - return methods; - } - - /** - * Returns init method points. - */ - public InitMethodPoint[] initMethodPoints() { - return initMethods; - } - - /** - * Returns destroy method points. - */ - public DestroyMethodPoint[] destroyMethodPoints() { - return destroyMethods; - } - - /** - * Returns parameters. - */ - public String[] params() { - return params; - } - - // ---------------------------------------------------------------- scope delegates - - /** - * Delegates to {@link jodd.petite.scope.Scope#lookup(String)}. - */ - protected Object scopeLookup() { - if (scope == null) { - throw new PetiteException("Scope not defined"); - } - return scope.lookup(name); - } - - /** - * Delegates to {@link jodd.petite.scope.Scope#register(jodd.petite.BeanDefinition, Object)} - * if scope is defined. - */ - protected void scopeRegister(final Object object) { - if (scope != null) { - scope.register(this, object); - } - } - - /** - * Delegates to {@link jodd.petite.scope.Scope#remove(String)}. - */ - protected void scopeRemove() { - scope.remove(name); - } - - // ---------------------------------------------------------------- appends - - /** - * Adds property injection point. - */ - protected void addPropertyInjectionPoint(final PropertyInjectionPoint pip) { - if (properties == null) { - properties = new PropertyInjectionPoint[1]; - properties[0] = pip; - } else { - properties = ArraysUtil.append(properties, pip); - } - } - - /** - * Adds set injection point. - */ - protected void addSetInjectionPoint(final SetInjectionPoint sip) { - if (sets == null) { - sets = new SetInjectionPoint[1]; - sets[0] = sip; - } else { - sets = ArraysUtil.append(sets, sip); - } - } - - /** - * Adds method injection point. - */ - protected void addMethodInjectionPoint(final MethodInjectionPoint mip) { - if (methods == null) { - methods = new MethodInjectionPoint[1]; - methods[0] = mip; - } else { - methods = ArraysUtil.append(methods, mip); - } - } - - /** - * Adds init methods. - */ - protected void addInitMethodPoints(final InitMethodPoint[] methods) { - if (initMethods == null) { - initMethods = methods; - } else { - initMethods = ArraysUtil.join(initMethods, methods); - } - } - - /** - * Adds destroy methods. - */ - protected void addDestroyMethodPoints(final DestroyMethodPoint[] methods) { - if (destroyMethods == null) { - destroyMethods = methods; - } else { - destroyMethods = ArraysUtil.join(destroyMethods, methods); - } - } - - // ---------------------------------------------------------------- toString - - @Override - public String toString() { - return "BeanDefinition{" + - "name=" + name + - ", type=" + type + - ", scope=" + (scope != null ? scope.getClass().getSimpleName() : "N/A") + - ", wiring=" + wiringMode + - '}'; - } -} diff --git a/jodd-petite/src/main/java/jodd/petite/ParamManager.java b/jodd-petite/src/main/java/jodd/petite/ParamManager.java deleted file mode 100644 index fafe94ef1..000000000 --- a/jodd-petite/src/main/java/jodd/petite/ParamManager.java +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.introspector.ClassDescriptor; -import jodd.introspector.ClassIntrospector; -import jodd.introspector.FieldDescriptor; -import jodd.introspector.MethodDescriptor; -import jodd.introspector.PropertyDescriptor; -import jodd.petite.def.ValueInjectionPoint; -import jodd.petite.meta.PetiteValue; -import jodd.util.PropertiesUtil; -import jodd.util.StringPool; -import jodd.util.StringTemplateParser; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Parameters storage and resolver. Parameters are injected into beans. - */ -public class ParamManager { - - protected final Map params; - protected final StringTemplateParser contextTemplateParser; - - public ParamManager() { - params = new HashMap<>(); - contextTemplateParser = StringTemplateParser.ofMap(params); - } - - /** - * Adds a parameter. - */ - public void put(final String name, final Object value) { - params.put(name, value); - } - - /** - * Returns parameter for given name or null - * if not found. - */ - public Object get(final String name) { - return params.get(name); - } - - public String parseKeyTemplate(final String input) { - return contextTemplateParser.apply(input); - } - - /** - * Returns an array of param keys that belongs to provided bean. - * Optionally resolves the value of returned parameters. - */ - public String[] filterParametersForBeanName(String beanName, final boolean resolveReferenceParams) { - beanName = beanName + '.'; - - final List list = new ArrayList<>(); - for (final Map.Entry entry : params.entrySet()) { - final String key = entry.getKey(); - if (!key.startsWith(beanName)) { - continue; - } - list.add(key); - if (!resolveReferenceParams) { - continue; - } - // resolve all references - final String value = PropertiesUtil.resolveProperty(params, key); - entry.setValue(value); - } - if (list.isEmpty()) { - return StringPool.EMPTY_ARRAY; - } else { - return list.toArray(new String[0]); - } - } - - public ValueInjectionPoint[] resolveParamInjectionPoints(final Class type) { - final ClassDescriptor cd = ClassIntrospector.get().lookup(type); - - final List valueInjectionPointList = new ArrayList<>(); - - for (final PropertyDescriptor pd : cd.getAllPropertyDescriptors()) { - final FieldDescriptor fd = pd.getFieldDescriptor(); - - if (fd != null) { - final PetiteValue petiteValue = fd.getField().getAnnotation(PetiteValue.class); - - if (petiteValue != null) { - valueInjectionPointList.add(new ValueInjectionPoint(pd.getName(), petiteValue.value())); - continue; - } - } - - final MethodDescriptor md = pd.getWriteMethodDescriptor(); - if (md != null) { - final PetiteValue petiteValue = md.getMethod().getAnnotation(PetiteValue.class); - - if (petiteValue != null) { - valueInjectionPointList.add(new ValueInjectionPoint(pd.getName(), petiteValue.value())); - continue; - } - } - } - - return valueInjectionPointList.toArray(new ValueInjectionPoint[0]); - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/PetiteBeans.java b/jodd-petite/src/main/java/jodd/petite/PetiteBeans.java deleted file mode 100644 index bd00f33da..000000000 --- a/jodd-petite/src/main/java/jodd/petite/PetiteBeans.java +++ /dev/null @@ -1,834 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.introspector.ClassDescriptor; -import jodd.introspector.ClassIntrospector; -import jodd.introspector.CtorDescriptor; -import jodd.introspector.MethodDescriptor; -import jodd.introspector.PropertyDescriptor; -import jodd.petite.def.BeanReferences; -import jodd.petite.def.CtorInjectionPoint; -import jodd.petite.def.DestroyMethodPoint; -import jodd.petite.def.InitMethodPoint; -import jodd.petite.def.MethodInjectionPoint; -import jodd.petite.def.PropertyInjectionPoint; -import jodd.petite.def.ProviderDefinition; -import jodd.petite.def.SetInjectionPoint; -import jodd.petite.meta.InitMethodInvocationStrategy; -import jodd.petite.resolver.ReferencesResolver; -import jodd.petite.scope.Scope; -import jodd.petite.scope.SingletonScope; -import jodd.props.Props; -import jodd.util.ClassUtil; -import jodd.util.StringPool; -import jodd.util.TypeCache; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; - -/** - * Base layer of {@link PetiteContainer Petite Container}. - * Holds beans and scopes definitions. - */ -public abstract class PetiteBeans { - - private static final Logger log = LoggerFactory.getLogger(PetiteBeans.class); - - /** - * Map of all beans definitions. - */ - protected final Map beans = new HashMap<>(); - - /** - * Map of alternative beans names. - */ - protected final Map beansAlt = new HashMap<>(); - - /** - * Map of all bean scopes. - */ - protected final TypeCache scopes = TypeCache.createDefault(); - - /** - * Map of all providers. - */ - protected final Map providers = new HashMap<>(); - - /** - * Map of all bean collections. - */ - protected final TypeCache beanCollections = TypeCache.createDefault(); - - /** - * Cache used for storing the internals about the external types that are not - * registered withing the container. - */ - protected TypeCache externalsCache = TypeCache.create().noCache().get(); - - /** - * Sets the type of cache used for storing the configurations for external types that - * are not part of the container. This affects usages of the methods - * like {@link PetiteContainer#wire(Object)} and {@link PetiteContainer#invokeMethod(Object, Method)}. - */ - public void setExternalsCache(final TypeCache typeCacheImplementation) { - this.externalsCache = typeCacheImplementation; - } - - /** - * {@link PetiteConfig Petite configuration}. - */ - protected final PetiteConfig petiteConfig; - - /** - * {@link ReferencesResolver bean reference resolver}. - */ - protected final ReferencesResolver referencesResolver; - - /** - * {@link PetiteResolvers Petite resolvers}. - */ - protected final PetiteResolvers petiteResolvers; - - /** - * {@link ParamManager Parameters manager}. - */ - protected final ParamManager paramManager; - - protected final AnnotationResolver annotationResolver; - - protected PetiteBeans(final PetiteConfig petiteConfig) { - this.petiteConfig = petiteConfig; - this.referencesResolver = new ReferencesResolver(petiteConfig); - this.petiteResolvers = new PetiteResolvers(referencesResolver); - this.paramManager = new ParamManager(); - this.annotationResolver = new AnnotationResolver(); - } - - /** - * Returns parameter manager. - */ - public ParamManager paramManager() { - return paramManager; - } - - /** - * Returns {@link PetiteConfig Petite configuration}. - * All changes on config should be done before - * beans registration process starts. - */ - public PetiteConfig config() { - return petiteConfig; - } - - // ---------------------------------------------------------------- scopes - - /** - * Resolves and registers scope from a scope type. - */ - @SuppressWarnings("unchecked") - public S resolveScope(final Class scopeType) { - S scope = (S) scopes.get(scopeType); - if (scope == null) { - - try { - scope = newInternalInstance(scopeType, (PetiteContainer) this); - } catch (final Exception ex) { - throw new PetiteException("Invalid Petite scope: " + scopeType.getName(), ex); - } - - registerScope(scopeType, scope); - scopes.put(scopeType, scope); - } - return scope; - } - - - /** - * Creates new instance of given type. In the first try, it tries to use - * constructor with a {@link PetiteContainer}. If that files, uses default - * constructor to builds an instance. - */ - private T newInternalInstance(final Class type, final PetiteContainer petiteContainer) throws Exception { - T t = null; - - // first try ctor(PetiteContainer) - try { - final Constructor ctor = type.getConstructor(PetiteContainer.class); - t = ctor.newInstance(petiteContainer); - } catch (final NoSuchMethodException nsmex) { - // ignore - } - - // if first try failed, try default ctor - if (t == null) { - return ClassUtil.newInstance(type); - } - - return t; - } - - - /** - * Registers new scope. It is not necessary to manually register scopes, - * since they become registered on first scope resolving. - * However, it is possible to pre-register some scopes, or to replace one scope - * type with another. Replacing may be important for testing purposes when - * using container-depended scopes. - */ - public void registerScope(final Class scopeType, final Scope scope) { - scopes.put(scopeType, scope); - } - - // ---------------------------------------------------------------- lookup beans - - /** - * Lookups for {@link BeanDefinition bean definition}. - * Returns null if bean name doesn't exist. - */ - public BeanDefinition lookupBeanDefinition(final String name) { - BeanDefinition beanDefinition = beans.get(name); - - // try alt bean names - if (beanDefinition == null) { - if (petiteConfig.isUseAltBeanNames()) { - beanDefinition = beansAlt.get(name); - } - } - - return beanDefinition; - } - - /** - * Lookups for first founded {@link BeanDefinition bean definition}. - * Returns null if none of the beans is found. - */ - protected BeanDefinition lookupBeanDefinitions(final BeanReferences beanReferences) { - final int total = beanReferences.size(); - for (int i = 0; i < total; i++) { - final String name = beanReferences.name(i); - - final BeanDefinition beanDefinition = lookupBeanDefinition(name); - - if (beanDefinition != null) { - return beanDefinition; - } - } - return null; - } - - /** - * Lookups for existing {@link jodd.petite.BeanDefinition bean definition}. - * Throws exception if bean is not found. - */ - protected BeanDefinition lookupExistingBeanDefinition(final String name) { - final BeanDefinition beanDefinition = lookupBeanDefinition(name); - if (beanDefinition == null) { - throw new PetiteException("Bean not found: " + name); - } - return beanDefinition; - } - - /** - * Returns true if bean name is registered. - */ - public boolean isBeanNameRegistered(final String name) { - return lookupBeanDefinition(name) != null; - } - - /** - * Resolves bean's name from bean annotation or type name. May be used for resolving bean name - * of base type during registration of bean subclass. - */ - public String resolveBeanName(final Class type) { - return annotationResolver.resolveBeanName(type, petiteConfig.getUseFullTypeNames()); - } - - // ---------------------------------------------------------------- register beans - - /** - * Creates {@link jodd.petite.BeanDefinition} on - * {@link #registerPetiteBean(Class, String, Class, WiringMode, boolean, Consumer) bean registration}. - * This is a hook for modifying the bean data, like passing proxifed class etc. - * By default returns new instance of {@link jodd.petite.BeanDefinition}. - */ - protected BeanDefinition createBeanDefinitionForRegistration( - final String name, - final Class type, - final Scope scope, - final WiringMode wiringMode, - final Consumer consumer) { - - return new BeanDefinition<>(name, type, scope, wiringMode, consumer); - } - - /** - * Creates {@link jodd.petite.BeanDefinition} for all external beans. - */ - protected BeanDefinition createBeandDefinitionForExternalBeans( - final Class type, - final WiringMode wiringMode) { - - final String name = resolveBeanName(type); - return new BeanDefinition<>(name, type, null, wiringMode, null); - } - - /** - * Registers a bean using provided class that is annotated. - */ - public BeanDefinition registerPetiteBean(final Class type) { - return registerPetiteBean(type, null, null, null, false, null); - } - /** - * Registers a bean using provided class that is annotated. - */ - public BeanDefinition registerPetiteBean(final Class type, final Consumer consumer) { - return registerPetiteBean(type, null, null, null, false, consumer); - } - - /** - * Registers or defines a bean. - * - * @param type bean type, must be specified - * @param name bean name, if null it will be resolved from the class (name or annotation) - * @param scopeType bean scope, if null it will be resolved from the class (annotation or default one) - * @param wiringMode wiring mode, if null it will be resolved from the class (annotation or default one) - * @param define when set to true bean will be defined - all injection points will be set to none - */ - public BeanDefinition registerPetiteBean( - final Class type, String name, - Class scopeType, - WiringMode wiringMode, - final boolean define, - final Consumer consumer - ) { - - if (name == null) { - name = resolveBeanName(type); - } - if (wiringMode == null) { - wiringMode = annotationResolver.resolveBeanWiringMode(type); - } - if (wiringMode == WiringMode.DEFAULT) { - wiringMode = petiteConfig.getDefaultWiringMode(); - } - if (scopeType == null) { - scopeType = annotationResolver.resolveBeanScopeType(type); - } - if (scopeType == null) { - scopeType = SingletonScope.class; - } - - // remove existing bean - final BeanDefinition existing = removeBean(name); - if (existing != null) { - if (petiteConfig.getDetectDuplicatedBeanNames()) { - throw new PetiteException( - "Duplicated bean name detected while registering class '" + type.getName() + "'. Petite bean class '" + - existing.type.getName() + "' is already registered with the name: " + name); - } - } - - // check if type is valid - if (type.isInterface()) { - throw new PetiteException("PetiteBean can not be an interface: " + type.getName()); - } - - // registration - if (log.isDebugEnabled()) { - log.info("Petite bean: [" + name + - "] --> " + type.getName() + - " @ " + scopeType.getSimpleName() + - ":" + wiringMode.toString()); - } - - // register - final Scope scope = resolveScope(scopeType); - final BeanDefinition beanDefinition = createBeanDefinitionForRegistration(name, type, scope, wiringMode, consumer); - - registerBean(name, beanDefinition); - - // providers - final ProviderDefinition[] providerDefinitions = petiteResolvers.resolveProviderDefinitions(type, name); - - if (providerDefinitions != null) { - for (final ProviderDefinition providerDefinition : providerDefinitions) { - providers.put(providerDefinition.name, providerDefinition); - } - } - - // define - if (define) { - beanDefinition.ctor = petiteResolvers.resolveCtorInjectionPoint(beanDefinition.type()); - beanDefinition.properties = PropertyInjectionPoint.EMPTY; - beanDefinition.methods = MethodInjectionPoint.EMPTY; - beanDefinition.initMethods = InitMethodPoint.EMPTY; - beanDefinition.destroyMethods = DestroyMethodPoint.EMPTY; - } - - // return - return beanDefinition; - } - - /** - * Registers bean definition by putting it in the beans map. If bean does - * not have petite name explicitly defined, alternative bean names - * will be registered. - */ - protected void registerBean(final String name, final BeanDefinition beanDefinition) { - beans.put(name, beanDefinition); - - if (!petiteConfig.isUseAltBeanNames()) { - return; - } - - final Class type = beanDefinition.type(); - - if (annotationResolver.beanHasAnnotationName(type)) { - return; - } - - final Class[] interfaces = ClassUtil.resolveAllInterfaces(type); - - for (final Class anInterface : interfaces) { - final String altName = annotationResolver.resolveBeanName(anInterface, petiteConfig.getUseFullTypeNames()); - - if (name.equals(altName)) { - continue; - } - - if (beans.containsKey(altName)) { - continue; - } - - if (beansAlt.containsKey(altName)) { - final BeanDefinition existing = beansAlt.get(altName); - - if (existing != null) { - beansAlt.put(altName, null); // store null as value to mark that alt name is duplicate - } - } - else { - beansAlt.put(altName, beanDefinition); - } - } - } - - /** - * Removes all petite beans of provided type. Bean name is not resolved from a type! - * Instead, all beans are iterated and only beans with equal types are removed. - * @see #removeBean(String) - */ - public void removeBean(final Class type) { - // collect bean names - final Set beanNames = new HashSet<>(); - - for (final BeanDefinition def : beans.values()) { - if (def.type.equals(type)) { - beanNames.add(def.name); - } - } - - // remove collected bean names - for (final String beanName : beanNames) { - removeBean(beanName); - } - } - - /** - * Removes bean and returns definition of removed bean. - * All resolvers references are deleted, too. - * Returns bean definition of removed bean or null. - */ - public BeanDefinition removeBean(final String name) { - final BeanDefinition bd = beans.remove(name); - if (bd == null) { - return null; - } - bd.scopeRemove(); - return bd; - } - - // ---------------------------------------------------------------- bean collections - - /** - * Resolves bean names for give type. - */ - protected String[] resolveBeanNamesForType(final Class type) { - String[] beanNames = beanCollections.get(type); - if (beanNames != null) { - return beanNames; - } - - final ArrayList list = new ArrayList<>(); - - for (final Map.Entry entry : beans.entrySet()) { - final BeanDefinition beanDefinition = entry.getValue(); - - if (ClassUtil.isTypeOf(beanDefinition.type, type)) { - final String beanName = entry.getKey(); - list.add(beanName); - } - } - - if (list.isEmpty()) { - beanNames = StringPool.EMPTY_ARRAY; - } else { - beanNames = list.toArray(new String[0]); - } - - beanCollections.put(type, beanNames); - return beanNames; - } - - // ---------------------------------------------------------------- injection points - - /** - * Registers constructor injection point. - * - * @param beanName bean name - * @param paramTypes constructor parameter types, may be null - * @param references references for arguments - */ - public void registerPetiteCtorInjectionPoint(final String beanName, final Class[] paramTypes, final String[] references) { - final BeanDefinition beanDefinition = lookupExistingBeanDefinition(beanName); - - final ClassDescriptor cd = ClassIntrospector.get().lookup(beanDefinition.type); - Constructor constructor = null; - - if (paramTypes == null) { - final CtorDescriptor[] ctors = cd.getAllCtorDescriptors(); - if (ctors != null && ctors.length > 0) { - if (ctors.length > 1) { - throw new PetiteException(ctors.length + " suitable constructor found as injection point for: " + beanDefinition.type.getName()); - } - constructor = ctors[0].getConstructor(); - } - } else { - final CtorDescriptor ctorDescriptor = cd.getCtorDescriptor(paramTypes, true); - - if (ctorDescriptor != null) { - constructor = ctorDescriptor.getConstructor(); - } - } - - if (constructor == null) { - throw new PetiteException("Constructor not found: " + beanDefinition.type.getName()); - } - - final BeanReferences[] ref = referencesResolver.resolveReferenceFromValues(constructor, references); - - beanDefinition.ctor = new CtorInjectionPoint(constructor, ref); - } - - /** - * Registers property injection point. - * - * @param beanName bean name - * @param property property name - * @param reference explicit injection reference, may be null - */ - public void registerPetitePropertyInjectionPoint(final String beanName, final String property, final String reference) { - final BeanDefinition beanDefinition = lookupExistingBeanDefinition(beanName); - - final ClassDescriptor cd = ClassIntrospector.get().lookup(beanDefinition.type); - final PropertyDescriptor propertyDescriptor = cd.getPropertyDescriptor(property, true); - - if (propertyDescriptor == null) { - throw new PetiteException("Property not found: " + beanDefinition.type.getName() + '#' + property); - } - - final BeanReferences ref = referencesResolver.resolveReferenceFromValue(propertyDescriptor, reference); - - final PropertyInjectionPoint pip = new PropertyInjectionPoint(propertyDescriptor, ref); - - beanDefinition.addPropertyInjectionPoint(pip); - } - - /** - * Registers set injection point. - * - * @param beanName bean name - * @param property set property name - */ - public void registerPetiteSetInjectionPoint(final String beanName, final String property) { - final BeanDefinition beanDefinition = lookupExistingBeanDefinition(beanName); - final ClassDescriptor cd = ClassIntrospector.get().lookup(beanDefinition.type); - - final PropertyDescriptor propertyDescriptor = cd.getPropertyDescriptor(property, true); - - if (propertyDescriptor == null) { - throw new PetiteException("Property not found: " + beanDefinition.type.getName() + '#' + property); - } - - final SetInjectionPoint sip = new SetInjectionPoint(propertyDescriptor); - - beanDefinition.addSetInjectionPoint(sip); - } - - /** - * Registers method injection point. - * - * @param beanName bean name - * @param methodName method name - * @param arguments method arguments, may be null - * @param references injection references - */ - public void registerPetiteMethodInjectionPoint(final String beanName, final String methodName, final Class[] arguments, final String[] references) { - final BeanDefinition beanDefinition = lookupExistingBeanDefinition(beanName); - - final ClassDescriptor cd = ClassIntrospector.get().lookup(beanDefinition.type); - - Method method = null; - if (arguments == null) { - final MethodDescriptor[] methods = cd.getAllMethodDescriptors(methodName); - - if (methods != null && methods.length > 0) { - if (methods.length > 1) { - throw new PetiteException(methods.length + " suitable methods found as injection points for: " + beanDefinition.type.getName() + '#' + methodName); - } - method = methods[0].getMethod(); - } - } else { - final MethodDescriptor md = cd.getMethodDescriptor(methodName, arguments, true); - if (md != null) { - method = md.getMethod(); - } - } - if (method == null) { - throw new PetiteException("Method not found: " + beanDefinition.type.getName() + '#' + methodName); - } - - final BeanReferences[] ref = referencesResolver.resolveReferenceFromValues(method, references); - - final MethodInjectionPoint mip = new MethodInjectionPoint(method, ref); - - beanDefinition.addMethodInjectionPoint(mip); - } - - /** - * Registers init method. - * - * @param beanName bean name - * @param invocationStrategy moment of invocation - * @param initMethodNames init method names - */ - public void registerPetiteInitMethods(final String beanName, final InitMethodInvocationStrategy invocationStrategy, String... initMethodNames) { - final BeanDefinition beanDefinition = lookupExistingBeanDefinition(beanName); - - final ClassDescriptor cd = ClassIntrospector.get().lookup(beanDefinition.type); - if (initMethodNames == null) { - initMethodNames = StringPool.EMPTY_ARRAY; - } - - final int total = initMethodNames.length; - final InitMethodPoint[] initMethodPoints = new InitMethodPoint[total]; - - int i; - for (i = 0; i < initMethodNames.length; i++) { - final MethodDescriptor md = cd.getMethodDescriptor(initMethodNames[i], ClassUtil.EMPTY_CLASS_ARRAY, true); - if (md == null) { - throw new PetiteException("Init method not found: " + beanDefinition.type.getName() + '#' + initMethodNames[i]); - } - initMethodPoints[i] = new InitMethodPoint(md.getMethod(), i, invocationStrategy); - } - - beanDefinition.addInitMethodPoints(initMethodPoints); - } - - /** - * Registers destroy method. - * - * @param beanName bean name - * @param destroyMethodNames destroy method names - */ - public void registerPetiteDestroyMethods(final String beanName, String... destroyMethodNames) { - final BeanDefinition beanDefinition = lookupExistingBeanDefinition(beanName); - - final ClassDescriptor cd = ClassIntrospector.get().lookup(beanDefinition.type); - if (destroyMethodNames == null) { - destroyMethodNames = StringPool.EMPTY_ARRAY; - } - - final int total = destroyMethodNames.length; - final DestroyMethodPoint[] destroyMethodPoints = new DestroyMethodPoint[total]; - - int i; - for (i = 0; i < destroyMethodNames.length; i++) { - final MethodDescriptor md = cd.getMethodDescriptor(destroyMethodNames[i], ClassUtil.EMPTY_CLASS_ARRAY, true); - if (md == null) { - throw new PetiteException("Destroy method not found: " + beanDefinition.type.getName() + '#' + destroyMethodNames[i]); - } - destroyMethodPoints[i] = new DestroyMethodPoint(md.getMethod()); - } - - beanDefinition.addDestroyMethodPoints(destroyMethodPoints); - } - - // ---------------------------------------------------------------- providers - - /** - * Registers instance method provider. - * - * @param providerName provider name - * @param beanName bean name - * @param methodName instance method name - * @param arguments method argument types - */ - public void registerPetiteProvider(final String providerName, final String beanName, final String methodName, final Class[] arguments) { - final BeanDefinition beanDefinition = lookupBeanDefinition(beanName); - - if (beanDefinition == null) { - throw new PetiteException("Bean not found: " + beanName); - } - - final Class beanType = beanDefinition.type; - - final ClassDescriptor cd = ClassIntrospector.get().lookup(beanType); - final MethodDescriptor md = cd.getMethodDescriptor(methodName, arguments, true); - - if (md == null) { - throw new PetiteException("Provider method not found: " + methodName); - } - - final ProviderDefinition providerDefinition = new ProviderDefinition(providerName, beanName, md.getMethod()); - - providers.put(providerName, providerDefinition); - } - - /** - * Registers static method provider. - * - * @param providerName provider name - * @param type class type - * @param staticMethodName static method name - * @param arguments method argument types - */ - public void registerPetiteProvider(final String providerName, final Class type, final String staticMethodName, final Class[] arguments) { - final ClassDescriptor cd = ClassIntrospector.get().lookup(type); - final MethodDescriptor md = cd.getMethodDescriptor(staticMethodName, arguments, true); - - if (md == null) { - throw new PetiteException("Provider method not found: " + staticMethodName); - } - - final ProviderDefinition providerDefinition = new ProviderDefinition(providerName, md.getMethod()); - - providers.put(providerName, providerDefinition); - } - - // ---------------------------------------------------------------- statistics - - /** - * Returns total number of registered beans. - */ - public int beansCount() { - return beans.size(); - } - - /** - * Returns total number of used scopes. - */ - public int scopesCount() { - return scopes.size(); - } - - /** - * Returns set of all bean names. The returned set is a safe - * snapshot of all bean names. - */ - public Set beanNames() { - return new HashSet<>(beans.keySet()); - } - - /** - * Iterates all beans. Iteration occurs over the {@link #beanNames() snapshot of bean names}. - */ - public void forEachBean(final Consumer beanDefinitionConsumer) { - final Set names = beanNames(); - for (final String beanName : names) { - final BeanDefinition beanDefinition = lookupBeanDefinition(beanName); - - if (beanDefinition != null) { - beanDefinitionConsumer.accept(beanDefinition); - } - } - } - - /** - * Iterates all beans that are of given type. - */ - public void forEachBeanType(final Class type, final Consumer beanNameConsumer) { - forEachBean(bd -> { - if (ClassUtil.isTypeOf(bd.type, type)) { - beanNameConsumer.accept(bd.name); - } - }); - } - - // ---------------------------------------------------------------- params - - /** - * Defines new parameter. Parameters with same name will be replaced. - */ - public void defineParameter(final String name, final Object value) { - paramManager.put(name, value); - } - - /** - * Returns defined parameter. - */ - public Object getParameter(final String name) { - return paramManager.get(name); - } - - /** - * Defines many parameters at once. - */ - public void defineParameters(final Map properties) { - for (final Map.Entry entry : properties.entrySet()) { - defineParameter(entry.getKey().toString(), entry.getValue()); - } - } - - /** - * Defines many parameters at once from {@link jodd.props.Props}. - */ - public void defineParameters(final Props props) { - final Map map = new HashMap<>(); - props.extractProps(map); - defineParameters(map); - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/PetiteConfig.java b/jodd-petite/src/main/java/jodd/petite/PetiteConfig.java deleted file mode 100644 index 5d4d6cdeb..000000000 --- a/jodd-petite/src/main/java/jodd/petite/PetiteConfig.java +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -/** - * Petite configuration. - */ -public class PetiteConfig { - - public PetiteConfig() { - defaultWiringMode = WiringMode.STRICT; - detectDuplicatedBeanNames = false; - resolveReferenceParameters = true; - useFullTypeNames = false; - lookupReferences = PetiteReferenceType.DEFAULT; - useParamo = true; - wireScopedProxy = false; - detectMixedScopes = false; - useAltBeanNames = true; - implicitParamInjection = true; - } - - // ---------------------------------------------------------------- - - protected boolean implicitParamInjection; - - /** - * Returns {@code true} if implicit parameter injection is enabled. - */ - public boolean isImplicitParamInjection() { - return implicitParamInjection; - } - - /** - * Enables implicit parameter injection. - */ - public void setImplicitParamInjection(final boolean implicitParamInjection) { - this.implicitParamInjection = implicitParamInjection; - } - // ---------------------------------------------------------------- - - protected boolean useAltBeanNames; - - /** - * Returns if alternative bean names are in use. - */ - public boolean isUseAltBeanNames() { - return useAltBeanNames; - } - - /** - * Enables alternative bean names. - */ - public PetiteConfig setUseAltBeanNames(final boolean useAltBeanNames) { - this.useAltBeanNames = useAltBeanNames; - return this; - } - - // ---------------------------------------------------------------- - - protected WiringMode defaultWiringMode; - /** - * Returns default wiring mode. - */ - public WiringMode getDefaultWiringMode() { - return defaultWiringMode; - } - /** - * Specifies default wiring mode. - */ - public PetiteConfig setDefaultWiringMode(final WiringMode defaultWiringMode) { - if ((defaultWiringMode == null) || (defaultWiringMode == WiringMode.DEFAULT)) { - throw new PetiteException("Invalid default wiring mode: " + defaultWiringMode); - } - this.defaultWiringMode = defaultWiringMode; - return this; - } - /** - * Resolves wiring mode by checking if default and null values. - */ - protected WiringMode resolveWiringMode(WiringMode wiringMode) { - if ((wiringMode == null) || (wiringMode == WiringMode.DEFAULT)) { - wiringMode = defaultWiringMode; - } - return wiringMode; - } - - - // ---------------------------------------------------------------- - - protected boolean detectDuplicatedBeanNames; - /** - * Returns true if container detects duplicated bean names. - */ - public boolean getDetectDuplicatedBeanNames() { - return detectDuplicatedBeanNames; - } - /** - * Specifies if an exception should be thrown if two beans with same exception are registered with this container. - */ - public PetiteConfig setDetectDuplicatedBeanNames(final boolean detectDuplicatedBeanNames) { - this.detectDuplicatedBeanNames = detectDuplicatedBeanNames; - return this; - } - - // ---------------------------------------------------------------- - - protected boolean resolveReferenceParameters; - /** - * Returns true if parameter references should be resolved. - */ - public boolean getResolveReferenceParameters() { - return resolveReferenceParameters; - } - /** - * Defines if reference parameters should be resolved. - */ - public PetiteConfig setResolveReferenceParameters(final boolean resolveReferenceParameters) { - this.resolveReferenceParameters = resolveReferenceParameters; - return this; - } - - // ---------------------------------------------------------------- - - protected boolean useFullTypeNames; - - public boolean getUseFullTypeNames() { - return useFullTypeNames; - } - - /** - * Specifies if type names should be full or short. - */ - public PetiteConfig setUseFullTypeNames(final boolean useFullTypeNames) { - this.useFullTypeNames = useFullTypeNames; - return this; - } - - // ---------------------------------------------------------------- references - - protected PetiteReferenceType[] lookupReferences; - - public PetiteReferenceType[] getLookupReferences() { - return lookupReferences; - } - - /** - * Specifies references for bean name lookup, when name - * is not specified, in given order. - */ - public PetiteConfig setLookupReferences(final PetiteReferenceType... lookupReferences) { - this.lookupReferences = lookupReferences; - return this; - } - - // ---------------------------------------------------------------- - - protected boolean useParamo; - - public boolean getUseParamo() { - return useParamo; - } - - /** - * Specifies if Paramo tool should be used to resolve - * method and ctor argument names. - */ - public void setUseParamo(final boolean useParamo) { - this.useParamo = useParamo; - } - - // ---------------------------------------------------------------- - - protected boolean wireScopedProxy; - protected boolean detectMixedScopes; - - public boolean isWireScopedProxy() { - return wireScopedProxy; - } - - /** - * Defines if scoped proxies should be wired. - */ - public PetiteConfig setWireScopedProxy(final boolean wireScopedProxy) { - this.wireScopedProxy = wireScopedProxy; - return this; - } - - public boolean isDetectMixedScopes() { - return detectMixedScopes; - } - - /** - * Defines if mixed scopes should be detected as errors. - * If {@link #wireScopedProxy} is not set, then enabling this flag - * will throw an exception on mixed scopes. If {@link #wireScopedProxy} is set - * enabling this flag will just issue a warn message in the log. - */ - public PetiteConfig setDetectMixedScopes(final boolean detectMixedScopes) { - this.detectMixedScopes = detectMixedScopes; - return this; - } -} diff --git a/jodd-petite/src/main/java/jodd/petite/PetiteContainer.java b/jodd-petite/src/main/java/jodd/petite/PetiteContainer.java deleted file mode 100644 index 7d0d0007d..000000000 --- a/jodd-petite/src/main/java/jodd/petite/PetiteContainer.java +++ /dev/null @@ -1,458 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.bean.BeanUtil; -import jodd.petite.def.BeanReferences; -import jodd.petite.def.MethodInjectionPoint; -import jodd.petite.def.ProviderDefinition; -import jodd.petite.meta.InitMethodInvocationStrategy; -import jodd.petite.scope.Scope; -import jodd.petite.scope.SingletonScope; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.lang.reflect.Method; - -/** - * Petite IOC container. - * @see PetiteRegistry for fluent java registration of Petite beans. - */ -public class PetiteContainer extends PetiteBeans { - - private static final Logger log = LoggerFactory.getLogger(PetiteContainer.class); - - /** - * Petite container reference name. - * Used when container itself is added as its bean. - * @see #addSelf() - * @see #addSelf(String) - */ - public static final String PETITE_CONTAINER_REF_NAME = "petiteContainer"; - - protected final ScopedProxyManager scopedProxyManager; - - /** - * Creates new Petite container using {@link PetiteConfig default configuration}. - */ - public PetiteContainer() { - this(new PetiteConfig()); - } - - /** - * Creates new Petite container using {@link PetiteContainer provided configuration}. - */ - public PetiteContainer(final PetiteConfig config) { - super(config); - - scopedProxyManager = new ScopedProxyManager(); - - if (log.isDebugEnabled()) { - log.debug("Petite container created"); - } - } - - // ---------------------------------------------------------------- core - - protected Object lookupMixingScopedBean(final BeanDefinition def, final BeanReferences refNames) { - final boolean mixing = petiteConfig.wireScopedProxy || petiteConfig.detectMixedScopes; - - Object value = null; - - if (mixing) { - final BeanDefinition refBeanDefinition = lookupBeanDefinitions(refNames); - - if (refBeanDefinition != null) { - value = scopedProxyManager.lookupValue(PetiteContainer.this, def, refBeanDefinition); - } - } - - if (value == null) { - value = PetiteContainer.this.getBean(refNames); - } - - return value; - } - - // ---------------------------------------------------------------- get beans - - /** - * Returns Petite bean instance. Bean name will be resolved from provided type. - */ - @SuppressWarnings({"unchecked"}) - public T getBean(final Class type) { - final String name = resolveBeanName(type); - return (T) getBean(name); - } - - /** - * Returns Petite bean instance named as one of the provided names. - * Returns {@code null} if bean is not found. - */ - protected Object getBean(final BeanReferences beanReferences) { - final int total = beanReferences.size(); - - for (int i = 0; i < total; i++) { - final String name = beanReferences.name(i); - - if (name != null) { - final Object bean = getBean(name); - if (bean != null) { - return bean; - } - } - } - return null; - } - - /** - * Returns Petite bean instance. - * Petite container will find the bean in corresponding scope and all its dependencies, - * either by constructor or property injection. When using constructor injection, cyclic dependencies - * can not be prevented, but at least they are detected. - * - * @see PetiteContainer#createBean(Class) - */ - public T getBean(final String name) { - - // Lookup for registered bean definition. - final BeanDefinition def = lookupBeanDefinition(name); - - if (def == null) { - - // try provider - final ProviderDefinition providerDefinition = providers.get(name); - - if (providerDefinition != null) { - return (T) invokeProvider(providerDefinition); - } - return null; - } - - // Find the bean in its scope - Object bean = def.scopeLookup(); - - if (bean == null) { - // synchronize bean creation on the bean definitions - synchronized (def) { - bean = def.scopeLookup(); - if (bean == null) { - // Create new bean in the scope - initBeanDefinition(def); - final BeanData beanData = new BeanData(this, def); - registerBeanAndWireAndInjectParamsAndInvokeInitMethods(beanData); - bean = beanData.bean(); - } - } - } - - return (T) bean; - } - - /** - * Resolves and initializes bean definition. May be called multiple times. - */ - protected void initBeanDefinition(final BeanDefinition def) { - // init methods - if (def.initMethods == null) { - def.initMethods = petiteResolvers.resolveInitMethodPoint(def.type); - } - // destroy methods - if (def.destroyMethods == null) { - def.destroyMethods = petiteResolvers.resolveDestroyMethodPoint(def.type); - } - // properties - if (def.properties == null) { - def.properties = petiteResolvers.resolvePropertyInjectionPoint(def.type, def.wiringMode == WiringMode.AUTOWIRE); - } - // methods - if (def.methods == null) { - def.methods = petiteResolvers.resolveMethodInjectionPoint(def.type); - } - // ctors - if (def.ctor == null) { - def.ctor = petiteResolvers.resolveCtorInjectionPoint(def.type); - } - // values - if (def.values == null) { - def.values = paramManager.resolveParamInjectionPoints(def.type); - } - // sets - if (def.sets == null) { - def.sets = petiteResolvers.resolveSetInjectionPoint(def.type, def.wiringMode == WiringMode.AUTOWIRE); - } - // params - if (def.params == null) { - def.params = paramManager.filterParametersForBeanName(def.name, petiteConfig.getResolveReferenceParameters()); - } - } - - /** - * Wires bean, injects parameters and invokes init methods. - * Such a loooong name :) - */ - protected void registerBeanAndWireAndInjectParamsAndInvokeInitMethods(final BeanData beanData) { - initBeanDefinition(beanData.definition()); - - beanData.scopeRegister(); - beanData.invokeInitMethods(InitMethodInvocationStrategy.POST_CONSTRUCT); - beanData.wireBean(); - beanData.invokeInitMethods(InitMethodInvocationStrategy.POST_DEFINE); - beanData.injectParams(paramManager, petiteConfig.isImplicitParamInjection()); - beanData.invokeInitMethods(InitMethodInvocationStrategy.POST_INITIALIZE); - beanData.invokeConsumerIfRegistered(); - } - - // ---------------------------------------------------------------- wire - - /** - * Wires provided bean with the container using default wiring mode. - * Bean is not registered withing container. - */ - public void wire(final Object bean) { - wire(bean, null); - } - - /** - * Wires provided bean with the container and optionally invokes init methods. - * Bean is not registered withing container. - */ - public void wire(final Object bean, final WiringMode wiringMode) { - final WiringMode finalWiringMode = petiteConfig.resolveWiringMode(wiringMode); - - final BeanDefinition def = externalsCache.get( - bean.getClass(), (c) -> { - final BeanDefinition beanDefinition = createBeandDefinitionForExternalBeans(c, finalWiringMode); - initBeanDefinition(beanDefinition); - return beanDefinition; - }); - - registerBeanAndWireAndInjectParamsAndInvokeInitMethods(new BeanData(this, def, bean)); - } - - /** - * Invokes the method of some bean with the container, when its parameters requires to be injected into. - * The bean is not registered within container. - */ - public T invokeMethod(final Object bean, final Method method) { - final WiringMode wiringMode = petiteConfig.resolveWiringMode(null); - - final BeanDefinition def = externalsCache.get( - bean.getClass(), (c) -> { - final BeanDefinition beanDefinition = createBeandDefinitionForExternalBeans(c, wiringMode); - initBeanDefinition(beanDefinition); - return beanDefinition; - }); - - final BeanData beanData = new BeanData(this, def, bean); - - for (final MethodInjectionPoint methodInjectionPoint : def.methods) { - if (methodInjectionPoint.method.equals(method)) { - return (T) beanData.invokeMethodInjectionPoint(methodInjectionPoint); - } - } - try { - return (T) method.invoke(bean); - } catch (final Exception e) { - throw new PetiteException(e); - } - } - - // ---------------------------------------------------------------- create - - /** - * Creates and wires a bean within the container using default wiring mode and default init methods flag. - * Bean is not registered. - */ - public E createBean(final Class type) { - return createBean(type, null); - } - - /** - * Creates and wires a bean within the container and optionally invokes init methods. However, bean is - * not registered. - */ - @SuppressWarnings({"unchecked"}) - public E createBean(final Class type, final WiringMode wiringMode) { - final WiringMode finalWiringMode = petiteConfig.resolveWiringMode(wiringMode); - - final BeanDefinition def = externalsCache.get( - type, (t) -> { - final BeanDefinition beanDefinition = createBeandDefinitionForExternalBeans(t, finalWiringMode); - initBeanDefinition(beanDefinition); - return beanDefinition; - }); - - final BeanData beanData = new BeanData(this, def); - registerBeanAndWireAndInjectParamsAndInvokeInitMethods(beanData); - return beanData.bean(); - } - - // ---------------------------------------------------------------- providers - - /** - * Invokes provider to get a bean. - */ - protected Object invokeProvider(final ProviderDefinition provider) { - if (provider.method != null) { - - final Object bean; - if (provider.beanName != null) { - // instance factory method - bean = getBean(provider.beanName); - } else { - // static factory method - bean = null; - } - try { - return provider.method.invoke(bean); - } catch (final Exception ex) { - throw new PetiteException("Invalid provider method: " + provider.method.getName(), ex); - } - } - - throw new PetiteException("Invalid provider"); - } - - // ---------------------------------------------------------------- add - - /** - * Adds object instance to the container as singleton bean using default - * wiring mode and default init method flag. - */ - public void addBean(final String name, final Object bean) { - addBean(name, bean, null); - } - - /** - * Adds object instance to the container as singleton bean. - */ - public void addBean(final String name, final Object bean, WiringMode wiringMode) { - wiringMode = petiteConfig.resolveWiringMode(wiringMode); - registerPetiteBean(bean.getClass(), name, SingletonScope.class, wiringMode, false, null); - final BeanDefinition def = lookupExistingBeanDefinition(name); - registerBeanAndWireAndInjectParamsAndInvokeInitMethods(new BeanData(this, def, bean)); - } - - /** - * Adds self instance to the container so internal beans may fetch - * container for further usage. No wiring is used and no init methods are invoked. - */ - public void addSelf(final String name) { - addBean(name, this, WiringMode.NONE); - } - - /** - * Adds self instance to the container so internal beans may fetch - * container for further usage. No wiring is used and no init methods are invoked. - */ - public void addSelf() { - addBean(PETITE_CONTAINER_REF_NAME, this, WiringMode.NONE); - } - - // ---------------------------------------------------------------- property - - /** - * Sets petite bean property. - */ - public void setBeanProperty(final String name, final Object value) { - Object bean = null; - int ndx = name.length(); - - while (true) { - ndx = name.lastIndexOf('.', ndx); - if (ndx == -1) { - break; - } - - final String beanName = name.substring(0, ndx); - bean = getBean(beanName); - if (bean != null) { - break; - } - ndx--; - } - - if (bean == null) { - throw new PetiteException("Invalid bean property: " + name); - } - - try { - BeanUtil.declared.setProperty(bean, name.substring(ndx + 1), value); - } catch (final Exception ex) { - throw new PetiteException("Invalid bean property: " + name, ex); - } - } - - /** - * Returns petite bean property value. - */ - public Object getBeanProperty(final String name) { - final int ndx = name.indexOf('.'); - if (ndx == -1) { - throw new PetiteException("Only bean name is specified, missing property name: " + name); - } - final String beanName = name.substring(0, ndx); - final Object bean = getBean(beanName); - if (bean == null) { - throw new PetiteException("Bean doesn't exist: " + name); - } - try { - return BeanUtil.declared.getProperty(bean, name.substring(ndx + 1)); - } catch (final Exception ex) { - throw new PetiteException("Invalid bean property: " + name, ex); - } - } - - - // ---------------------------------------------------------------- registry - - /** - * Creates {@link PetiteRegistry} helper tool for this container. - */ - public PetiteRegistry createContainerRegistry() { - return PetiteRegistry.of(this); - } - - - // ---------------------------------------------------------------- shutdown - - /** - * Shutdowns container. After container is down, it can't be used anymore. - */ - public void shutdown() { - scopes.forEachValue(Scope::shutdown); - - - externalsCache.clear(); - beans.clear(); - beansAlt.clear(); - scopes.clear(); - providers.clear(); - beanCollections.clear(); - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/PetiteException.java b/jodd-petite/src/main/java/jodd/petite/PetiteException.java deleted file mode 100644 index a53bcbacd..000000000 --- a/jodd-petite/src/main/java/jodd/petite/PetiteException.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.exception.UncheckedException; - -/** - * Petite exception. - */ -public class PetiteException extends UncheckedException { - - public PetiteException(final Throwable t) { - super(t); - } - - public PetiteException(final String message) { - super(message); - } - - public PetiteException(final String message, final Throwable t) { - super(message, t); - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/PetiteReferenceType.java b/jodd-petite/src/main/java/jodd/petite/PetiteReferenceType.java deleted file mode 100644 index ea10a2794..000000000 --- a/jodd-petite/src/main/java/jodd/petite/PetiteReferenceType.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -/** - * {@link jodd.petite.meta.PetiteInject Petite injection} references. - * When injection annotation is used without the explicit bean name, - * Petite Container will try to resolve name from various sources, - * defined by this enumeration. - */ -public enum PetiteReferenceType { - - /** - * Field or argument name is used as bean name. - */ - NAME, - - /** - * Un-capitalized short type name is used as bean name. - */ - TYPE_SHORT_NAME, - - /** - * Full type name (package and class name) is used as bean name. - */ - TYPE_FULL_NAME; - - /** - * Default array of reference types. - */ - public static PetiteReferenceType[] DEFAULT = new PetiteReferenceType[] { - PetiteReferenceType.NAME, - PetiteReferenceType.TYPE_SHORT_NAME, - PetiteReferenceType.TYPE_FULL_NAME - }; - -} diff --git a/jodd-petite/src/main/java/jodd/petite/PetiteRegistry.java b/jodd-petite/src/main/java/jodd/petite/PetiteRegistry.java deleted file mode 100644 index 0fc677010..000000000 --- a/jodd-petite/src/main/java/jodd/petite/PetiteRegistry.java +++ /dev/null @@ -1,481 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.meta.InitMethodInvocationStrategy; -import jodd.petite.scope.Scope; -import jodd.util.ClassUtil; - -import java.util.function.Consumer; - -/** - * Petite registry helps with manual registration - * of Petite beans by allowing fluent interface. - */ -public class PetiteRegistry { - - // ---------------------------------------------------------------- static - - /** - * Starts with fluent registration. - */ - public static PetiteRegistry of(final PetiteContainer petiteContainer) { - return new PetiteRegistry(petiteContainer); - } - - // ---------------------------------------------------------------- ctor - - private final PetiteContainer petiteContainer; - - /** - * Creates Petite registry. - */ - public PetiteRegistry(final PetiteContainer petiteContainer) { - this.petiteContainer = petiteContainer; - } - - /** - * Returns {@link PetiteContainer}. - */ - public PetiteContainer petiteContainer() { - return petiteContainer; - } - - // ---------------------------------------------------------------- register bean - - /** - * Starts with bean registration. Example: - * bean(Foo.class).name("").scope(...).wiringMode(...).define().register(); - * - * @see PetiteBeans#registerPetiteBean(Class, String, Class, WiringMode, boolean, Consumer) - */ - public BeanRegister bean(final Class beanType) { - return new BeanRegister(beanType); - } - - public class BeanRegister { - - private final Class beanType; - private String beanName; - private Class scopeType; - private WiringMode wiringMode; - private boolean define; - private Consumer consumer; - - private BeanRegister(final Class beanType) { - this.beanType = beanType; - } - - /** - * Defines bean name. If missing, it will be - * resolved from type name. - */ - public BeanRegister name(final String name) { - this.beanName = name; - return this; - } - - /** - * Defines beans scope. - */ - public BeanRegister scope(final Class scope) { - this.scopeType = scope; - return this; - } - - /** - * Defines beans wire mode. - */ - public BeanRegister wire(final WiringMode wiringMode) { - this.wiringMode = wiringMode; - return this; - } - - /** - * Bean will be defined rather just registered. - */ - public BeanRegister define() { - this.define = true; - return this; - } - - public BeanRegister with(final Consumer consumer) { - this.consumer = consumer; - return this; - } - - /** - * Registers a bean. - */ - public void register() { - petiteContainer.registerPetiteBean(beanType, beanName, scopeType, wiringMode, define, consumer); - } - } - - // ---------------------------------------------------------------- wiring - - /** - * Starts with defining injection points (i.e. wiring) for existing bean. - */ - public BeanWire wire(final String beanName) { - petiteContainer.lookupExistingBeanDefinition(beanName); - return new BeanWire(beanName); - } - - /** - * Bean wiring. - */ - public class BeanWire { - - protected final String beanName; - - private BeanWire(final String beanName) { - this.beanName = beanName; - } - - // ---------------------------------------------------------------- property - - /** - * Wires beans property. Example: - * wire("").property("").ref(...).bind(); - * @see PetiteBeans#registerPetitePropertyInjectionPoint(String, String, String) - */ - public BeanWireProperty property(final String propertyName) { - return new BeanWireProperty(propertyName); - } - - public class BeanWireProperty { - - protected final String propertyName; - protected String reference; - - private BeanWireProperty(final String propertyName) { - this.propertyName = propertyName; - } - - /** - * Defines property reference, - */ - public BeanWireProperty ref(final String reference) { - this.reference = reference; - return this; - } - - /** - * Registers property injection point. - */ - public void bind() { - petiteContainer.registerPetitePropertyInjectionPoint(beanName, propertyName, reference); - } - } - - // ---------------------------------------------------------------- ctor - - /** - * Wires beans constructor. - * @see PetiteBeans#registerPetiteCtorInjectionPoint(String, Class[], String[]) - */ - public BeanWireCtor ctor(final Class... ctorArgumentTypes) { - return new BeanWireCtor(ctorArgumentTypes); - } - - public class BeanWireCtor { - - protected final Class[] ctorArgumentTypes; - protected String[] references; - - private BeanWireCtor(Class... ctorArgumentTypes) { - if (ctorArgumentTypes.length == 0) { - ctorArgumentTypes = null; - } - this.ctorArgumentTypes = ctorArgumentTypes; - } - - /** - * Defines constructor references. - */ - public BeanWireCtor ref(String... references) { - if (references.length == 0) { - references = null; - } - this.references = references; - return this; - } - - /** - * Registers constructor injection point. - */ - public void bind() { - petiteContainer.registerPetiteCtorInjectionPoint(beanName, ctorArgumentTypes, references); - } - } - - // ---------------------------------------------------------------- method - /** - * Wires beans method. - * @see PetiteBeans#registerPetiteCtorInjectionPoint(String, Class[], String[]) - */ - public BeanWireMethod method(final String methodName) { - return new BeanWireMethod(methodName); - } - - public class BeanWireMethod { - - protected final String methodName; - protected Class[] methodArgumentTypes; - protected String[] references; - - private BeanWireMethod(final String methodName) { - this.methodName = methodName; - } - - /** - * Defines method argument types. - */ - public BeanWireMethod args(Class... methodArgumentTypes) { - if (methodArgumentTypes.length == 0) { - methodArgumentTypes = null; - } - this.methodArgumentTypes = methodArgumentTypes; - return this; - } - - /** - * Defines method references. - */ - public BeanWireMethod ref(String... references) { - if (references.length == 0) { - references = null; - } - this.references = references; - return this; - } - - /** - * Registers method injection point. - */ - public void bind() { - petiteContainer.registerPetiteMethodInjectionPoint(beanName, methodName, methodArgumentTypes, references); - } - } - - // ---------------------------------------------------------------- set - - /** - * Wires beans set. Example: - * wire("").set("").ref(...).bind(); - * @see PetiteBeans#registerPetitePropertyInjectionPoint(String, String, String) - */ - public BeanWireSet set(final String setPropertyName) { - return new BeanWireSet(setPropertyName); - } - - public class BeanWireSet { - - protected final String setPropertyName; - protected String reference; - - private BeanWireSet(final String setPropertyName) { - this.setPropertyName = setPropertyName; - } - - /** - * Defines set references. - */ - public BeanWireSet ref(final String reference) { - this.reference = reference; - return this; - } - - /** - * Defines set injection point. - */ - public void bind() { - petiteContainer.registerPetiteSetInjectionPoint(beanName, setPropertyName); - } - } - } - - // ---------------------------------------------------------------- init - - /** - * Starts registration of init method. - */ - public BeanInit init(final String beanName) { - petiteContainer.lookupExistingBeanDefinition(beanName); - return new BeanInit(beanName); - } - - public class BeanInit { - - protected final String beanName; - protected String[] methods; - protected InitMethodInvocationStrategy strategy; - - private BeanInit(final String beanName) { - this.beanName = beanName; - } - - /** - * Defines init methods. - */ - public BeanInit methods(String... methods) { - if (methods.length == 0) { - methods = null; - } - this.methods = methods; - return this; - } - - /** - * Defines init method invocation strategy, - */ - public BeanInit invoke(final InitMethodInvocationStrategy strategy) { - this.strategy = strategy; - return this; - } - - /** - * Registers init methods. - */ - public void register() { - petiteContainer.registerPetiteInitMethods(beanName, strategy, methods); - } - } - - // ---------------------------------------------------------------- destroy - - /** - * Starts registration of destroy method. - */ - public BeanDestroy destroy(final String beanName) { - petiteContainer.lookupExistingBeanDefinition(beanName); - return new BeanDestroy(beanName); - } - - public class BeanDestroy { - - protected final String beanName; - protected String[] methods; - - private BeanDestroy(final String beanName) { - this.beanName = beanName; - } - - /** - * Defines destroy methods. - */ - public BeanDestroy methods(String... methods) { - if (methods.length == 0) { - methods = null; - } - this.methods = methods; - return this; - } - - /** - * Registers destroy methods. - */ - public void register() { - petiteContainer.registerPetiteDestroyMethods(beanName, methods); - } - } - - // ---------------------------------------------------------------- provider - - /** - * Starts with provider definition. - */ - public BeanProvider provider(final String providerName) { - return new BeanProvider(providerName); - } - - public class BeanProvider { - - protected final String providerName; - protected String beanName; - protected Class type; - protected String methodName; - protected Class[] methodArgsTypes; - - private BeanProvider(final String providerName) { - this.providerName = providerName; - } - - /** - * Defines bean name. - */ - public BeanProvider bean(final String beanName) { - if (type != null) { - throw new PetiteException("Petite provider type already defined"); - } - this.beanName = beanName; - return this; - } - - /** - * Defines bean type. - */ - public BeanProvider type(final Class type) { - if (beanName != null) { - throw new PetiteException("Petite provider bean name already defined"); - } - this.type = type; - return this; - } - - /** - * Defines provider method name. - */ - public BeanProvider method(final String methodName) { - this.methodName = methodName; - return this; - } - - /** - * Defines method argument types. - */ - public BeanProvider args(Class... methodArgsTypes) { - if (methodArgsTypes.length == 0) { - methodArgsTypes = ClassUtil.EMPTY_CLASS_ARRAY; - } - this.methodArgsTypes = methodArgsTypes; - return this; - } - - /** - * Registers provider. - */ - public void register() { - if (type != null) { - petiteContainer.registerPetiteProvider(providerName, type, methodName, methodArgsTypes); - } else { - petiteContainer.registerPetiteProvider(providerName, beanName, methodName, methodArgsTypes); - } - } - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/PetiteResolvers.java b/jodd-petite/src/main/java/jodd/petite/PetiteResolvers.java deleted file mode 100644 index 896448a3d..000000000 --- a/jodd-petite/src/main/java/jodd/petite/PetiteResolvers.java +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.def.CtorInjectionPoint; -import jodd.petite.def.DestroyMethodPoint; -import jodd.petite.def.InitMethodPoint; -import jodd.petite.def.MethodInjectionPoint; -import jodd.petite.def.PropertyInjectionPoint; -import jodd.petite.def.ProviderDefinition; -import jodd.petite.def.SetInjectionPoint; -import jodd.petite.resolver.CtorResolver; -import jodd.petite.resolver.DestroyMethodResolver; -import jodd.petite.resolver.InitMethodResolver; -import jodd.petite.resolver.MethodResolver; -import jodd.petite.resolver.PropertyResolver; -import jodd.petite.resolver.ProviderResolver; -import jodd.petite.resolver.ReferencesResolver; -import jodd.petite.resolver.SetResolver; - -/** - * Holds all resolvers instances and offers delegate methods. - */ -public class PetiteResolvers { - - protected final ReferencesResolver referencesResolver; - protected final CtorResolver ctorResolver; - protected final PropertyResolver propertyResolver; - protected final MethodResolver methodResolver; - protected final SetResolver setResolver; - protected final InitMethodResolver initMethodResolver; - protected final DestroyMethodResolver destroyMethodResolver; - protected final ProviderResolver providerResolver; - - public PetiteResolvers(final ReferencesResolver referencesResolver) { - this.referencesResolver = referencesResolver; - this.ctorResolver = new CtorResolver(referencesResolver); - this.methodResolver = new MethodResolver(referencesResolver); - this.propertyResolver = new PropertyResolver(referencesResolver); - this.setResolver = new SetResolver(); - this.initMethodResolver = new InitMethodResolver(); - this.destroyMethodResolver = new DestroyMethodResolver(); - this.providerResolver = new ProviderResolver(); - } - - // ---------------------------------------------------------------- delegates - - /** - * Resolves constructor injection point. - */ - public CtorInjectionPoint resolveCtorInjectionPoint(final Class type) { - return ctorResolver.resolve(type, true); - } - - /** - * Resolves property injection points. - */ - public PropertyInjectionPoint[] resolvePropertyInjectionPoint(final Class type, final boolean autowire) { - return propertyResolver.resolve(type, autowire); - } - - /** - * Resolves method injection points. - */ - public MethodInjectionPoint[] resolveMethodInjectionPoint(final Class type) { - return methodResolver.resolve(type); - } - - /** - * Resolves set injection points. - */ - public SetInjectionPoint[] resolveSetInjectionPoint(final Class type, final boolean autowire) { - return setResolver.resolve(type, autowire); - } - - /** - * Resolves init method points. - */ - public InitMethodPoint[] resolveInitMethodPoint(final Class type) { - return initMethodResolver.resolve(type); - } - - /** - * Resolves destroy method points. - */ - public DestroyMethodPoint[] resolveDestroyMethodPoint(final Class type) { - return destroyMethodResolver.resolve(type); - } - - /** - * Resolves provider definition defined in a bean. - */ - public ProviderDefinition[] resolveProviderDefinitions(final Class type, final String name) { - return providerResolver.resolve(type, name); - } - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/ScopedProxyAdvice.java b/jodd-petite/src/main/java/jodd/petite/ScopedProxyAdvice.java deleted file mode 100644 index 3da5ececb..000000000 --- a/jodd-petite/src/main/java/jodd/petite/ScopedProxyAdvice.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -import java.lang.reflect.Method; - -/** - * Scoped proxy advice. For each wrapped method, - * it will lookup for the bean from the container - * and will delegate the method call to it. - */ -public class ScopedProxyAdvice implements ProxyAdvice { - - /** - * Petite container. - */ - public PetiteContainer petiteContainer; - /** - * Bean name for lookup. - */ - public String name; - - public Object execute() throws Exception { - Object target = petiteContainer.getBean(name); - - // collect data about target method call - - String methodName = ProxyTarget.targetMethodName(); - - Class[] methodArgumentTypes = ProxyTarget.createArgumentsClassArray(); - - Object[] methodArguments = ProxyTarget.createArgumentsArray(); - - // delegate method call to target - - Method targetMethod = target.getClass().getMethod(methodName, methodArgumentTypes); - - Object result = targetMethod.invoke(target, methodArguments); - - // return target result - - return ProxyTarget.returnValue(result); - } -} diff --git a/jodd-petite/src/main/java/jodd/petite/ScopedProxyManager.java b/jodd-petite/src/main/java/jodd/petite/ScopedProxyManager.java deleted file mode 100644 index 403c9879b..000000000 --- a/jodd-petite/src/main/java/jodd/petite/ScopedProxyManager.java +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.proxetta.ProxettaBeanDefinition; -import jodd.petite.scope.Scope; -import jodd.proxetta.Proxetta; -import jodd.proxetta.ProxyAspect; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.impl.ProxyProxettaFactory; -import jodd.proxetta.pointcuts.AllMethodsPointcut; -import jodd.util.ArraysUtil; -import jodd.util.ClassUtil; -import jodd.util.TypeCache; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; - -/** - * Manager for mixing scopes. - * 'Mixed scopes' is the situation when 'smaller' scope - * is injected into the 'bigger' scope. Trivial example - * is when prototype scoped bean is injected into - * singleton bean. - *

- * Mixed scopes are handled using smart factory/proxy-wrapper singletons - * instead of 'smaller' scoped beans. On each method call of - * wrapped factory, smaller scoped bean will be looked up and - * that instance will be used for passing by the method call. - *

- * Manager also has to determine if scope combination is candidate for - * mixed scopes. - */ -public class ScopedProxyManager { - - private static final Logger log = LoggerFactory.getLogger(ScopedProxyManager.class); - - protected ProxyAspect aspect = new ProxyAspect(ScopedProxyAdvice.class, new AllMethodsPointcut()); - - protected TypeCache proxyClasses = TypeCache.createDefault(); - protected Map proxies = new HashMap<>(); - - public ScopedProxyManager() { - log.debug("ScopedProxyManager created"); - } - - /** - * Returns scoped proxy bean if injection scopes are mixed on some injection point. - * May return null if mixing scopes is not detected. - */ - public Object lookupValue(final PetiteContainer petiteContainer, final BeanDefinition targetBeanDefinition, final BeanDefinition refBeanDefinition) { - final Scope targetScope = targetBeanDefinition.scope; - final Scope refBeanScope = refBeanDefinition.scope; - - final boolean detectMixedScopes = petiteContainer.config().isDetectMixedScopes(); - final boolean wireScopedProxy = petiteContainer.config().isWireScopedProxy(); - - // when target scope is null then all beans can be injected into it - // similar to prototype scope - if (targetScope != null && !targetScope.accept(refBeanScope)) { - - if (!wireScopedProxy) { - if (detectMixedScopes) { - throw new PetiteException(createMixingMessage(targetBeanDefinition, refBeanDefinition)); - } - return null; - } - - if (detectMixedScopes) { - if (log.isWarnEnabled()) { - log.warn(createMixingMessage(targetBeanDefinition, refBeanDefinition)); - } - } else { - if (log.isDebugEnabled()) { - log.debug(createMixingMessage(targetBeanDefinition, refBeanDefinition)); - } - } - - final String scopedProxyBeanName = refBeanDefinition.name; - - Object proxy = proxies.get(scopedProxyBeanName); - - if (proxy == null) { - proxy = createScopedProxyBean(petiteContainer, refBeanDefinition); - - proxies.put(scopedProxyBeanName, proxy); - } - - return proxy; - } - - return null; - } - - /** - * Creates mixed scope message. - */ - protected String createMixingMessage(final BeanDefinition targetBeanDefinition, final BeanDefinition refBeanDefinition) { - return "Scopes mixing detected: " + - refBeanDefinition.name + "@" + refBeanDefinition.scope.getClass().getSimpleName() + " -> " + - targetBeanDefinition.name + "@" + targetBeanDefinition.scope.getClass().getSimpleName(); - } - - - /** - * Creates scoped proxy bean for given bean definition. - */ - protected Object createScopedProxyBean(final PetiteContainer petiteContainer, final BeanDefinition refBeanDefinition) { - - final Class beanType = refBeanDefinition.type; - - Class proxyClass = proxyClasses.get(beanType); - - if (proxyClass == null) { - // create proxy class only once - - if (refBeanDefinition instanceof ProxettaBeanDefinition) { - // special case, double proxy! - - final ProxettaBeanDefinition pbd = - (ProxettaBeanDefinition) refBeanDefinition; - - final ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspects(ArraysUtil.insert(pbd.proxyAspects, aspect, 0)); - - proxetta.setClassNameSuffix("$ScopedProxy"); - proxetta.setVariableClassName(true); - - final ProxyProxettaFactory builder = proxetta.proxy().setTarget(pbd.originalTarget); - - proxyClass = builder.define(); - - proxyClasses.put(beanType, proxyClass); - } - else { - final ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspect(aspect); - - proxetta.setClassNameSuffix("$ScopedProxy"); - proxetta.setVariableClassName(true); - - final ProxyProxettaFactory builder = proxetta.proxy().setTarget(beanType); - - proxyClass = builder.define(); - - proxyClasses.put(beanType, proxyClass); - } - } - - final Object proxy; - - try { - proxy = ClassUtil.newInstance(proxyClass); - - Field field = proxyClass.getField("$__petiteContainer$0"); - - field.set(proxy, petiteContainer); - - field = proxyClass.getField("$__name$0"); - - field.set(proxy, refBeanDefinition.name); - } catch (final Exception ex) { - throw new PetiteException(ex); - } - - return proxy; - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/WiringMode.java b/jodd-petite/src/main/java/jodd/petite/WiringMode.java deleted file mode 100644 index a5859c9f9..000000000 --- a/jodd-petite/src/main/java/jodd/petite/WiringMode.java +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -/** - * Wiring modes for Petite beans. - */ -public enum WiringMode { - - /** - * Default wiring mode is set by the container. - */ - DEFAULT(-1), - - /** - * No wiring at all. Petite beans are not injected even when there is an - * explicit definition of injection. - */ - NONE(0), - /** - * Explicit and strict wiring. Wires explicitly defined injection points. - * Throws an exception if wiring can not be satisfied. - */ - STRICT(1), - /** - * Explicit and loose wiring. Wires only explicitly defined injection points. - * Does not throw exception if wiring can not be satisfied. - */ - OPTIONAL(2), - /** - * Auto-wires beans. Beans will be injected for defined injection points - * and in all places where naming convention is satisfied. - * No exception is thrown if wiring ca not be satisfied. - */ - AUTOWIRE(3); - - private final int value; - - WiringMode(final int value) { - this.value = value; - } - - public int value() { - return value; - } - - @Override - public String toString() { - return name(); - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/def/BeanReferences.java b/jodd-petite/src/main/java/jodd/petite/def/BeanReferences.java deleted file mode 100644 index dcc00493e..000000000 --- a/jodd-petite/src/main/java/jodd/petite/def/BeanReferences.java +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.def; - -import java.util.Objects; - -/** - * Set of names that represent bean reference for the single injection point. - * Each injection point can have more then one definition of bean references. - * They are used when reference name is not explicitly defined. - */ -public class BeanReferences { - - private final String[] names; - - /** - * Creates new bean reference. - */ - public static BeanReferences of(final String... names) { - Objects.requireNonNull(names); - return new BeanReferences(names); - } - - BeanReferences(final String... names) { - this.names = names; - } - - /** - * Returns {@code} true if BeanReferences is empty. - */ - public boolean isEmpty() { - return names.length == 0; - } - - /** - * Returns the number of name references in this set. - */ - public int size() { - return names.length; - } - - /** - * Returns the name on the index. - */ - public String name(final int ndx) { - return names[ndx]; - } - - /** - * Removes later duplicated references in an array. - * Returns new instance of BeanReferences if there was changes, - * otherwise returns the same instance. - */ - public BeanReferences removeDuplicateNames() { - if (names.length < 2) { - return this; - } - - int nullCount = 0; - - for (int i = 1; i < names.length; i++) { - String thisRef = names[i]; - - if (thisRef == null) { - nullCount++; - continue; - } - - for (int j = 0; j < i; j++) { - if (names[j] == null) { - continue; - } - if (thisRef.equals(names[j])) { - names[i] = null; - break; - } - } - } - - if (nullCount == 0) { - return this; - } - - String[] newRefs = new String[names.length - nullCount]; - int ndx = 0; - - for (String name : names) { - if (name == null) { - continue; - } - newRefs[ndx] = name; - ndx++; - } - - return new BeanReferences(newRefs); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - - sb.append('['); - for (int i = 0; i < names.length; i++) { - if (i != 0) { - sb.append(','); - } - sb.append(names[i]); - } - sb.append(']'); - - return sb.toString(); - } -} diff --git a/jodd-petite/src/main/java/jodd/petite/def/CtorInjectionPoint.java b/jodd-petite/src/main/java/jodd/petite/def/CtorInjectionPoint.java deleted file mode 100644 index f8b4c7f94..000000000 --- a/jodd-petite/src/main/java/jodd/petite/def/CtorInjectionPoint.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.def; - -import java.lang.reflect.Constructor; -import java.util.Objects; - -/** - * Holder for constructor injection points. - */ -public class CtorInjectionPoint { - - public static final CtorInjectionPoint EMPTY = new CtorInjectionPoint(); - - public final Constructor constructor; - public final BeanReferences[] references; - - private CtorInjectionPoint() { - this.constructor = null; - this.references = null; - } - - public CtorInjectionPoint(final Constructor constructor, final BeanReferences[] references) { - Objects.requireNonNull(constructor); - Objects.requireNonNull(references); - - this.constructor = constructor; - this.references = references; - } -} - diff --git a/jodd-petite/src/main/java/jodd/petite/def/DestroyMethodPoint.java b/jodd-petite/src/main/java/jodd/petite/def/DestroyMethodPoint.java deleted file mode 100644 index 869093ec2..000000000 --- a/jodd-petite/src/main/java/jodd/petite/def/DestroyMethodPoint.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.def; - -import java.lang.reflect.Method; -import java.util.Objects; - -/** - * Destroy method point. - */ -public class DestroyMethodPoint { - - public static final DestroyMethodPoint[] EMPTY = new DestroyMethodPoint[0]; - - public final Method method; - - public DestroyMethodPoint(final Method method) { - Objects.requireNonNull(method); - - this.method = method; - } - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/def/InitMethodPoint.java b/jodd-petite/src/main/java/jodd/petite/def/InitMethodPoint.java deleted file mode 100644 index ea3715349..000000000 --- a/jodd-petite/src/main/java/jodd/petite/def/InitMethodPoint.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.def; - -import jodd.petite.meta.InitMethodInvocationStrategy; - -import java.lang.reflect.Method; -import java.util.Objects; - -/** - * Init method point. - */ -public class InitMethodPoint implements Comparable { - - public static final InitMethodPoint[] EMPTY = new InitMethodPoint[0]; - - public final Method method; - public final int order; - public final InitMethodInvocationStrategy invocationStrategy; - - public InitMethodPoint(final Method method, final int order, final InitMethodInvocationStrategy invocationStrategy) { - Objects.requireNonNull(method); - Objects.requireNonNull(invocationStrategy); - - this.method = method; - this.order = order == 0 ? (Integer.MAX_VALUE >> 1) : (order < 0 ? Integer.MAX_VALUE + order: order); - this.invocationStrategy = invocationStrategy; - } - - @Override - public int compareTo(final Object other) { - InitMethodPoint that = (InitMethodPoint) other; - return Integer.compare(this.order, that.order); - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/def/MethodInjectionPoint.java b/jodd-petite/src/main/java/jodd/petite/def/MethodInjectionPoint.java deleted file mode 100644 index afb2c4a4a..000000000 --- a/jodd-petite/src/main/java/jodd/petite/def/MethodInjectionPoint.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.def; - -import java.lang.reflect.Method; -import java.util.Objects; - -/** - * Method injection points. - */ -public class MethodInjectionPoint { - - public static final MethodInjectionPoint[] EMPTY = new MethodInjectionPoint[0]; - - public final Method method; - public final BeanReferences[] references; - - public MethodInjectionPoint(final Method method, final BeanReferences[] references) { - Objects.requireNonNull(method); - Objects.requireNonNull(references); - - this.method = method; - this.references = references; - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/def/PropertyInjectionPoint.java b/jodd-petite/src/main/java/jodd/petite/def/PropertyInjectionPoint.java deleted file mode 100644 index 1d98c89fe..000000000 --- a/jodd-petite/src/main/java/jodd/petite/def/PropertyInjectionPoint.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.def; - -import jodd.introspector.PropertyDescriptor; - -import java.util.Objects; - -/** - * Property injection point. - */ -public class PropertyInjectionPoint { - - public static final PropertyInjectionPoint[] EMPTY = new PropertyInjectionPoint[0]; - - public final PropertyDescriptor propertyDescriptor; - public final BeanReferences references; - - public PropertyInjectionPoint(final PropertyDescriptor propertyDescriptor, final BeanReferences references) { - Objects.requireNonNull(propertyDescriptor); - Objects.requireNonNull(references); - - this.propertyDescriptor = propertyDescriptor; - this.references = references; - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/def/ProviderDefinition.java b/jodd-petite/src/main/java/jodd/petite/def/ProviderDefinition.java deleted file mode 100644 index 8d6bdb584..000000000 --- a/jodd-petite/src/main/java/jodd/petite/def/ProviderDefinition.java +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.def; - -import jodd.petite.PetiteException; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Objects; - -/** - * Bean provider definition. - */ -public class ProviderDefinition { - - public static final ProviderDefinition[] EMPTY = new ProviderDefinition[0]; - - public final String name; - public final String beanName; - public final Method method; - - public ProviderDefinition(final String name, final String beanName, final Method method) { - Objects.requireNonNull(name); - Objects.requireNonNull(beanName); - Objects.requireNonNull(method); - - this.name = name; - this.beanName = beanName; - this.method = method; - } - - public ProviderDefinition(final String name, final Method staticMethod) { - Objects.requireNonNull(name); - Objects.requireNonNull(staticMethod); - - this.name = name; - if (!Modifier.isStatic(staticMethod.getModifiers())) { - throw new PetiteException("Provider method is not static: " + staticMethod); - } - - this.method = staticMethod; - this.beanName = null; - } - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/def/SetInjectionPoint.java b/jodd-petite/src/main/java/jodd/petite/def/SetInjectionPoint.java deleted file mode 100644 index e311a6ab8..000000000 --- a/jodd-petite/src/main/java/jodd/petite/def/SetInjectionPoint.java +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.def; - -import jodd.introspector.FieldDescriptor; -import jodd.introspector.MethodDescriptor; -import jodd.introspector.PropertyDescriptor; -import jodd.introspector.Setter; -import jodd.petite.PetiteException; -import jodd.util.ClassUtil; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Objects; - -/** - * Set injection point. - */ -public class SetInjectionPoint { - - public static final SetInjectionPoint[] EMPTY = new SetInjectionPoint[0]; - - public final PropertyDescriptor propertyDescriptor; - - public final Class type; - - public final Class targetClass; - - public SetInjectionPoint(final PropertyDescriptor propertyDescriptor) { - Objects.requireNonNull(propertyDescriptor); - - this.propertyDescriptor = propertyDescriptor; - this.type = resolveSetType(propertyDescriptor); - - // resolve component type - Class targetClass = null; - - MethodDescriptor writeMethodDescriptor = propertyDescriptor.getWriteMethodDescriptor(); - FieldDescriptor fieldDescriptor = propertyDescriptor.getFieldDescriptor(); - - if (writeMethodDescriptor != null) { - targetClass = Setter.of(writeMethodDescriptor).getSetterRawComponentType(); - } - if (targetClass == null && fieldDescriptor != null) { - targetClass = fieldDescriptor.getRawComponentType(); - } - - this.targetClass = targetClass; - - if (targetClass == null) { - throw new PetiteException("Unknown Petite set component type " + - type.getSimpleName() + '.' + propertyDescriptor.getName()); - } - } - - @SuppressWarnings({"unchecked"}) - protected Class resolveSetType(final PropertyDescriptor propertyDescriptor) { - Class type = (Class) propertyDescriptor.getType(); - - if (ClassUtil.isTypeOf(type, Collection.class)) { - return type; - } - throw new PetiteException("Unsupported Petite set type: " + type.getName()); - } - - /** - * Creates target set for injection. For now it creates HashSet, - * but custom implementation can change this setting. - */ - public Collection createSet(final int length) { - return new HashSet<>(length); - } -} diff --git a/jodd-petite/src/main/java/jodd/petite/def/ValueInjectionPoint.java b/jodd-petite/src/main/java/jodd/petite/def/ValueInjectionPoint.java deleted file mode 100644 index 0bd59da4b..000000000 --- a/jodd-petite/src/main/java/jodd/petite/def/ValueInjectionPoint.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.def; - -public class ValueInjectionPoint { - - public final String property; - public final String valueTemplate; - - public ValueInjectionPoint(final String property, final String valueTemplate) { - this.property = property; - this.valueTemplate = valueTemplate.isEmpty() ? "${" + property + "}" : valueTemplate; - } -} diff --git a/jodd-petite/src/main/java/jodd/petite/def/package-info.java b/jodd-petite/src/main/java/jodd/petite/def/package-info.java deleted file mode 100644 index 8e564580a..000000000 --- a/jodd-petite/src/main/java/jodd/petite/def/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Bean definition classes. - */ -package jodd.petite.def; \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/meta/InitMethodInvocationStrategy.java b/jodd-petite/src/main/java/jodd/petite/meta/InitMethodInvocationStrategy.java deleted file mode 100644 index e29719df4..000000000 --- a/jodd-petite/src/main/java/jodd/petite/meta/InitMethodInvocationStrategy.java +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.meta; - -/** - * Invocation strategy for init methods define moment - * when init methods are invoked. - */ -public enum InitMethodInvocationStrategy { - - /** - * Init methods are invoked right after class is created, i.e. - * after constructor is called and before bean is wired. - */ - POST_CONSTRUCT, - - /** - * Init methods are invoked after the wiring and before parameters - * are injected. - */ - POST_DEFINE, - - /** - * Init methods are invoked after bean is completely initialized, - * i.e. after wiring and parameters injection. Default strategy. - */ - POST_INITIALIZE - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/meta/PetiteBean.java b/jodd-petite/src/main/java/jodd/petite/meta/PetiteBean.java deleted file mode 100644 index 7009636f1..000000000 --- a/jodd-petite/src/main/java/jodd/petite/meta/PetiteBean.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.meta; - -import jodd.petite.WiringMode; -import jodd.petite.scope.Scope; -import jodd.petite.scope.SingletonScope; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Petite bean annotation for classes markups the Petite components. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface PetiteBean { - - /** - * Unique bean name. - */ - String value() default ""; - - /** - * Bean scope, {@link jodd.petite.scope.SingletonScope singleton} by default. - */ - Class scope() default SingletonScope.class; - - /** - * Wiring mode. - */ - WiringMode wiring() default WiringMode.DEFAULT; - -} diff --git a/jodd-petite/src/main/java/jodd/petite/meta/PetiteDestroyMethod.java b/jodd-petite/src/main/java/jodd/petite/meta/PetiteDestroyMethod.java deleted file mode 100644 index e62ddc0cd..000000000 --- a/jodd-petite/src/main/java/jodd/petite/meta/PetiteDestroyMethod.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.meta; - -import jodd.petite.PetiteContainer; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Markups the Petite bean destroy method. - * Destroy methods are called without an order when container is stopped. - * @see PetiteContainer#shutdown() - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -public @interface PetiteDestroyMethod { - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/meta/PetiteInitMethod.java b/jodd-petite/src/main/java/jodd/petite/meta/PetiteInitMethod.java deleted file mode 100644 index fa8dd7709..000000000 --- a/jodd-petite/src/main/java/jodd/petite/meta/PetiteInitMethod.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.meta; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import static jodd.petite.meta.InitMethodInvocationStrategy.POST_INITIALIZE; - -/** - * Markups the Petite bean initialization method. Initialization methods are called once when - * component instance is created. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -public @interface PetiteInitMethod { - - /** - * Indicates the order of init method. Order number of first methods starts from 1. - * Order number of last methods starts from -1 to negatives. 0 is default and - * marks 'in between' methods: methods that executes after first ones and before last ones. - */ - int order() default 0; - - /** - * Defines init method invocation strategy, i.e. moment in beans lifecycle when - * init methods will be invoked. - */ - InitMethodInvocationStrategy invoke() default POST_INITIALIZE; - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/meta/PetiteInject.java b/jodd-petite/src/main/java/jodd/petite/meta/PetiteInject.java deleted file mode 100644 index 8eaf50d08..000000000 --- a/jodd-petite/src/main/java/jodd/petite/meta/PetiteInject.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.meta; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Petite bean reference for fields and constructor arguments. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER}) -public @interface PetiteInject { - - /** - * Name(s) of bean(s) to inject. - */ - String value() default ""; - -} diff --git a/jodd-petite/src/main/java/jodd/petite/meta/PetiteProvider.java b/jodd-petite/src/main/java/jodd/petite/meta/PetiteProvider.java deleted file mode 100644 index 712581b8e..000000000 --- a/jodd-petite/src/main/java/jodd/petite/meta/PetiteProvider.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.meta; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Marker for Petite providers. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE}) -public @interface PetiteProvider { - - /** - * Defines provider name that will be used to - * provide instance to inject. - */ - String value() default ""; - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/meta/PetiteValue.java b/jodd-petite/src/main/java/jodd/petite/meta/PetiteValue.java deleted file mode 100644 index 20323d078..000000000 --- a/jodd-petite/src/main/java/jodd/petite/meta/PetiteValue.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.meta; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Petite parameter value. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.FIELD}) -public @interface PetiteValue { - - /** - * Defines parameter key which value will be injected. - */ - String value() default ""; - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/meta/package-info.java b/jodd-petite/src/main/java/jodd/petite/meta/package-info.java deleted file mode 100644 index 4f1e1563a..000000000 --- a/jodd-petite/src/main/java/jodd/petite/meta/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Annotations used by Petite container. - */ -package jodd.petite.meta; \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/package-info.java b/jodd-petite/src/main/java/jodd/petite/package-info.java deleted file mode 100644 index 11ad18a67..000000000 --- a/jodd-petite/src/main/java/jodd/petite/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Petite container. Simple, small, fast. - */ -package jodd.petite; \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/proxetta/ProxettaAwarePetiteContainer.java b/jodd-petite/src/main/java/jodd/petite/proxetta/ProxettaAwarePetiteContainer.java deleted file mode 100644 index 057ad2c02..000000000 --- a/jodd-petite/src/main/java/jodd/petite/proxetta/ProxettaAwarePetiteContainer.java +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.proxetta; - -import jodd.petite.BeanDefinition; -import jodd.petite.PetiteConfig; -import jodd.petite.PetiteContainer; -import jodd.petite.WiringMode; -import jodd.petite.scope.Scope; -import jodd.proxetta.Proxetta; -import jodd.proxetta.ProxettaFactory; -import jodd.proxetta.ProxyAspect; - -import java.util.function.Consumer; - -/** - * Proxetta-aware Petite container that applies proxies on bean registration. - */ -public class ProxettaAwarePetiteContainer extends PetiteContainer { - - protected final Proxetta proxetta; - - public ProxettaAwarePetiteContainer(final Proxetta proxetta) { - this.proxetta = proxetta; - } - public ProxettaAwarePetiteContainer(final Proxetta proxetta, final PetiteConfig petiteConfig) { - super(petiteConfig); - this.proxetta = proxetta; - } - - /** - * Applies proxetta on bean class before bean registration. - */ - @SuppressWarnings("unchecked") - @Override - protected BeanDefinition createBeanDefinitionForRegistration( - final String name, - Class type, - final Scope scope, - final WiringMode wiringMode, - final Consumer consumer) - { - if (proxetta != null) { - final Class originalType = type; - - final ProxettaFactory builder = proxetta.proxy(); - - builder.setTarget(type); - - type = builder.define(); - - return new ProxettaBeanDefinition( - name, - type, - scope, - wiringMode, - originalType, - proxetta.getAspects(new ProxyAspect[0]), - consumer); - } - - return super.createBeanDefinitionForRegistration(name, type, scope, wiringMode, consumer); - } - - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/proxetta/ProxettaBeanDefinition.java b/jodd-petite/src/main/java/jodd/petite/proxetta/ProxettaBeanDefinition.java deleted file mode 100644 index cf838f8e6..000000000 --- a/jodd-petite/src/main/java/jodd/petite/proxetta/ProxettaBeanDefinition.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.proxetta; - -import jodd.petite.BeanDefinition; -import jodd.petite.WiringMode; -import jodd.petite.scope.Scope; -import jodd.proxetta.ProxyAspect; - -import java.util.function.Consumer; - -/** - * Enhanced version of {@link BeanDefinition} that keeps data about original - * target class and applied proxy aspects. - */ -public class ProxettaBeanDefinition extends BeanDefinition { - - public final ProxyAspect[] proxyAspects; - public final Class originalTarget; - - public ProxettaBeanDefinition( - final String name, - final Class type, - final Scope scope, - final WiringMode wiringMode, - final Class originalTarget, - final ProxyAspect[] proxyAspects, - final Consumer consumer) - { - super(name, type, scope, wiringMode, consumer); - this.originalTarget = originalTarget; - this.proxyAspects = proxyAspects; - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/proxetta/package-info.java b/jodd-petite/src/main/java/jodd/petite/proxetta/package-info.java deleted file mode 100644 index 11d7dade2..000000000 --- a/jodd-petite/src/main/java/jodd/petite/proxetta/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Proxetta aware Petite container. - */ -package jodd.petite.proxetta; \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/resolver/CtorResolver.java b/jodd-petite/src/main/java/jodd/petite/resolver/CtorResolver.java deleted file mode 100644 index 59224f4ae..000000000 --- a/jodd-petite/src/main/java/jodd/petite/resolver/CtorResolver.java +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.resolver; - -import jodd.introspector.ClassDescriptor; -import jodd.introspector.ClassIntrospector; -import jodd.introspector.CtorDescriptor; -import jodd.petite.PetiteException; -import jodd.petite.def.BeanReferences; -import jodd.petite.def.CtorInjectionPoint; - -import java.lang.reflect.Constructor; - -/** - * Resolver for constructor injection points. - */ -public class CtorResolver { - - protected final ReferencesResolver referencesResolver; - - public CtorResolver(final ReferencesResolver referencesResolver) { - this.referencesResolver = referencesResolver; - } - - /** - * Resolves constructor injection point from type. Looks for single annotated constructor. - * If no annotated constructors found, the total number of constructors will be checked. - * If there is only one constructor, that one will be used as injection point. If more - * constructors exist, the default one will be used as injection point. Otherwise, exception - * is thrown. - */ - public CtorInjectionPoint resolve(final Class type, final boolean useAnnotation) { - // lookup methods - ClassDescriptor cd = ClassIntrospector.get().lookup(type); - CtorDescriptor[] allCtors = cd.getAllCtorDescriptors(); - Constructor foundedCtor = null; - Constructor defaultCtor = null; - BeanReferences[] references = null; - - for (CtorDescriptor ctorDescriptor : allCtors) { - Constructor ctor = ctorDescriptor.getConstructor(); - - Class[] paramTypes = ctor.getParameterTypes(); - if (paramTypes.length == 0) { - defaultCtor = ctor; // detects default ctors - } - - if (!useAnnotation) { - continue; - } - - BeanReferences[] ctorReferences = referencesResolver.readAllReferencesFromAnnotation(ctor); - - if (ctorReferences == null) { - continue; - } - if (foundedCtor != null) { - throw new PetiteException("Two or more constructors are annotated as injection points in the bean: " + type.getName()); - } - - foundedCtor = ctor; - references = ctorReferences; - } - - if (foundedCtor == null) { - // there is no annotated constructor - if (allCtors.length == 1) { - foundedCtor = allCtors[0].getConstructor(); - } else { - foundedCtor = defaultCtor; - } - - if (foundedCtor == null) { - // no matching ctor found - // still this is not an error if bean is already instantiated. - return CtorInjectionPoint.EMPTY; - } - - references = referencesResolver.readAllReferencesFromAnnotation(foundedCtor); - - if (references == null) { - references = new BeanReferences[0]; - } - } - - return new CtorInjectionPoint(foundedCtor, references); - } - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/resolver/DestroyMethodResolver.java b/jodd-petite/src/main/java/jodd/petite/resolver/DestroyMethodResolver.java deleted file mode 100644 index 224f49b38..000000000 --- a/jodd-petite/src/main/java/jodd/petite/resolver/DestroyMethodResolver.java +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.resolver; - -import jodd.introspector.ClassDescriptor; -import jodd.introspector.MethodDescriptor; -import jodd.petite.PetiteException; -import jodd.petite.def.DestroyMethodPoint; -import jodd.petite.meta.PetiteDestroyMethod; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -/** - * Resolver for destroy methods. - */ -public class DestroyMethodResolver { - - public DestroyMethodPoint[] resolve(final Class type) { - // lookup methods - List list = new ArrayList<>(); - ClassDescriptor cd = new ClassDescriptor(type, false, false, false, null); - MethodDescriptor[] allMethods = cd.getAllMethodDescriptors(); - - for (MethodDescriptor methodDescriptor : allMethods) { - Method method = methodDescriptor.getMethod(); - - PetiteDestroyMethod petiteDestroyMethod = method.getAnnotation(PetiteDestroyMethod.class); - if (petiteDestroyMethod == null) { - continue; - } - if (method.getParameterTypes().length > 0) { - throw new PetiteException("Arguments are not allowed for Petite destroy method: " + type.getName() + '#' + method.getName()); - } - list.add(new DestroyMethodPoint(method)); - } - - DestroyMethodPoint[] methods; - - if (list.isEmpty()) { - methods = DestroyMethodPoint.EMPTY; - } else { - methods = list.toArray(new DestroyMethodPoint[0]); - } - - return methods; - } - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/resolver/InitMethodResolver.java b/jodd-petite/src/main/java/jodd/petite/resolver/InitMethodResolver.java deleted file mode 100644 index 29bfc6b01..000000000 --- a/jodd-petite/src/main/java/jodd/petite/resolver/InitMethodResolver.java +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.resolver; - -import jodd.introspector.ClassDescriptor; -import jodd.introspector.MethodDescriptor; -import jodd.petite.PetiteException; -import jodd.petite.def.InitMethodPoint; -import jodd.petite.meta.PetiteInitMethod; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Resolver for bean init methods. - */ -public class InitMethodResolver { - - public InitMethodPoint[] resolve(final Class type) { - // lookup methods - List list = new ArrayList<>(); - ClassDescriptor cd = new ClassDescriptor(type, false, false, false, null); - MethodDescriptor[] allMethods = cd.getAllMethodDescriptors(); - - for (MethodDescriptor methodDescriptor : allMethods) { - Method method = methodDescriptor.getMethod(); - - PetiteInitMethod petiteInitMethod = method.getAnnotation(PetiteInitMethod.class); - if (petiteInitMethod == null) { - continue; - } - if (method.getParameterTypes().length > 0) { - throw new PetiteException("Arguments are not allowed for Petite init method: " + type.getName() + '#' + method.getName()); - } - int order = petiteInitMethod.order(); - list.add(new InitMethodPoint(method, order, petiteInitMethod.invoke())); - } - - InitMethodPoint[] methods; - - if (list.isEmpty()) { - methods = InitMethodPoint.EMPTY; - } else { - Collections.sort(list); - methods = list.toArray(new InitMethodPoint[0]); - } - - return methods; - } - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/resolver/MethodResolver.java b/jodd-petite/src/main/java/jodd/petite/resolver/MethodResolver.java deleted file mode 100644 index b67eeb89d..000000000 --- a/jodd-petite/src/main/java/jodd/petite/resolver/MethodResolver.java +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.resolver; - -import jodd.introspector.ClassDescriptor; -import jodd.introspector.ClassIntrospector; -import jodd.introspector.MethodDescriptor; -import jodd.petite.def.BeanReferences; -import jodd.petite.def.MethodInjectionPoint; -import jodd.util.ClassUtil; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -/** - * Methods injection points resolver. - */ -public class MethodResolver { - - protected final ReferencesResolver referencesResolver; - - public MethodResolver(final ReferencesResolver referencesResolver) { - this.referencesResolver = referencesResolver; - } - - /** - * Resolve method injection points in given class. - */ - public MethodInjectionPoint[] resolve(final Class type) { - // lookup methods - final ClassDescriptor cd = ClassIntrospector.get().lookup(type); - final List list = new ArrayList<>(); - final MethodDescriptor[] allMethods = cd.getAllMethodDescriptors(); - - for (final MethodDescriptor methodDescriptor : allMethods) { - final Method method = methodDescriptor.getMethod(); - - if (ClassUtil.isBeanPropertySetter(method)) { - // ignore setters - continue; - } - - if (method.getParameterTypes().length == 0) { - // ignore methods with no argument - continue; - } - - final BeanReferences[] references = referencesResolver.readAllReferencesFromAnnotation(method); - - if (references != null) { - final MethodInjectionPoint methodInjectionPoint = new MethodInjectionPoint(method, references); - - list.add(methodInjectionPoint); - } - } - - final MethodInjectionPoint[] methodInjectionPoints; - - if (list.isEmpty()) { - methodInjectionPoints = MethodInjectionPoint.EMPTY; - } else { - methodInjectionPoints = list.toArray(new MethodInjectionPoint[0]); - } - - return methodInjectionPoints; - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/resolver/PropertyResolver.java b/jodd-petite/src/main/java/jodd/petite/resolver/PropertyResolver.java deleted file mode 100644 index 1dc06c5f3..000000000 --- a/jodd-petite/src/main/java/jodd/petite/resolver/PropertyResolver.java +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.resolver; - -import jodd.introspector.ClassDescriptor; -import jodd.introspector.ClassIntrospector; -import jodd.introspector.PropertyDescriptor; -import jodd.petite.def.BeanReferences; -import jodd.petite.def.PropertyInjectionPoint; -import jodd.util.ClassUtil; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Resolves properties. - */ -public class PropertyResolver { - - protected final ReferencesResolver referencesResolver; - - public PropertyResolver(final ReferencesResolver referencesResolver) { - this.referencesResolver = referencesResolver; - } - - /** - * Resolves all properties for given type. - */ - public PropertyInjectionPoint[] resolve(Class type, final boolean autowire) { - final List list = new ArrayList<>(); - final Set usedPropertyNames = new HashSet<>(); - - // lookup fields - while (type != Object.class) { - - final ClassDescriptor cd = ClassIntrospector.get().lookup(type); - final PropertyDescriptor[] allPropertyDescriptors = cd.getAllPropertyDescriptors(); - - for (final PropertyDescriptor propertyDescriptor : allPropertyDescriptors) { - - if (propertyDescriptor.isGetterOnly()) { - continue; - } - - if (usedPropertyNames.contains(propertyDescriptor.getName())) { - continue; - } - - final Class propertyType = propertyDescriptor.getType(); - if (ClassUtil.isTypeOf(propertyType, Collection.class)) { - continue; - } - - BeanReferences reference = referencesResolver.readReferenceFromAnnotation(propertyDescriptor); - - if (reference == null) { - if (!autowire) { - continue; - } else { - reference = referencesResolver.buildDefaultReference(propertyDescriptor); - } - } - - list.add(new PropertyInjectionPoint(propertyDescriptor, reference)); - - usedPropertyNames.add(propertyDescriptor.getName()); - } - - // go to the supertype - type = type.getSuperclass(); - } - - final PropertyInjectionPoint[] fields; - - if (list.isEmpty()) { - fields = PropertyInjectionPoint.EMPTY; - } else { - fields = list.toArray(new PropertyInjectionPoint[0]); - } - - return fields; - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/resolver/ProviderResolver.java b/jodd-petite/src/main/java/jodd/petite/resolver/ProviderResolver.java deleted file mode 100644 index fb15ebb83..000000000 --- a/jodd-petite/src/main/java/jodd/petite/resolver/ProviderResolver.java +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.resolver; - -import jodd.introspector.ClassDescriptor; -import jodd.introspector.ClassIntrospector; -import jodd.introspector.MethodDescriptor; -import jodd.petite.def.ProviderDefinition; -import jodd.petite.meta.PetiteProvider; -import jodd.util.StringUtil; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.List; - -/** - * Provider resolver. - */ -public class ProviderResolver { - - /** - * Resolves all providers in the class - */ - public ProviderDefinition[] resolve(final Class type, final String name) { - final ClassDescriptor cd = ClassIntrospector.get().lookup(type); - final MethodDescriptor[] methods = cd.getAllMethodDescriptors(); - - final List list = new ArrayList<>(); - - for (final MethodDescriptor methodDescriptor : methods) { - final Method method = methodDescriptor.getMethod(); - - final PetiteProvider petiteProvider = method.getAnnotation(PetiteProvider.class); - if (petiteProvider == null) { - continue; - } - - String providerName = petiteProvider.value(); - - if (StringUtil.isBlank(providerName)) { - // default provider name - providerName = method.getName(); - - if (providerName.endsWith("Provider")) { - providerName = StringUtil.substring(providerName, 0, -8); - } - } - - final ProviderDefinition providerDefinition; - - if (Modifier.isStatic(method.getModifiers())) { - providerDefinition = new ProviderDefinition(providerName, method); - } else { - providerDefinition = new ProviderDefinition(providerName, name, method); - } - - list.add(providerDefinition); - } - - final ProviderDefinition[] providers; - - if (list.isEmpty()) { - providers = ProviderDefinition.EMPTY; - } else { - providers = list.toArray(new ProviderDefinition[0]); - } - - return providers; - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/resolver/ReferencesResolver.java b/jodd-petite/src/main/java/jodd/petite/resolver/ReferencesResolver.java deleted file mode 100644 index 1f77f9f5d..000000000 --- a/jodd-petite/src/main/java/jodd/petite/resolver/ReferencesResolver.java +++ /dev/null @@ -1,374 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.resolver; - -import jodd.introspector.FieldDescriptor; -import jodd.introspector.MethodDescriptor; -import jodd.introspector.PropertyDescriptor; -import jodd.paramo.MethodParameter; -import jodd.paramo.Paramo; -import jodd.petite.PetiteConfig; -import jodd.petite.PetiteException; -import jodd.petite.PetiteReferenceType; -import jodd.petite.def.BeanReferences; -import jodd.petite.meta.PetiteInject; -import jodd.typeconverter.Converter; -import jodd.util.StringUtil; - -import java.lang.reflect.Executable; -import java.lang.reflect.Parameter; - -/** - * Annotation reader for methods and constructors. - */ -public class ReferencesResolver { - - private final PetiteConfig petiteConfig; - - public ReferencesResolver(final PetiteConfig petiteConfig) { - this.petiteConfig = petiteConfig; - } - - /** - * Resolves reference from given values. Returns bean reference of given value or defaults - * if given name is blank. - */ - public BeanReferences resolveReferenceFromValue(final PropertyDescriptor propertyDescriptor, final String refName) { - BeanReferences references; - - if (refName == null || refName.isEmpty()) { - references = buildDefaultReference(propertyDescriptor); - } - else { - references = BeanReferences.of(refName); - } - - references = references.removeDuplicateNames(); - - return references; - } - - /** - * Takes given parameters references and returns reference set for given method or constructor. - */ - public BeanReferences[] resolveReferenceFromValues(final Executable methodOrCtor, final String... parameterReferences) { - BeanReferences[] references = convertRefToReferences(parameterReferences); - - if (references == null || references.length == 0) { - references = buildDefaultReferences(methodOrCtor); - } - - if (methodOrCtor.getParameterTypes().length != references.length) { - throw new PetiteException("Different number of method parameters and references for: " + - methodOrCtor.getDeclaringClass().getName() + '#' + methodOrCtor.getName()); - } - - removeAllDuplicateNames(references); - - return references; - } - - /** - * Extracts references for given property. Returns {@code null} if property is not marked with an - * annotation. - */ - public BeanReferences readReferenceFromAnnotation(final PropertyDescriptor propertyDescriptor) { - final MethodDescriptor writeMethodDescriptor = propertyDescriptor.getWriteMethodDescriptor(); - final FieldDescriptor fieldDescriptor = propertyDescriptor.getFieldDescriptor(); - - PetiteInject ref = null; - if (writeMethodDescriptor != null) { - ref = writeMethodDescriptor.getMethod().getAnnotation(PetiteInject.class); - } - if (ref == null && fieldDescriptor != null) { - ref = fieldDescriptor.getField().getAnnotation(PetiteInject.class); - } - - if (ref == null) { - return null; - } - - BeanReferences reference = null; - - final String name = ref.value().trim(); - if (name.length() != 0) { - reference = BeanReferences.of(name); - } - - reference = updateReferencesWithDefaultsIfNeeded(propertyDescriptor, reference); - - reference = reference.removeDuplicateNames(); - - return reference; - } - - public BeanReferences readReferenceFromAnnotation(final FieldDescriptor fieldDescriptor) { - final PetiteInject ref = fieldDescriptor.getField().getAnnotation(PetiteInject.class); - - if (ref == null) { - return null; - } - - BeanReferences reference = null; - - final String name = ref.value().trim(); - if (name.length() != 0) { - reference = BeanReferences.of(name); - } - - //reference = updateReferencesWithDefaultsIfNeeded(propertyDescriptor, reference); - - reference = reference.removeDuplicateNames(); - - return reference; - } - - /** - * Extracts references from method or constructor annotation. - */ - public BeanReferences[] readAllReferencesFromAnnotation(final Executable methodOrCtor) { - PetiteInject petiteInject = methodOrCtor.getAnnotation(PetiteInject.class); - - final Parameter[] parameters = methodOrCtor.getParameters(); - - BeanReferences[] references; - - final boolean hasAnnotationOnMethodOrCtor; - - if (petiteInject != null) { - references = convertAnnValueToReferences(petiteInject.value()); - - hasAnnotationOnMethodOrCtor = true; - } - else { - references = new BeanReferences[parameters.length]; - - hasAnnotationOnMethodOrCtor = false; - } - - int parametersWithAnnotationCount = 0; - - for (int i = 0; i < parameters.length; i++) { - final Parameter parameter = parameters[i]; - - petiteInject = parameter.getAnnotation(PetiteInject.class); - - if (petiteInject == null) { - // no annotation on argument - continue; - } - - // there is annotation on argument, override values - final String annotationValue = readAnnotationValue(petiteInject); - - if (annotationValue != null) { - references[i] = BeanReferences.of(annotationValue); - } - - parametersWithAnnotationCount++; - } - - if (!hasAnnotationOnMethodOrCtor) { - if (parametersWithAnnotationCount == 0) { - return null; - } - if (parametersWithAnnotationCount != parameters.length) { - throw new PetiteException("All arguments must be annotated with PetiteInject"); - } - } - - references = updateReferencesWithDefaultsIfNeeded(methodOrCtor, references); - - removeAllDuplicateNames(references); - - return references; - } - - /** - * Reads annotation value and returns {@code null} if value is empty. - */ - private String readAnnotationValue(final PetiteInject annotation) { - final String value = annotation.value().trim(); - - if (value.isEmpty()) { - return null; - } - return value; - } - - private BeanReferences[] updateReferencesWithDefaultsIfNeeded(final Executable methodOrCtor, BeanReferences[] references) { - final BeanReferences[] defaultReferences = buildDefaultReferences(methodOrCtor); - - if (references == null || references.length == 0) { - references = defaultReferences; - } - - if (methodOrCtor.getParameterTypes().length != references.length) { - throw new PetiteException( - "Different number of parameters and references for: " + methodOrCtor.getName()); - } - - // apply default parameters - for (int i = 0; i < references.length; i++) { - final BeanReferences parameterReferences = references[i]; - - if (parameterReferenceIsNotSet(parameterReferences)) { - references[i] = defaultReferences[i]; - } - } - - return references; - } - - private BeanReferences updateReferencesWithDefaultsIfNeeded(final PropertyDescriptor propertyDescriptor, BeanReferences references) { - if (references == null || references.isEmpty()) { - references = buildDefaultReference(propertyDescriptor); - } - - return references; - } - - /** - * Returns {@code true} if given parameter references is not set. - */ - private boolean parameterReferenceIsNotSet(final BeanReferences parameterReferences) { - if (parameterReferences == null) { - return true; - } - return parameterReferences.isEmpty(); - } - - /** - * Builds default method references. - */ - private BeanReferences[] buildDefaultReferences(final Executable methodOrCtor) { - final boolean useParamo = petiteConfig.getUseParamo(); - final PetiteReferenceType[] lookupReferences = petiteConfig.getLookupReferences(); - MethodParameter[] methodParameters = null; - - if (useParamo) { - methodParameters = Paramo.resolveParameters(methodOrCtor); - } - - final Class[] paramTypes = methodOrCtor.getParameterTypes(); - final BeanReferences[] references = new BeanReferences[paramTypes.length]; - - for (int j = 0; j < paramTypes.length; j++) { - final String[] ref = new String[lookupReferences.length]; - references[j] = BeanReferences.of(ref); - - for (int i = 0; i < ref.length; i++) { - switch (lookupReferences[i]) { - case NAME: - ref[i] = methodParameters != null ? methodParameters[j].getName() : null; - break; - case TYPE_SHORT_NAME: - ref[i] = StringUtil.uncapitalize(paramTypes[j].getSimpleName()); - break; - case TYPE_FULL_NAME: - ref[i] = paramTypes[j].getName(); - break; - } - } - } - - return references; - } - - /** - * Builds default field references. - */ - public BeanReferences buildDefaultReference(final PropertyDescriptor propertyDescriptor) { - final PetiteReferenceType[] lookupReferences = petiteConfig.getLookupReferences(); - - final String[] references = new String[lookupReferences.length]; - - for (int i = 0; i < references.length; i++) { - switch (lookupReferences[i]) { - case NAME: - references[i] = propertyDescriptor.getName(); - break; - case TYPE_SHORT_NAME: - references[i] = StringUtil.uncapitalize(propertyDescriptor.getType().getSimpleName()); - break; - case TYPE_FULL_NAME: - references[i] = propertyDescriptor.getType().getName(); - break; - } - } - - return BeanReferences.of(references); - } - - /** - * Removes duplicate names from bean references. - */ - private void removeAllDuplicateNames(final BeanReferences[] allBeanReferences) { - for (int i = 0; i < allBeanReferences.length; i++) { - final BeanReferences references = allBeanReferences[i]; - allBeanReferences[i] = references.removeDuplicateNames(); - } - } - - - /** - * Converts single string array to an array of bean references. - */ - private BeanReferences[] convertRefToReferences(final String[] references) { - if (references == null) { - return null; - } - final BeanReferences[] ref = new BeanReferences[references.length]; - - for (int i = 0; i < references.length; i++) { - ref[i] = BeanReferences.of(references[i]); - } - return ref; - } - - /** - * Converts comma-separated string into array of Bean references. - */ - private BeanReferences[] convertAnnValueToReferences(String value) { - if (value == null) { - return null; - } - - value = value.trim(); - if (value.length() == 0) { - return null; - } - - final String[] refNames = Converter.get().toStringArray(value); - - final BeanReferences[] references = new BeanReferences[refNames.length]; - for (int i = 0; i < refNames.length; i++) { - references[i] = BeanReferences.of(refNames[i].trim()); - } - return references; - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/resolver/SetResolver.java b/jodd-petite/src/main/java/jodd/petite/resolver/SetResolver.java deleted file mode 100644 index 6996df592..000000000 --- a/jodd-petite/src/main/java/jodd/petite/resolver/SetResolver.java +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.resolver; - -import jodd.introspector.ClassDescriptor; -import jodd.introspector.ClassIntrospector; -import jodd.introspector.FieldDescriptor; -import jodd.introspector.MethodDescriptor; -import jodd.introspector.PropertyDescriptor; -import jodd.petite.def.SetInjectionPoint; -import jodd.petite.meta.PetiteInject; -import jodd.util.ClassUtil; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * Resolves collection fields. - */ -public class SetResolver { - - /** - * Resolves all collections for given type. - */ - public SetInjectionPoint[] resolve(final Class type, final boolean autowire) { - final ClassDescriptor cd = ClassIntrospector.get().lookup(type); - final List list = new ArrayList<>(); - - final PropertyDescriptor[] allProperties = cd.getAllPropertyDescriptors(); - - for (final PropertyDescriptor propertyDescriptor : allProperties) { - - if (propertyDescriptor.isGetterOnly()) { - continue; - } - - final Class propertyType = propertyDescriptor.getType(); - if (!ClassUtil.isTypeOf(propertyType, Collection.class)) { - continue; - } - - final MethodDescriptor writeMethodDescriptor = propertyDescriptor.getWriteMethodDescriptor(); - final FieldDescriptor fieldDescriptor = propertyDescriptor.getFieldDescriptor(); - - PetiteInject ref = null; - - if (writeMethodDescriptor != null) { - ref = writeMethodDescriptor.getMethod().getAnnotation(PetiteInject.class); - } - if (ref == null && fieldDescriptor != null) { - ref = fieldDescriptor.getField().getAnnotation(PetiteInject.class); - } - - if ((!autowire) && (ref == null)) { - continue; - } - - list.add(new SetInjectionPoint(propertyDescriptor)); - } - - final SetInjectionPoint[] fields; - - if (list.isEmpty()) { - fields = SetInjectionPoint.EMPTY; - } else { - fields = list.toArray(new SetInjectionPoint[0]); - } - return fields; - } - -} diff --git a/jodd-petite/src/main/java/jodd/petite/resolver/package-info.java b/jodd-petite/src/main/java/jodd/petite/resolver/package-info.java deleted file mode 100644 index 6b9e1fa4f..000000000 --- a/jodd-petite/src/main/java/jodd/petite/resolver/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Petite resolvers defines and resolves injection points. - */ -package jodd.petite.resolver; \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/scope/ProtoScope.java b/jodd-petite/src/main/java/jodd/petite/scope/ProtoScope.java deleted file mode 100644 index 6d9ad5b67..000000000 --- a/jodd-petite/src/main/java/jodd/petite/scope/ProtoScope.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.scope; - -import jodd.petite.BeanDefinition; - -/** - * Prototype scope doesn't pool any beans, so each time bean is requested, - * a new instance will be created. Prototype scope does not call - * destroy methods. - */ -public class ProtoScope implements Scope { - - /** - * Returns null as no bean instance is stored. - */ - @Override - public Object lookup(final String name) { - return null; - } - - /** - * Does nothing, as bean instances are not stored. - */ - @Override - public void register(final BeanDefinition beanDefinition, final Object bean) { - } - - /** - * Does nothing. - */ - @Override - public void remove(final String name) { - } - - /** - * Allows all scopes to be injected into prototype scoped beans. - */ - @Override - public boolean accept(final Scope referenceScope) { - return true; - } - - /** - * Does nothing. - */ - @Override - public void shutdown() { - } - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/scope/RequestScope.java b/jodd-petite/src/main/java/jodd/petite/scope/RequestScope.java deleted file mode 100644 index a851b823f..000000000 --- a/jodd-petite/src/main/java/jodd/petite/scope/RequestScope.java +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.scope; - -import jodd.petite.BeanData; -import jodd.petite.BeanDefinition; -import jodd.petite.PetiteContainer; -import jodd.petite.PetiteException; -import jodd.servlet.RequestContextListener; - -import javax.servlet.http.HttpServletRequest; -import java.util.HashMap; -import java.util.Map; - -/** - * Request scope. - */ -public class RequestScope implements Scope { - - private final PetiteContainer pc; - - public RequestScope(final PetiteContainer pc) { - this.pc = pc; - } - - /** - * Since request map is stored in the requests, app server may want to - * persist it during the restart (for example). - */ - private class TransientBeanData { - - private final transient BeanData beanData; - - private TransientBeanData(final BeanData beanData) { - this.beanData = beanData; - } - - public BeanData get() { - return beanData; - } - } - - // ---------------------------------------------------------------- request map - - protected static final String ATTR_NAME = RequestScope.class.getName() + ".MAP."; - - /** - * Returns instance map from http request. - */ - @SuppressWarnings("unchecked") - protected Map getRequestMap(final HttpServletRequest servletRequest) { - return (Map) servletRequest.getAttribute(ATTR_NAME); - } - - /** - * Removes instance map from the request. - */ - protected void removeRequestMap(final HttpServletRequest servletRequest) { - servletRequest.removeAttribute(ATTR_NAME); - } - - /** - * Creates instance map and stores it in the request. - */ - protected Map createRequestMap(final HttpServletRequest servletRequest) { - Map map = new HashMap<>(); - servletRequest.setAttribute(ATTR_NAME, map); - return map; - } - - - // ---------------------------------------------------------------- scope - - @Override - public void shutdown() { - } - - @Override - public Object lookup(final String name) { - HttpServletRequest servletRequest = getCurrentHttpRequest(); - Map map = getRequestMap(servletRequest); - if (map == null) { - return null; - } - - BeanData beanData = map.get(name).get(); - if (beanData == null) { - return null; - } - return beanData.bean(); - } - - @Override - public void register(final BeanDefinition beanDefinition, final Object bean) { - HttpServletRequest servletRequest = getCurrentHttpRequest(); - Map map = getRequestMap(servletRequest); - if (map == null) { - map = createRequestMap(servletRequest); - } - - map.put(beanDefinition.name(), new TransientBeanData(new BeanData(pc, beanDefinition, bean))); - } - - @Override - public void remove(final String name) { - HttpServletRequest servletRequest = getCurrentHttpRequest(); - Map map = getRequestMap(servletRequest); - if (map != null) { - map.remove(name); - } - } - - @Override - public boolean accept(final Scope referenceScope) { - Class refScopeType = referenceScope.getClass(); - - if (refScopeType == ProtoScope.class) { - return true; - } - - if (refScopeType == SingletonScope.class) { - return true; - } - - if (refScopeType == SessionScope.class) { - return true; - } - - if (refScopeType == RequestScope.class) { - return true; - } - - return false; - } - - // ---------------------------------------------------------------- util - - /** - * Returns request from current thread. - */ - protected HttpServletRequest getCurrentHttpRequest() { - HttpServletRequest request = RequestContextListener.getRequest(); - if (request == null) { - throw new PetiteException("No HTTP request bound to the current thread. Is RequestContextListener registered?"); - } - return request; - } - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/scope/Scope.java b/jodd-petite/src/main/java/jodd/petite/scope/Scope.java deleted file mode 100644 index 0253ccf61..000000000 --- a/jodd-petite/src/main/java/jodd/petite/scope/Scope.java +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.scope; - -import jodd.petite.BeanDefinition; - -/** - * Petite container bean scope. Scopes actually represents wrapper over none, one or many internal - * bean pools. Which pool is used depends on scopes behaviour and external data. - *

- * Scopes are instantiated once on their first usage and stored within one container. - */ -public interface Scope { - - /** - * Lookups for bean name. Returns null if bean is not - * found or yet registered. - */ - Object lookup(String name); - - /** - * Registers the bean within the current scope. - * Usually registers it by its name from {@link jodd.petite.BeanDefinition}. - * Also it may register destroy methods of a bean within this scope. - */ - void register(BeanDefinition beanDefinition, Object bean); - - /** - * Removes the bean from the scope entirely. Destroy methods are not - * called as it is assumed that bean is destroyed manually. - */ - void remove(String name); - - /** - * Returns true if a bean of referenced scope can be - * injected into target bean of this scope. Otherwise, returns - * false, which may be a sign for scoped proxy to be - * injected. - *

- * In general, injection of 'shorter' reference scopes - * into the 'longer' target scopes should not be accepted. - * In other words, if reference scope is 'longer' or equal (same), - * this method should return true. - *

- * Helpful is to ask the following question: "May the reference scope - * bean be injected into bean of this scope?". - */ - boolean accept(Scope referenceScope); - - /** - * Shutdowns the scope by removing all beans and calling - * destroy methods. - */ - void shutdown(); - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/scope/SessionScope.java b/jodd-petite/src/main/java/jodd/petite/scope/SessionScope.java deleted file mode 100644 index 3d3608ff1..000000000 --- a/jodd-petite/src/main/java/jodd/petite/scope/SessionScope.java +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.scope; - -import jodd.petite.BeanData; -import jodd.petite.BeanDefinition; -import jodd.petite.PetiteContainer; -import jodd.petite.PetiteException; -import jodd.servlet.RequestContextListener; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.servlet.http.HttpSessionBindingEvent; -import javax.servlet.http.HttpSessionBindingListener; -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -/** - * Session scope stores unique object instances per single http session. - * Upon creation, new session listener is registered (dynamically) that will - * keep track on active sessions. {@link RequestContextListener} is used for accessing - * the request and the session. - */ -public class SessionScope extends ShutdownAwareScope { - - private final PetiteContainer pc; - - public SessionScope(final PetiteContainer pc) { - this.pc = pc; - } - - - // ---------------------------------------------------------------- destory - - protected static final String SESSION_BEANS_NAME = SessionScope.class.getName() + ".SESSION_BEANS."; - - /** - * Registers new session destroy callback if not already registered. - */ - protected Map registerSessionBeans(final HttpSession httpSession) { - SessionBeans sessionBeans = new SessionBeans(); - httpSession.setAttribute(SESSION_BEANS_NAME, sessionBeans); - return sessionBeans.getBeanMap(); - } - - /** - * Returns instance map from http session. - */ - @SuppressWarnings("unchecked") - protected Map getSessionMap(final HttpSession session) { - SessionBeans sessionBeans = (SessionBeans) session.getAttribute(SESSION_BEANS_NAME); - if (sessionBeans == null) { - return null; - } - return sessionBeans.getBeanMap(); - } - - - /** - * Session beans holder and manager. - */ - public class SessionBeans implements HttpSessionBindingListener, Serializable { - - protected Map beanMap = new HashMap<>(); - - /** - * Returns bean map used in this session. - */ - public Map getBeanMap() { - return beanMap; - } - - @Override - public void valueBound(final HttpSessionBindingEvent event) { - // do nothing - } - - /** - * Session is destroyed. - */ - @Override - public void valueUnbound(final HttpSessionBindingEvent event) { - for (BeanData beanData : beanMap.values()) { - destroyBean(beanData); - } - } - } - - // ---------------------------------------------------------------- scope - - /** - * Shutdowns the Session scope. Calls destroyable methods on - * all destroyable beans available in this moment. - */ - @Override - public void shutdown() { - super.shutdown(); - } - - @Override - public Object lookup(final String name) { - HttpSession session = getCurrentHttpSession(); - Map map = getSessionMap(session); - if (map == null) { - return null; - } - - BeanData beanData = map.get(name); - if (beanData == null) { - return null; - } - return beanData.bean(); - } - - @Override - public void register(final BeanDefinition beanDefinition, final Object bean) { - HttpSession session = getCurrentHttpSession(); - Map map = getSessionMap(session); - if (map == null) { - map = registerSessionBeans(session); - } - - final BeanData beanData = new BeanData(pc, beanDefinition, bean); - - map.put(beanDefinition.name(), beanData); - - registerDestroyableBeans(beanData); - } - - @Override - public void remove(final String name) { - if (totalRegisteredDestroyableBeans() == 0) { - return; - } - HttpSession session = getCurrentHttpSession(); - Map map = getSessionMap(session); - if (map != null) { - map.remove(name); - } - } - - @Override - public boolean accept(final Scope referenceScope) { - Class refScopeType = referenceScope.getClass(); - - if (refScopeType == ProtoScope.class) { - return true; - } - - if (refScopeType == SingletonScope.class) { - return true; - } - - if (refScopeType == SessionScope.class) { - return true; - } - - return false; - } - - // ---------------------------------------------------------------- util - - /** - * Returns request from current thread. - */ - protected HttpSession getCurrentHttpSession() { - HttpServletRequest request = RequestContextListener.getRequest(); - if (request == null) { - throw new PetiteException("No HTTP request bound to the current thread. Is RequestContextListener registered?"); - } - return request.getSession(); - } - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/scope/ShutdownAwareScope.java b/jodd-petite/src/main/java/jodd/petite/scope/ShutdownAwareScope.java deleted file mode 100644 index a372afc1f..000000000 --- a/jodd-petite/src/main/java/jodd/petite/scope/ShutdownAwareScope.java +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.scope; - -import jodd.petite.BeanData; -import jodd.petite.def.DestroyMethodPoint; - -import java.util.ArrayList; -import java.util.List; - -/** - * Base {@link Scope} class for scopes that collect - * destroyable beans and implement shutdown routine. - */ -public abstract class ShutdownAwareScope implements Scope { - - protected List destroyableBeans; - - /** - * Returns true if bean is destroyable. - */ - protected boolean isBeanDestroyable(final BeanData beanData) { - DestroyMethodPoint[] dmp = beanData.definition().destroyMethodPoints(); - return dmp != null && dmp.length != 0; - } - - /** - * Checks if bean data is destroyable (has destroy methods) and - * registers it for later {@link #shutdown()}. - */ - protected void registerDestroyableBeans(final BeanData beanData) { - if (!isBeanDestroyable(beanData)) { - return; - } - if (destroyableBeans == null) { - destroyableBeans = new ArrayList<>(); - } - destroyableBeans.add(beanData); - } - - /** - * Returns number of destroyable beans that have been registered. - */ - protected int totalRegisteredDestroyableBeans() { - if (destroyableBeans == null) { - return 0; - } - return destroyableBeans.size(); - } - - /** - * Removes destroyable bean from the list and calls it destroy methods. - * If bean is not destroyable, does nothing. Bean gets destroyed only once. - */ - protected void destroyBean(final BeanData beanData) { - if (destroyableBeans == null) { - return; - } - if (!isBeanDestroyable(beanData)) { - return; - } - if (destroyableBeans.remove(beanData)) { - beanData.callDestroyMethods(); - } - } - - /** - * Shutdowns the scope and calls all collected destroyable beans. - */ - @Override - public void shutdown() { - if (destroyableBeans == null) { - return; - } - - for (final BeanData destroyableBean : destroyableBeans) { - destroyableBean.callDestroyMethods(); - } - - destroyableBeans.clear(); - } - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/scope/SingletonScope.java b/jodd-petite/src/main/java/jodd/petite/scope/SingletonScope.java deleted file mode 100644 index 0bdfc0a17..000000000 --- a/jodd-petite/src/main/java/jodd/petite/scope/SingletonScope.java +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.scope; - -import jodd.petite.BeanData; -import jodd.petite.BeanDefinition; -import jodd.petite.PetiteContainer; - -import java.util.HashMap; -import java.util.Map; - -/** - * Singleton scope pools all bean instances so they will be created only once in - * the container context. - */ -public class SingletonScope implements Scope { - - private final PetiteContainer pc; - - public SingletonScope(final PetiteContainer pc) { - this.pc = pc; - } - - - protected Map instances = new HashMap<>(); - - @Override - public Object lookup(final String name) { - BeanData beanData = instances.get(name); - if (beanData == null) { - return null; - } - return beanData.bean(); - } - - @Override - public void register(final BeanDefinition beanDefinition, final Object bean) { - instances.put(beanDefinition.name(), new BeanData(pc, beanDefinition, bean)); - } - - @Override - public void remove(final String name) { - instances.remove(name); - } - - /** - * Allows only singleton scoped beans to be injected into the target singleton bean. - */ - @Override - public boolean accept(final Scope referenceScope) { - Class refScopeType = referenceScope.getClass(); - - if (refScopeType == ProtoScope.class) { - return true; - } - - if (refScopeType == SingletonScope.class) { - return true; - } - - return false; - } - - /** - * Iterate all beans and invokes registered destroy methods. - */ - @Override - public void shutdown() { - for (final BeanData beanData : instances.values()) { - beanData.callDestroyMethods(); - } - instances.clear(); - } -} diff --git a/jodd-petite/src/main/java/jodd/petite/scope/ThreadLocalScope.java b/jodd-petite/src/main/java/jodd/petite/scope/ThreadLocalScope.java deleted file mode 100644 index c9751429b..000000000 --- a/jodd-petite/src/main/java/jodd/petite/scope/ThreadLocalScope.java +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.scope; - -import jodd.petite.BeanData; -import jodd.petite.BeanDefinition; -import jodd.petite.PetiteContainer; - -import java.util.HashMap; -import java.util.Map; - -/** - * Thread local Petite bean scope. Holds beans in thread local scopes. - * Be careful with this scope, if you do not have control on threads! - * For example, app servers may have a thread pools, so threads may not - * finish when expected. ThreadLocalScope can not invoke destroy methods. - */ -public class ThreadLocalScope implements Scope { - - private final PetiteContainer pc; - - public ThreadLocalScope(final PetiteContainer pc) { - this.pc = pc; - } - - - protected static ThreadLocal> context = new ThreadLocal>() { - @Override - protected synchronized Map initialValue() { - return new HashMap<>(); - } - }; - - @Override - public Object lookup(final String name) { - Map threadLocalMap = context.get(); - BeanData beanData = threadLocalMap.get(name); - if (beanData == null) { - return null; - } - return beanData.bean(); - } - - @Override - public void register(final BeanDefinition beanDefinition, final Object bean) { - Map threadLocalMap = context.get(); - threadLocalMap.put(beanDefinition.name(), new BeanData(pc, beanDefinition, bean)); - } - - @Override - public void remove(final String name) { - Map threadLocalMap = context.get(); - threadLocalMap.remove(name); - } - - /** - * Defines allowed referenced scopes that can be injected into the - * thread-local scoped bean. - */ - @Override - public boolean accept(final Scope referenceScope) { - Class refScopeType = referenceScope.getClass(); - - if (refScopeType == ProtoScope.class) { - return true; - } - - if (refScopeType == SingletonScope.class) { - return true; - } - - if (refScopeType == ThreadLocalScope.class) { - return true; - } - - return false; - } - - @Override - public void shutdown() { - } - -} \ No newline at end of file diff --git a/jodd-petite/src/main/java/jodd/petite/scope/package-info.java b/jodd-petite/src/main/java/jodd/petite/scope/package-info.java deleted file mode 100644 index 63250271f..000000000 --- a/jodd-petite/src/main/java/jodd/petite/scope/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Petite bean scopes. - */ -package jodd.petite.scope; \ No newline at end of file diff --git a/jodd-petite/src/main/resources/META-INF/LICENSE b/jodd-petite/src/main/resources/META-INF/LICENSE deleted file mode 100644 index a040a3b95..000000000 --- a/jodd-petite/src/main/resources/META-INF/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2003-present, Jodd Team (https://jodd.org) -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, -this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright -notice, this list of conditions and the following disclaimer in the -documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. diff --git a/jodd-petite/src/test/java/jodd/petite/AddStringAdvice.java b/jodd-petite/src/test/java/jodd/petite/AddStringAdvice.java deleted file mode 100644 index 7a37575c3..000000000 --- a/jodd-petite/src/test/java/jodd/petite/AddStringAdvice.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -public class AddStringAdvice implements ProxyAdvice { - - public Object execute() throws Exception { - String value = ProxyTarget.invoke().toString(); - - value += " And Universe, too!"; - - return value; - } -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/AutomagicPetiteConfiguratorTest.java b/jodd-petite/src/test/java/jodd/petite/AutomagicPetiteConfiguratorTest.java deleted file mode 100644 index a79668e8e..000000000 --- a/jodd-petite/src/test/java/jodd/petite/AutomagicPetiteConfiguratorTest.java +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.tst.Foo; -import jodd.test.DisabledOnJava; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -class AutomagicPetiteConfiguratorTest { - - @BeforeEach - void setUp() { - Foo.instanceCounter = 0; - } - - @Test - @DisabledOnJava(value = 9, description = "Automagic configuration only works with MR-JAR jars as they don't work in exploded mode.") - void testContainer() { - PetiteContainer pc = new PetiteContainer(); - AutomagicPetiteConfigurator petiteConfigurator = new AutomagicPetiteConfigurator(pc); - - petiteConfigurator.withScanner(classScanner -> - classScanner - .excludeAllEntries(true) - .includeEntries("jodd.petite.fixtures.*") - .excludeEntries("jodd.petite.fixtures.data.*", "jodd.petite.fixtures.tst3.*", "jodd.petite.fixtures.tst.Ses") - .excludeEntries( - "jodd.petite.fixtures.data.*", "jodd.petite.fixtures.tst6.*", "jodd.petite.fixtures.tst.Ses", - "*Public*", "*Secret*", "*$*", "jodd.petite.proxy.*", "jodd.petite.fixtures.rainbow.*")); - - petiteConfigurator.configure(); - - assertEquals(1, pc.beansCount()); - assertEquals(1, pc.scopesCount()); - assertEquals(0, Foo.instanceCounter); - - Foo foo = pc.getBean("foo"); - assertNotNull(foo); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/ConsumerTest.java b/jodd-petite/src/test/java/jodd/petite/ConsumerTest.java deleted file mode 100644 index 43df6a020..000000000 --- a/jodd-petite/src/test/java/jodd/petite/ConsumerTest.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.data.PojoBean; -import jodd.petite.fixtures.data.SomeService; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class ConsumerTest { - - @Test - void testConsumer() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(SomeService.class, null, null, null, false, null); - pc.registerPetiteBean(PojoBean.class, "pojo", null, null, false, pb -> pb.count = 7); - pc.registerPetiteCtorInjectionPoint("pojo", null, null); - - PojoBean pb = pc.getBean("pojo"); - assertEquals(7, pb.count); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/FullTypeTest.java b/jodd-petite/src/test/java/jodd/petite/FullTypeTest.java deleted file mode 100644 index 269aa49bd..000000000 --- a/jodd-petite/src/test/java/jodd/petite/FullTypeTest.java +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.tst2.Joo; -import jodd.petite.fixtures.tst2.Koo; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -class FullTypeTest { - - private void registerBean(PetiteContainer petiteContainer, Class beanType) { - petiteContainer.registerPetiteBean(beanType, null, null, null, false, null); - } - - @Test - void testFullTypeProperty() { - PetiteContainer pc = new PetiteContainer(); - pc.config().setUseFullTypeNames(true); - - registerBean(pc, Koo.class); - registerBean(pc, Joo.class); - - assertEquals(2, pc.beansCount()); - - assertNull(pc.getBean("koo")); - assertNull(pc.getBean("joo")); - - Koo koo = pc.getBean(Koo.class); - assertNotNull(koo); - Joo joo = pc.getBean(Joo.class); - assertNotNull(joo); - - koo = pc.getBean(Koo.class.getName()); - assertNotNull(koo); - joo = pc.getBean(Joo.class.getName()); - assertNotNull(joo); - - assertNotNull(koo.joo); - assertNotNull(koo.someNoJooName); - assertEquals(joo, koo.joo); - assertEquals(joo, koo.someNoJooName); - } - - @Test - void testFullTypeMethodCtor() { - PetiteContainer pc = new PetiteContainer(); - pc.config().setUseFullTypeNames(true); - - registerBean(pc, Koo.class); - registerBean(pc, Joo.class); - - Koo koo = pc.getBean(Koo.class.getName()); - assertNotNull(koo); - Joo joo = pc.getBean(Joo.class.getName()); - assertNotNull(joo); - - assertNotNull(koo.joo); - assertNotNull(koo.someNoJooName); - assertNotNull(koo.mjoo); - assertNotNull(koo.mjoo2); - assertNotNull(koo.joojoo); - } - - @Test - void testOptionalAndNotAllReferences() { - PetiteContainer pc = new PetiteContainer(); - pc.config().setDefaultWiringMode(WiringMode.OPTIONAL); - pc.config().setUseFullTypeNames(false); - pc.config().setLookupReferences(PetiteReferenceType.NAME); - - registerBean(pc, Koo.class); - registerBean(pc, Joo.class); - - assertEquals(2, pc.beansCount()); - - Koo koo = pc.getBean(Koo.class); - assertNotNull(koo); - Joo joo = pc.getBean(Joo.class); - assertNotNull(joo); - - assertNull(koo.someNoJooName); - assertNotNull(koo.joo); - - koo = pc.getBean(Koo.class.getName()); - assertNull(koo); - joo = pc.getBean(Joo.class.getName()); - assertNull(joo); - - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/InitMethodTest.java b/jodd-petite/src/test/java/jodd/petite/InitMethodTest.java deleted file mode 100644 index dcb784dba..000000000 --- a/jodd-petite/src/test/java/jodd/petite/InitMethodTest.java +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.tst4.Bar; -import jodd.petite.fixtures.tst4.Foo; -import jodd.petite.fixtures.tst4.Foo2; -import org.junit.jupiter.api.Test; - -import static jodd.petite.meta.InitMethodInvocationStrategy.POST_CONSTRUCT; -import static jodd.petite.meta.InitMethodInvocationStrategy.POST_DEFINE; -import static jodd.petite.meta.InitMethodInvocationStrategy.POST_INITIALIZE; -import static org.junit.jupiter.api.Assertions.assertEquals; - -class InitMethodTest { - - private void defineBean(PetiteContainer petiteContainer, String beanName, Class type) { - petiteContainer.registerPetiteBean(type, beanName, null, null, true, null); - } - - @Test - void testPostConstructor() { - PetiteContainer petiteContainer = new PetiteContainer(); - - // define two beans - defineBean(petiteContainer, "bar", Bar.class); - defineBean(petiteContainer, "foo", Foo.class); - - // wiring - petiteContainer.registerPetitePropertyInjectionPoint("foo", "bar", "bar"); - - // init method - petiteContainer.registerPetiteInitMethods("foo", POST_CONSTRUCT, "init"); - - // param - petiteContainer.defineParameter("foo.data", "data"); - - // get bean - Foo foo = petiteContainer.getBean("foo"); - - assertEquals("ctor null null", foo.result); - assertEquals("bar", foo.bar.toString()); - assertEquals("data", foo.data); - } - - @Test - void testPostDefine() { - PetiteContainer petiteContainer = new PetiteContainer(); - - // define two beans - defineBean(petiteContainer, "bar", Bar.class); - defineBean(petiteContainer, "foo", Foo.class); - - // wiring - petiteContainer.registerPetitePropertyInjectionPoint("foo", "bar", "bar"); - - // init method - petiteContainer.registerPetiteInitMethods("foo", POST_DEFINE, "init"); - - // param - petiteContainer.defineParameter("foo.data", "data"); - - // get bean - Foo foo = petiteContainer.getBean("foo"); - - assertEquals("ctor bar null", foo.result); - assertEquals("bar", foo.bar.toString()); - assertEquals("data", foo.data); - } - - @Test - void testPostInitialize() { - PetiteContainer petiteContainer = new PetiteContainer(); - - // define two beans - defineBean(petiteContainer, "bar", Bar.class); - defineBean(petiteContainer, "foo", Foo.class); - - // wiring - petiteContainer.registerPetitePropertyInjectionPoint("foo", "bar", "bar"); - - // init method - petiteContainer.registerPetiteInitMethods("foo", POST_INITIALIZE, "init"); - - // param - petiteContainer.defineParameter("foo.data", "data"); - - // get bean - Foo foo = petiteContainer.getBean("foo"); - - assertEquals("ctor bar data", foo.result); - assertEquals("bar", foo.bar.toString()); - assertEquals("data", foo.data); - } - - @Test - void testPostAll() { - PetiteContainer petiteContainer = new PetiteContainer(); - - // define two beans - defineBean(petiteContainer, "bar", Bar.class); - defineBean(petiteContainer, "foo", Foo2.class); - - // wiring - petiteContainer.registerPetitePropertyInjectionPoint("foo", "bar", "bar"); - - // init method - petiteContainer.registerPetiteInitMethods("foo", POST_CONSTRUCT, "init1"); - petiteContainer.registerPetiteInitMethods("foo", POST_DEFINE, "init2"); - petiteContainer.registerPetiteInitMethods("foo", POST_INITIALIZE, "init3"); - - // param - petiteContainer.defineParameter("foo.data", "data"); - - // get bean - Foo2 foo = petiteContainer.getBean("foo"); - - assertEquals("1 null null 2 bar null 3 bar data", foo.result); - assertEquals("bar", foo.bar.toString()); - assertEquals("data", foo.data); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/ManualTest.java b/jodd-petite/src/test/java/jodd/petite/ManualTest.java deleted file mode 100644 index a83d7f364..000000000 --- a/jodd-petite/src/test/java/jodd/petite/ManualTest.java +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.data.PojoAnnBean; -import jodd.petite.fixtures.data.PojoBean; -import jodd.petite.fixtures.data.SomeService; -import org.junit.jupiter.api.Test; - -import java.util.Set; - -import static jodd.petite.meta.InitMethodInvocationStrategy.POST_INITIALIZE; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class ManualTest { - - @Test - void testManualRegistration() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(SomeService.class, null, null, null, false, null); - pc.registerPetiteBean(PojoBean.class, "pojo", null, null, false, null); - assertEquals(2, pc.beansCount()); - - Set names = pc.beanNames(); - assertEquals(2, names.size()); - - assertTrue(names.contains("pojo")); - assertTrue(names.contains("someService")); - - pc.registerPetiteCtorInjectionPoint("pojo", null, null); - pc.registerPetitePropertyInjectionPoint("pojo", "service", "someService"); - pc.registerPetiteMethodInjectionPoint("pojo", "injectService", null, new String[]{"someService"}); - pc.registerPetiteInitMethods("pojo", POST_INITIALIZE, "init"); - - PojoBean pojoBean = pc.getBean("pojo"); - SomeService ss = pc.getBean("someService"); - - assertNotNull(pojoBean); - assertNotNull(ss); - assertSame(ss, pojoBean.fservice); - assertSame(ss, pojoBean.service); - assertSame(ss, pojoBean.service2); - assertEquals(1, pojoBean.count); - } - - @Test - void testManualRegistration2() { - PetiteContainer pc = new PetiteContainer(); - - PetiteRegistry.of(pc).bean(SomeService.class).register(); - PetiteRegistry.of(pc).bean(PojoBean.class).name("pojo").register(); - - assertEquals(2, pc.beansCount()); - - PetiteRegistry.of(pc).wire("pojo").ctor().bind(); - PetiteRegistry.of(pc).wire("pojo").property("service").ref("someService").bind(); - PetiteRegistry.of(pc).wire("pojo").method("injectService").ref("someService").bind(); - PetiteRegistry.of(pc).init("pojo").invoke(POST_INITIALIZE).methods("init").register(); - - PojoBean pojoBean = pc.getBean("pojo"); - SomeService ss = pc.getBean("someService"); - - assertNotNull(pojoBean); - assertNotNull(ss); - assertSame(ss, pojoBean.fservice); - assertSame(ss, pojoBean.service); - assertSame(ss, pojoBean.service2); - assertEquals(1, pojoBean.count); - } - - @Test - void testManualRegistrationUsingAnnotations() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(SomeService.class, null, null, null, false, null); - pc.registerPetiteBean(PojoAnnBean.class, "pojo", null, null, false, null); - assertEquals(2, pc.beansCount()); - - PojoAnnBean pojoBean = pc.getBean("pojo"); - SomeService ss = pc.getBean("someService"); - - assertNotNull(pojoBean); - assertNotNull(ss); - assertSame(ss, pojoBean.fservice); - assertSame(ss, pojoBean.service); - assertSame(ss, pojoBean.service2); - assertEquals(1, pojoBean.count); - } - - @Test - void testManualRegistrationUsingAnnotations2() { - PetiteContainer pc = new PetiteContainer(); - - PetiteRegistry.of(pc).bean(SomeService.class).register(); - PetiteRegistry.of(pc).bean(PojoAnnBean.class).name("pojo").register(); - - assertEquals(2, pc.beansCount()); - - PojoAnnBean pojoBean = pc.getBean("pojo"); - SomeService ss = pc.getBean("someService"); - - assertNotNull(pojoBean); - assertNotNull(ss); - assertSame(ss, pojoBean.fservice); - assertSame(ss, pojoBean.service); - assertSame(ss, pojoBean.service2); - assertEquals(1, pojoBean.count); - } - - @Test - void testManualDefinitionUsingAnnotations() { - - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(SomeService.class, null, null, null, false, null); - pc.registerPetiteBean(PojoAnnBean.class, "pojo", null, null, true, null); - assertEquals(2, pc.beansCount()); - - PojoAnnBean pojoBean = pc.getBean("pojo"); - SomeService ss = pc.getBean("someService"); - - assertNotNull(pojoBean); - assertNotNull(ss); - assertSame(ss, pojoBean.fservice); - assertNull(pojoBean.service); - assertNull(pojoBean.service2); - assertEquals(0, pojoBean.count); - } - - @Test - void testManualDefinitionUsingAnnotations2() { - - PetiteContainer pc = new PetiteContainer(); - - PetiteRegistry.of(pc).bean(SomeService.class).register(); - PetiteRegistry.of(pc).bean(PojoAnnBean.class).name("pojo").define().register(); - - assertEquals(2, pc.beansCount()); - - PojoAnnBean pojoBean = pc.getBean("pojo"); - SomeService ss = pc.getBean("someService"); - - assertNotNull(pojoBean); - assertNotNull(ss); - assertSame(ss, pojoBean.fservice); - assertNull(pojoBean.service); - assertNull(pojoBean.service2); - assertEquals(0, pojoBean.count); - } - - @Test - void testManualDefinition() { - - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(SomeService.class, null, null, null, false, null); - pc.registerPetiteBean(PojoBean.class, "pojo", null, null, true, null); - assertEquals(2, pc.beansCount()); - - pc.registerPetiteCtorInjectionPoint("pojo", null, null); - pc.registerPetitePropertyInjectionPoint("pojo", "service", "someService"); - pc.registerPetiteMethodInjectionPoint("pojo", "injectService", null, new String[] {"someService"}); - pc.registerPetiteInitMethods("pojo", POST_INITIALIZE, "init"); - - PojoBean pojoBean = pc.getBean("pojo"); - SomeService ss = pc.getBean("someService"); - - assertNotNull(pojoBean); - assertNotNull(ss); - assertSame(ss, pojoBean.fservice); - assertSame(ss, pojoBean.service); - assertSame(ss, pojoBean.service2); - assertEquals(1, pojoBean.count); - } - - @Test - void testManualDefinition2() { - PetiteRegistry petiteRegistry = PetiteRegistry.of(new PetiteContainer()); - - petiteRegistry.bean(SomeService.class).register(); - petiteRegistry.bean(PojoBean.class).name("pojo").define().register(); - - assertEquals(2, petiteRegistry.petiteContainer().beansCount()); - - - petiteRegistry.wire("pojo").ctor().bind(); - petiteRegistry.wire("pojo").property("service").ref("someService").bind(); - petiteRegistry.wire("pojo").method("injectService").ref("someService").bind(); - petiteRegistry.init("pojo").invoke(POST_INITIALIZE).methods("init").register(); - - PojoBean pojoBean = petiteRegistry.petiteContainer().getBean("pojo"); - SomeService ss = petiteRegistry.petiteContainer().getBean("someService"); - - assertNotNull(pojoBean); - assertNotNull(ss); - assertSame(ss, pojoBean.fservice); - assertSame(ss, pojoBean.service); - assertSame(ss, pojoBean.service2); - assertEquals(1, pojoBean.count); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/MiscTest.java b/jodd-petite/src/test/java/jodd/petite/MiscTest.java deleted file mode 100644 index 2625decf0..000000000 --- a/jodd-petite/src/test/java/jodd/petite/MiscTest.java +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.data.Biz; -import jodd.petite.fixtures.data.DefaultBiz; -import jodd.petite.fixtures.data.DefaultBizImpl; -import jodd.petite.fixtures.tst.Boo; -import jodd.petite.fixtures.tst.Foo; -import jodd.petite.fixtures.tst.Zoo; -import jodd.petite.meta.PetiteBean; -import jodd.petite.meta.PetiteInject; -import jodd.petite.scope.ProtoScope; -import org.junit.jupiter.api.Test; - -import static jodd.petite.meta.InitMethodInvocationStrategy.POST_INITIALIZE; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class MiscTest { - - @Test - void testOne() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(DefaultBizImpl.class, null, null, null, false, null); - assertEquals(1, pc.beansCount()); - - Object bizI = pc.getBean("biz"); - assertTrue(bizI instanceof Biz); - assertTrue(bizI instanceof DefaultBizImpl); - - pc = new PetiteContainer(); - pc.registerPetiteBean(DefaultBizImpl.class, null, null, null, false, null); - pc.registerPetiteBean(DefaultBiz.class, null, null, null, false, null); // override! - assertEquals(1, pc.beansCount()); - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - pc.registerPetitePropertyInjectionPoint("biz", "foo", null); - pc.registerPetiteInitMethods("biz", POST_INITIALIZE, "init", "init2"); - - assertEquals(2, pc.beansCount()); - bizI = pc.getBean("biz"); - assertTrue(bizI instanceof Biz); - assertFalse(bizI instanceof DefaultBizImpl); - assertTrue(bizI instanceof DefaultBiz); - - assertNotNull(((DefaultBiz) bizI).getFoo()); - assertEquals(2, ((DefaultBiz) bizI).initCount); - } - - @Test - void testTwo() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(DefaultBizImpl.class, null, null, null, false, null); - assertEquals(1, pc.beansCount()); - - Object bizI = pc.getBean("biz"); - assertTrue(bizI instanceof Biz); - assertFalse(bizI instanceof DefaultBiz); - assertTrue(bizI instanceof DefaultBizImpl); - - //pc = new PetiteContainer(); // same container!!! - pc.registerPetiteBean(DefaultBiz.class, null, null, null, false, null); // override! instance will be removed from the scope - assertEquals(1, pc.beansCount()); - bizI = pc.getBean("biz"); - assertTrue(bizI instanceof Biz); - assertFalse(bizI instanceof DefaultBizImpl); - assertTrue(bizI instanceof DefaultBiz); - } - - - @Test - void testAdd() { - PetiteContainer pc = new PetiteContainer(); - Foo foo = new Foo(); - pc.addBean("foo", foo); - Foo foo2 = (Foo) pc.getBean("foo"); - assertNotNull(foo2); - assertSame(foo, foo2); - } - - @Test - void testAdd2WithCircDep() { - Foo.instanceCounter = 0; - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - pc.registerPetiteBean(Zoo.class, null, null, null, false, null); - - Foo foo = (Foo) pc.getBean("foo"); - Boo boo = new Boo(); - assertNull(boo.getFoo()); - - pc.addBean("boo", boo, null); - assertNotNull(boo.getFoo()); - assertSame(foo, boo.getFoo()); - assertNotNull(boo.zoo); - - Zoo zoo = (Zoo) pc.getBean("zoo"); - assertNotNull(zoo.boo); - assertSame(zoo, boo.zoo); // circular dependency - assertSame(boo, zoo.boo); - - Boo boo2 = (Boo) pc.getBean("boo"); - assertNotNull(boo2); - assertSame(boo, boo2); - assertFalse(boo.orders.isEmpty()); - assertEquals(6, boo.orders.size()); - assertEquals("[first, second, third, init, beforeLast, last]", boo.orders.toString()); - assertNotNull(boo2.getFoo()); - assertSame(foo, boo2.getFoo()); - assertEquals(1, boo2.getFoo().hello()); - assertEquals(1, boo2.getFoo().getCounter()); - - pc.addBean("boo", boo); - boo2 = (Boo) pc.getBean("boo"); - assertNotNull(boo2); - assertSame(boo, boo2); - assertNotNull(boo2.getFoo()); - assertSame(foo, boo2.getFoo()); - assertEquals(1, boo2.getFoo().hello()); - assertEquals(2, boo2.getFoo().getCounter()); - assertEquals(12, boo.orders.size()); // init methods are called again due to re-add - } - - @Test - void testNoAdd2WithCircDep() { - Foo.instanceCounter = 0; - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - pc.registerPetiteBean(Zoo.class, null, null, null, false, null); - pc.registerPetiteBean(Boo.class, null, null, null, false, null); - - Boo boo = (Boo) pc.getBean("boo"); - Foo foo = (Foo) pc.getBean("foo"); - Zoo zoo = (Zoo) pc.getBean("zoo"); - - assertNotNull(boo.getFoo()); - assertSame(foo, boo.getFoo()); - - assertNotNull(zoo.boo); - assertSame(boo, zoo.boo); - assertSame(zoo, boo.zoo); - - Boo boo2 = (Boo) pc.getBean("boo"); - assertNotNull(boo2); - assertSame(boo, boo2); - assertFalse(boo.orders.isEmpty()); - assertNotNull(boo2.getFoo()); - assertSame(foo, boo2.getFoo()); - assertEquals(1, boo2.getFoo().hello()); - assertEquals(1, boo2.getFoo().getCounter()); - assertEquals("[first, second, third, init, beforeLast, last]", boo.orders.toString()); - } - - public static class PetiteDemo { - static Integer getOne() { - return new Integer(123); - } - } - - @Test - void test243() { - PetiteContainer pc = new PetiteContainer(); - new PetiteRegistry(pc).provider("provider").type(PetiteDemo.class).method("getOne").args().register(); - } - - @PetiteBean(scope = ProtoScope.class) - public static class BeanTwo { - } - - @PetiteBean - public static class BeanOne { - - BeanTwo ctor; - @PetiteInject - BeanTwo setter; - - @PetiteInject - public BeanOne(BeanTwo bean) { - this.ctor = bean; - } - } - - @Test - void test244() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(BeanOne.class, null, null, null, false, null); - pc.registerPetiteBean(BeanTwo.class, null, null, null, false, null); - - BeanOne petiteBean = pc.getBean(BeanOne.class); - - assertTrue(petiteBean.ctor != petiteBean.setter); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/MixScopeTest.java b/jodd-petite/src/test/java/jodd/petite/MixScopeTest.java deleted file mode 100644 index b79c68f10..000000000 --- a/jodd-petite/src/test/java/jodd/petite/MixScopeTest.java +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.mix.Big; -import jodd.petite.fixtures.mix.Big2; -import jodd.petite.fixtures.mix.Small; -import jodd.petite.scope.ProtoScope; -import jodd.petite.scope.SingletonScope; -import jodd.petite.scope.ThreadLocalScope; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class MixScopeTest { - - @Test - void testPrototypeInSingleton() { - Small.instanceCounter = 0; - - PetiteContainer pc = new PetiteContainer(); - pc.config().setWireScopedProxy(true); - pc.config().setDetectMixedScopes(true); - - pc.registerPetiteBean(Big.class, "big", SingletonScope.class, null, false, null); - pc.registerPetiteBean(Big.class, "big2", SingletonScope.class, null, false, null); - pc.registerPetiteBean(Small.class, "small", ProtoScope.class, null, false, null); - - Big big = pc.getBean("big"); - - Small small1 = big.getSmall(); - Small small2 = big.getSmall(); - - assertSame(small1, small2); // factory !!! - - assertEquals(1, Small.instanceCounter); - - assertTrue(small1.toString().equals(small2.toString())); - - assertEquals("small 1", small1.name()); - assertEquals("small 1", small2.name()); - - assertEquals(1, Small.instanceCounter); - - Big big2 = pc.getBean("big2"); - Small small3 = big2.getSmall(); - - assertEquals("small 2", small3.name()); - - assertEquals(2, Small.instanceCounter); - } - - @Test - void testPrototypeInSingleton2() { - Small.instanceCounter = 0; - - PetiteContainer pc = new PetiteContainer(); - pc.config().setWireScopedProxy(true); - pc.config().setDetectMixedScopes(true); - - pc.registerPetiteBean(Big2.class, "big", SingletonScope.class, null, false, null); - pc.registerPetiteBean(Small.class, "small", ProtoScope.class, null, false, null); - - Big2 big = pc.getBean("big"); - - Small small1 = big.getSmall(); - Small small2 = big.getSmall(); - - assertSame(small1, small2); // factory !!! - - assertEquals(1, Small.instanceCounter); - - assertEquals("small 1", small1.name()); - assertEquals("small 1", small2.name()); - - assertEquals(1, Small.instanceCounter); - - assertTrue(small1.toString().equals(small2.toString())); - - assertEquals(1, Small.instanceCounter); - } - - @Test - void testSingleFactoryInstance() { - - Small.instanceCounter = 0; - - PetiteContainer pc = new PetiteContainer(); - pc.config().setWireScopedProxy(true); - pc.config().setDetectMixedScopes(true); - - pc.registerPetiteBean(Big.class, "big", SingletonScope.class, null, false, null); - pc.registerPetiteBean(Big.class, "big2", SingletonScope.class, null, false, null); - pc.registerPetiteBean(Small.class, "small", ProtoScope.class, null, false, null); - - Big big = pc.getBean("big"); - - Small small1 = big.getSmall(); - Small small2 = big.getSmall(); - - assertSame(small1, small2); // factory !!! - - assertEquals(1, Small.instanceCounter); - - Big big2 = pc.getBean("big2"); - - Small small3 = big2.getSmall(); - Small small4 = big2.getSmall(); - - assertSame(small3, small4); // factory !!! - - assertNotSame(small1, small4); - } - - @Test - void testThreadLocalScopeInSingleton() { - - Small.instanceCounter = 0; - - PetiteContainer pc = new PetiteContainer(); - pc.config().setWireScopedProxy(true); - pc.config().setDetectMixedScopes(true); - - pc.registerPetiteBean(Big.class, "big", SingletonScope.class, null, false, null); - pc.registerPetiteBean(Small.class, "small", ThreadLocalScope.class, null, false, null); - - final Big big = pc.getBean("big"); - - Small small1 = big.getSmall(); - Small small2 = big.getSmall(); - - assertSame(small1, small2); - - // one 'small' instance is created for the factory wrapper. - assertEquals(1, Small.instanceCounter); - - // on next small method call, new 'small' instance will be created, - // from the ThreadLocal scope factory - assertEquals("small 2", small1.name()); - - // no 'small' instance will be created, the same instance from above will be used - assertEquals("small 2", small2.name()); - - // create new thread - Thread thread = new Thread() { - @Override - public void run() { - Small small3 = big.getSmall(); - - assertEquals(2, Small.instanceCounter); - - assertEquals("small 3", small3.name()); - assertEquals("small 3", small3.name()); - - assertEquals(3, Small.instanceCounter); - - } - }; - - thread.start(); - - try { - thread.join(); - } catch (InterruptedException ignore) { - } - - assertEquals(3, Small.instanceCounter); - - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/MultipleArgumentTest.java b/jodd-petite/src/test/java/jodd/petite/MultipleArgumentTest.java deleted file mode 100644 index d9385322f..000000000 --- a/jodd-petite/src/test/java/jodd/petite/MultipleArgumentTest.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.tst6.DaDrum; -import jodd.petite.fixtures.tst6.Guitar; -import jodd.petite.fixtures.tst6.TheBand; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -class MultipleArgumentTest { - - @Test - void testWiringMethodArguments() { - PetiteContainer pc = new PetiteContainer(); - - pc.config().setDefaultWiringMode(WiringMode.OPTIONAL); - - PetiteRegistry petiteRegistry = pc.createContainerRegistry(); - - petiteRegistry.bean(DaDrum.class).register(); - petiteRegistry.bean(Guitar.class).register(); - petiteRegistry.bean(TheBand.class).register(); - - TheBand theBand = pc.getBean(TheBand.class); - - assertTrue(theBand.isBandReady()); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/NamesParamsAndReferencesTest.java b/jodd-petite/src/test/java/jodd/petite/NamesParamsAndReferencesTest.java deleted file mode 100644 index e06e27381..000000000 --- a/jodd-petite/src/test/java/jodd/petite/NamesParamsAndReferencesTest.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - - -import jodd.petite.fixtures.rainbow.Blue; -import jodd.petite.fixtures.rainbow.Purple; -import jodd.petite.fixtures.rainbow.Red; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -class NamesParamsAndReferencesTest { - - @Test - void testDefaultNamings() { - PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(Red.class); - pc.registerPetiteBean(Blue.class); - pc.registerPetiteBean(Purple.class); - - Red red = pc.getBean("red"); - assertNotNull(red); - - Purple purple = pc.getBean("purple"); - assertNotNull(purple); - assertNotNull(purple.blue); - assertNotNull(purple.red); - - red = pc.getBean(Red.class.getName()); - assertNull(red); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/OutsideObjectsTest.java b/jodd-petite/src/test/java/jodd/petite/OutsideObjectsTest.java deleted file mode 100644 index 4540528d4..000000000 --- a/jodd-petite/src/test/java/jodd/petite/OutsideObjectsTest.java +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.meta.PetiteInject; -import jodd.util.TypeCache; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -class OutsideObjectsTest { - - public static class InBean { - } - - public static class BeBean { - @PetiteInject public InBean inBean; - } - - @Test - void testWire() { - final PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(InBean.class); - - final BeBean beBean = new BeBean(); - - assertNull(beBean.inBean); - - pc.wire(beBean); - - assertNotNull(beBean.inBean); - assertNotNull(pc.lookupBeanDefinition("inBean")); - assertNull(pc.lookupBeanDefinition("beBean")); - assertEquals(1, pc.beansCount()); - assertEquals(0, pc.externalsCache.size()); - } - - @Test - void testWire_withCache() { - final PetiteContainer pc = new PetiteContainer(); - pc.setExternalsCache(TypeCache.createDefault()); - pc.registerPetiteBean(InBean.class); - - BeBean beBean = new BeBean(); - - assertNull(beBean.inBean); - - pc.wire(beBean); - - assertNotNull(beBean.inBean); - assertNotNull(pc.lookupBeanDefinition("inBean")); - assertNull(pc.lookupBeanDefinition("beBean")); - assertEquals(1, pc.beansCount()); - - // repeating - beBean = new BeBean(); - pc.wire(beBean); - assertNotNull(beBean.inBean); - assertEquals(1, pc.beansCount()); - assertEquals(1, pc.externalsCache.size()); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/ParamTest.java b/jodd-petite/src/test/java/jodd/petite/ParamTest.java deleted file mode 100644 index 66e9ba0d3..000000000 --- a/jodd-petite/src/test/java/jodd/petite/ParamTest.java +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.tst.Foo; -import jodd.petite.fixtures.tst.Val; -import org.junit.jupiter.api.Test; - -import java.util.Properties; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -class ParamTest { - - @Test - void testSimpleParams() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - - pc.defineParameter("foo.name", "FOONAME"); - - Foo foo = pc.getBean("foo"); - assertNotNull(foo); - assertEquals("FOONAME", foo.getName()); - } - - @Test - void testRefParams() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - - pc.defineParameter("foo.name", "$${name}"); - pc.defineParameter("name", "${name${num}}"); - pc.defineParameter("num", "2"); - pc.defineParameter("name2", "FOONAME"); - pc.defineParameter("FOONAME", "aaa"); - - Foo foo = pc.getBean("foo"); - assertNotNull(foo); - assertEquals("$FOONAME", foo.getName()); - } - - @Test - void testRefParamsEscape() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - - pc.defineParameter("foo.name", "\\${name}"); - - Foo foo = pc.getBean("foo"); - assertNotNull(foo); - assertEquals("${name}", foo.getName()); - } - - @Test - void testRefParamsNoResolve() { - PetiteContainer pc = new PetiteContainer(); - pc.config().setResolveReferenceParameters(false); - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - - pc.defineParameter("foo.name", "${name}"); - pc.defineParameter("name", "${name2}"); - pc.defineParameter("name2", "FOONAME"); - - Foo foo = pc.getBean("foo"); - assertNotNull(foo); - assertEquals("${name}", foo.getName()); - } - - @Test - void testProperties() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - - Properties p = new Properties(); - p.setProperty("foo.name", "${name}"); - p.setProperty("name", "${name2}"); - p.setProperty("name2", "FOONAME"); - pc.defineParameters(p); - - Foo foo = pc.getBean("foo"); - assertNotNull(foo); - assertEquals("FOONAME", foo.getName()); - } - - @Test - void testInjectedParams() { - final PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Val.class, null, null, null, false, null); - pc.config().setImplicitParamInjection(false); - - pc.defineParameter("someValue", "173"); - pc.defineParameter("jodd.is.cool", "yes!"); - - Val val = pc.getBean("val"); - assertNotNull(val); - assertEquals("{foo=173,hello='WOO-yes!173'}", val.toString()); - - } - - @Test - void testEmptyParam() { - final PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Val.class, null, null, null, false, null); - pc.config().setImplicitParamInjection(false); - - pc.defineParameter("someValue", "173"); - pc.defineParameter("justValue", "aaa"); - - Val val = pc.getBean("val"); - assertNotNull(val); - assertEquals("aaa", val.getJustValue()); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/PetiteInvokeMethodTest.java b/jodd-petite/src/test/java/jodd/petite/PetiteInvokeMethodTest.java deleted file mode 100644 index faeb9c0ce..000000000 --- a/jodd-petite/src/test/java/jodd/petite/PetiteInvokeMethodTest.java +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.meta.PetiteInject; -import jodd.util.ClassUtil; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Method; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class PetiteInvokeMethodTest { - - @PetiteBean - public static class Moon { - public String name() { - return "moon"; - } - } - - public static class Hello { - public String world1(@PetiteInject Moon moon) { - return "world" + moon.name(); - } - public String world2() { - return "world"; - } - } - - @Test - public void invokeMethod() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Moon.class); - - Hello hello = new Hello(); - Method world1 = ClassUtil.findMethod(Hello.class, "world1"); - Method world2 = ClassUtil.findMethod(Hello.class, "world2"); - - String string = pc.invokeMethod(hello, world1); - assertEquals("worldmoon", string); - - string = pc.invokeMethod(hello, world2); - assertEquals("world", string); - - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/PetiteShutdownTest.java b/jodd-petite/src/test/java/jodd/petite/PetiteShutdownTest.java deleted file mode 100644 index 93bc1e653..000000000 --- a/jodd-petite/src/test/java/jodd/petite/PetiteShutdownTest.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.data.PojoBean; -import jodd.petite.fixtures.data.SomeService; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class PetiteShutdownTest { - - @Test - void testShutdown() { - PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(SomeService.class, null, null, null, false, null); - pc.registerPetiteBean(PojoBean.class, "pojo", null, null, false, null); - - assertEquals(2, pc.beansCount()); - - pc.shutdown(); - - assertEquals(0, pc.beansCount()); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/PrivateInjectionTest.java b/jodd-petite/src/test/java/jodd/petite/PrivateInjectionTest.java deleted file mode 100644 index dd12b3cd2..000000000 --- a/jodd-petite/src/test/java/jodd/petite/PrivateInjectionTest.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.tst.Loo; -import jodd.petite.fixtures.tst.YujinpingBaseService; -import jodd.petite.fixtures.tst.YujinpingUserService; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class PrivateInjectionTest { - - @Test - void testPrivateInjection() { - PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(Loo.class); - pc.registerPetiteBean(YujinpingBaseService.class); - pc.registerPetiteBean(YujinpingUserService.class); - - YujinpingUserService service = pc.getBean(YujinpingUserService.class); - - assertTrue(service.check2()); - assertTrue(service.check()); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/PropertyTest.java b/jodd-petite/src/test/java/jodd/petite/PropertyTest.java deleted file mode 100644 index b91031575..000000000 --- a/jodd-petite/src/test/java/jodd/petite/PropertyTest.java +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.data.PojoBean2; -import jodd.petite.fixtures.tst2.Joo; -import jodd.petite.fixtures.tst2.Moo; -import jodd.props.Props; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.fail; - -class PropertyTest { - - @Test - void testSet() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(PojoBean2.class, null, null, null, false, null); - - pc.setBeanProperty("pojoBean2.val1", "value"); - pc.setBeanProperty("pojoBean2.val2", "173"); - - PojoBean2 pojo2 = pc.getBean("pojoBean2"); - assertEquals("value", pojo2.getVal1()); - assertEquals(173, pojo2.getVal2().intValue()); - } - - @Test - void testSetWithMultipleDots() { - PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(PojoBean2.class, "pojo", null, null, false, null); - - try { - pc.setBeanProperty("poco", null); - fail("error"); - } catch (PetiteException ignore) { - } - pc.setBeanProperty("pojo.val1", "value"); - pc.setBeanProperty("pojo.bean.name", "foo"); - - PojoBean2 pojo2 = pc.getBean("pojo"); - assertEquals("value", pojo2.getVal1()); - assertEquals("foo", pojo2.getBean().getName()); - - pc.registerPetiteBean(PojoBean2.class, "pojo.bean", null, null, false, null); - pc.setBeanProperty("pojo.bean.val1", "value"); - pc.setBeanProperty("pojo.bean.val2", "173"); - - pojo2 = pc.getBean("pojo.bean"); - assertEquals("value", pojo2.getVal1()); - assertEquals(173, pojo2.getVal2().intValue()); - } - - @Test - void testGet() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(PojoBean2.class, null, null, null, false, null); - - PojoBean2 pojo2 = pc.getBean("pojoBean2"); - pojo2.setVal1("value"); - pojo2.setVal2(Integer.valueOf(173)); - - pc.setBeanProperty("pojoBean2.val1", "value"); - pc.setBeanProperty("pojoBean2.val2", "173"); - - - assertEquals("value", pc.getBeanProperty("pojoBean2.val1")); - assertEquals(Integer.valueOf(173), pc.getBeanProperty("pojoBean2.val2")); - } - - @Test - void testCount() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Moo.class, null, null, null, false, null); - pc.registerPetiteBean(Joo.class, null, null, null, false, null); - Moo moo = pc.getBean(Moo.class); - assertNotNull(moo.joo); - assertNull(moo.jooNo); - - BeanDefinition bd = pc.lookupBeanDefinition("moo"); - assertEquals(1, bd.properties.length); - - - pc = new PetiteContainer(); - pc.config().setDefaultWiringMode(WiringMode.AUTOWIRE); - pc.registerPetiteBean(Moo.class, null, null, null, false, null); - pc.registerPetiteBean(Joo.class, null, null, null, false, null); - - moo = pc.getBean(Moo.class); - assertNotNull(moo.joo); - assertNotNull(moo.jooNo); - assertEquals(moo.joo, moo.jooNo); - - bd = pc.lookupBeanDefinition("moo"); - assertEquals(2, bd.properties.length); - } - - @Test - void testProps() { - Props props = new Props(); - props.load("pojoBean2.val2=123"); - props.load("pojoBean2.val1=\\\\${pojo}"); - - assertEquals("123", props.getValue("pojoBean2.val2")); - assertEquals("\\${pojo}", props.getValue("pojoBean2.val1")); - - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(PojoBean2.class, null, null, null, false, null); - pc.defineParameters(props); - - PojoBean2 pojoBean2 = pc.getBean(PojoBean2.class); - - assertEquals(123, pojoBean2.getVal2().intValue()); - assertEquals("${pojo}", pojoBean2.getVal1()); - } - - @Test - void testParam_wireExternal() { - PetiteContainer pc = new PetiteContainer(); - pc.defineParameter("pojoBean2.val1", "123"); - - final PojoBean2 pojoBean2 = new PojoBean2(); - pc.wire(pojoBean2, WiringMode.AUTOWIRE); - assertEquals("123", pojoBean2.getVal1()); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/ProviderTest.java b/jodd-petite/src/test/java/jodd/petite/ProviderTest.java deleted file mode 100644 index ea94c0b7a..000000000 --- a/jodd-petite/src/test/java/jodd/petite/ProviderTest.java +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.tst5.Planet; -import jodd.petite.fixtures.tst5.Solar; -import jodd.petite.fixtures.tst5.Solar2; -import jodd.petite.fixtures.tst5.Solar3; -import jodd.petite.fixtures.tst5.Sun; -import jodd.petite.fixtures.tst5.Sun2; -import jodd.util.ClassUtil; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class ProviderTest { - - @Test - void testInstanceMethodProvider() { - PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(Solar.class, null, null, null, false, null); - pc.registerPetiteBean(Sun.class, null, null, null, false, null); - - Sun sun = pc.getBean(Sun.class); - - assertEquals("Sun{Earth}", sun.toString()); - } - - - @Test - void testInstanceMethodProviderManualRegistration() { - PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(Solar2.class, null, null, null, false, null); - pc.registerPetiteBean(Sun2.class, null, null, null, false, null); - - pc.registerPetiteProvider("planet", "solar2", "planetProvider", ClassUtil.EMPTY_CLASS_ARRAY); - pc.registerPetitePropertyInjectionPoint("sun2", "planet", null); - - Sun2 sun = pc.getBean(Sun2.class); - - assertEquals("Sun{Earth}", sun.toString()); - } - - - @Test - void testInstanceStaticMethodProvider() { - PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(Solar3.class, null, null, null, false, null); // still needs to be a bean - pc.registerPetiteBean(Sun.class, null, null, null, false, null); - - Sun sun = pc.getBean(Sun.class); - - assertEquals("Sun{Earth}", sun.toString()); - } - - - - @Test - void testProviderLookup() { - PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(Solar3.class, null, null, null, false, null); - - Planet earth = pc.getBean("planet"); - - assertEquals("Earth", earth.toString()); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/ProxettaAwareContainerTest.java b/jodd-petite/src/test/java/jodd/petite/ProxettaAwareContainerTest.java deleted file mode 100644 index d75291608..000000000 --- a/jodd-petite/src/test/java/jodd/petite/ProxettaAwareContainerTest.java +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.meta.PetiteInject; -import jodd.petite.proxetta.ProxettaAwarePetiteContainer; -import jodd.proxetta.Proxetta; -import jodd.proxetta.ProxyAspect; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.pointcuts.AllRealMethodsPointcut; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -class ProxettaAwareContainerTest { - - @PetiteBean - public static class SecretService { - } - - // non-private field - @PetiteBean - public static class PublicService { - - @PetiteInject - SecretService secretService; - - public String hello() { - return "Hello World!"; - } - } - - // private field with setter - @PetiteBean - public static class PublicService2 { - - @PetiteInject - private SecretService secretService; - - public void setSecretService(SecretService secretService) { - this.secretService = secretService; - } - - public String hello() { - return "Hello World!"; - } - } - - // private field with annotated setter - @PetiteBean - public static class PublicService3 { - - private SecretService secretService; - - @PetiteInject - public void setSecretService(SecretService secretService) { - this.secretService = secretService; - } - - public String hello() { - return "Hello World!"; - } - } - - @Test - void testProxyProxetta() { - ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspect( - new ProxyAspect(AddStringAdvice.class, new AllRealMethodsPointcut())); - - PetiteContainer papc = new ProxettaAwarePetiteContainer(proxetta); - - papc.registerPetiteBean(SecretService.class, null, null, null, false, null); - BeanDefinition beanDefinition = papc.registerPetiteBean(PublicService.class, null, null, null, false, null); - papc.registerPetiteBean(PublicService2.class, null, null, null, false, null); - papc.registerPetiteBean(PublicService3.class, null, null, null, false, null); - - assertNotEquals(PublicService.class, beanDefinition.type()); - - PublicService publicService = papc.getBean(beanDefinition.name()); - assertNotNull(publicService.secretService); - assertEquals("Hello World! And Universe, too!", publicService.hello()); - - PublicService2 publicService2 = papc.getBean(PublicService2.class); - assertNotNull(publicService2.secretService); - assertEquals("Hello World! And Universe, too!", publicService2.hello()); - - PublicService3 publicService3 = papc.getBean(PublicService3.class); - assertNotNull(publicService3.secretService); - assertEquals("Hello World! And Universe, too!", publicService3.hello()); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/ScopeTest.java b/jodd-petite/src/test/java/jodd/petite/ScopeTest.java deleted file mode 100644 index 091997226..000000000 --- a/jodd-petite/src/test/java/jodd/petite/ScopeTest.java +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.tst.Boo; -import jodd.petite.fixtures.tst.Foo; -import jodd.petite.fixtures.tst.Zoo; -import jodd.petite.scope.ProtoScope; -import jodd.petite.scope.RequestScope; -import jodd.petite.scope.SessionScope; -import jodd.petite.scope.SingletonScope; -import jodd.petite.scope.ThreadLocalScope; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.Semaphore; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class ScopeTest { - - @Test - void testThreadLocalScope() throws InterruptedException { - final PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(Foo.class, "foo", null, null, false, null); - pc.registerPetiteBean(Zoo.class, null, null, null, false, null); - pc.registerPetiteBean(Boo.class, null, ThreadLocalScope.class, null, false, null); - - assertEquals(3, pc.beansCount()); - assertEquals(2, pc.scopesCount()); - - final Boo boo = (Boo) pc.getBean("boo"); - final Foo foo = (Foo) pc.getBean("foo"); - assertSame(boo.getFoo(), foo); - - - final Semaphore sem = new Semaphore(1); - sem.acquire(); - - Thread thread = new Thread() { - @Override - public void run() { - Boo boo2 = (Boo) pc.getBean("boo"); - Foo foo2 = (Foo) pc.getBean("foo"); - assertSame(foo2, foo); - assertNotSame(boo2, boo); - assertSame(foo2, boo2.getFoo()); - sem.release(); - } - }; - thread.start(); - sem.acquire(); - sem.release(); - } - - @Test - void testScopeAccept() { - final PetiteContainer pc = new PetiteContainer(); - - SingletonScope singletonScope = pc.resolveScope(SingletonScope.class); - ProtoScope protoScope = pc.resolveScope(ProtoScope.class); - SessionScope sessionScope = pc.resolveScope(SessionScope.class); - RequestScope requestScope = pc.resolveScope(RequestScope.class); - - assertTrue(singletonScope.accept(singletonScope)); - assertTrue(singletonScope.accept(protoScope)); - assertFalse(singletonScope.accept(sessionScope)); - assertFalse(singletonScope.accept(requestScope)); - - assertTrue(protoScope.accept(singletonScope)); - assertTrue(protoScope.accept(protoScope)); - assertTrue(protoScope.accept(sessionScope)); - assertTrue(protoScope.accept(requestScope)); - - assertTrue(sessionScope.accept(singletonScope)); - assertTrue(sessionScope.accept(protoScope)); - assertTrue(sessionScope.accept(sessionScope)); - assertFalse(sessionScope.accept(requestScope)); - - assertTrue(requestScope.accept(singletonScope)); - assertTrue(requestScope.accept(protoScope)); - assertTrue(requestScope.accept(sessionScope)); - assertTrue(requestScope.accept(requestScope)); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/ServletsMockitoUtil.java b/jodd-petite/src/test/java/jodd/petite/ServletsMockitoUtil.java deleted file mode 100644 index 4c1dfc351..000000000 --- a/jodd-petite/src/test/java/jodd/petite/ServletsMockitoUtil.java +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import javax.servlet.ServletRequestEvent; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.servlet.http.HttpSessionBindingEvent; -import javax.servlet.http.HttpSessionEvent; -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Some nice Mockito utils for servlets. - */ -public class ServletsMockitoUtil { - - /** - * Creates a session for given session id. - */ - public static HttpSession createSession(String sessionId) { - HttpSession session = mock(HttpSession.class); - - final Map attrs = new HashMap<>(); - when(session.getId()).thenReturn(sessionId); - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - String key = (String) invocation.getArguments()[0]; - Object value = invocation.getArguments()[1]; - attrs.put(key, value); - return null; - } - }).when(session).setAttribute(anyString(), anyObject()); - when(session.getAttribute(anyString())).then(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return attrs.get(invocation.getArguments()[0].toString()); - } - }); - - return session; - } - - public static HttpServletRequest createRequest(HttpSession session) { - HttpServletRequest request = mock(HttpServletRequest.class); - when(request.getSession()).thenReturn(session); - return request; - } - - public static ServletRequestEvent createServletRequestEvent(HttpServletRequest request) { - ServletRequestEvent event = mock(ServletRequestEvent.class); - when(event.getServletRequest()).thenReturn(request); - return event; - } - - public static HttpSessionEvent createHttpSessionEvent(HttpSession session) { - HttpSessionEvent sessionEvent = mock(HttpSessionEvent.class); - when(sessionEvent.getSession()).thenReturn(session); - return sessionEvent; - } - - public static HttpSessionBindingEvent createHttpSessionBindingEvent(HttpSession session) { - HttpSessionBindingEvent sessionBindingEvent = mock(HttpSessionBindingEvent.class); - when(sessionBindingEvent.getSession()).thenReturn(session); - return sessionBindingEvent; - } -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/SetsTest.java b/jodd-petite/src/test/java/jodd/petite/SetsTest.java deleted file mode 100644 index ebd55b17a..000000000 --- a/jodd-petite/src/test/java/jodd/petite/SetsTest.java +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.tst3.Batgirl; -import jodd.petite.fixtures.tst3.Batman; -import jodd.petite.fixtures.tst3.GothamCity; -import jodd.petite.fixtures.tst3.Metropolis; -import jodd.petite.fixtures.tst3.Superman; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class SetsTest { - - @Test - void testEmptySet() { - final PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(GothamCity.class, null, null, null, false, null); - - GothamCity gothamCity = pc.getBean(GothamCity.class); - - assertNotNull(gothamCity.superHeros); - assertTrue(gothamCity.superHeros.isEmpty()); - } - - @Test - void testOneHero() { - final PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(Batman.class, null, null, null, false, null); - pc.registerPetiteBean(GothamCity.class, null, null, null, false, null); - - GothamCity gothamCity = pc.getBean(GothamCity.class); - - assertNotNull(gothamCity.superHeros); - assertFalse(gothamCity.superHeros.isEmpty()); - assertEquals(1, gothamCity.superHeros.size()); - - String str = gothamCity.whoIsThere(); - assertEquals("Batman", str); - } - - @Test - void testTwoHeros() { - final PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(Batman.class, null, null, null, false, null); - pc.registerPetiteBean(GothamCity.class, null, null, null, false, null); - pc.registerPetiteBean(Batgirl.class, null, null, null, false, null); - - GothamCity gothamCity = pc.getBean(GothamCity.class); - - assertNotNull(gothamCity.superHeros); - assertFalse(gothamCity.superHeros.isEmpty()); - assertEquals(2, gothamCity.superHeros.size()); - - String str = gothamCity.whoIsThere(); - assertTrue(str.contains("Batman")); - assertTrue(str.contains("Batgirl")); - } - - @Test - void testCollection() { - final PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(Superman.class, null, null, null, false, null); - pc.registerPetiteBean(Metropolis.class, null, null, null, false, null); - - Metropolis metropolis = pc.getBean(Metropolis.class); - - assertNotNull(metropolis.superHeros); - assertFalse(metropolis.superHeros.isEmpty()); - assertEquals(1, metropolis.superHeros.size()); - - String str = metropolis.whoIsThere(); - assertTrue(str.contains("Superman")); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/ShutdownTest.java b/jodd-petite/src/test/java/jodd/petite/ShutdownTest.java deleted file mode 100644 index aeb136db8..000000000 --- a/jodd-petite/src/test/java/jodd/petite/ShutdownTest.java +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.tst.Boo; -import jodd.petite.fixtures.tst.Foo; -import jodd.petite.fixtures.tst.Ses; -import jodd.petite.fixtures.tst.Zoo; -import jodd.petite.scope.SessionScope; -import jodd.servlet.RequestContextListener; -import org.junit.jupiter.api.Test; - -import javax.servlet.ServletRequestEvent; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.servlet.http.HttpSessionBindingEvent; - -import static jodd.petite.ServletsMockitoUtil.createHttpSessionBindingEvent; -import static jodd.petite.ServletsMockitoUtil.createRequest; -import static jodd.petite.ServletsMockitoUtil.createServletRequestEvent; -import static jodd.petite.ServletsMockitoUtil.createSession; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -class ShutdownTest { - - public static final String ATTR_NAME = SessionScope.class.getName() + ".SESSION_BEANS."; - - @Test - void testSingletonDestroyMethods() { - PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - pc.registerPetiteBean(Zoo.class, null, null, null, false, null); - pc.registerPetiteBean(Boo.class, null, null, null, false, null); - - Boo boo = (Boo) pc.getBean("boo"); - assertEquals(0, boo.getCount2()); - - pc.shutdown(); - - assertEquals(2, boo.getCount2()); - } - - @Test - void testSessionExpired() { - // http session - HttpSession session = createSession("S1"); - HttpServletRequest request = createRequest(session); - ServletRequestEvent requestEvent = createServletRequestEvent(request); - HttpSessionBindingEvent event = createHttpSessionBindingEvent(session); - - // jodd - RequestContextListener requestContextListener = new RequestContextListener(); - - // start session, init request - requestContextListener.requestInitialized(requestEvent); - - // petite - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Ses.class, null, null, null, false, null); - - // callback not yet added - SessionScope.SessionBeans sessionBeans = (SessionScope.SessionBeans) session.getAttribute(ATTR_NAME); - assertNull(sessionBeans); - - Ses ses = (Ses) pc.getBean("ses"); - assertNotNull(ses); - - // callback added - sessionBeans = (SessionScope.SessionBeans) session.getAttribute(ATTR_NAME); - assertNotNull(sessionBeans); - - ses.setValue("jodd"); - - // session expired - sessionBeans.valueUnbound(event); - - assertEquals("-jodd", ses.getValue()); - - pc.shutdown(); - - assertEquals("-jodd", ses.getValue()); - } - - @Test - void testSessionShutdown() { - // http session - HttpSession session = createSession("S2"); - HttpServletRequest request = createRequest(session); - ServletRequestEvent requestEvent = createServletRequestEvent(request); - HttpSessionBindingEvent event = createHttpSessionBindingEvent(session); - - // jodd - RequestContextListener requestContextListener = new RequestContextListener(); - - // start session, init request - requestContextListener.requestInitialized(requestEvent); - - // petite - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Ses.class, null, null, null, false, null); - - Ses ses = (Ses) pc.getBean("ses"); - assertNotNull(ses); - ses.setValue("jodd"); - - // session not expired - assertEquals("jodd", ses.getValue()); - - // shutdown - pc.shutdown(); - - assertEquals("-jodd", ses.getValue()); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/SingleImplementationTest.java b/jodd-petite/src/test/java/jodd/petite/SingleImplementationTest.java deleted file mode 100644 index 0a92c6213..000000000 --- a/jodd-petite/src/test/java/jodd/petite/SingleImplementationTest.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.data.BizUser; -import jodd.petite.fixtures.data.OneBiz; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class SingleImplementationTest { - - @Test - void testSingleImplementation() { - final PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(BizUser.class, null, null, null, false, null); - pc.registerPetiteBean(OneBiz.class, null, null, null, false, null); - assertEquals(2, pc.beansCount()); - - final BizUser bizUser = pc.getBean(BizUser.class); - assertNotNull(bizUser); - assertNotNull(bizUser.biz); - assertTrue(bizUser.biz instanceof OneBiz); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/SyntheticTest.java b/jodd-petite/src/test/java/jodd/petite/SyntheticTest.java deleted file mode 100644 index e63803d05..000000000 --- a/jodd-petite/src/test/java/jodd/petite/SyntheticTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package jodd.petite; - -import org.junit.jupiter.api.Test; - -import java.util.HashMap; -import java.util.Map; - -class SyntheticTest { - - public static class BeanA { - public void test() { - final Map map = new HashMap(); - new Thread(() -> System.out.print(map)); - } - } - - @Test - void synthTest() { - final PetiteContainer pc = new PetiteContainer(); - pc.addBean("foo", new BeanA()); - pc.getBean("foo"); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/TestOneInterfaceLookup.java b/jodd-petite/src/test/java/jodd/petite/TestOneInterfaceLookup.java deleted file mode 100644 index 173a35459..000000000 --- a/jodd-petite/src/test/java/jodd/petite/TestOneInterfaceLookup.java +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.data.Biz; -import jodd.petite.fixtures.data.MyBiz; -import jodd.petite.fixtures.data.MyBiz2; -import jodd.petite.fixtures.data.MyBiz3; -import jodd.petite.fixtures.data.WeBiz; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.fail; - -public class TestOneInterfaceLookup { - - @Test - public void testLookupBiz() { - PetiteContainer pc = new PetiteContainer(); - - pc.registerPetiteBean(MyBiz.class); - - BeanDefinition beanDefinition = pc.lookupBeanDefinition("myBiz"); - assertNotNull(beanDefinition); - assertEquals("myBiz", beanDefinition.name()); - - Biz myBiz = pc.getBean("myBiz"); - assertNotNull(myBiz); - - BeanDefinition altBeanDefinition = pc.lookupBeanDefinition("biz"); - assertNotNull(altBeanDefinition); - assertEquals("myBiz", altBeanDefinition.name()); - assertSame(beanDefinition, altBeanDefinition); - - Biz myBiz2 = pc.getBean("biz"); - assertNotNull(myBiz2); - assertSame(myBiz, myBiz2); - - WeBiz weBiz = new WeBiz(); - pc.wire(weBiz); - assertNotNull(weBiz.biz); - assertSame(myBiz, weBiz.biz); - - - // register second one - - pc.registerPetiteBean(MyBiz2.class); - - beanDefinition = pc.lookupBeanDefinition("myBiz"); - assertNotNull(beanDefinition); - assertEquals("myBiz", beanDefinition.name()); - - altBeanDefinition = pc.lookupBeanDefinition("biz"); - assertNull(altBeanDefinition); - - myBiz2 = pc.getBean("biz"); - assertNull(myBiz2); - - weBiz = new WeBiz(); - try { - pc.wire(weBiz); - fail("error"); - } - catch (PetiteException ignore) {} - - // register third one - - pc.registerPetiteBean(MyBiz3.class); - - beanDefinition = pc.lookupBeanDefinition("myBiz"); - assertNotNull(beanDefinition); - assertEquals("myBiz", beanDefinition.name()); - - altBeanDefinition = pc.lookupBeanDefinition("biz"); - assertNull(altBeanDefinition); - - myBiz2 = pc.getBean("biz"); - assertNull(myBiz2); - - weBiz = new WeBiz(); - try { - pc.wire(weBiz); - fail("error"); - } - catch (PetiteException ignore) {} - assertNull(weBiz.biz); - - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/ThreadSafeTest.java b/jodd-petite/src/test/java/jodd/petite/ThreadSafeTest.java deleted file mode 100644 index 400024de4..000000000 --- a/jodd-petite/src/test/java/jodd/petite/ThreadSafeTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package jodd.petite; - -import jodd.petite.fixtures.data.WeBiz; -import jodd.petite.scope.ProtoScope; -import jodd.petite.scope.SingletonScope; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.CountDownLatch; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -class ThreadSafeTest { - - @Test - void testThreadSafeSingleton() throws InterruptedException { - int count = 10000; - while (count-- > 0) { - final PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(WeBiz.class, "pojo", SingletonScope.class, WiringMode.AUTOWIRE, false, null); - - final CountDownLatch countDownLatch = new CountDownLatch(2); - final Object[] beans = new Object[2]; - final Thread thread1 = new Thread(() -> { - beans[0] = pc.getBean("pojo"); - countDownLatch.countDown(); - }); - final Thread thread2 = new Thread(() -> { - beans[1] = pc.getBean("pojo"); - countDownLatch.countDown(); - }); - - thread1.start(); - thread2.start(); - - countDownLatch.await(); - assertEquals(beans[0], beans[1]); - } - } - - @Test - void testThreadSafePrototype() throws InterruptedException { - int count = 1000; - while (count-- > 0) { - final PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(WeBiz.class, "pojo", ProtoScope.class, WiringMode.AUTOWIRE, false, null); - - final CountDownLatch countDownLatch = new CountDownLatch(2); - final Object[] beans = new Object[2]; - final Thread thread1 = new Thread(() -> { - beans[0] = pc.getBean("pojo"); - countDownLatch.countDown(); - }); - final Thread thread2 = new Thread(() -> { - beans[1] = pc.getBean("pojo"); - countDownLatch.countDown(); - }); - - thread1.start(); - thread2.start(); - - countDownLatch.await(); - assertNotEquals(beans[0], beans[1]); - } - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/WireTest.java b/jodd-petite/src/test/java/jodd/petite/WireTest.java deleted file mode 100644 index 760080cb6..000000000 --- a/jodd-petite/src/test/java/jodd/petite/WireTest.java +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.tst.Boo; -import jodd.petite.fixtures.tst.BooC; -import jodd.petite.fixtures.tst.BooC2; -import jodd.petite.fixtures.tst.Foo; -import jodd.petite.fixtures.tst.Goo; -import jodd.petite.fixtures.tst.Ioo; -import jodd.petite.fixtures.tst.Loo; -import jodd.petite.fixtures.tst.Zoo; -import jodd.petite.fixtures.tst.impl.DefaultIoo; -import jodd.petite.scope.ProtoScope; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.fail; - -class WireTest { - - @BeforeEach - void setUp() { - Foo.instanceCounter = 0; - } - - @Test - void testContainer() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Foo.class); - - assertEquals(1, pc.beansCount()); - assertEquals(1, pc.scopesCount()); - assertEquals(0, Foo.instanceCounter); - - Foo foo = pc.getBean("foo"); - assertNotNull(foo); - assertEquals(1, foo.hello()); - foo = pc.getBean("foo"); - assertEquals(1, foo.hello()); - - - // register again the same class, but this time with proto scope - pc.registerPetiteBean(Foo.class, "foo2", ProtoScope.class, null, false, null); - assertEquals(2, pc.beansCount()); - assertEquals(2, pc.scopesCount()); - - assertEquals(2, ((Foo) pc.getBean("foo2")).hello()); - assertEquals(3, ((Foo) pc.getBean("foo2")).hello()); - - - // register boo - pc.registerPetiteBean(Boo.class, null, null, null, false, null); - assertEquals(3, pc.beansCount()); - assertEquals(2, pc.scopesCount()); - - Boo boo; - try { - //noinspection UnusedAssignment - boo = pc.getBean("boo"); - fail("error"); - } catch (PetiteException pex) { - // zoo class is missing - } - - - // registering missing dependency. - // however we need to remove existing bean that requires this dependency - // as it has been already initialized. - pc.registerPetiteBean(Zoo.class, null, null, null, false, null); - pc.removeBean(Boo.class); - pc.registerPetiteBean(Boo.class, null, null, null, false, null); - - assertEquals(4, pc.beansCount()); - assertEquals(2, pc.scopesCount()); - - boo = pc.getBean("boo"); - assertNotNull(boo); - assertNotNull(boo.getFoo()); - assertNotNull(boo.zoo); - assertSame(boo.zoo.boo, boo); - assertEquals(3, boo.getFoo().hello()); - assertEquals(2, boo.getFoo().getCounter()); // '2' because the first time we getBean('boo') the wiring occurred before exception was throwed! - } - - @Test - void testCreate() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - pc.registerPetiteBean(Zoo.class, null, null, null, false, null); - pc.registerPetiteBean(Boo.class, null, null, null, false, null); - assertEquals(3, pc.beansCount()); - assertEquals(1, pc.scopesCount()); - assertEquals(0, Foo.instanceCounter); - - Boo boo = pc.createBean(Boo.class); - assertNotNull(boo); - assertNotNull(boo.getFoo()); - assertNotNull(boo.zoo); - assertNotSame(boo.zoo.boo, boo); // not equal instances!!! - assertEquals(1, boo.getFoo().hello()); - assertEquals(1, boo.getCount()); - } - - @Test - void testCtor() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(BooC.class, null, null, null, false, null); - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - assertEquals(2, pc.beansCount()); - assertEquals(1, pc.scopesCount()); - assertEquals(0, Foo.instanceCounter); - - BooC boo = pc.getBean("booC"); - assertNotNull(boo); - assertNotNull(boo.getFoo()); - assertEquals(1, boo.getFoo().hello()); - - pc.registerPetiteBean(BooC2.class, "boo", null, null, false, null); - pc.registerPetiteBean(Zoo.class, null, null, null, false, null); - assertEquals(4, pc.beansCount()); - assertEquals(1, pc.scopesCount()); - assertEquals(1, Foo.instanceCounter); - - try { - pc.getBean("boo"); - fail("error"); - } catch (PetiteException pex) { - // ignore // cyclic dependency - } - } - - @Test - void testAutowire() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Goo.class, null, ProtoScope.class, null, false, null); - pc.registerPetiteBean(Loo.class, null, null, null, false, null); - - assertEquals(2, pc.beansCount()); - - Goo goo = pc.getBean("goo"); - assertNotNull(goo); - assertNotNull(goo.looCustom); - assertNull(goo.foo); - - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - goo = pc.getBean("goo"); - assertNotNull(goo); - assertNotNull(goo.looCustom); - assertNull(goo.foo); - - pc = new PetiteContainer(); - pc.config().setDefaultWiringMode(WiringMode.AUTOWIRE); - pc.registerPetiteBean(Goo.class, null, ProtoScope.class, null, false, null); - pc.registerPetiteBean(Loo.class, null, null, null, false, null); - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - - goo = pc.getBean("goo"); - assertNotNull(goo); - assertNotNull(goo.looCustom); - assertNotNull(goo.foo); - - pc.removeBean(Goo.class); - } - - @Test - void testInterface() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - pc.registerPetiteBean(DefaultIoo.class, "ioo", null, null, false, null); - - assertEquals(2, pc.beansCount()); - Ioo ioo = pc.getBean("ioo"); - assertNotNull(ioo); - assertNotNull(ioo.getFoo()); - assertEquals(DefaultIoo.class, ioo.getClass()); - } - - @Test - void testSelf() { - PetiteContainer pc = new PetiteContainer(); - pc.addSelf(); - - assertEquals(1, pc.beansCount()); - - PetiteContainer pc2 = pc.getBean(PetiteContainer.PETITE_CONTAINER_REF_NAME); - assertEquals(pc2, pc); - - } - - @Test - void testInit() { - PetiteContainer pc = new PetiteContainer(); - pc.registerPetiteBean(Foo.class, null, null, null, false, null); - pc.registerPetiteBean(Zoo.class, null, null, null, false, null); - pc.registerPetiteBean(Boo.class, null, null, null, false, null); - pc.registerPetiteBean(Boo.class, "boo2", null, null, false, null); - - Boo boo = pc.getBean("boo"); - assertNotNull(boo.getFoo()); - assertEquals(1, boo.getCount()); - - Boo boo2 = pc.getBean("boo2"); - assertNotSame(boo, boo2); - assertEquals(1, boo2.getCount()); - - assertSame(boo.getFoo(), boo2.getFoo()); - - - List order = boo.orders; - - assertEquals(6, order.size()); - assertEquals("first", order.get(0)); - assertEquals("second", order.get(1)); // Collections.sort() is stable: equals methods are not reordered. - assertEquals("third", order.get(2)); - assertEquals("init", order.get(3)); - assertEquals("beforeLast", order.get(4)); - assertEquals("last", order.get(5)); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/WiringModeTest.java b/jodd-petite/src/test/java/jodd/petite/WiringModeTest.java deleted file mode 100644 index e8c42f472..000000000 --- a/jodd-petite/src/test/java/jodd/petite/WiringModeTest.java +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite; - -import jodd.petite.fixtures.rainbow.Blue; -import jodd.petite.fixtures.rainbow.Green; -import jodd.petite.fixtures.rainbow.Yellow; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class WiringModeTest { - - @Test - void testWireMode_none() { - PetiteContainer pc = new PetiteContainer(); - - final WiringMode wiringMode = WiringMode.NONE; - pc.registerPetiteBean(Green.class, null, null, wiringMode, false, null); - pc.registerPetiteBean(Blue.class, null, null, wiringMode, false, null); - pc.registerPetiteBean(Yellow.class, null, null, wiringMode, false, null); - - Green green = pc.getBean("green"); - - assertNotNull(green); - assertNull(green.blue); - assertNull(green.yellow); - } - - @Test - void testWireMode_strict() { - PetiteContainer pc = new PetiteContainer(); - - final WiringMode wiringMode = WiringMode.STRICT; - pc.registerPetiteBean(Green.class, null, null, wiringMode, false, null); - pc.registerPetiteBean(Blue.class, null, null, wiringMode, false, null); - pc.registerPetiteBean(Yellow.class, null, null, wiringMode, false, null); - - assertThrows(PetiteException.class, () -> pc.getBean("green")); - } - - @Test - void testWireMode_optional() { - PetiteContainer pc = new PetiteContainer(); - - final WiringMode wiringMode = WiringMode.OPTIONAL; - pc.registerPetiteBean(Green.class, null, null, wiringMode, false, null); - pc.registerPetiteBean(Blue.class, null, null, wiringMode, false, null); - pc.registerPetiteBean(Yellow.class, null, null, wiringMode, false, null); - - Green green = pc.getBean("green"); - - assertNotNull(green); - assertNotNull(green.blue); - assertNull(green.yellow); - assertNull(green.red); - } - - @Test - void testWireMode_auto() { - PetiteContainer pc = new PetiteContainer(); - - final WiringMode wiringMode = WiringMode.AUTOWIRE; - pc.registerPetiteBean(Green.class, null, null, wiringMode, false, null); - pc.registerPetiteBean(Blue.class, null, null, wiringMode, false, null); - pc.registerPetiteBean(Yellow.class, null, null, wiringMode, false, null); - - Green green = pc.getBean("green"); - - assertNotNull(green); - assertNotNull(green.blue); - assertNotNull(green.yellow); - assertNull(green.red); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/Revolver.java b/jodd-petite/src/test/java/jodd/petite/fixtures/Revolver.java deleted file mode 100644 index 96a3c246f..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/Revolver.java +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures; - -import jodd.petite.meta.PetiteInject; - -public class Revolver { - - @PetiteInject - private String onlyAnnotation; - - private String nothing; - - @PetiteInject("inn") - private String valued; - - // ---------------------------------------------------------------- - - public void noAnnotation(String ex) {} - - public static class NoAnnotation { - public NoAnnotation(String ex) {} - } - - // ---------------------------------------------------------------- - - @PetiteInject - public void onlyAnnotation() {} - - public static class OnlyAnnotation { - @PetiteInject - public OnlyAnnotation() {} - } - - // ---------------------------------------------------------------- - - @PetiteInject - public void someArguments(String in1, Integer in2) {} - - public static class SomeArguments { - @PetiteInject - public SomeArguments(String in1, Integer in2) {} - } - - // ---------------------------------------------------------------- - - @PetiteInject("innn1, innn2") - public void someArguments_csv(String in1, Integer in2) {} - - public static class SomeArguments_csv { - @PetiteInject("innn1, innn2") - public SomeArguments_csv(String in1, Integer in2) {} - } - - // ---------------------------------------------------------------- - - @PetiteInject("innn1, innn2, inn3") - public void someArguments_wrongAnnotation(String in1, Integer in2) {} - - public static class SomeArguments_wrongAnnotation { - @PetiteInject("innn1, innn2, inn3") - public SomeArguments_wrongAnnotation(String in1, Integer in2) {} - } - - // ---------------------------------------------------------------- - - public void noMethodArgument( - @PetiteInject String in1, - @PetiteInject Integer in2 - ) {} - - public static class NoMethodArgument { - public NoMethodArgument( - @PetiteInject String in1, - @PetiteInject Integer in2 - ) {} - } - - // ---------------------------------------------------------------- - - public void noMethodArgument_partial( - @PetiteInject("innn1") String in1, - @PetiteInject Integer in2 - ) {} - - public static class NoMethodArgument_partial { - public NoMethodArgument_partial( - @PetiteInject("innn1") String in1, - @PetiteInject Integer in2 - ) {} - } - - // ---------------------------------------------------------------- - - @PetiteInject("aaaa, bbbb") - public void mix( - @PetiteInject("innn1") String in1, - Integer in2 - ) {} - - public static class Mix { - @PetiteInject("aaaa, bbbb") - public Mix( - @PetiteInject("innn1") String in1, - Integer in2 - ) {} - } -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/Biz.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/Biz.java deleted file mode 100644 index b8242f5f9..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/Biz.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -public interface Biz { - - void calculate(); -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/BizUser.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/BizUser.java deleted file mode 100644 index c618b7d6c..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/BizUser.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -import jodd.petite.meta.PetiteInject; - -public class BizUser { - - @PetiteInject public Biz biz; - - public void use() { - biz.calculate(); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/DefaultBiz.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/DefaultBiz.java deleted file mode 100644 index 5d86d65fd..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/DefaultBiz.java +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.fixtures.tst.Foo; - -@PetiteBean("biz") -public class DefaultBiz implements Biz { - - Foo foo; - - public Foo getFoo() { - return foo; - } - - public int initCount; - - public void init() { - initCount++; - } - - public void init2() { - initCount++; - } - - public void calculate() { - System.out.println("DefaultBizImpl.calculate"); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/DefaultBizImpl.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/DefaultBizImpl.java deleted file mode 100644 index 728625daa..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/DefaultBizImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -import jodd.petite.meta.PetiteBean; - -@PetiteBean("biz") -public class DefaultBizImpl implements Biz { - - public void calculate() { - System.out.println("DefaultBizImpl.calculate"); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/MyBiz.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/MyBiz.java deleted file mode 100644 index 7f4f73e95..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/MyBiz.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -import jodd.petite.meta.PetiteBean; - -@PetiteBean -public class MyBiz implements Biz { - - @Override - public void calculate() { - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/MyBiz2.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/MyBiz2.java deleted file mode 100644 index 35f275039..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/MyBiz2.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -public class MyBiz2 implements Biz { - - @Override - public void calculate() { - } -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/MyBiz3.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/MyBiz3.java deleted file mode 100644 index 4821c9a3a..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/MyBiz3.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -public class MyBiz3 implements Biz { - - @Override - public void calculate() { - } -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/OneBiz.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/OneBiz.java deleted file mode 100644 index 6df3793ac..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/OneBiz.java +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -public class OneBiz implements Biz { - - @Override - public void calculate() { - - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/PojoAnnBean.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/PojoAnnBean.java deleted file mode 100644 index eabe3b2e1..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/PojoAnnBean.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -import jodd.petite.meta.PetiteInject; -import jodd.petite.meta.PetiteInitMethod; -import jodd.petite.meta.PetiteBean; - -@PetiteBean("pojo") -public class PojoAnnBean { - - public final SomeService fservice; - - @PetiteInject - public PojoAnnBean(SomeService fservice) { - this.fservice = fservice; - } - - @PetiteInject("someService") - public SomeService service; - - public SomeService service2; - - @PetiteInject("someService") - public void injectService(SomeService service) { - service2 = service; - } - - public int count; - - @PetiteInitMethod - public void init() { - count++; - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/PojoBean.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/PojoBean.java deleted file mode 100644 index beb2c9bf1..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/PojoBean.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -public class PojoBean { - - public final SomeService fservice; - - public PojoBean(SomeService fservice) { - this.fservice = fservice; - } - - public SomeService service; - - public SomeService service2; - - public void injectService(SomeService service) { - service2 = service; - } - - public int count; - - public void init() { - count++; - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/PojoBean2.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/PojoBean2.java deleted file mode 100644 index 5dae90abf..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/PojoBean2.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -public class PojoBean2 { - - protected String val1; - - protected Integer val2; - - protected PojoBean3 bean = new PojoBean3(); - - public String getVal1() { - return val1; - } - - public void setVal1(String val1) { - this.val1 = val1; - } - - public Integer getVal2() { - return val2; - } - - public void setVal2(Integer val2) { - this.val2 = val2; - } - - public PojoBean3 getBean() { - return bean; - } - - public void setBean(PojoBean3 bean) { - this.bean = bean; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/PojoBean3.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/PojoBean3.java deleted file mode 100644 index e19869a52..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/PojoBean3.java +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -public class PojoBean3 { - - private String name; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/SomeService.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/SomeService.java deleted file mode 100644 index 39257bf38..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/SomeService.java +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -import jodd.petite.meta.PetiteBean; - -@PetiteBean -public class SomeService { -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/data/WeBiz.java b/jodd-petite/src/test/java/jodd/petite/fixtures/data/WeBiz.java deleted file mode 100644 index 70fc251b6..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/data/WeBiz.java +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.data; - -import jodd.petite.meta.PetiteInject; - -public class WeBiz { - - @PetiteInject - public Biz biz; -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/mix/Big.java b/jodd-petite/src/test/java/jodd/petite/fixtures/mix/Big.java deleted file mode 100644 index d6a7c5533..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/mix/Big.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.mix; - -import jodd.petite.meta.PetiteInject; - -public class Big { - - @PetiteInject - private Small small; - - public Small getSmall() { - return small; - } - - public void setSmall(Small small) { - this.small = small; - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/mix/Big2.java b/jodd-petite/src/test/java/jodd/petite/fixtures/mix/Big2.java deleted file mode 100644 index 726b8e4e2..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/mix/Big2.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.mix; - -import jodd.petite.meta.PetiteInject; - -public class Big2 { - - private Small small; - - public Small getSmall() { - return small; - } - - @PetiteInject - public void setSmall(Small small) { - this.small = small; - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/mix/Small.java b/jodd-petite/src/test/java/jodd/petite/fixtures/mix/Small.java deleted file mode 100644 index e188d4c24..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/mix/Small.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.mix; - -public class Small { - - public static int instanceCounter; - - private final int id; - - public Small() { - id = ++instanceCounter; - } - - public String name() { - return "small " + id; - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Blue.java b/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Blue.java deleted file mode 100644 index 475694bed..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Blue.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.rainbow; - -public class Blue { - - private String value; - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Green.java b/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Green.java deleted file mode 100644 index 65eeff228..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Green.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.rainbow; - -import jodd.petite.meta.PetiteInject; - -public class Green { - @PetiteInject public Blue blue; - public Yellow yellow; - - @PetiteInject("non-existing") public Red red; -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Purple.java b/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Purple.java deleted file mode 100644 index c53015f6d..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Purple.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.rainbow; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.meta.PetiteInject; - -@PetiteBean -public class Purple { - - @PetiteInject public Red red; - @PetiteInject public Blue blue; -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Red.java b/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Red.java deleted file mode 100644 index abaf485a1..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Red.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.rainbow; - -import jodd.petite.meta.PetiteBean; - -@PetiteBean -public class Red { - - private String value; - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Yellow.java b/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Yellow.java deleted file mode 100644 index 8e872a87f..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/rainbow/Yellow.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.rainbow; - -public class Yellow { -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Boo.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Boo.java deleted file mode 100644 index 18ebb2a6b..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Boo.java +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst; - -import jodd.petite.meta.PetiteDestroyMethod; -import jodd.petite.meta.PetiteInject; -import jodd.petite.meta.PetiteInitMethod; - -import java.util.List; -import java.util.ArrayList; - -public class Boo { - - public List orders = new ArrayList<>(); - - @PetiteInject - private Foo foo; - - public Foo getFoo() { - return foo; - } - - public void setFoo(Foo foo) { - foo.counter++; - this.foo = foo; - } - - private int count; - private int count2; - - public int getCount() { - return count; - } - public int getCount2() { - return count2; - } - - @PetiteInitMethod - void init() { - count++; - orders.add("init"); - } - - @PetiteInitMethod(order = 100) - void third() { - orders.add("third"); - } - - @PetiteInitMethod(order = -1) - void last() { - orders.add("last"); - } - - @PetiteInitMethod(order = -2) - void beforeLast() { - orders.add("beforeLast"); - } - - @PetiteInitMethod(order = 1) - void first() { - orders.add("first"); - } - - @PetiteInitMethod(order = 2) - void second() { - orders.add("second"); - } - - @PetiteDestroyMethod - void ciao() { - count2++; - } - @PetiteDestroyMethod - void buy() { - count2++; - } - - @PetiteInject - public final Zoo zoo = null; - -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/BooC.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst/BooC.java deleted file mode 100644 index 55db74ef2..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/BooC.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst; - -import jodd.petite.meta.PetiteInject; - -public class BooC { - - private final Foo foo; - - public BooC() { - foo = null; - } - @PetiteInject - private BooC(Foo foo) { - this.foo = foo; - } - - public Foo getFoo() { - return foo; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/BooC2.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst/BooC2.java deleted file mode 100644 index 77aa82d5c..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/BooC2.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst; - -import jodd.petite.meta.PetiteInject; - -public class BooC2 { - - private Foo foo; - private Zoo zoo; - - @PetiteInject - private BooC2(Foo foo, Zoo zoo) { - this.foo = foo; - this.zoo = zoo; - } - - public Foo getFoo() { - return foo; - } - - - public Zoo getZoo() { - return zoo; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Foo.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Foo.java deleted file mode 100644 index 9a63e113a..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Foo.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst; - -import jodd.petite.meta.PetiteBean; - -@PetiteBean -public class Foo { - - public static int instanceCounter; - - int counter; - - public Foo() { - instanceCounter++; - counter = 0; - } - - public int hello() { - return instanceCounter; - } - - - public int getCounter() { - return counter; - } - - - private String name; - public String getName() { - return name; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Goo.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Goo.java deleted file mode 100644 index d46f8624f..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Goo.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst; - -import jodd.petite.meta.PetiteInject; - -public class Goo { - - public Foo foo; - - @PetiteInject("loo") - public Loo looCustom; - -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Ioo.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Ioo.java deleted file mode 100644 index 6892f5307..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Ioo.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst; - -public interface Ioo { - - void hello(); - - Foo getFoo(); -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Loo.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Loo.java deleted file mode 100644 index 66b14ecec..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Loo.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst; - -public class Loo { -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Ses.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Ses.java deleted file mode 100644 index f60c13590..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Ses.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.meta.PetiteDestroyMethod; -import jodd.petite.scope.SessionScope; - -@PetiteBean(scope = SessionScope.class) -public class Ses { - - private String value; - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - @PetiteDestroyMethod - public void ciao() { - value = "-" + value; - } -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Val.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Val.java deleted file mode 100644 index cfd7cac1d..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Val.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst; - -import jodd.petite.meta.PetiteValue; - -public class Val { - - @PetiteValue("${someValue}") - private Integer foo; - - private String hello; - - @PetiteValue - private String justValue; - - @PetiteValue("WOO-${jodd.is.cool}${someValue}") - public void setHello(String hello) { - this.hello = hello; - } - - public String getJustValue() { - return justValue; - } - - @Override - public String toString() { - return "{" + - "foo=" + foo + - ",hello='" + hello + '\'' + - '}'; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/YujinpingBaseService.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst/YujinpingBaseService.java deleted file mode 100644 index 74a1756c9..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/YujinpingBaseService.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst; - -import jodd.petite.meta.PetiteInject; - -public class YujinpingBaseService { - - @PetiteInject - private Loo loo; - - public boolean check() { - return loo != null; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/YujinpingUserService.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst/YujinpingUserService.java deleted file mode 100644 index 3126ad82f..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/YujinpingUserService.java +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst; - -import jodd.petite.meta.PetiteInject; - -public class YujinpingUserService extends YujinpingBaseService { - - @PetiteInject - private Loo loo2; - - public boolean check2() { - return loo2 != null; - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Zoo.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Zoo.java deleted file mode 100644 index e5215953d..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/Zoo.java +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst; - -import jodd.petite.meta.PetiteInject; - -public class Zoo { - - @PetiteInject - public final Boo boo = null; -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/impl/DefaultIoo.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst/impl/DefaultIoo.java deleted file mode 100644 index 88784a82a..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst/impl/DefaultIoo.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst.impl; - -import jodd.petite.fixtures.tst.Ioo; -import jodd.petite.fixtures.tst.Foo; -import jodd.petite.meta.PetiteInject; - -public class DefaultIoo implements Ioo { - - @PetiteInject - Foo foo; - - public void hello() { - System.out.println("DefaultIoo.hello"); - } - - public Foo getFoo() { - return foo; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst2/Joo.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst2/Joo.java deleted file mode 100644 index d4445ae25..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst2/Joo.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst2; - -public class Joo { -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst2/Koo.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst2/Koo.java deleted file mode 100644 index 01ce349c8..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst2/Koo.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst2; - -import jodd.petite.meta.PetiteInject; - -public class Koo { - - @PetiteInject - public Koo(Joo joo) { - this.joojoo = joo; - } - public Joo joojoo; - - @PetiteInject - public void injectMee(Joo joo, Joo joo2) { - mjoo = joo; - mjoo2 = joo2; - } - - public Joo mjoo; - public Joo mjoo2; - - - @PetiteInject - public Joo joo; - - @PetiteInject - public Joo someNoJooName; - -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst2/Moo.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst2/Moo.java deleted file mode 100644 index 6ea962138..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst2/Moo.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst2; - -import jodd.petite.meta.PetiteInject; - -public class Moo { - - public Joo jooNo; - - @PetiteInject - public Joo joo; - -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/Batgirl.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/Batgirl.java deleted file mode 100644 index a9d9464f1..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/Batgirl.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst3; - -import jodd.petite.meta.PetiteBean; - -@PetiteBean -public class Batgirl implements SuperHero { - - public String getHeroName() { - return "Batgirl"; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/Batman.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/Batman.java deleted file mode 100644 index 34dc631c4..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/Batman.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst3; - -import jodd.petite.meta.PetiteBean; - -@PetiteBean -public class Batman implements SuperHero { - - public String getHeroName() { - return "Batman"; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/GothamCity.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/GothamCity.java deleted file mode 100644 index 03b515c10..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/GothamCity.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst3; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.meta.PetiteInject; - -import java.util.Set; - -@PetiteBean -public class GothamCity { - - @PetiteInject - public Set superHeros; - - public String whoIsThere() { - String superHeroes = ""; - for (SuperHero superHero : superHeros) { - superHeroes += superHero.getHeroName() + " "; - } - - return superHeroes.trim(); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/Metropolis.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/Metropolis.java deleted file mode 100644 index e5e85c67d..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/Metropolis.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst3; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.meta.PetiteInject; - -import java.util.Collection; - -@PetiteBean -public class Metropolis implements SuperHero { - - @PetiteInject - public Collection superHeros; - - public String whoIsThere() { - String superHeroes = ""; - for (SuperHero superHero : superHeros) { - superHeroes += superHero.getHeroName() + " "; - } - - return superHeroes.trim(); - } - - public String getHeroName() { - return "delegate"; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/SuperHero.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/SuperHero.java deleted file mode 100644 index 0d7dcec1c..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/SuperHero.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst3; - -public interface SuperHero { - - String getHeroName(); -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/Superman.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/Superman.java deleted file mode 100644 index b5466c5cd..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst3/Superman.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst3; - -import jodd.petite.meta.PetiteBean; - -@PetiteBean -public class Superman implements SuperHero { - - public String getHeroName() { - return "Superman"; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst4/Bar.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst4/Bar.java deleted file mode 100644 index 0f1197db7..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst4/Bar.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst4; - -public class Bar { - public String toString() {return "bar";} -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst4/Foo.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst4/Foo.java deleted file mode 100644 index fe22f01df..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst4/Foo.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst4; - -public class Foo { - public String data; - - public Bar bar; - - void init() { - result = "ctor " + bar + ' ' + data; - } - - public String result; -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst4/Foo2.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst4/Foo2.java deleted file mode 100644 index cf6b1e899..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst4/Foo2.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst4; - -public class Foo2 { - - public String data; - - public Bar bar; - - void init1() { - result = "1 " + bar + ' ' + data; - } - void init2() { - result += " 2 " + bar + ' ' + data; - } - void init3() { - result += " 3 " + bar + ' ' + data; - } - - public String result; - -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Planet.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Planet.java deleted file mode 100644 index 8adee2f52..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Planet.java +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst5; - -public class Planet { - - @Override - public String toString() { - return "Earth"; - } -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Solar.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Solar.java deleted file mode 100644 index c9e3d8931..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Solar.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst5; - -import jodd.petite.meta.PetiteProvider; - -public class Solar { - - @PetiteProvider("planet") - public Planet planetProvider() { - return new Planet(); - } - -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Solar2.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Solar2.java deleted file mode 100644 index 299ad3ae5..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Solar2.java +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst5; - -public class Solar2 { - - public Planet planetProvider() { - return new Planet(); - } - -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Solar3.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Solar3.java deleted file mode 100644 index 99a3190c8..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Solar3.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst5; - -import jodd.petite.meta.PetiteProvider; - -public class Solar3 { - - @PetiteProvider // default name: "planet" - public static Planet planetProvider() { - return new Planet(); - } - -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Sun.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Sun.java deleted file mode 100644 index e76ed7625..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Sun.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst5; - -import jodd.petite.meta.PetiteInject; - -public class Sun { - - @PetiteInject - Planet planet; - - @Override - public String toString() { - return "Sun{" + planet + '}'; - } - -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Sun2.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Sun2.java deleted file mode 100644 index 5261470da..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst5/Sun2.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst5; - -public class Sun2 { - - Planet planet; - - @Override - public String toString() { - return "Sun{" + planet + '}'; - } - -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst6/DaDrum.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst6/DaDrum.java deleted file mode 100644 index 81d2ff4ca..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst6/DaDrum.java +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst6; - -import jodd.petite.meta.PetiteBean; - -@PetiteBean -public class DaDrum { -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst6/Guitar.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst6/Guitar.java deleted file mode 100644 index d50d389e7..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst6/Guitar.java +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst6; - -import jodd.petite.meta.PetiteBean; - -@PetiteBean -public class Guitar { -} diff --git a/jodd-petite/src/test/java/jodd/petite/fixtures/tst6/TheBand.java b/jodd-petite/src/test/java/jodd/petite/fixtures/tst6/TheBand.java deleted file mode 100644 index a6080e8fe..000000000 --- a/jodd-petite/src/test/java/jodd/petite/fixtures/tst6/TheBand.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.fixtures.tst6; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.meta.PetiteInject; - -@PetiteBean -public class TheBand { - - private DaDrum drum; - private Guitar guitar; - - public void inject( - @PetiteInject Guitar soloGuitar, - @PetiteInject DaDrum drumster) { - - this.guitar = soloGuitar; - this.drum = drumster; - } - - public boolean isBandReady() { - return drum != null && guitar != null; - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/proxy/LogProxyAdvice.java b/jodd-petite/src/test/java/jodd/petite/proxy/LogProxyAdvice.java deleted file mode 100644 index ba470ffcf..000000000 --- a/jodd-petite/src/test/java/jodd/petite/proxy/LogProxyAdvice.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.proxy; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -public class LogProxyAdvice implements ProxyAdvice { - - @Override - public Object execute() throws Exception { - System.out.println("execute now : " + ProxyTarget.targetClass().getCanonicalName()); - return ProxyTarget.invoke(); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/proxy/Logged.java b/jodd-petite/src/test/java/jodd/petite/proxy/Logged.java deleted file mode 100644 index 7118356a6..000000000 --- a/jodd-petite/src/test/java/jodd/petite/proxy/Logged.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.proxy; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.ANNOTATION_TYPE; -import static java.lang.annotation.ElementType.CONSTRUCTOR; -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.LOCAL_VARIABLE; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.PACKAGE; -import static java.lang.annotation.ElementType.PARAMETER; -import static java.lang.annotation.ElementType.TYPE; - -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target(value = {TYPE, ANNOTATION_TYPE, CONSTRUCTOR, FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, PACKAGE}) -public @interface Logged { -} \ No newline at end of file diff --git a/jodd-petite/src/test/java/jodd/petite/proxy/MixedScope343Test.java b/jodd-petite/src/test/java/jodd/petite/proxy/MixedScope343Test.java deleted file mode 100644 index f2dcd5e77..000000000 --- a/jodd-petite/src/test/java/jodd/petite/proxy/MixedScope343Test.java +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.proxy; - -import jodd.petite.AutomagicPetiteConfigurator; -import jodd.petite.PetiteConfig; -import jodd.petite.PetiteContainer; -import jodd.petite.proxetta.ProxettaAwarePetiteContainer; -import jodd.petite.proxy.example1.ExternalBean; -import jodd.proxetta.ProxettaNames; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.test.DisabledOnJava; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class MixedScope343Test { - - private PetiteContainer petiteContainer; - - @BeforeEach - void setupPetiteContainer() { - final PetiteConfig petiteConfig = PetiteHelper.createPetiteConfig(); - - final ProxyProxetta proxyProxetta = PetiteHelper.createProxyProxetta(); - petiteContainer = new ProxettaAwarePetiteContainer(proxyProxetta, petiteConfig); - - final AutomagicPetiteConfigurator petiteConfigurator = new AutomagicPetiteConfigurator(petiteContainer); - petiteConfigurator.withScanner(scanner -> scanner.includeEntries(this.getClass().getPackage().getName() + ".*")); - petiteConfigurator.configure(); - } - - @AfterEach - void teardownPetiteContainer() { - petiteContainer.shutdown(); - } - - private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); - private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); - - @BeforeEach - void setUpStreams() { - System.setOut(new PrintStream(outContent)); - System.setErr(new PrintStream(errContent)); - } - - @AfterEach - void cleanUpStreams() { - System.setOut(null); - System.setErr(null); - } - - @Test - @DisabledOnJava(value = 9, description = "Automagic configuration only works with MR-JAR jars as they don't work in exploded mode.") - void testWithMixingScopesSingletonAndProto() { - ExternalBean externalBean = new ExternalBean(); - // --> inject - - petiteContainer.wire(externalBean); - - // <-- injection done - - System.out.println("RUN!"); - externalBean.execute(); - assertEquals("RUN!" + System.lineSeparator() + - "execute now : jodd.petite.proxy.example1.impl.MainPetiteBean" + System.lineSeparator() + - "execute now : jodd.petite.proxy.example1.impl.SubPetiteBean" + System.lineSeparator() + - "Executing jodd.petite.proxy.example1.impl.SubPetiteBean" + ProxettaNames.proxyClassNameSuffix + System.lineSeparator() + - "executing jodd.petite.proxy.example1.impl.MainPetiteBean" + ProxettaNames.proxyClassNameSuffix + System.lineSeparator() + - "executing non jodd petite bean -> jodd.petite.proxy.example1.ExternalBean" + System.lineSeparator(), - outContent.toString()); - } -} diff --git a/jodd-petite/src/test/java/jodd/petite/proxy/PetiteHelper.java b/jodd-petite/src/test/java/jodd/petite/proxy/PetiteHelper.java deleted file mode 100644 index 1de723eab..000000000 --- a/jodd-petite/src/test/java/jodd/petite/proxy/PetiteHelper.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.proxy; - -import jodd.petite.PetiteConfig; -import jodd.proxetta.Proxetta; -import jodd.proxetta.ProxyAspect; -import jodd.proxetta.ProxyPointcut; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.pointcuts.MethodWithAnnotationPointcut; - -public class PetiteHelper { - - public static PetiteConfig createPetiteConfig() { - PetiteConfig petiteConfig = new PetiteConfig(); - petiteConfig.setDetectDuplicatedBeanNames(true); - petiteConfig.setWireScopedProxy(true); - petiteConfig.setDetectMixedScopes(true); - - return petiteConfig; - } - - public static ProxyProxetta createProxyProxetta() { - - ProxyPointcut pointcut_logged = new MethodWithAnnotationPointcut(Logged.class); - ProxyAspect aspect_logged = new ProxyAspect(LogProxyAdvice.class, pointcut_logged); - - ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspect(aspect_logged); - //proxetta.setDebugFolder(SystemUtil.userHome() + "\\inka\\proxetta"); - - return proxetta; - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/proxy/example1/ExternalBean.java b/jodd-petite/src/test/java/jodd/petite/proxy/example1/ExternalBean.java deleted file mode 100644 index 4600fb987..000000000 --- a/jodd-petite/src/test/java/jodd/petite/proxy/example1/ExternalBean.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.proxy.example1; - -import jodd.petite.meta.PetiteInject; - -public class ExternalBean { - - @PetiteInject - private IMainPetiteBean mainPetiteBean; - - public void execute() { - mainPetiteBean.execute(); - System.out.println("executing non jodd petite bean -> " + this.getClass().getCanonicalName()); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/proxy/example1/IMainPetiteBean.java b/jodd-petite/src/test/java/jodd/petite/proxy/example1/IMainPetiteBean.java deleted file mode 100644 index cbe9b9f83..000000000 --- a/jodd-petite/src/test/java/jodd/petite/proxy/example1/IMainPetiteBean.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.proxy.example1; - -public interface IMainPetiteBean { - void execute(); -} diff --git a/jodd-petite/src/test/java/jodd/petite/proxy/example1/ISubPetiteBean.java b/jodd-petite/src/test/java/jodd/petite/proxy/example1/ISubPetiteBean.java deleted file mode 100644 index 309b1c124..000000000 --- a/jodd-petite/src/test/java/jodd/petite/proxy/example1/ISubPetiteBean.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.proxy.example1; - -public interface ISubPetiteBean { - void execute_sub(); -} diff --git a/jodd-petite/src/test/java/jodd/petite/proxy/example1/impl/MainPetiteBean.java b/jodd-petite/src/test/java/jodd/petite/proxy/example1/impl/MainPetiteBean.java deleted file mode 100644 index b3e7fafa2..000000000 --- a/jodd-petite/src/test/java/jodd/petite/proxy/example1/impl/MainPetiteBean.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.proxy.example1.impl; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.meta.PetiteInject; -import jodd.petite.proxy.Logged; -import jodd.petite.proxy.example1.IMainPetiteBean; -import jodd.petite.proxy.example1.ISubPetiteBean; -import jodd.petite.scope.SingletonScope; - -@PetiteBean (scope = SingletonScope.class) -public class MainPetiteBean implements IMainPetiteBean { - - @PetiteInject - ISubPetiteBean subPetiteBean; - - @Override - @Logged - public void execute() { - subPetiteBean.execute_sub(); - System.out.println("executing " + this.getClass().getCanonicalName()); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/proxy/example1/impl/SubPetiteBean.java b/jodd-petite/src/test/java/jodd/petite/proxy/example1/impl/SubPetiteBean.java deleted file mode 100644 index 7681f59a8..000000000 --- a/jodd-petite/src/test/java/jodd/petite/proxy/example1/impl/SubPetiteBean.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.proxy.example1.impl; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.proxy.Logged; -import jodd.petite.proxy.example1.ISubPetiteBean; -import jodd.petite.scope.ProtoScope; - -@PetiteBean (scope = ProtoScope.class) -public class SubPetiteBean implements ISubPetiteBean { - - @Override - @Logged - public void execute_sub() { - System.out.println("Executing " + this.getClass().getCanonicalName()); - } - -} diff --git a/jodd-petite/src/test/java/jodd/petite/resolver/ReferenceResolverTest.java b/jodd-petite/src/test/java/jodd/petite/resolver/ReferenceResolverTest.java deleted file mode 100644 index 439243ed5..000000000 --- a/jodd-petite/src/test/java/jodd/petite/resolver/ReferenceResolverTest.java +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.petite.resolver; - -import jodd.introspector.ClassIntrospector; -import jodd.introspector.PropertyDescriptor; -import jodd.petite.PetiteConfig; -import jodd.petite.PetiteException; -import jodd.petite.def.BeanReferences; -import jodd.petite.fixtures.Revolver; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.Arrays; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -class ReferenceResolverTest { - - ReferencesResolver referencesResolver = new ReferencesResolver(new PetiteConfig()); - - @Test - void testNoAnnotation() { - Arrays.asList( - method(Revolver.class, "noAnnotation"), - ctor(Revolver.NoAnnotation.class) - ).forEach(methodOrCtor -> { - BeanReferences[] refs = referencesResolver.readAllReferencesFromAnnotation(method(Revolver.class, "noAnnotation")); - assertEquals(null, refs); - }); - } - - @Test - void testAnnotation_noArguments() { - Arrays.asList( - method(Revolver.class, "onlyAnnotation"), - ctor(Revolver.OnlyAnnotation.class) - ).forEach(methodOrCtor -> { - BeanReferences[] refs = referencesResolver.readAllReferencesFromAnnotation(methodOrCtor); - - assertEquals(0, refs.length); - }); - } - - @Test - void testAnnotation_withArguments() { - Arrays.asList( - method(Revolver.class, "someArguments"), - ctor(Revolver.SomeArguments.class) - ).forEach(methodOrCtor -> { - BeanReferences[] refs = referencesResolver.readAllReferencesFromAnnotation(methodOrCtor); - - assertEquals(2, refs.length); - - assertEquals(3, refs[0].size()); - assertEquals("in1", refs[0].name(0)); - assertEquals("string", refs[0].name(1)); - assertEquals("java.lang.String", refs[0].name(2)); - - assertEquals(3, refs[1].size()); - - assertEquals("in2", refs[1].name(0)); - assertEquals("integer", refs[1].name(1)); - assertEquals("java.lang.Integer", refs[1].name(2)); - }); - } - - @Test - void testAnnotation_withCsvValue() { - Arrays.asList( - method(Revolver.class, "someArguments_csv"), - ctor(Revolver.SomeArguments_csv.class) - ).forEach(methodOrCtor -> { - BeanReferences[] refs = referencesResolver.readAllReferencesFromAnnotation(methodOrCtor); - - assertEquals(2, refs.length); - - assertEquals(1, refs[0].size()); - assertEquals("innn1", refs[0].name(0)); - - assertEquals(1, refs[1].size()); - - assertEquals("innn2", refs[1].name(0)); - }); - } - - @Test - void testAnnotation_withWrongValue() { - Arrays.asList( - method(Revolver.class, "someArguments_wrongAnnotation"), - ctor(Revolver.SomeArguments_wrongAnnotation.class) - ).forEach(methodOrCtor -> { - assertThrows(PetiteException.class, () -> - referencesResolver.readAllReferencesFromAnnotation(methodOrCtor)); - }); - } - - @Test - void testAnnotation_noMethodArguments() { - Arrays.asList( - method(Revolver.class, "noMethodArgument"), - ctor(Revolver.NoMethodArgument.class) - ).forEach(methodOrCtor -> { - BeanReferences[] refs = referencesResolver.readAllReferencesFromAnnotation(methodOrCtor); - - assertEquals(2, refs.length); - - assertEquals(3, refs[0].size()); - assertEquals("in1", refs[0].name(0)); - assertEquals("string", refs[0].name(1)); - assertEquals("java.lang.String", refs[0].name(2)); - - assertEquals(3, refs[1].size()); - - assertEquals("in2", refs[1].name(0)); - assertEquals("integer", refs[1].name(1)); - assertEquals("java.lang.Integer", refs[1].name(2)); - }); - } - - @Test - void testAnnotation_noMethodArguments_partial() { - Arrays.asList( - method(Revolver.class, "noMethodArgument_partial"), - ctor(Revolver.NoMethodArgument_partial.class) - ).forEach(methodOrCtor -> { - BeanReferences[] refs = referencesResolver.readAllReferencesFromAnnotation(methodOrCtor); - - assertEquals(2, refs.length); - - assertEquals(1, refs[0].size()); - assertEquals("innn1", refs[0].name(0)); - - assertEquals(3, refs[1].size()); - - assertEquals("in2", refs[1].name(0)); - assertEquals("integer", refs[1].name(1)); - assertEquals("java.lang.Integer", refs[1].name(2)); - }); - } - - @Test - void testAnnotation_mix() { - Arrays.asList( - method(Revolver.class, "mix"), - ctor(Revolver.Mix.class) - ).forEach(methodOrCtor -> { - BeanReferences[] refs = referencesResolver.readAllReferencesFromAnnotation(methodOrCtor); - - assertEquals(2, refs.length); - - assertEquals(1, refs[0].size()); - assertEquals("innn1", refs[0].name(0)); - - assertEquals(1, refs[1].size()); - - assertEquals("bbbb", refs[1].name(0)); - }); - } - - @Test - void testFieldAnnotation_annotation() { - BeanReferences refs = referencesResolver.readReferenceFromAnnotation(field(Revolver.class, "onlyAnnotation")); - assertEquals(3, refs.size()); - assertEquals("onlyAnnotation", refs.name(0)); - assertEquals("string", refs.name(1)); - assertEquals("java.lang.String", refs.name(2)); - } - @Test - void testFieldAnnotation_withValue() { - BeanReferences refs = referencesResolver.readReferenceFromAnnotation(field(Revolver.class, "valued")); - assertEquals(1, refs.size()); - assertEquals("inn", refs.name(0)); - } - @Test - void testFieldAnnotation_nothing() { - BeanReferences refs = referencesResolver.readReferenceFromAnnotation(field(Revolver.class, "nothing")); - - assertEquals(null, refs); - } - - - @Test - void testResolveReferenceFromValues_explicit() { - Arrays.asList( - method(Revolver.class, "someArguments"), - ctor(Revolver.SomeArguments.class) - ).forEach(methodOrCtor -> { - BeanReferences[] refs = referencesResolver.resolveReferenceFromValues(methodOrCtor, "i1", "i2"); - - assertEquals(2, refs.length); - - assertEquals(1, refs[0].size()); - assertEquals("i1", refs[0].name(0)); - - assertEquals(1, refs[1].size()); - - assertEquals("i2", refs[1].name(0)); - }); - } - - @Test - void testResolveReferenceFromValues_defaults() { - Arrays.asList( - method(Revolver.class, "someArguments"), - ctor(Revolver.SomeArguments.class) - ).forEach(methodOrCtor -> { - BeanReferences[] refs = referencesResolver.resolveReferenceFromValues(methodOrCtor); - - assertEquals(2, refs.length); - - assertEquals(3, refs[0].size()); - assertEquals("in1", refs[0].name(0)); - assertEquals("string", refs[0].name(1)); - assertEquals("java.lang.String", refs[0].name(2)); - - assertEquals(3, refs[1].size()); - - assertEquals("in2", refs[1].name(0)); - assertEquals("integer", refs[1].name(1)); - assertEquals("java.lang.Integer", refs[1].name(2)); - - }); - } - - @Test - void testResolveReferenceFromValues_invalidNumberOfRefs() { - Arrays.asList( - method(Revolver.class, "someArguments"), - ctor(Revolver.SomeArguments.class) - ).forEach(methodOrCtor -> { - assertThrows(PetiteException.class, () -> { - referencesResolver.resolveReferenceFromValues(methodOrCtor, "i1"); - }); - }); - } - - // ---------------------------------------------------------------- util - - private PropertyDescriptor field(Class type, String name) { - PropertyDescriptor[] propertyDescriptors = ClassIntrospector.get().lookup(type).getAllPropertyDescriptors(); - - for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { - if (propertyDescriptor.getName().equals(name)) { - return propertyDescriptor; - } - } - throw new IllegalArgumentException(); - } - - private Method method(Class type, String name) { - Method[] methods = type.getMethods(); - - for (Method method : methods) { - if (method.getName().equals(name)) { - return method; - } - } - throw new IllegalArgumentException(); - } - - private Constructor ctor(Class type) { - return type.getConstructors()[0]; - } - -} \ No newline at end of file diff --git a/jodd-proxetta/build.gradle b/jodd-proxetta/build.gradle deleted file mode 100644 index c1ec67c0b..000000000 --- a/jodd-proxetta/build.gradle +++ /dev/null @@ -1,14 +0,0 @@ - -ext.moduleName = 'Jodd Proxetta' -ext.moduleDescription = 'Jodd Proxetta is the fastest proxy creator with unique approach for defying pointcuts and advices.' - -apply plugin: 'kotlin' - -dependencies { - api project(':jodd-core') - api 'org.slf4j:slf4j-api:1.7.30' - - testImplementation project(':jodd-petite') - testImplementation lib.junit5 - testImplementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" -} diff --git a/jodd-proxetta/src/main/java/jodd/aop/AopProxy.java b/jodd-proxetta/src/main/java/jodd/aop/AopProxy.java deleted file mode 100644 index 5d03e0712..000000000 --- a/jodd-proxetta/src/main/java/jodd/aop/AopProxy.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.aop; - -import jodd.util.ClassUtil; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Proxy; - -/** - * Factory for proxies, created using Java own library. - */ -public class AopProxy { - - /** - * Creates a proxy of given target and the aspect. - */ - @SuppressWarnings("unchecked") - public static T proxyOf(final T target, final Class aspectClass) { - final Aspect aspect; - - try { - aspect = ClassUtil.newInstance(aspectClass, target); - } - catch (Exception e) { - throw new IllegalArgumentException("Can't create new instance of aspect class", e); - } - - return (T) newProxyInstance(target.getClass().getClassLoader(), aspect, target.getClass().getInterfaces()); - } - - /** - * Creates a proxy from given {@link Aspect}. - */ - @SuppressWarnings("unchecked") - public static T proxyOf(final Aspect aspect) { - final Object target = aspect.getTarget(); - return (T) newProxyInstance(target.getClass().getClassLoader(), aspect, target.getClass().getInterfaces()); - } - - /** - * Simple wrapper for javas {@code newProxyInstance}. - */ - @SuppressWarnings("unchecked") - public static T newProxyInstance(final ClassLoader classloader, final InvocationHandler invocationHandler, final Class... interfaces) { - if (interfaces.length == 0) { - throw new IllegalArgumentException("No interfaces of target class found."); - } - return (T) Proxy.newProxyInstance(classloader, interfaces, invocationHandler); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/aop/Aspect.java b/jodd-proxetta/src/main/java/jodd/aop/Aspect.java deleted file mode 100644 index 0217e5424..000000000 --- a/jodd-proxetta/src/main/java/jodd/aop/Aspect.java +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.aop; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * Base aspect class that holds the target instance. - */ -public abstract class Aspect implements InvocationHandler { - - private Object target; - - public Aspect(final Object target) { - this.target = target; - } - - /** - * Returns target object. - */ - public final Object getTarget() { - return this.target; - } - - /** - * Runs before targets method. Returns {@code true} if target method - * should run. - */ - public abstract boolean before(Object target, Method method, Object[] args); - - /** - * Runs after targets method. Returns {@code true} if aspect method should - * return value, otherwise {@code null}. - */ - public abstract boolean after(Object target, Method method, Object[] args); - - /** - * Invoked after exception. - */ - public abstract boolean afterException(Object target, Method method, Object[] args, Throwable throwable); - - @Override - public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { - Object result = null; - - if (before(target, method, args)) { - try { - result = method.invoke(target, args); - } - catch (InvocationTargetException e) { - afterException(args, method, args, e.getTargetException()); - } - catch (Exception ex) { - throw ex; - } - } - if (after(target, method, args)) { - return result; - } - return null; - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/aop/package-info.java b/jodd-proxetta/src/main/java/jodd/aop/package-info.java deleted file mode 100644 index 71c95f3a1..000000000 --- a/jodd-proxetta/src/main/java/jodd/aop/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Simple java native aspects. - */ -package jodd.aop; \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/asm/AnnotationVisitorAdapter.java b/jodd-proxetta/src/main/java/jodd/asm/AnnotationVisitorAdapter.java deleted file mode 100644 index ef4e85ff4..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm/AnnotationVisitorAdapter.java +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.asm; - -import jodd.asm7.AnnotationVisitor; - -/** - * Annotation visitor adapter. - */ -public class AnnotationVisitorAdapter extends EmptyAnnotationVisitor { - - protected final AnnotationVisitor dest; - - public AnnotationVisitorAdapter(final AnnotationVisitor dest) { - this.dest = dest; - } - - @Override - public void visit(final String name, final Object value) { - dest.visit(name, value); - } - - @Override - public void visitEnum(final String name, final String desc, final String value) { - dest.visitEnum(name, desc, value); - } - - @Override - public AnnotationVisitor visitAnnotation(final String name, final String desc) { - return new AnnotationVisitorAdapter(dest.visitAnnotation(name, desc)); - } - - @Override - public AnnotationVisitor visitArray(final String name) { - return new AnnotationVisitorAdapter(dest.visitArray(name)); - } - - @Override - public void visitEnd() { - dest.visitEnd(); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/asm/AsmUtil.java b/jodd-proxetta/src/main/java/jodd/asm/AsmUtil.java deleted file mode 100644 index 2e68220a1..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm/AsmUtil.java +++ /dev/null @@ -1,436 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.asm; - -import jodd.asm7.MethodVisitor; -import jodd.mutable.MutableInteger; - -import static jodd.asm7.Opcodes.CHECKCAST; -import static jodd.asm7.Opcodes.INVOKESTATIC; -import static jodd.asm7.Opcodes.INVOKEVIRTUAL; - -/** - * Generic ASM utils. - */ -public class AsmUtil { - - // types - - public static final int TYPE_BYTE = 'B'; - public static final int TYPE_CHAR = 'C'; - public static final int TYPE_DOUBLE = 'D'; - public static final int TYPE_FLOAT = 'F'; - public static final int TYPE_INT = 'I'; - public static final int TYPE_LONG = 'J'; - public static final int TYPE_REFERENCE = 'L'; - public static final int TYPE_SHORT = 'S'; - public static final int TYPE_BOOLEAN = 'Z'; - public static final int TYPE_VOID = 'V'; - public static final int TYPE_ARRAY = '['; -// public static final int TYPE_STRING = 's'; -// public static final int TYPE_ENUM = 'e'; -// public static final int TYPE_CLASS = 'c'; - public static final int TYPE_ANNOTATION = '@'; - - // access flags - - public static final int ACC_PUBLIC = 0x0001; // class, field, method - public static final int ACC_PRIVATE = 0x0002; // class, field, method - public static final int ACC_PROTECTED = 0x0004; // class, field, method - public static final int ACC_STATIC = 0x0008; // field, method - public static final int ACC_FINAL = 0x0010; // class, field, method - public static final int ACC_SUPER = 0x0020; // class - public static final int ACC_SYNCHRONIZED = 0x0020; // method - public static final int ACC_VOLATILE = 0x0040; // field - public static final int ACC_BRIDGE = 0x0040; // method - public static final int ACC_VARARGS = 0x0080; // method - public static final int ACC_TRANSIENT = 0x0080; // field - public static final int ACC_NATIVE = 0x0100; // method - public static final int ACC_INTERFACE = 0x0200; // class - public static final int ACC_ABSTRACT = 0x0400; // class, method - public static final int ACC_STRICT = 0x0800; // method - public static final int ACC_SYNTHETIC = 0x1000; // class, field, method - public static final int ACC_ANNOTATION = 0x2000; // class - public static final int ACC_ENUM = 0x4000; // class(?) field inner - - - // signatures - - public static final String SIGNATURE_JAVA_LANG_OBJECT = "java/lang/Object"; - public static final String SIGNATURE_JAVA_LANG_CLASS = "java/lang/Class"; - public static final String SIGNATURE_JAVA_LANG_BYTE = "java/lang/Byte"; - public static final String SIGNATURE_JAVA_LANG_CHARACTER = "java/lang/Character"; - public static final String SIGNATURE_JAVA_LANG_SHORT = "java/lang/Short"; - public static final String SIGNATURE_JAVA_LANG_INTEGER = "java/lang/Integer"; - public static final String SIGNATURE_JAVA_LANG_BOOLEAN = "java/lang/Boolean"; - public static final String SIGNATURE_JAVA_LANG_LONG = "java/lang/Long"; - public static final String SIGNATURE_JAVA_LANG_FLOAT = "java/lang/Float"; - public static final String SIGNATURE_JAVA_LANG_DOUBLE = "java/lang/Double"; - public static final String SIGNATURE_JAVA_LANG_VOID = "java/lang/Void"; - - public static final String L_SIGNATURE_JAVA_LANG_OBJECT = "Ljava/lang/Object;"; - public static final String L_SIGNATURE_JAVA_LANG_STRING = "Ljava/lang/String;"; - public static final String L_SIGNATURE_JAVA_LANG_CLASS = "Ljava/lang/Class;"; - - private static final String INVALID_BASE_TYPE = "Invalid base type: "; - private static final String INVALID_TYPE_DESCRIPTION = "Invalid type description: "; - - // ---------------------------------------------------------------- class relates - - /** - * Converts bytecode-like description to java class name that can be loaded - * with a classloader. Uses less-known feature of class loaders for loading - * array classes. - * - * @see #typedescToSignature(String, jodd.mutable.MutableInteger) - */ - public static String typedesc2ClassName(final String desc) { - String className = desc; - switch (desc.charAt(0)) { - case 'B': - case 'C': - case 'D': - case 'F': - case 'I': - case 'J': - case 'S': - case 'Z': - case 'V': - if (desc.length() != 1) { - throw new IllegalArgumentException(INVALID_BASE_TYPE + desc); - } - break; - case 'L': - className = className.substring(1, className.length() - 1); break; - case '[': - // uses less-known feature of class loaders for loading array types - // using bytecode-like signatures. - className = className.replace('/', '.'); - break; - default: throw new IllegalArgumentException(INVALID_TYPE_DESCRIPTION + desc); - } - - return className; - } - - /** - * Converts type reference to java-name. - */ - public static String typeref2Name(final String desc) { - if (desc.charAt(0) != TYPE_REFERENCE) { - throw new IllegalArgumentException(INVALID_TYPE_DESCRIPTION + desc); - } - String name = desc.substring(1, desc.length() - 1); - return name.replace('/', '.'); - } - - // ---------------------------------------------------------------- description - - /** - * Returns type-name to type char. - * Arrays are not supported. - */ - public static char typeNameToOpcode(final String typeName) { - switch (typeName) { - case "byte" : return 'B'; - case "char": return 'C'; - case "double": return 'D'; - case "float": return 'F'; - case "int": return 'I'; - case "long": return 'J'; - case "short": return 'S'; - case "boolean": return 'Z'; - case "void": return 'V'; - default: return 'L'; - } - } - - /** - * Returns java-like signature of a bytecode-like description. - * @see #typedescToSignature(String, jodd.mutable.MutableInteger) - */ - public static String typedescToSignature(final String desc) { - return typedescToSignature(desc, new MutableInteger()); - } - - /** - * Returns java-like signature of a bytecode-like description. - * Only first description is parsed. - * - * The field signature represents the value of an argument to a function or - * the value of a variable. It is a series of bytes generated by the - * following grammar: - * - *
{@code
-	 *  ::= 
-	 *       ::= ||
-	 *        ::= B|C|D|F|I|J|S|Z
-	 *      ::= L;
-	 *       ::= [
-	 *
-	 * The meaning of the base types is as follows:
-	 * B byte signed byte
-	 * C char character
-	 * D double double precision IEEE float
-	 * F float single precision IEEE float
-	 * I int integer
-	 * J long long integer
-	 * L; ... an object of the given class
-	 * S short signed short
-	 * Z boolean true or false
-	 * [ ... array
-	 * }
- * - * This method converts this string into a Java type declaration such as - * String[]. - */ - public static String typedescToSignature(final String desc, final MutableInteger from) { - int fromIndex = from.get(); - from.value++; // default usage for most cases - - switch (desc.charAt(fromIndex)) { - case 'B': return "byte"; - case 'C': return "char"; - case 'D': return "double"; - case 'F': return "float"; - case 'I': return "int"; - case 'J': return "long"; - case 'S': return "short"; - case 'Z': return "boolean"; - case 'V': return "void"; - - case 'L': - int index = desc.indexOf(';', fromIndex); - if (index < 0) { - throw new IllegalArgumentException(INVALID_TYPE_DESCRIPTION + desc); - } - from.set(index + 1); - String str = desc.substring(fromIndex + 1, index); - return str.replace('/', '.'); - - case 'T': - return desc.substring(from.value); - - case '[': - StringBuilder brackets = new StringBuilder(); - int n = fromIndex; - while (desc.charAt(n) == '[') { // count opening brackets - brackets.append("[]"); - n++; - } - from.value = n; - String type = typedescToSignature(desc, from); // the rest of the string denotes a `' - return type + brackets; - - default: - if (from.value == 0) { - throw new IllegalArgumentException(INVALID_TYPE_DESCRIPTION + desc); - } - // generics! - return desc.substring(from.value); - } - } - - // ---------------------------------------------------------------- type - - /** - * Converts java-class name ("foo.Bar") to bytecode-signature ("foo/bar"). - */ - public static String typeToSignature(final String className) { - return className.replace('.', '/'); - } - - /** - * Converts java-class name ("foo.Bar") to bytecode-name ("foo/bar"). - */ - public static String typeToSignature(final Class type) { - return typeToSignature(type.getName()); - } - - /** - * Converts type to byteccode type ref. - */ - public static String typeToTyperef(final Class type) { - if (!type.isArray()) { - if (!type.isPrimitive()) { - return 'L' + typeToSignature(type) + ';'; - } - if (type == int.class) { - return "I"; - } - if (type == long.class) { - return "J"; - } - if (type == boolean.class) { - return "Z"; - } - if (type == double.class) { - return "D"; - } - if (type == float.class) { - return "F"; - } - if (type == short.class) { - return "S"; - } - if (type == void.class) { - return "V"; - } - if (type == byte.class) { - return "B"; - } - if (type == char.class) { - return "C"; - } - } - - return type.getName(); - } - - // ---------------------------------------------------------------- boxing - - /** - * Converts Integer object to an int. - */ - public static void intValue(final MethodVisitor mv) { - mv.visitTypeInsn(CHECKCAST, SIGNATURE_JAVA_LANG_INTEGER); - mv.visitMethodInsn(INVOKEVIRTUAL, SIGNATURE_JAVA_LANG_INTEGER, "intValue", "()I", false); - } - - /** - * Converts Long object to a long. - */ - public static void longValue(final MethodVisitor mv) { - mv.visitTypeInsn(CHECKCAST, SIGNATURE_JAVA_LANG_LONG); - mv.visitMethodInsn(INVOKEVIRTUAL, SIGNATURE_JAVA_LANG_LONG, "longValue", "()J", false); - } - - /** - * Converts Float object to a float. - */ - public static void floatValue(final MethodVisitor mv) { - mv.visitTypeInsn(CHECKCAST, SIGNATURE_JAVA_LANG_FLOAT); - mv.visitMethodInsn(INVOKEVIRTUAL, SIGNATURE_JAVA_LANG_FLOAT, "floatValue", "()F", false); - } - - /** - * Converts Double object to a double. - */ - public static void doubleValue(final MethodVisitor mv) { - mv.visitTypeInsn(CHECKCAST, SIGNATURE_JAVA_LANG_DOUBLE); - mv.visitMethodInsn(INVOKEVIRTUAL, SIGNATURE_JAVA_LANG_DOUBLE, "doubleValue", "()D", false); - } - - /** - * Converts Byte object to a byte. - */ - public static void byteValue(final MethodVisitor mv) { - mv.visitTypeInsn(CHECKCAST, SIGNATURE_JAVA_LANG_BYTE); - mv.visitMethodInsn(INVOKEVIRTUAL, SIGNATURE_JAVA_LANG_BYTE, "byteValue", "()B", false); - } - - /** - * Converts Short object to a short. - */ - public static void shortValue(final MethodVisitor mv) { - mv.visitTypeInsn(CHECKCAST, SIGNATURE_JAVA_LANG_SHORT); - mv.visitMethodInsn(INVOKEVIRTUAL, SIGNATURE_JAVA_LANG_SHORT, "shortValue", "()S", false); - } - - /** - * Converts Boolean object to a boolean. - */ - public static void booleanValue(final MethodVisitor mv) { - mv.visitTypeInsn(CHECKCAST, SIGNATURE_JAVA_LANG_BOOLEAN); - mv.visitMethodInsn(INVOKEVIRTUAL, SIGNATURE_JAVA_LANG_BOOLEAN, "booleanValue", "()Z", false); - } - - /** - * Converts Character object to a char. - */ - public static void charValue(final MethodVisitor mv) { - mv.visitTypeInsn(CHECKCAST, SIGNATURE_JAVA_LANG_CHARACTER); - mv.visitMethodInsn(INVOKEVIRTUAL, SIGNATURE_JAVA_LANG_CHARACTER, "charValue", "()C", false); - } - - public static void valueOfInteger(final MethodVisitor mv) { - mv.visitMethodInsn(INVOKESTATIC, SIGNATURE_JAVA_LANG_INTEGER, "valueOf", "(I)Ljava/lang/Integer;", false); - } - - public static void valueOfLong(final MethodVisitor mv) { - mv.visitMethodInsn(INVOKESTATIC, SIGNATURE_JAVA_LANG_LONG, "valueOf", "(J)Ljava/lang/Long;", false); - } - - public static void valueOfFloat(final MethodVisitor mv) { - mv.visitMethodInsn(INVOKESTATIC, SIGNATURE_JAVA_LANG_FLOAT, "valueOf", "(F)Ljava/lang/Float;", false); - } - - public static void valueOfDouble(final MethodVisitor mv) { - mv.visitMethodInsn(INVOKESTATIC, SIGNATURE_JAVA_LANG_DOUBLE, "valueOf", "(D)Ljava/lang/Double;", false); - } - - public static void valueOfByte(final MethodVisitor mv) { - mv.visitMethodInsn(INVOKESTATIC, SIGNATURE_JAVA_LANG_BYTE, "valueOf", "(B)Ljava/lang/Byte;", false); - } - - public static void valueOfShort(final MethodVisitor mv) { - mv.visitMethodInsn(INVOKESTATIC, SIGNATURE_JAVA_LANG_SHORT, "valueOf", "(S)Ljava/lang/Short;", false); - } - - public static void valueOfBoolean(final MethodVisitor mv) { - mv.visitMethodInsn(INVOKESTATIC, SIGNATURE_JAVA_LANG_BOOLEAN, "valueOf", "(Z)Ljava/lang/Boolean;", false); - } - - public static void valueOfCharacter(final MethodVisitor mv) { - mv.visitMethodInsn(INVOKESTATIC, SIGNATURE_JAVA_LANG_CHARACTER, "valueOf", "(C)Ljava/lang/Character;", false); - } - - public static String removeGenericsFromSignature(final String signature) { - final StringBuilder result = new StringBuilder(signature.length()); - - int genericCount = 0; - int ndx = 0; - while (ndx != signature.length()) { - final char c = signature.charAt(ndx); - if (c == '<') { - genericCount++; - ndx++; - continue; - } - if (c == '>') { - genericCount--; - ndx++; - continue; - } - if (genericCount == 0) { - result.append(c); - } - ndx++; - } - - return result.toString(); - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/asm/ClassAdapter.java b/jodd-proxetta/src/main/java/jodd/asm/ClassAdapter.java deleted file mode 100644 index c3975d832..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm/ClassAdapter.java +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.asm; - -import jodd.asm7.ClassVisitor; -import jodd.asm7.Opcodes; - -/** - * An empty ClassVisitor that delegates to another ClassVisitor. - * This class can be used as a super class to quickly implement useful class - * adapter classes, just by overriding the necessary methods. - */ -public abstract class ClassAdapter extends ClassVisitor { - - protected ClassAdapter(final ClassVisitor cv) { - super(Opcodes.ASM7, cv); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm/EmptyAnnotationVisitor.java b/jodd-proxetta/src/main/java/jodd/asm/EmptyAnnotationVisitor.java deleted file mode 100644 index 3ac0815c1..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm/EmptyAnnotationVisitor.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.asm; - -import jodd.asm7.AnnotationVisitor; -import jodd.asm7.Opcodes; - -/** - * Empty annotation visitor. - */ -public abstract class EmptyAnnotationVisitor extends AnnotationVisitor { - - protected EmptyAnnotationVisitor() { - super(Opcodes.ASM6); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/asm/EmptyClassVisitor.java b/jodd-proxetta/src/main/java/jodd/asm/EmptyClassVisitor.java deleted file mode 100644 index c7546fdbd..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm/EmptyClassVisitor.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.asm; - -import jodd.asm7.ClassVisitor; -import jodd.asm7.Opcodes; - -/** - * Empty class visitor. - */ -public abstract class EmptyClassVisitor extends ClassVisitor { - - protected EmptyClassVisitor() { - super(Opcodes.ASM7); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/asm/EmptyMethodVisitor.java b/jodd-proxetta/src/main/java/jodd/asm/EmptyMethodVisitor.java deleted file mode 100644 index 0bd33c655..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm/EmptyMethodVisitor.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.asm; - -import jodd.asm7.MethodVisitor; -import jodd.asm7.Opcodes; - -/** - * Empty method visitor. - */ -public abstract class EmptyMethodVisitor extends MethodVisitor { - - protected EmptyMethodVisitor() { - super(Opcodes.ASM7); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/asm/MethodAdapter.java b/jodd-proxetta/src/main/java/jodd/asm/MethodAdapter.java deleted file mode 100644 index 85d14cd92..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm/MethodAdapter.java +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.asm; - -import jodd.asm7.MethodVisitor; -import jodd.asm7.Opcodes; - -/** - * An empty MethodVisitor that delegates to another MethodVisitor. This class - * can be used as a super class to quickly implement useful method adapter - * classes, just by overriding the necessary methods. - */ -public abstract class MethodAdapter extends MethodVisitor { - - protected MethodAdapter(final MethodVisitor mv) { - super(Opcodes.ASM7, mv); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm/TraceSignatureVisitor.java b/jodd-proxetta/src/main/java/jodd/asm/TraceSignatureVisitor.java deleted file mode 100644 index 00b97b2be..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm/TraceSignatureVisitor.java +++ /dev/null @@ -1,365 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm; - -import jodd.asm7.Opcodes; -import jodd.asm7.signature.SignatureVisitor; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -/** - * A {@link SignatureVisitor} that builds the Java generic type declaration corresponding to the - * signature it visits. - *

- * Changes made by Igor (http://jodd.org): - *

    - *
  • removed final for the class
  • - *
  • some private scopes made protected
  • - *
  • public constructor change to accept boolean
  • - *
  • use AsmUtil constants
  • - *
  • use StringBuilder instead of StringBuffer
  • - *
  • getExceptions() and getReturnType() removed
  • - *
- * - * @author Eugene Kuleshov - * @author Eric Bruneton - */ -public class TraceSignatureVisitor extends SignatureVisitor { // jodd: no final - - private static final String COMMA_SEPARATOR = ", "; - private static final String EXTENDS_SEPARATOR = " extends "; - private static final String IMPLEMENTS_SEPARATOR = " implements "; - - private static final Map BASE_TYPES; - - static { - HashMap baseTypes = new HashMap<>(); - baseTypes.put('Z', "boolean"); - baseTypes.put('B', "byte"); - baseTypes.put('C', "char"); - baseTypes.put('S', "short"); - baseTypes.put('I', "int"); - baseTypes.put('J', "long"); - baseTypes.put('F', "float"); - baseTypes.put('D', "double"); - baseTypes.put('V', "void"); - BASE_TYPES = Collections.unmodifiableMap(baseTypes); - } - - /** Whether the visited signature is a class signature of a Java interface. */ - protected final boolean isInterface; // jodd: protected - - /** The Java generic type declaration corresponding to the visited signature. */ - protected final StringBuilder declaration; // jodd: protected - - /** The Java generic method return type declaration corresponding to the visited signature. */ - private StringBuilder returnType; - - /** The Java generic exception types declaration corresponding to the visited signature. */ - private StringBuilder exceptions; - - /** Whether {@link #visitFormalTypeParameter} has been called. */ - private boolean formalTypeParameterVisited; - - /** Whether {@link #visitInterfaceBound} has been called. */ - private boolean interfaceBoundVisited; - - /** Whether {@link #visitParameterType} has been called. */ - private boolean parameterTypeVisited; - - /** Whether {@link #visitInterface} has been called. */ - private boolean interfaceVisited; - - /** - * The stack used to keep track of class types that have arguments. Each element of this stack is - * a boolean encoded in one bit. The top of the stack is the least significant bit. Pushing false - * = *2, pushing true = *2+1, popping = /2. - */ - protected int argumentStack; // jodd: protected - - /** - * The stack used to keep track of array class types. Each element of this stack is a boolean - * encoded in one bit. The top of the stack is the lowest order bit. Pushing false = *2, pushing - * true = *2+1, popping = /2. - */ - private int arrayStack; - - /** The separator to append before the next visited class or inner class type. */ - private String separator = ""; - -// jodd: removed -// /** -// * Constructs a new {@link TraceSignatureVisitor}. -// * -// * @param accessFlags for class type signatures, the access flags of the class. -// */ -// public TraceSignatureVisitor(final int accessFlags) { -// super(Opcodes.ASM7); -// this.isInterface = (accessFlags & Opcodes.ACC_INTERFACE) != 0; -// this.declaration = new StringBuilder(); -// } - - protected TraceSignatureVisitor(final StringBuilder stringBuilder) { // jodd: protected - super(Opcodes.ASM7); - this.isInterface = false; - this.declaration = stringBuilder; - } - - // jodd: added the variant of the ctor - - public TraceSignatureVisitor(final StringBuilder stringBuilder, final boolean isInterface) { - super(Opcodes.ASM7); - this.isInterface = isInterface; - this.declaration = stringBuilder; - } - - @Override - public void visitFormalTypeParameter(final String name) { - declaration.append(formalTypeParameterVisited ? COMMA_SEPARATOR : "<").append(name); - formalTypeParameterVisited = true; - interfaceBoundVisited = false; - } - - @Override - public SignatureVisitor visitClassBound() { - separator = EXTENDS_SEPARATOR; - startType(); - return this; - } - - @Override - public SignatureVisitor visitInterfaceBound() { - separator = interfaceBoundVisited ? COMMA_SEPARATOR : EXTENDS_SEPARATOR; - interfaceBoundVisited = true; - startType(); - return this; - } - - @Override - public SignatureVisitor visitSuperclass() { - endFormals(); - separator = EXTENDS_SEPARATOR; - startType(); - return this; - } - - @Override - public SignatureVisitor visitInterface() { - if (interfaceVisited) { - separator = COMMA_SEPARATOR; - } else { - separator = isInterface ? EXTENDS_SEPARATOR : IMPLEMENTS_SEPARATOR; - interfaceVisited = true; - } - startType(); - return this; - } - - @Override - public SignatureVisitor visitParameterType() { - endFormals(); - if (parameterTypeVisited) { - declaration.append(COMMA_SEPARATOR); - } else { - declaration.append('('); - parameterTypeVisited = true; - } - startType(); - return this; - } - - @Override - public SignatureVisitor visitReturnType() { - endFormals(); - if (parameterTypeVisited) { - parameterTypeVisited = false; - } else { - declaration.append('('); - } - declaration.append(')'); - returnType = new StringBuilder(); - return new TraceSignatureVisitor(returnType); - } - - @Override - public SignatureVisitor visitExceptionType() { - if (exceptions == null) { - exceptions = new StringBuilder(); - } else { - exceptions.append(COMMA_SEPARATOR); - } - return new TraceSignatureVisitor(exceptions); - } - - @Override - public void visitBaseType(final char descriptor) { - String baseType = BASE_TYPES.get(descriptor); - if (baseType == null) { - throw new IllegalArgumentException(); - } - declaration.append(baseType); - endType(); - } - - @Override - public void visitTypeVariable(final String name) { - declaration.append(separator).append(name); - separator = ""; - endType(); - } - - @Override - public SignatureVisitor visitArrayType() { - startType(); - arrayStack |= 1; - return this; - } - - @Override - public void visitClassType(final String name) { - if ("java/lang/Object".equals(name)) { - // 'Map' or 'abstract public V get(Object key);' should have - // Object 'but java.lang.String extends java.lang.Object' is unnecessary. - boolean needObjectClass = argumentStack % 2 != 0 || parameterTypeVisited; - if (needObjectClass) { - declaration.append(separator).append(name.replace('/', '.')); - } - } else { - declaration.append(separator).append(name.replace('/', '.')); - } - separator = ""; - argumentStack *= 2; - } - - @Override - public void visitInnerClassType(final String name) { - if (argumentStack % 2 != 0) { - declaration.append('>'); - } - argumentStack /= 2; - declaration.append('.'); - declaration.append(separator).append(name.replace('/', '.')); - separator = ""; - argumentStack *= 2; - } - - @Override - public void visitTypeArgument() { - if (argumentStack % 2 == 0) { - ++argumentStack; - declaration.append('<'); - } else { - declaration.append(COMMA_SEPARATOR); - } - declaration.append('?'); - } - - @Override - public SignatureVisitor visitTypeArgument(final char tag) { - if (argumentStack % 2 == 0) { - ++argumentStack; - declaration.append('<'); - } else { - declaration.append(COMMA_SEPARATOR); - } - - if (tag == EXTENDS) { - declaration.append("? extends "); - } else if (tag == SUPER) { - declaration.append("? super "); - } - - startType(); - return this; - } - - @Override - public void visitEnd() { - if (argumentStack % 2 != 0) { - declaration.append('>'); - } - argumentStack /= 2; - endType(); - } - - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the Java generic type declaration corresponding to the visited signature. - * - * @return the Java generic type declaration corresponding to the visited signature. - */ - public String getDeclaration() { - return declaration.toString(); - } - - // jodd: comment out the method, we have more suitable version - -// /** -// * @return the Java generic method return type declaration corresponding to the visited signature. -// */ -// public String getReturnType() { -// return returnType == null ? null : returnType.toString(); -// } - - - // jodd: comment out the method, we have more suitable version - -// /** -// * @return the Java generic exception types declaration corresponding to the visited signature. -// */ -// public String getExceptions() { -// return exceptions == null ? null : exceptions.toString(); -// } - - // ----------------------------------------------------------------------------------------------- - - private void endFormals() { - if (formalTypeParameterVisited) { - declaration.append('>'); - formalTypeParameterVisited = false; - } - } - - protected void startType() { // jodd: made protected - arrayStack *= 2; - } - - protected void endType() { // jodd: made protected - if (arrayStack % 2 == 0) { - arrayStack /= 2; - } else { - while (arrayStack % 2 != 0) { - arrayStack /= 2; - declaration.append("[]"); - } - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm/package-info.java b/jodd-proxetta/src/main/java/jodd/asm/package-info.java deleted file mode 100644 index 89b4f96b7..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Some common ASM classes. - */ -package jodd.asm; \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/asm7/AnnotationVisitor.java b/jodd-proxetta/src/main/java/jodd/asm7/AnnotationVisitor.java deleted file mode 100644 index c8490a9a1..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/AnnotationVisitor.java +++ /dev/null @@ -1,145 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * A visitor to visit a Java annotation. The methods of this class must be called in the following - * order: ( {@code visit} | {@code visitEnum} | {@code visitAnnotation} | {@code visitArray} )* - * {@code visitEnd}. - * - * @author Eric Bruneton - * @author Eugene Kuleshov - */ -public abstract class AnnotationVisitor { - - /** - * The ASM API version implemented by this visitor. The value of this field must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - */ - protected final int api; - - /** The annotation visitor to which this visitor must delegate method calls. May be null. */ - protected AnnotationVisitor av; - - /** - * Constructs a new {@link AnnotationVisitor}. - * - * @param api the ASM API version implemented by this visitor. Must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - */ - public AnnotationVisitor(final int api) { - this(api, null); - } - - /** - * Constructs a new {@link AnnotationVisitor}. - * - * @param api the ASM API version implemented by this visitor. Must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - * @param annotationVisitor the annotation visitor to which this visitor must delegate method - * calls. May be null. - */ - public AnnotationVisitor(final int api, final AnnotationVisitor annotationVisitor) { - if (api != Opcodes.ASM7 && api != Opcodes.ASM6 && api != Opcodes.ASM5 && api != Opcodes.ASM4) { - throw new IllegalArgumentException("Unsupported api " + api); - } - this.api = api; - this.av = annotationVisitor; - } - - /** - * Visits a primitive value of the annotation. - * - * @param name the value name. - * @param value the actual value, whose type must be {@link Byte}, {@link Boolean}, {@link - * Character}, {@link Short}, {@link Integer} , {@link Long}, {@link Float}, {@link Double}, - * {@link String} or {@link Type} of {@link Type#OBJECT} or {@link Type#ARRAY} sort. This - * value can also be an array of byte, boolean, short, char, int, long, float or double values - * (this is equivalent to using {@link #visitArray} and visiting each array element in turn, - * but is more convenient). - */ - public void visit(final String name, final Object value) { - if (av != null) { - av.visit(name, value); - } - } - - /** - * Visits an enumeration value of the annotation. - * - * @param name the value name. - * @param descriptor the class descriptor of the enumeration class. - * @param value the actual enumeration value. - */ - public void visitEnum(final String name, final String descriptor, final String value) { - if (av != null) { - av.visitEnum(name, descriptor, value); - } - } - - /** - * Visits a nested annotation value of the annotation. - * - * @param name the value name. - * @param descriptor the class descriptor of the nested annotation class. - * @return a visitor to visit the actual nested annotation value, or {@literal null} if this - * visitor is not interested in visiting this nested annotation. The nested annotation - * value must be fully visited before calling other methods on this annotation visitor. - */ - public AnnotationVisitor visitAnnotation(final String name, final String descriptor) { - if (av != null) { - return av.visitAnnotation(name, descriptor); - } - return null; - } - - /** - * Visits an array value of the annotation. Note that arrays of primitive types (such as byte, - * boolean, short, char, int, long, float or double) can be passed as value to {@link #visit - * visit}. This is what {@link ClassReader} does. - * - * @param name the value name. - * @return a visitor to visit the actual array value elements, or {@literal null} if this visitor - * is not interested in visiting these values. The 'name' parameters passed to the methods of - * this visitor are ignored. All the array values must be visited before calling other - * methods on this annotation visitor. - */ - public AnnotationVisitor visitArray(final String name) { - if (av != null) { - return av.visitArray(name); - } - return null; - } - - /** Visits the end of the annotation. */ - public void visitEnd() { - if (av != null) { - av.visitEnd(); - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/AnnotationWriter.java b/jodd-proxetta/src/main/java/jodd/asm7/AnnotationWriter.java deleted file mode 100644 index 1495ae105..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/AnnotationWriter.java +++ /dev/null @@ -1,551 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * An {@link AnnotationVisitor} that generates a corresponding 'annotation' or 'type_annotation' - * structure, as defined in the Java Virtual Machine Specification (JVMS). AnnotationWriter - * instances can be chained in a doubly linked list, from which Runtime[In]Visible[Type]Annotations - * attributes can be generated with the {@link #putAnnotations} method. Similarly, arrays of such - * lists can be used to generate Runtime[In]VisibleParameterAnnotations attributes. - * - * @see JVMS - * 4.7.16 - * @see JVMS - * 4.7.20 - * @author Eric Bruneton - * @author Eugene Kuleshov - */ -final class AnnotationWriter extends AnnotationVisitor { - - /** Where the constants used in this AnnotationWriter must be stored. */ - private final SymbolTable symbolTable; - - /** - * Whether values are named or not. AnnotationWriter instances used for annotation default and - * annotation arrays use unnamed values (i.e. they generate an 'element_value' structure for each - * value, instead of an element_name_index followed by an element_value). - */ - private final boolean useNamedValues; - - /** - * The 'annotation' or 'type_annotation' JVMS structure corresponding to the annotation values - * visited so far. All the fields of these structures, except the last one - the - * element_value_pairs array, must be set before this ByteVector is passed to the constructor - * (num_element_value_pairs can be set to 0, it is reset to the correct value in {@link - * #visitEnd()}). The element_value_pairs array is filled incrementally in the various visit() - * methods. - * - *

Note: as an exception to the above rules, for AnnotationDefault attributes (which contain a - * single element_value by definition), this ByteVector is initially empty when passed to the - * constructor, and {@link #numElementValuePairsOffset} is set to -1. - */ - private final ByteVector annotation; - - /** - * The offset in {@link #annotation} where {@link #numElementValuePairs} must be stored (or -1 for - * the case of AnnotationDefault attributes). - */ - private final int numElementValuePairsOffset; - - /** The number of element value pairs visited so far. */ - private int numElementValuePairs; - - /** - * The previous AnnotationWriter. This field is used to store the list of annotations of a - * Runtime[In]Visible[Type]Annotations attribute. It is unused for nested or array annotations - * (annotation values of annotation type), or for AnnotationDefault attributes. - */ - private final AnnotationWriter previousAnnotation; - - /** - * The next AnnotationWriter. This field is used to store the list of annotations of a - * Runtime[In]Visible[Type]Annotations attribute. It is unused for nested or array annotations - * (annotation values of annotation type), or for AnnotationDefault attributes. - */ - private AnnotationWriter nextAnnotation; - - // ----------------------------------------------------------------------------------------------- - // Constructors and factories - // ----------------------------------------------------------------------------------------------- - - /** - * Constructs a new {@link AnnotationWriter}. - * - * @param symbolTable where the constants used in this AnnotationWriter must be stored. - * @param useNamedValues whether values are named or not. AnnotationDefault and annotation arrays - * use unnamed values. - * @param annotation where the 'annotation' or 'type_annotation' JVMS structure corresponding to - * the visited content must be stored. This ByteVector must already contain all the fields of - * the structure except the last one (the element_value_pairs array). - * @param previousAnnotation the previously visited annotation of the - * Runtime[In]Visible[Type]Annotations attribute to which this annotation belongs, or null in - * other cases (e.g. nested or array annotations). - */ - AnnotationWriter( - final SymbolTable symbolTable, - final boolean useNamedValues, - final ByteVector annotation, - final AnnotationWriter previousAnnotation) { - super(Opcodes.ASM7); - this.symbolTable = symbolTable; - this.useNamedValues = useNamedValues; - this.annotation = annotation; - // By hypothesis, num_element_value_pairs is stored in the last unsigned short of 'annotation'. - this.numElementValuePairsOffset = annotation.length == 0 ? -1 : annotation.length - 2; - this.previousAnnotation = previousAnnotation; - if (previousAnnotation != null) { - previousAnnotation.nextAnnotation = this; - } - } - - /** - * Creates a new {@link AnnotationWriter} using named values. - * - * @param symbolTable where the constants used in this AnnotationWriter must be stored. - * @param descriptor the class descriptor of the annotation class. - * @param previousAnnotation the previously visited annotation of the - * Runtime[In]Visible[Type]Annotations attribute to which this annotation belongs, or null in - * other cases (e.g. nested or array annotations). - */ - static AnnotationWriter create( - final SymbolTable symbolTable, - final String descriptor, - final AnnotationWriter previousAnnotation) { - // Create a ByteVector to hold an 'annotation' JVMS structure. - // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16. - ByteVector annotation = new ByteVector(); - // Write type_index and reserve space for num_element_value_pairs. - annotation.putShort(symbolTable.addConstantUtf8(descriptor)).putShort(0); - return new AnnotationWriter( - symbolTable, /* useNamedValues = */ true, annotation, previousAnnotation); - } - - /** - * Creates a new {@link AnnotationWriter} using named values. - * - * @param symbolTable where the constants used in this AnnotationWriter must be stored. - * @param typeRef a reference to the annotated type. The sort of this type reference must be - * {@link TypeReference#CLASS_TYPE_PARAMETER}, {@link - * TypeReference#CLASS_TYPE_PARAMETER_BOUND} or {@link TypeReference#CLASS_EXTENDS}. See - * {@link TypeReference}. - * @param typePath the path to the annotated type argument, wildcard bound, array element type, or - * static inner type within 'typeRef'. May be {@literal null} if the annotation targets - * 'typeRef' as a whole. - * @param descriptor the class descriptor of the annotation class. - * @param previousAnnotation the previously visited annotation of the - * Runtime[In]Visible[Type]Annotations attribute to which this annotation belongs, or null in - * other cases (e.g. nested or array annotations). - */ - static AnnotationWriter create( - final SymbolTable symbolTable, - final int typeRef, - final TypePath typePath, - final String descriptor, - final AnnotationWriter previousAnnotation) { - // Create a ByteVector to hold a 'type_annotation' JVMS structure. - // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.20. - ByteVector typeAnnotation = new ByteVector(); - // Write target_type, target_info, and target_path. - TypeReference.putTarget(typeRef, typeAnnotation); - TypePath.put(typePath, typeAnnotation); - // Write type_index and reserve space for num_element_value_pairs. - typeAnnotation.putShort(symbolTable.addConstantUtf8(descriptor)).putShort(0); - return new AnnotationWriter( - symbolTable, /* useNamedValues = */ true, typeAnnotation, previousAnnotation); - } - - // ----------------------------------------------------------------------------------------------- - // Implementation of the AnnotationVisitor abstract class - // ----------------------------------------------------------------------------------------------- - - @Override - public void visit(final String name, final Object value) { - // Case of an element_value with a const_value_index, class_info_index or array_index field. - // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16.1. - ++numElementValuePairs; - if (useNamedValues) { - annotation.putShort(symbolTable.addConstantUtf8(name)); - } - if (value instanceof String) { - annotation.put12('s', symbolTable.addConstantUtf8((String) value)); - } else if (value instanceof Byte) { - annotation.put12('B', symbolTable.addConstantInteger(((Byte) value).byteValue()).index); - } else if (value instanceof Boolean) { - int booleanValue = ((Boolean) value).booleanValue() ? 1 : 0; - annotation.put12('Z', symbolTable.addConstantInteger(booleanValue).index); - } else if (value instanceof Character) { - annotation.put12('C', symbolTable.addConstantInteger(((Character) value).charValue()).index); - } else if (value instanceof Short) { - annotation.put12('S', symbolTable.addConstantInteger(((Short) value).shortValue()).index); - } else if (value instanceof Type) { - annotation.put12('c', symbolTable.addConstantUtf8(((Type) value).getDescriptor())); - } else if (value instanceof byte[]) { - byte[] byteArray = (byte[]) value; - annotation.put12('[', byteArray.length); - for (byte byteValue : byteArray) { - annotation.put12('B', symbolTable.addConstantInteger(byteValue).index); - } - } else if (value instanceof boolean[]) { - boolean[] booleanArray = (boolean[]) value; - annotation.put12('[', booleanArray.length); - for (boolean booleanValue : booleanArray) { - annotation.put12('Z', symbolTable.addConstantInteger(booleanValue ? 1 : 0).index); - } - } else if (value instanceof short[]) { - short[] shortArray = (short[]) value; - annotation.put12('[', shortArray.length); - for (short shortValue : shortArray) { - annotation.put12('S', symbolTable.addConstantInteger(shortValue).index); - } - } else if (value instanceof char[]) { - char[] charArray = (char[]) value; - annotation.put12('[', charArray.length); - for (char charValue : charArray) { - annotation.put12('C', symbolTable.addConstantInteger(charValue).index); - } - } else if (value instanceof int[]) { - int[] intArray = (int[]) value; - annotation.put12('[', intArray.length); - for (int intValue : intArray) { - annotation.put12('I', symbolTable.addConstantInteger(intValue).index); - } - } else if (value instanceof long[]) { - long[] longArray = (long[]) value; - annotation.put12('[', longArray.length); - for (long longValue : longArray) { - annotation.put12('J', symbolTable.addConstantLong(longValue).index); - } - } else if (value instanceof float[]) { - float[] floatArray = (float[]) value; - annotation.put12('[', floatArray.length); - for (float floatValue : floatArray) { - annotation.put12('F', symbolTable.addConstantFloat(floatValue).index); - } - } else if (value instanceof double[]) { - double[] doubleArray = (double[]) value; - annotation.put12('[', doubleArray.length); - for (double doubleValue : doubleArray) { - annotation.put12('D', symbolTable.addConstantDouble(doubleValue).index); - } - } else { - Symbol symbol = symbolTable.addConstant(value); - annotation.put12(".s.IFJDCS".charAt(symbol.tag), symbol.index); - } - } - - @Override - public void visitEnum(final String name, final String descriptor, final String value) { - // Case of an element_value with an enum_const_value field. - // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16.1. - ++numElementValuePairs; - if (useNamedValues) { - annotation.putShort(symbolTable.addConstantUtf8(name)); - } - annotation - .put12('e', symbolTable.addConstantUtf8(descriptor)) - .putShort(symbolTable.addConstantUtf8(value)); - } - - @Override - public AnnotationVisitor visitAnnotation(final String name, final String descriptor) { - // Case of an element_value with an annotation_value field. - // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16.1. - ++numElementValuePairs; - if (useNamedValues) { - annotation.putShort(symbolTable.addConstantUtf8(name)); - } - // Write tag and type_index, and reserve 2 bytes for num_element_value_pairs. - annotation.put12('@', symbolTable.addConstantUtf8(descriptor)).putShort(0); - return new AnnotationWriter(symbolTable, /* useNamedValues = */ true, annotation, null); - } - - @Override - public AnnotationVisitor visitArray(final String name) { - // Case of an element_value with an array_value field. - // https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.16.1 - ++numElementValuePairs; - if (useNamedValues) { - annotation.putShort(symbolTable.addConstantUtf8(name)); - } - // Write tag, and reserve 2 bytes for num_values. Here we take advantage of the fact that the - // end of an element_value of array type is similar to the end of an 'annotation' structure: an - // unsigned short num_values followed by num_values element_value, versus an unsigned short - // num_element_value_pairs, followed by num_element_value_pairs { element_name_index, - // element_value } tuples. This allows us to use an AnnotationWriter with unnamed values to - // visit the array elements. Its num_element_value_pairs will correspond to the number of array - // elements and will be stored in what is in fact num_values. - annotation.put12('[', 0); - return new AnnotationWriter(symbolTable, /* useNamedValues = */ false, annotation, null); - } - - @Override - public void visitEnd() { - if (numElementValuePairsOffset != -1) { - byte[] data = annotation.data; - data[numElementValuePairsOffset] = (byte) (numElementValuePairs >>> 8); - data[numElementValuePairsOffset + 1] = (byte) numElementValuePairs; - } - } - - // ----------------------------------------------------------------------------------------------- - // Utility methods - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the size of a Runtime[In]Visible[Type]Annotations attribute containing this annotation - * and all its predecessors (see {@link #previousAnnotation}. Also adds the attribute name - * to the constant pool of the class (if not null). - * - * @param attributeName one of "Runtime[In]Visible[Type]Annotations", or null. - * @return the size in bytes of a Runtime[In]Visible[Type]Annotations attribute containing this - * annotation and all its predecessors. This includes the size of the attribute_name_index and - * attribute_length fields. - */ - int computeAnnotationsSize(final String attributeName) { - if (attributeName != null) { - symbolTable.addConstantUtf8(attributeName); - } - // The attribute_name_index, attribute_length and num_annotations fields use 8 bytes. - int attributeSize = 8; - AnnotationWriter annotationWriter = this; - while (annotationWriter != null) { - attributeSize += annotationWriter.annotation.length; - annotationWriter = annotationWriter.previousAnnotation; - } - return attributeSize; - } - - /** - * Returns the size of the Runtime[In]Visible[Type]Annotations attributes containing the given - * annotations and all their predecessors (see {@link #previousAnnotation}. Also adds the - * attribute names to the constant pool of the class (if not null). - * - * @param lastRuntimeVisibleAnnotation The last runtime visible annotation of a field, method or - * class. The previous ones can be accessed with the {@link #previousAnnotation} field. May be - * {@literal null}. - * @param lastRuntimeInvisibleAnnotation The last runtime invisible annotation of this a field, - * method or class. The previous ones can be accessed with the {@link #previousAnnotation} - * field. May be {@literal null}. - * @param lastRuntimeVisibleTypeAnnotation The last runtime visible type annotation of this a - * field, method or class. The previous ones can be accessed with the {@link - * #previousAnnotation} field. May be {@literal null}. - * @param lastRuntimeInvisibleTypeAnnotation The last runtime invisible type annotation of a - * field, method or class field. The previous ones can be accessed with the {@link - * #previousAnnotation} field. May be {@literal null}. - * @return the size in bytes of a Runtime[In]Visible[Type]Annotations attribute containing the - * given annotations and all their predecessors. This includes the size of the - * attribute_name_index and attribute_length fields. - */ - static int computeAnnotationsSize( - final AnnotationWriter lastRuntimeVisibleAnnotation, - final AnnotationWriter lastRuntimeInvisibleAnnotation, - final AnnotationWriter lastRuntimeVisibleTypeAnnotation, - final AnnotationWriter lastRuntimeInvisibleTypeAnnotation) { - int size = 0; - if (lastRuntimeVisibleAnnotation != null) { - size += - lastRuntimeVisibleAnnotation.computeAnnotationsSize( - Constants.RUNTIME_VISIBLE_ANNOTATIONS); - } - if (lastRuntimeInvisibleAnnotation != null) { - size += - lastRuntimeInvisibleAnnotation.computeAnnotationsSize( - Constants.RUNTIME_INVISIBLE_ANNOTATIONS); - } - if (lastRuntimeVisibleTypeAnnotation != null) { - size += - lastRuntimeVisibleTypeAnnotation.computeAnnotationsSize( - Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS); - } - if (lastRuntimeInvisibleTypeAnnotation != null) { - size += - lastRuntimeInvisibleTypeAnnotation.computeAnnotationsSize( - Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS); - } - return size; - } - - /** - * Puts a Runtime[In]Visible[Type]Annotations attribute containing this annotations and all its - * predecessors (see {@link #previousAnnotation} in the given ByteVector. Annotations are - * put in the same order they have been visited. - * - * @param attributeNameIndex the constant pool index of the attribute name (one of - * "Runtime[In]Visible[Type]Annotations"). - * @param output where the attribute must be put. - */ - void putAnnotations(final int attributeNameIndex, final ByteVector output) { - int attributeLength = 2; // For num_annotations. - int numAnnotations = 0; - AnnotationWriter annotationWriter = this; - AnnotationWriter firstAnnotation = null; - while (annotationWriter != null) { - // In case the user forgot to call visitEnd(). - annotationWriter.visitEnd(); - attributeLength += annotationWriter.annotation.length; - numAnnotations++; - firstAnnotation = annotationWriter; - annotationWriter = annotationWriter.previousAnnotation; - } - output.putShort(attributeNameIndex); - output.putInt(attributeLength); - output.putShort(numAnnotations); - annotationWriter = firstAnnotation; - while (annotationWriter != null) { - output.putByteArray(annotationWriter.annotation.data, 0, annotationWriter.annotation.length); - annotationWriter = annotationWriter.nextAnnotation; - } - } - - /** - * Puts the Runtime[In]Visible[Type]Annotations attributes containing the given annotations and - * all their predecessors (see {@link #previousAnnotation} in the given ByteVector. - * Annotations are put in the same order they have been visited. - * - * @param symbolTable where the constants used in the AnnotationWriter instances are stored. - * @param lastRuntimeVisibleAnnotation The last runtime visible annotation of a field, method or - * class. The previous ones can be accessed with the {@link #previousAnnotation} field. May be - * {@literal null}. - * @param lastRuntimeInvisibleAnnotation The last runtime invisible annotation of this a field, - * method or class. The previous ones can be accessed with the {@link #previousAnnotation} - * field. May be {@literal null}. - * @param lastRuntimeVisibleTypeAnnotation The last runtime visible type annotation of this a - * field, method or class. The previous ones can be accessed with the {@link - * #previousAnnotation} field. May be {@literal null}. - * @param lastRuntimeInvisibleTypeAnnotation The last runtime invisible type annotation of a - * field, method or class field. The previous ones can be accessed with the {@link - * #previousAnnotation} field. May be {@literal null}. - * @param output where the attributes must be put. - */ - static void putAnnotations( - final SymbolTable symbolTable, - final AnnotationWriter lastRuntimeVisibleAnnotation, - final AnnotationWriter lastRuntimeInvisibleAnnotation, - final AnnotationWriter lastRuntimeVisibleTypeAnnotation, - final AnnotationWriter lastRuntimeInvisibleTypeAnnotation, - final ByteVector output) { - if (lastRuntimeVisibleAnnotation != null) { - lastRuntimeVisibleAnnotation.putAnnotations( - symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_ANNOTATIONS), output); - } - if (lastRuntimeInvisibleAnnotation != null) { - lastRuntimeInvisibleAnnotation.putAnnotations( - symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_ANNOTATIONS), output); - } - if (lastRuntimeVisibleTypeAnnotation != null) { - lastRuntimeVisibleTypeAnnotation.putAnnotations( - symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS), output); - } - if (lastRuntimeInvisibleTypeAnnotation != null) { - lastRuntimeInvisibleTypeAnnotation.putAnnotations( - symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS), output); - } - } - - /** - * Returns the size of a Runtime[In]VisibleParameterAnnotations attribute containing all the - * annotation lists from the given AnnotationWriter sub-array. Also adds the attribute name to the - * constant pool of the class. - * - * @param attributeName one of "Runtime[In]VisibleParameterAnnotations". - * @param annotationWriters an array of AnnotationWriter lists (designated by their last - * element). - * @param annotableParameterCount the number of elements in annotationWriters to take into account - * (elements [0..annotableParameterCount[ are taken into account). - * @return the size in bytes of a Runtime[In]VisibleParameterAnnotations attribute corresponding - * to the given sub-array of AnnotationWriter lists. This includes the size of the - * attribute_name_index and attribute_length fields. - */ - static int computeParameterAnnotationsSize( - final String attributeName, - final AnnotationWriter[] annotationWriters, - final int annotableParameterCount) { - // Note: attributeName is added to the constant pool by the call to computeAnnotationsSize - // below. This assumes that there is at least one non-null element in the annotationWriters - // sub-array (which is ensured by the lazy instantiation of this array in MethodWriter). - // The attribute_name_index, attribute_length and num_parameters fields use 7 bytes, and each - // element of the parameter_annotations array uses 2 bytes for its num_annotations field. - int attributeSize = 7 + 2 * annotableParameterCount; - for (int i = 0; i < annotableParameterCount; ++i) { - AnnotationWriter annotationWriter = annotationWriters[i]; - attributeSize += - annotationWriter == null ? 0 : annotationWriter.computeAnnotationsSize(attributeName) - 8; - } - return attributeSize; - } - - /** - * Puts a Runtime[In]VisibleParameterAnnotations attribute containing all the annotation lists - * from the given AnnotationWriter sub-array in the given ByteVector. - * - * @param attributeNameIndex constant pool index of the attribute name (one of - * Runtime[In]VisibleParameterAnnotations). - * @param annotationWriters an array of AnnotationWriter lists (designated by their last - * element). - * @param annotableParameterCount the number of elements in annotationWriters to put (elements - * [0..annotableParameterCount[ are put). - * @param output where the attribute must be put. - */ - static void putParameterAnnotations( - final int attributeNameIndex, - final AnnotationWriter[] annotationWriters, - final int annotableParameterCount, - final ByteVector output) { - // The num_parameters field uses 1 byte, and each element of the parameter_annotations array - // uses 2 bytes for its num_annotations field. - int attributeLength = 1 + 2 * annotableParameterCount; - for (int i = 0; i < annotableParameterCount; ++i) { - AnnotationWriter annotationWriter = annotationWriters[i]; - attributeLength += - annotationWriter == null ? 0 : annotationWriter.computeAnnotationsSize(null) - 8; - } - output.putShort(attributeNameIndex); - output.putInt(attributeLength); - output.putByte(annotableParameterCount); - for (int i = 0; i < annotableParameterCount; ++i) { - AnnotationWriter annotationWriter = annotationWriters[i]; - AnnotationWriter firstAnnotation = null; - int numAnnotations = 0; - while (annotationWriter != null) { - // In case user the forgot to call visitEnd(). - annotationWriter.visitEnd(); - numAnnotations++; - firstAnnotation = annotationWriter; - annotationWriter = annotationWriter.previousAnnotation; - } - output.putShort(numAnnotations); - annotationWriter = firstAnnotation; - while (annotationWriter != null) { - output.putByteArray( - annotationWriter.annotation.data, 0, annotationWriter.annotation.length); - annotationWriter = annotationWriter.nextAnnotation; - } - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/Attribute.java b/jodd-proxetta/src/main/java/jodd/asm7/Attribute.java deleted file mode 100644 index 1b1631c00..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/Attribute.java +++ /dev/null @@ -1,392 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * A non standard class, field, method or code attribute, as defined in the Java Virtual Machine - * Specification (JVMS). - * - * @see JVMS - * 4.7 - * @see JVMS - * 4.7.3 - * @author Eric Bruneton - * @author Eugene Kuleshov - */ -public class Attribute { - - /** The type of this attribute, also called its name in the JVMS. */ - public final String type; - - /** - * The raw content of this attribute, only used for unknown attributes (see {@link #isUnknown()}). - * The 6 header bytes of the attribute (attribute_name_index and attribute_length) are not - * included. - */ - private byte[] content; - - /** - * The next attribute in this attribute list (Attribute instances can be linked via this field to - * store a list of class, field, method or code attributes). May be {@literal null}. - */ - Attribute nextAttribute; - - /** - * Constructs a new empty attribute. - * - * @param type the type of the attribute. - */ - protected Attribute(final String type) { - this.type = type; - } - - /** - * Returns {@literal true} if this type of attribute is unknown. This means that the attribute - * content can't be parsed to extract constant pool references, labels, etc. Instead, the - * attribute content is read as an opaque byte array, and written back as is. This can lead to - * invalid attributes, if the content actually contains constant pool references, labels, or other - * symbolic references that need to be updated when there are changes to the constant pool, the - * method bytecode, etc. The default implementation of this method always returns {@literal true}. - * - * @return {@literal true} if this type of attribute is unknown. - */ - public boolean isUnknown() { - return true; - } - - /** - * Returns {@literal true} if this type of attribute is a code attribute. - * - * @return {@literal true} if this type of attribute is a code attribute. - */ - public boolean isCodeAttribute() { - return false; - } - - /** - * Returns the labels corresponding to this attribute. - * - * @return the labels corresponding to this attribute, or {@literal null} if this attribute is not - * a code attribute that contains labels. - */ - protected Label[] getLabels() { - return new Label[0]; - } - - /** - * Reads a {@link #type} attribute. This method must return a new {@link Attribute} object, - * of type {@link #type}, corresponding to the 'length' bytes starting at 'offset', in the given - * ClassReader. - * - * @param classReader the class that contains the attribute to be read. - * @param offset index of the first byte of the attribute's content in {@link ClassReader}. The 6 - * attribute header bytes (attribute_name_index and attribute_length) are not taken into - * account here. - * @param length the length of the attribute's content (excluding the 6 attribute header bytes). - * @param charBuffer the buffer to be used to call the ClassReader methods requiring a - * 'charBuffer' parameter. - * @param codeAttributeOffset index of the first byte of content of the enclosing Code attribute - * in {@link ClassReader}, or -1 if the attribute to be read is not a code attribute. The 6 - * attribute header bytes (attribute_name_index and attribute_length) are not taken into - * account here. - * @param labels the labels of the method's code, or {@literal null} if the attribute to be read - * is not a code attribute. - * @return a new {@link Attribute} object corresponding to the specified bytes. - */ - protected Attribute read( - final ClassReader classReader, - final int offset, - final int length, - final char[] charBuffer, - final int codeAttributeOffset, - final Label[] labels) { - Attribute attribute = new Attribute(type); - attribute.content = new byte[length]; - System.arraycopy(classReader.classFileBuffer, offset, attribute.content, 0, length); - return attribute; - } - - /** - * Returns the byte array form of the content of this attribute. The 6 header bytes - * (attribute_name_index and attribute_length) must not be added in the returned - * ByteVector. - * - * @param classWriter the class to which this attribute must be added. This parameter can be used - * to add the items that corresponds to this attribute to the constant pool of this class. - * @param code the bytecode of the method corresponding to this code attribute, or {@literal null} - * if this attribute is not a code attribute. Corresponds to the 'code' field of the Code - * attribute. - * @param codeLength the length of the bytecode of the method corresponding to this code - * attribute, or 0 if this attribute is not a code attribute. Corresponds to the 'code_length' - * field of the Code attribute. - * @param maxStack the maximum stack size of the method corresponding to this code attribute, or - * -1 if this attribute is not a code attribute. - * @param maxLocals the maximum number of local variables of the method corresponding to this code - * attribute, or -1 if this attribute is not a code attribute. - * @return the byte array form of this attribute. - */ - protected ByteVector write( - final ClassWriter classWriter, - final byte[] code, - final int codeLength, - final int maxStack, - final int maxLocals) { - return new ByteVector(content); - } - - /** - * Returns the number of attributes of the attribute list that begins with this attribute. - * - * @return the number of attributes of the attribute list that begins with this attribute. - */ - final int getAttributeCount() { - int count = 0; - Attribute attribute = this; - while (attribute != null) { - count += 1; - attribute = attribute.nextAttribute; - } - return count; - } - - /** - * Returns the total size in bytes of all the attributes in the attribute list that begins with - * this attribute. This size includes the 6 header bytes (attribute_name_index and - * attribute_length) per attribute. Also adds the attribute type names to the constant pool. - * - * @param symbolTable where the constants used in the attributes must be stored. - * @return the size of all the attributes in this attribute list. This size includes the size of - * the attribute headers. - */ - final int computeAttributesSize(final SymbolTable symbolTable) { - final byte[] code = null; - final int codeLength = 0; - final int maxStack = -1; - final int maxLocals = -1; - return computeAttributesSize(symbolTable, code, codeLength, maxStack, maxLocals); - } - - /** - * Returns the total size in bytes of all the attributes in the attribute list that begins with - * this attribute. This size includes the 6 header bytes (attribute_name_index and - * attribute_length) per attribute. Also adds the attribute type names to the constant pool. - * - * @param symbolTable where the constants used in the attributes must be stored. - * @param code the bytecode of the method corresponding to these code attributes, or {@literal - * null} if they are not code attributes. Corresponds to the 'code' field of the Code - * attribute. - * @param codeLength the length of the bytecode of the method corresponding to these code - * attributes, or 0 if they are not code attributes. Corresponds to the 'code_length' field of - * the Code attribute. - * @param maxStack the maximum stack size of the method corresponding to these code attributes, or - * -1 if they are not code attributes. - * @param maxLocals the maximum number of local variables of the method corresponding to these - * code attributes, or -1 if they are not code attribute. - * @return the size of all the attributes in this attribute list. This size includes the size of - * the attribute headers. - */ - final int computeAttributesSize( - final SymbolTable symbolTable, - final byte[] code, - final int codeLength, - final int maxStack, - final int maxLocals) { - final ClassWriter classWriter = symbolTable.classWriter; - int size = 0; - Attribute attribute = this; - while (attribute != null) { - symbolTable.addConstantUtf8(attribute.type); - size += 6 + attribute.write(classWriter, code, codeLength, maxStack, maxLocals).length; - attribute = attribute.nextAttribute; - } - return size; - } - - /** - * Returns the total size in bytes of all the attributes that correspond to the given field, - * method or class access flags and signature. This size includes the 6 header bytes - * (attribute_name_index and attribute_length) per attribute. Also adds the attribute type names - * to the constant pool. - * - * @param symbolTable where the constants used in the attributes must be stored. - * @param accessFlags some field, method or class access flags. - * @param signatureIndex the constant pool index of a field, method of class signature. - * @return the size of all the attributes in bytes. This size includes the size of the attribute - * headers. - */ - static int computeAttributesSize( - final SymbolTable symbolTable, final int accessFlags, final int signatureIndex) { - int size = 0; - // Before Java 1.5, synthetic fields are represented with a Synthetic attribute. - if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 - && symbolTable.getMajorVersion() < Opcodes.V1_5) { - // Synthetic attributes always use 6 bytes. - symbolTable.addConstantUtf8(Constants.SYNTHETIC); - size += 6; - } - if (signatureIndex != 0) { - // Signature attributes always use 8 bytes. - symbolTable.addConstantUtf8(Constants.SIGNATURE); - size += 8; - } - // ACC_DEPRECATED is ASM specific, the ClassFile format uses a Deprecated attribute instead. - if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) { - // Deprecated attributes always use 6 bytes. - symbolTable.addConstantUtf8(Constants.DEPRECATED); - size += 6; - } - return size; - } - - /** - * Puts all the attributes of the attribute list that begins with this attribute, in the given - * byte vector. This includes the 6 header bytes (attribute_name_index and attribute_length) per - * attribute. - * - * @param symbolTable where the constants used in the attributes must be stored. - * @param output where the attributes must be written. - */ - final void putAttributes(final SymbolTable symbolTable, final ByteVector output) { - final byte[] code = null; - final int codeLength = 0; - final int maxStack = -1; - final int maxLocals = -1; - putAttributes(symbolTable, code, codeLength, maxStack, maxLocals, output); - } - - /** - * Puts all the attributes of the attribute list that begins with this attribute, in the given - * byte vector. This includes the 6 header bytes (attribute_name_index and attribute_length) per - * attribute. - * - * @param symbolTable where the constants used in the attributes must be stored. - * @param code the bytecode of the method corresponding to these code attributes, or {@literal - * null} if they are not code attributes. Corresponds to the 'code' field of the Code - * attribute. - * @param codeLength the length of the bytecode of the method corresponding to these code - * attributes, or 0 if they are not code attributes. Corresponds to the 'code_length' field of - * the Code attribute. - * @param maxStack the maximum stack size of the method corresponding to these code attributes, or - * -1 if they are not code attributes. - * @param maxLocals the maximum number of local variables of the method corresponding to these - * code attributes, or -1 if they are not code attribute. - * @param output where the attributes must be written. - */ - final void putAttributes( - final SymbolTable symbolTable, - final byte[] code, - final int codeLength, - final int maxStack, - final int maxLocals, - final ByteVector output) { - final ClassWriter classWriter = symbolTable.classWriter; - Attribute attribute = this; - while (attribute != null) { - ByteVector attributeContent = - attribute.write(classWriter, code, codeLength, maxStack, maxLocals); - // Put attribute_name_index and attribute_length. - output.putShort(symbolTable.addConstantUtf8(attribute.type)).putInt(attributeContent.length); - output.putByteArray(attributeContent.data, 0, attributeContent.length); - attribute = attribute.nextAttribute; - } - } - - /** - * Puts all the attributes that correspond to the given field, method or class access flags and - * signature, in the given byte vector. This includes the 6 header bytes (attribute_name_index and - * attribute_length) per attribute. - * - * @param symbolTable where the constants used in the attributes must be stored. - * @param accessFlags some field, method or class access flags. - * @param signatureIndex the constant pool index of a field, method of class signature. - * @param output where the attributes must be written. - */ - static void putAttributes( - final SymbolTable symbolTable, - final int accessFlags, - final int signatureIndex, - final ByteVector output) { - // Before Java 1.5, synthetic fields are represented with a Synthetic attribute. - if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 - && symbolTable.getMajorVersion() < Opcodes.V1_5) { - output.putShort(symbolTable.addConstantUtf8(Constants.SYNTHETIC)).putInt(0); - } - if (signatureIndex != 0) { - output - .putShort(symbolTable.addConstantUtf8(Constants.SIGNATURE)) - .putInt(2) - .putShort(signatureIndex); - } - if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) { - output.putShort(symbolTable.addConstantUtf8(Constants.DEPRECATED)).putInt(0); - } - } - - /** A set of attribute prototypes (attributes with the same type are considered equal). */ - static final class Set { - - private static final int SIZE_INCREMENT = 6; - - private int size; - private Attribute[] data = new Attribute[SIZE_INCREMENT]; - - void addAttributes(final Attribute attributeList) { - Attribute attribute = attributeList; - while (attribute != null) { - if (!contains(attribute)) { - add(attribute); - } - attribute = attribute.nextAttribute; - } - } - - Attribute[] toArray() { - Attribute[] result = new Attribute[size]; - System.arraycopy(data, 0, result, 0, size); - return result; - } - - private boolean contains(final Attribute attribute) { - for (int i = 0; i < size; ++i) { - if (data[i].type.equals(attribute.type)) { - return true; - } - } - return false; - } - - private void add(final Attribute attribute) { - if (size >= data.length) { - Attribute[] newData = new Attribute[data.length + SIZE_INCREMENT]; - System.arraycopy(data, 0, newData, 0, size); - data = newData; - } - data[size++] = attribute; - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/ByteVector.java b/jodd-proxetta/src/main/java/jodd/asm7/ByteVector.java deleted file mode 100644 index 45795a119..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/ByteVector.java +++ /dev/null @@ -1,361 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * A dynamically extensible vector of bytes. This class is roughly equivalent to a DataOutputStream - * on top of a ByteArrayOutputStream, but is more efficient. - * - * @author Eric Bruneton - */ -public class ByteVector { - - /** The content of this vector. Only the first {@link #length} bytes contain real data. */ - byte[] data; - - /** The actual number of bytes in this vector. */ - int length; - - /** Constructs a new {@link ByteVector} with a default initial capacity. */ - public ByteVector() { - data = new byte[64]; - } - - /** - * Constructs a new {@link ByteVector} with the given initial capacity. - * - * @param initialCapacity the initial capacity of the byte vector to be constructed. - */ - public ByteVector(final int initialCapacity) { - data = new byte[initialCapacity]; - } - - /** - * Constructs a new {@link ByteVector} from the given initial data. - * - * @param data the initial data of the new byte vector. - */ - ByteVector(final byte[] data) { - this.data = data; - this.length = data.length; - } - - /** - * Puts a byte into this byte vector. The byte vector is automatically enlarged if necessary. - * - * @param byteValue a byte. - * @return this byte vector. - */ - public ByteVector putByte(final int byteValue) { - int currentLength = length; - if (currentLength + 1 > data.length) { - enlarge(1); - } - data[currentLength++] = (byte) byteValue; - length = currentLength; - return this; - } - - /** - * Puts two bytes into this byte vector. The byte vector is automatically enlarged if necessary. - * - * @param byteValue1 a byte. - * @param byteValue2 another byte. - * @return this byte vector. - */ - final ByteVector put11(final int byteValue1, final int byteValue2) { - int currentLength = length; - if (currentLength + 2 > data.length) { - enlarge(2); - } - byte[] currentData = data; - currentData[currentLength++] = (byte) byteValue1; - currentData[currentLength++] = (byte) byteValue2; - length = currentLength; - return this; - } - - /** - * Puts a short into this byte vector. The byte vector is automatically enlarged if necessary. - * - * @param shortValue a short. - * @return this byte vector. - */ - public ByteVector putShort(final int shortValue) { - int currentLength = length; - if (currentLength + 2 > data.length) { - enlarge(2); - } - byte[] currentData = data; - currentData[currentLength++] = (byte) (shortValue >>> 8); - currentData[currentLength++] = (byte) shortValue; - length = currentLength; - return this; - } - - /** - * Puts a byte and a short into this byte vector. The byte vector is automatically enlarged if - * necessary. - * - * @param byteValue a byte. - * @param shortValue a short. - * @return this byte vector. - */ - final ByteVector put12(final int byteValue, final int shortValue) { - int currentLength = length; - if (currentLength + 3 > data.length) { - enlarge(3); - } - byte[] currentData = data; - currentData[currentLength++] = (byte) byteValue; - currentData[currentLength++] = (byte) (shortValue >>> 8); - currentData[currentLength++] = (byte) shortValue; - length = currentLength; - return this; - } - - /** - * Puts two bytes and a short into this byte vector. The byte vector is automatically enlarged if - * necessary. - * - * @param byteValue1 a byte. - * @param byteValue2 another byte. - * @param shortValue a short. - * @return this byte vector. - */ - final ByteVector put112(final int byteValue1, final int byteValue2, final int shortValue) { - int currentLength = length; - if (currentLength + 4 > data.length) { - enlarge(4); - } - byte[] currentData = data; - currentData[currentLength++] = (byte) byteValue1; - currentData[currentLength++] = (byte) byteValue2; - currentData[currentLength++] = (byte) (shortValue >>> 8); - currentData[currentLength++] = (byte) shortValue; - length = currentLength; - return this; - } - - /** - * Puts an int into this byte vector. The byte vector is automatically enlarged if necessary. - * - * @param intValue an int. - * @return this byte vector. - */ - public ByteVector putInt(final int intValue) { - int currentLength = length; - if (currentLength + 4 > data.length) { - enlarge(4); - } - byte[] currentData = data; - currentData[currentLength++] = (byte) (intValue >>> 24); - currentData[currentLength++] = (byte) (intValue >>> 16); - currentData[currentLength++] = (byte) (intValue >>> 8); - currentData[currentLength++] = (byte) intValue; - length = currentLength; - return this; - } - - /** - * Puts one byte and two shorts into this byte vector. The byte vector is automatically enlarged - * if necessary. - * - * @param byteValue a byte. - * @param shortValue1 a short. - * @param shortValue2 another short. - * @return this byte vector. - */ - final ByteVector put122(final int byteValue, final int shortValue1, final int shortValue2) { - int currentLength = length; - if (currentLength + 5 > data.length) { - enlarge(5); - } - byte[] currentData = data; - currentData[currentLength++] = (byte) byteValue; - currentData[currentLength++] = (byte) (shortValue1 >>> 8); - currentData[currentLength++] = (byte) shortValue1; - currentData[currentLength++] = (byte) (shortValue2 >>> 8); - currentData[currentLength++] = (byte) shortValue2; - length = currentLength; - return this; - } - - /** - * Puts a long into this byte vector. The byte vector is automatically enlarged if necessary. - * - * @param longValue a long. - * @return this byte vector. - */ - public ByteVector putLong(final long longValue) { - int currentLength = length; - if (currentLength + 8 > data.length) { - enlarge(8); - } - byte[] currentData = data; - int intValue = (int) (longValue >>> 32); - currentData[currentLength++] = (byte) (intValue >>> 24); - currentData[currentLength++] = (byte) (intValue >>> 16); - currentData[currentLength++] = (byte) (intValue >>> 8); - currentData[currentLength++] = (byte) intValue; - intValue = (int) longValue; - currentData[currentLength++] = (byte) (intValue >>> 24); - currentData[currentLength++] = (byte) (intValue >>> 16); - currentData[currentLength++] = (byte) (intValue >>> 8); - currentData[currentLength++] = (byte) intValue; - length = currentLength; - return this; - } - - /** - * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if - * necessary. - * - * @param stringValue a String whose UTF8 encoded length must be less than 65536. - * @return this byte vector. - */ - // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility). - public ByteVector putUTF8(final String stringValue) { - int charLength = stringValue.length(); - if (charLength > 65535) { - throw new IllegalArgumentException("UTF8 string too large"); - } - int currentLength = length; - if (currentLength + 2 + charLength > data.length) { - enlarge(2 + charLength); - } - byte[] currentData = data; - // Optimistic algorithm: instead of computing the byte length and then serializing the string - // (which requires two loops), we assume the byte length is equal to char length (which is the - // most frequent case), and we start serializing the string right away. During the - // serialization, if we find that this assumption is wrong, we continue with the general method. - currentData[currentLength++] = (byte) (charLength >>> 8); - currentData[currentLength++] = (byte) charLength; - for (int i = 0; i < charLength; ++i) { - char charValue = stringValue.charAt(i); - if (charValue >= '\u0001' && charValue <= '\u007F') { - currentData[currentLength++] = (byte) charValue; - } else { - length = currentLength; - return encodeUtf8(stringValue, i, 65535); - } - } - length = currentLength; - return this; - } - - /** - * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if - * necessary. The string length is encoded in two bytes before the encoded characters, if there is - * space for that (i.e. if this.length - offset - 2 >= 0). - * - * @param stringValue the String to encode. - * @param offset the index of the first character to encode. The previous characters are supposed - * to have already been encoded, using only one byte per character. - * @param maxByteLength the maximum byte length of the encoded string, including the already - * encoded characters. - * @return this byte vector. - */ - final ByteVector encodeUtf8(final String stringValue, final int offset, final int maxByteLength) { - int charLength = stringValue.length(); - int byteLength = offset; - for (int i = offset; i < charLength; ++i) { - char charValue = stringValue.charAt(i); - if (charValue >= 0x0001 && charValue <= 0x007F) { - byteLength++; - } else if (charValue <= 0x07FF) { - byteLength += 2; - } else { - byteLength += 3; - } - } - if (byteLength > maxByteLength) { - throw new IllegalArgumentException("UTF8 string too large"); - } - // Compute where 'byteLength' must be stored in 'data', and store it at this location. - int byteLengthOffset = length - offset - 2; - if (byteLengthOffset >= 0) { - data[byteLengthOffset] = (byte) (byteLength >>> 8); - data[byteLengthOffset + 1] = (byte) byteLength; - } - if (length + byteLength - offset > data.length) { - enlarge(byteLength - offset); - } - int currentLength = length; - for (int i = offset; i < charLength; ++i) { - char charValue = stringValue.charAt(i); - if (charValue >= 0x0001 && charValue <= 0x007F) { - data[currentLength++] = (byte) charValue; - } else if (charValue <= 0x07FF) { - data[currentLength++] = (byte) (0xC0 | charValue >> 6 & 0x1F); - data[currentLength++] = (byte) (0x80 | charValue & 0x3F); - } else { - data[currentLength++] = (byte) (0xE0 | charValue >> 12 & 0xF); - data[currentLength++] = (byte) (0x80 | charValue >> 6 & 0x3F); - data[currentLength++] = (byte) (0x80 | charValue & 0x3F); - } - } - length = currentLength; - return this; - } - - /** - * Puts an array of bytes into this byte vector. The byte vector is automatically enlarged if - * necessary. - * - * @param byteArrayValue an array of bytes. May be {@literal null} to put {@code byteLength} null - * bytes into this byte vector. - * @param byteOffset index of the first byte of byteArrayValue that must be copied. - * @param byteLength number of bytes of byteArrayValue that must be copied. - * @return this byte vector. - */ - public ByteVector putByteArray( - final byte[] byteArrayValue, final int byteOffset, final int byteLength) { - if (length + byteLength > data.length) { - enlarge(byteLength); - } - if (byteArrayValue != null) { - System.arraycopy(byteArrayValue, byteOffset, data, length, byteLength); - } - length += byteLength; - return this; - } - - /** - * Enlarges this byte vector so that it can receive 'size' more bytes. - * - * @param size number of additional bytes that this byte vector should be able to receive. - */ - private void enlarge(final int size) { - int doubleCapacity = 2 * data.length; - int minimalCapacity = length + size; - byte[] newData = new byte[doubleCapacity > minimalCapacity ? doubleCapacity : minimalCapacity]; - System.arraycopy(data, 0, newData, 0, length); - data = newData; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/ClassReader.java b/jodd-proxetta/src/main/java/jodd/asm7/ClassReader.java deleted file mode 100644 index 1b6fad78e..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/ClassReader.java +++ /dev/null @@ -1,3619 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * A parser to make a {@link ClassVisitor} visit a ClassFile structure, as defined in the Java - * Virtual Machine Specification (JVMS). This class parses the ClassFile content and calls the - * appropriate visit methods of a given {@link ClassVisitor} for each field, method and bytecode - * instruction encountered. - * - * @see JVMS 4 - * @author Eric Bruneton - * @author Eugene Kuleshov - */ -public class ClassReader { - - /** - * A flag to skip the Code attributes. If this flag is set the Code attributes are neither parsed - * nor visited. - */ - public static final int SKIP_CODE = 1; - - /** - * A flag to skip the SourceFile, SourceDebugExtension, LocalVariableTable, LocalVariableTypeTable - * and LineNumberTable attributes. If this flag is set these attributes are neither parsed nor - * visited (i.e. {@link ClassVisitor#visitSource}, {@link MethodVisitor#visitLocalVariable} and - * {@link MethodVisitor#visitLineNumber} are not called). - */ - public static final int SKIP_DEBUG = 2; - - /** - * A flag to skip the StackMap and StackMapTable attributes. If this flag is set these attributes - * are neither parsed nor visited (i.e. {@link MethodVisitor#visitFrame} is not called). This flag - * is useful when the {@link ClassWriter#COMPUTE_FRAMES} option is used: it avoids visiting frames - * that will be ignored and recomputed from scratch. - */ - public static final int SKIP_FRAMES = 4; - - /** - * A flag to expand the stack map frames. By default stack map frames are visited in their - * original format (i.e. "expanded" for classes whose version is less than V1_6, and "compressed" - * for the other classes). If this flag is set, stack map frames are always visited in expanded - * format (this option adds a decompression/compression step in ClassReader and ClassWriter which - * degrades performance quite a lot). - */ - public static final int EXPAND_FRAMES = 8; - - /** - * A flag to expand the ASM specific instructions into an equivalent sequence of standard bytecode - * instructions. When resolving a forward jump it may happen that the signed 2 bytes offset - * reserved for it is not sufficient to store the bytecode offset. In this case the jump - * instruction is replaced with a temporary ASM specific instruction using an unsigned 2 bytes - * offset (see {@link Label#resolve}). This internal flag is used to re-read classes containing - * such instructions, in order to replace them with standard instructions. In addition, when this - * flag is used, goto_w and jsr_w are not converted into goto and jsr, to make sure that - * infinite loops where a goto_w is replaced with a goto in ClassReader and converted back to a - * goto_w in ClassWriter cannot occur. - */ - static final int EXPAND_ASM_INSNS = 256; - - /** The size of the temporary byte array used to read class input streams chunk by chunk. */ - private static final int INPUT_STREAM_DATA_CHUNK_SIZE = 4096; - - /** - * A byte array containing the JVMS ClassFile structure to be parsed. - * - * @deprecated Use {@link #readByte(int)} and the other read methods instead. This field will - * eventually be deleted. - */ - @Deprecated - // DontCheck(MemberName): can't be renamed (for backward binary compatibility). - public final byte[] b; - - /** - * A byte array containing the JVMS ClassFile structure to be parsed. The content of this array - * must not be modified. This field is intended for {@link Attribute} sub classes, and is normally - * not needed by class visitors. - * - *

NOTE: the ClassFile structure can start at any offset within this array, i.e. it does not - * necessarily start at offset 0. Use {@link #getItem} and {@link #header} to get correct - * ClassFile element offsets within this byte array. - */ - final byte[] classFileBuffer; - - /** - * The offset in bytes, in {@link #classFileBuffer}, of each cp_info entry of the ClassFile's - * constant_pool array, plus one. In other words, the offset of constant pool entry i is - * given by cpInfoOffsets[i] - 1, i.e. its cp_info's tag field is given by b[cpInfoOffsets[i] - - * 1]. - */ - private final int[] cpInfoOffsets; - - /** - * The String objects corresponding to the CONSTANT_Utf8 constant pool items. This cache avoids - * multiple parsing of a given CONSTANT_Utf8 constant pool item. - */ - private final String[] constantUtf8Values; - - /** - * The ConstantDynamic objects corresponding to the CONSTANT_Dynamic constant pool items. This - * cache avoids multiple parsing of a given CONSTANT_Dynamic constant pool item. - */ - private final ConstantDynamic[] constantDynamicValues; - - /** - * The start offsets in {@link #classFileBuffer} of each element of the bootstrap_methods array - * (in the BootstrapMethods attribute). - * - * @see JVMS - * 4.7.23 - */ - private final int[] bootstrapMethodOffsets; - - /** - * A conservative estimate of the maximum length of the strings contained in the constant pool of - * the class. - */ - private final int maxStringLength; - - /** The offset in bytes of the ClassFile's access_flags field. */ - public final int header; - - // ----------------------------------------------------------------------------------------------- - // Constructors - // ----------------------------------------------------------------------------------------------- - - /** - * Constructs a new {@link ClassReader} object. - * - * @param classFile the JVMS ClassFile structure to be read. - */ - public ClassReader(final byte[] classFile) { - this(classFile, 0, classFile.length); - } - - /** - * Constructs a new {@link ClassReader} object. - * - * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read. - * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read. - * @param classFileLength the length in bytes of the ClassFile to be read. - */ - public ClassReader( - final byte[] classFileBuffer, - final int classFileOffset, - final int classFileLength) { // NOPMD(UnusedFormalParameter) used for backward compatibility. - this(classFileBuffer, classFileOffset, /* checkClassVersion = */ true); - } - - /** - * Constructs a new {@link ClassReader} object. This internal constructor must not be exposed - * as a public API. - * - * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read. - * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read. - * @param checkClassVersion whether to check the class version or not. - */ - ClassReader( - final byte[] classFileBuffer, final int classFileOffset, final boolean checkClassVersion) { - this.classFileBuffer = classFileBuffer; - this.b = classFileBuffer; - // Check the class' major_version. This field is after the magic and minor_version fields, which - // use 4 and 2 bytes respectively. - if (checkClassVersion && readShort(classFileOffset + 6) > Opcodes.V13) { - throw new IllegalArgumentException( - "Unsupported class file major version " + readShort(classFileOffset + 6)); - } - // Create the constant pool arrays. The constant_pool_count field is after the magic, - // minor_version and major_version fields, which use 4, 2 and 2 bytes respectively. - int constantPoolCount = readUnsignedShort(classFileOffset + 8); - cpInfoOffsets = new int[constantPoolCount]; - constantUtf8Values = new String[constantPoolCount]; - // Compute the offset of each constant pool entry, as well as a conservative estimate of the - // maximum length of the constant pool strings. The first constant pool entry is after the - // magic, minor_version, major_version and constant_pool_count fields, which use 4, 2, 2 and 2 - // bytes respectively. - int currentCpInfoIndex = 1; - int currentCpInfoOffset = classFileOffset + 10; - int currentMaxStringLength = 0; - boolean hasBootstrapMethods = false; - boolean hasConstantDynamic = false; - // The offset of the other entries depend on the total size of all the previous entries. - while (currentCpInfoIndex < constantPoolCount) { - cpInfoOffsets[currentCpInfoIndex++] = currentCpInfoOffset + 1; - int cpInfoSize; - switch (classFileBuffer[currentCpInfoOffset]) { - case Symbol.CONSTANT_FIELDREF_TAG: - case Symbol.CONSTANT_METHODREF_TAG: - case Symbol.CONSTANT_INTERFACE_METHODREF_TAG: - case Symbol.CONSTANT_INTEGER_TAG: - case Symbol.CONSTANT_FLOAT_TAG: - case Symbol.CONSTANT_NAME_AND_TYPE_TAG: - cpInfoSize = 5; - break; - case Symbol.CONSTANT_DYNAMIC_TAG: - cpInfoSize = 5; - hasBootstrapMethods = true; - hasConstantDynamic = true; - break; - case Symbol.CONSTANT_INVOKE_DYNAMIC_TAG: - cpInfoSize = 5; - hasBootstrapMethods = true; - break; - case Symbol.CONSTANT_LONG_TAG: - case Symbol.CONSTANT_DOUBLE_TAG: - cpInfoSize = 9; - currentCpInfoIndex++; - break; - case Symbol.CONSTANT_UTF8_TAG: - cpInfoSize = 3 + readUnsignedShort(currentCpInfoOffset + 1); - if (cpInfoSize > currentMaxStringLength) { - // The size in bytes of this CONSTANT_Utf8 structure provides a conservative estimate - // of the length in characters of the corresponding string, and is much cheaper to - // compute than this exact length. - currentMaxStringLength = cpInfoSize; - } - break; - case Symbol.CONSTANT_METHOD_HANDLE_TAG: - cpInfoSize = 4; - break; - case Symbol.CONSTANT_CLASS_TAG: - case Symbol.CONSTANT_STRING_TAG: - case Symbol.CONSTANT_METHOD_TYPE_TAG: - case Symbol.CONSTANT_PACKAGE_TAG: - case Symbol.CONSTANT_MODULE_TAG: - cpInfoSize = 3; - break; - default: - throw new IllegalArgumentException(); - } - currentCpInfoOffset += cpInfoSize; - } - maxStringLength = currentMaxStringLength; - // The Classfile's access_flags field is just after the last constant pool entry. - header = currentCpInfoOffset; - - // Allocate the cache of ConstantDynamic values, if there is at least one. - constantDynamicValues = hasConstantDynamic ? new ConstantDynamic[constantPoolCount] : null; - - // Read the BootstrapMethods attribute, if any (only get the offset of each method). - bootstrapMethodOffsets = - hasBootstrapMethods ? readBootstrapMethodsAttribute(currentMaxStringLength) : null; - } - - /** - * Constructs a new {@link ClassReader} object. - * - * @param inputStream an input stream of the JVMS ClassFile structure to be read. This input - * stream must contain nothing more than the ClassFile structure itself. It is read from its - * current position to its end. - * @throws IOException if a problem occurs during reading. - */ - public ClassReader(final InputStream inputStream) throws IOException { - this(readStream(inputStream, false)); - } - - /** - * Constructs a new {@link ClassReader} object. - * - * @param className the fully qualified name of the class to be read. The ClassFile structure is - * retrieved with the current class loader's {@link ClassLoader#getSystemResourceAsStream}. - * @throws IOException if an exception occurs during reading. - */ - public ClassReader(final String className) throws IOException { - this( - readStream( - ClassLoader.getSystemResourceAsStream(className.replace('.', '/') + ".class"), true)); - } - - /** - * Reads the given input stream and returns its content as a byte array. - * - * @param inputStream an input stream. - * @param close true to close the input stream after reading. - * @return the content of the given input stream. - * @throws IOException if a problem occurs during reading. - */ - private static byte[] readStream(final InputStream inputStream, final boolean close) - throws IOException { - if (inputStream == null) { - throw new IOException("Class not found"); - } - try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { - byte[] data = new byte[INPUT_STREAM_DATA_CHUNK_SIZE]; - int bytesRead; - while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) { - outputStream.write(data, 0, bytesRead); - } - outputStream.flush(); - return outputStream.toByteArray(); - } finally { - if (close) { - inputStream.close(); - } - } - } - - // ----------------------------------------------------------------------------------------------- - // Accessors - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the class's access flags (see {@link Opcodes}). This value may not reflect Deprecated - * and Synthetic flags when bytecode is before 1.5 and those flags are represented by attributes. - * - * @return the class access flags. - * @see ClassVisitor#visit(int, int, String, String, String, String[]) - */ - public int getAccess() { - return readUnsignedShort(header); - } - - /** - * Returns the internal name of the class (see {@link Type#getInternalName()}). - * - * @return the internal class name. - * @see ClassVisitor#visit(int, int, String, String, String, String[]) - */ - public String getClassName() { - // this_class is just after the access_flags field (using 2 bytes). - return readClass(header + 2, new char[maxStringLength]); - } - - /** - * Returns the internal of name of the super class (see {@link Type#getInternalName()}). For - * interfaces, the super class is {@link Object}. - * - * @return the internal name of the super class, or {@literal null} for {@link Object} class. - * @see ClassVisitor#visit(int, int, String, String, String, String[]) - */ - public String getSuperName() { - // super_class is after the access_flags and this_class fields (2 bytes each). - return readClass(header + 4, new char[maxStringLength]); - } - - /** - * Returns the internal names of the implemented interfaces (see {@link Type#getInternalName()}). - * - * @return the internal names of the directly implemented interfaces. Inherited implemented - * interfaces are not returned. - * @see ClassVisitor#visit(int, int, String, String, String, String[]) - */ - public String[] getInterfaces() { - // interfaces_count is after the access_flags, this_class and super_class fields (2 bytes each). - int currentOffset = header + 6; - int interfacesCount = readUnsignedShort(currentOffset); - String[] interfaces = new String[interfacesCount]; - if (interfacesCount > 0) { - char[] charBuffer = new char[maxStringLength]; - for (int i = 0; i < interfacesCount; ++i) { - currentOffset += 2; - interfaces[i] = readClass(currentOffset, charBuffer); - } - } - return interfaces; - } - - // ----------------------------------------------------------------------------------------------- - // Public methods - // ----------------------------------------------------------------------------------------------- - - /** - * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this - * {@link ClassReader}. - * - * @param classVisitor the visitor that must visit this class. - * @param parsingOptions the options to use to parse this class. One or more of {@link - * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}. - */ - public void accept(final ClassVisitor classVisitor, final int parsingOptions) { - accept(classVisitor, new Attribute[0], parsingOptions); - } - - /** - * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this - * {@link ClassReader}. - * - * @param classVisitor the visitor that must visit this class. - * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of - * the class. Any attribute whose type is not equal to the type of one the prototypes will not - * be parsed: its byte array value will be passed unchanged to the ClassWriter. This may - * corrupt it if this value contains references to the constant pool, or has syntactic or - * semantic links with a class element that has been transformed by a class adapter between - * the reader and the writer. - * @param parsingOptions the options to use to parse this class. One or more of {@link - * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}. - */ - public void accept( - final ClassVisitor classVisitor, - final Attribute[] attributePrototypes, - final int parsingOptions) { - Context context = new Context(); - context.attributePrototypes = attributePrototypes; - context.parsingOptions = parsingOptions; - context.charBuffer = new char[maxStringLength]; - - // Read the access_flags, this_class, super_class, interface_count and interfaces fields. - char[] charBuffer = context.charBuffer; - int currentOffset = header; - int accessFlags = readUnsignedShort(currentOffset); - String thisClass = readClass(currentOffset + 2, charBuffer); - String superClass = readClass(currentOffset + 4, charBuffer); - String[] interfaces = new String[readUnsignedShort(currentOffset + 6)]; - currentOffset += 8; - for (int i = 0; i < interfaces.length; ++i) { - interfaces[i] = readClass(currentOffset, charBuffer); - currentOffset += 2; - } - - // Read the class attributes (the variables are ordered as in Section 4.7 of the JVMS). - // Attribute offsets exclude the attribute_name_index and attribute_length fields. - // - The offset of the InnerClasses attribute, or 0. - int innerClassesOffset = 0; - // - The offset of the EnclosingMethod attribute, or 0. - int enclosingMethodOffset = 0; - // - The string corresponding to the Signature attribute, or null. - String signature = null; - // - The string corresponding to the SourceFile attribute, or null. - String sourceFile = null; - // - The string corresponding to the SourceDebugExtension attribute, or null. - String sourceDebugExtension = null; - // - The offset of the RuntimeVisibleAnnotations attribute, or 0. - int runtimeVisibleAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. - int runtimeInvisibleAnnotationsOffset = 0; - // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. - int runtimeVisibleTypeAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. - int runtimeInvisibleTypeAnnotationsOffset = 0; - // - The offset of the Module attribute, or 0. - int moduleOffset = 0; - // - The offset of the ModulePackages attribute, or 0. - int modulePackagesOffset = 0; - // - The string corresponding to the ModuleMainClass attribute, or null. - String moduleMainClass = null; - // - The string corresponding to the NestHost attribute, or null. - String nestHostClass = null; - // - The offset of the NestMembers attribute, or 0. - int nestMembersOffset = 0; - // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). - // This list in the reverse order or their order in the ClassFile structure. - Attribute attributes = null; - - int currentAttributeOffset = getFirstAttributeOffset(); - for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) { - // Read the attribute_info's attribute_name and attribute_length fields. - String attributeName = readUTF8(currentAttributeOffset, charBuffer); - int attributeLength = readInt(currentAttributeOffset + 2); - currentAttributeOffset += 6; - // The tests are sorted in decreasing frequency order (based on frequencies observed on - // typical classes). - if (Constants.SOURCE_FILE.equals(attributeName)) { - sourceFile = readUTF8(currentAttributeOffset, charBuffer); - } else if (Constants.INNER_CLASSES.equals(attributeName)) { - innerClassesOffset = currentAttributeOffset; - } else if (Constants.ENCLOSING_METHOD.equals(attributeName)) { - enclosingMethodOffset = currentAttributeOffset; - } else if (Constants.NEST_HOST.equals(attributeName)) { - nestHostClass = readClass(currentAttributeOffset, charBuffer); - } else if (Constants.NEST_MEMBERS.equals(attributeName)) { - nestMembersOffset = currentAttributeOffset; - } else if (Constants.SIGNATURE.equals(attributeName)) { - signature = readUTF8(currentAttributeOffset, charBuffer); - } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleAnnotationsOffset = currentAttributeOffset; - } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleTypeAnnotationsOffset = currentAttributeOffset; - } else if (Constants.DEPRECATED.equals(attributeName)) { - accessFlags |= Opcodes.ACC_DEPRECATED; - } else if (Constants.SYNTHETIC.equals(attributeName)) { - accessFlags |= Opcodes.ACC_SYNTHETIC; - } else if (Constants.SOURCE_DEBUG_EXTENSION.equals(attributeName)) { - sourceDebugExtension = - readUtf(currentAttributeOffset, attributeLength, new char[attributeLength]); - } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleAnnotationsOffset = currentAttributeOffset; - } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleTypeAnnotationsOffset = currentAttributeOffset; - } else if (Constants.MODULE.equals(attributeName)) { - moduleOffset = currentAttributeOffset; - } else if (Constants.MODULE_MAIN_CLASS.equals(attributeName)) { - moduleMainClass = readClass(currentAttributeOffset, charBuffer); - } else if (Constants.MODULE_PACKAGES.equals(attributeName)) { - modulePackagesOffset = currentAttributeOffset; - } else if (!Constants.BOOTSTRAP_METHODS.equals(attributeName)) { - // The BootstrapMethods attribute is read in the constructor. - Attribute attribute = - readAttribute( - attributePrototypes, - attributeName, - currentAttributeOffset, - attributeLength, - charBuffer, - -1, - null); - attribute.nextAttribute = attributes; - attributes = attribute; - } - currentAttributeOffset += attributeLength; - } - - // Visit the class declaration. The minor_version and major_version fields start 6 bytes before - // the first constant pool entry, which itself starts at cpInfoOffsets[1] - 1 (by definition). - classVisitor.visit( - readInt(cpInfoOffsets[1] - 7), accessFlags, thisClass, signature, superClass, interfaces); - - // Visit the SourceFile and SourceDebugExtenstion attributes. - if ((parsingOptions & SKIP_DEBUG) == 0 - && (sourceFile != null || sourceDebugExtension != null)) { - classVisitor.visitSource(sourceFile, sourceDebugExtension); - } - - // Visit the Module, ModulePackages and ModuleMainClass attributes. - if (moduleOffset != 0) { - readModuleAttributes( - classVisitor, context, moduleOffset, modulePackagesOffset, moduleMainClass); - } - - // Visit the NestHost attribute. - if (nestHostClass != null) { - classVisitor.visitNestHost(nestHostClass); - } - - // Visit the EnclosingMethod attribute. - if (enclosingMethodOffset != 0) { - String className = readClass(enclosingMethodOffset, charBuffer); - int methodIndex = readUnsignedShort(enclosingMethodOffset + 2); - String name = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex], charBuffer); - String type = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex] + 2, charBuffer); - classVisitor.visitOuterClass(className, name, type); - } - - // Visit the RuntimeVisibleAnnotations attribute. - if (runtimeVisibleAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset); - int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeInvisibleAnnotations attribute. - if (runtimeInvisibleAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset); - int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeVisibleTypeAnnotations attribute. - if (runtimeVisibleTypeAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset); - int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the target_type, target_info and target_path fields. - currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - classVisitor.visitTypeAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeInvisibleTypeAnnotations attribute. - if (runtimeInvisibleTypeAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset); - int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the target_type, target_info and target_path fields. - currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - classVisitor.visitTypeAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the non standard attributes. - while (attributes != null) { - // Copy and reset the nextAttribute field so that it can also be used in ClassWriter. - Attribute nextAttribute = attributes.nextAttribute; - attributes.nextAttribute = null; - classVisitor.visitAttribute(attributes); - attributes = nextAttribute; - } - - // Visit the NestedMembers attribute. - if (nestMembersOffset != 0) { - int numberOfNestMembers = readUnsignedShort(nestMembersOffset); - int currentNestMemberOffset = nestMembersOffset + 2; - while (numberOfNestMembers-- > 0) { - classVisitor.visitNestMember(readClass(currentNestMemberOffset, charBuffer)); - currentNestMemberOffset += 2; - } - } - - // Visit the InnerClasses attribute. - if (innerClassesOffset != 0) { - int numberOfClasses = readUnsignedShort(innerClassesOffset); - int currentClassesOffset = innerClassesOffset + 2; - while (numberOfClasses-- > 0) { - classVisitor.visitInnerClass( - readClass(currentClassesOffset, charBuffer), - readClass(currentClassesOffset + 2, charBuffer), - readUTF8(currentClassesOffset + 4, charBuffer), - readUnsignedShort(currentClassesOffset + 6)); - currentClassesOffset += 8; - } - } - - // Visit the fields and methods. - int fieldsCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (fieldsCount-- > 0) { - currentOffset = readField(classVisitor, context, currentOffset); - } - int methodsCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (methodsCount-- > 0) { - currentOffset = readMethod(classVisitor, context, currentOffset); - } - - // Visit the end of the class. - classVisitor.visitEnd(); - } - - // ---------------------------------------------------------------------------------------------- - // Methods to parse modules, fields and methods - // ---------------------------------------------------------------------------------------------- - - /** - * Reads the Module, ModulePackages and ModuleMainClass attributes and visit them. - * - * @param classVisitor the current class visitor - * @param context information about the class being parsed. - * @param moduleOffset the offset of the Module attribute (excluding the attribute_info's - * attribute_name_index and attribute_length fields). - * @param modulePackagesOffset the offset of the ModulePackages attribute (excluding the - * attribute_info's attribute_name_index and attribute_length fields), or 0. - * @param moduleMainClass the string corresponding to the ModuleMainClass attribute, or null. - */ - private void readModuleAttributes( - final ClassVisitor classVisitor, - final Context context, - final int moduleOffset, - final int modulePackagesOffset, - final String moduleMainClass) { - char[] buffer = context.charBuffer; - - // Read the module_name_index, module_flags and module_version_index fields and visit them. - int currentOffset = moduleOffset; - String moduleName = readModule(currentOffset, buffer); - int moduleFlags = readUnsignedShort(currentOffset + 2); - String moduleVersion = readUTF8(currentOffset + 4, buffer); - currentOffset += 6; - ModuleVisitor moduleVisitor = classVisitor.visitModule(moduleName, moduleFlags, moduleVersion); - if (moduleVisitor == null) { - return; - } - - // Visit the ModuleMainClass attribute. - if (moduleMainClass != null) { - moduleVisitor.visitMainClass(moduleMainClass); - } - - // Visit the ModulePackages attribute. - if (modulePackagesOffset != 0) { - int packageCount = readUnsignedShort(modulePackagesOffset); - int currentPackageOffset = modulePackagesOffset + 2; - while (packageCount-- > 0) { - moduleVisitor.visitPackage(readPackage(currentPackageOffset, buffer)); - currentPackageOffset += 2; - } - } - - // Read the 'requires_count' and 'requires' fields. - int requiresCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (requiresCount-- > 0) { - // Read the requires_index, requires_flags and requires_version fields and visit them. - String requires = readModule(currentOffset, buffer); - int requiresFlags = readUnsignedShort(currentOffset + 2); - String requiresVersion = readUTF8(currentOffset + 4, buffer); - currentOffset += 6; - moduleVisitor.visitRequire(requires, requiresFlags, requiresVersion); - } - - // Read the 'exports_count' and 'exports' fields. - int exportsCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (exportsCount-- > 0) { - // Read the exports_index, exports_flags, exports_to_count and exports_to_index fields - // and visit them. - String exports = readPackage(currentOffset, buffer); - int exportsFlags = readUnsignedShort(currentOffset + 2); - int exportsToCount = readUnsignedShort(currentOffset + 4); - currentOffset += 6; - String[] exportsTo = null; - if (exportsToCount != 0) { - exportsTo = new String[exportsToCount]; - for (int i = 0; i < exportsToCount; ++i) { - exportsTo[i] = readModule(currentOffset, buffer); - currentOffset += 2; - } - } - moduleVisitor.visitExport(exports, exportsFlags, exportsTo); - } - - // Reads the 'opens_count' and 'opens' fields. - int opensCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (opensCount-- > 0) { - // Read the opens_index, opens_flags, opens_to_count and opens_to_index fields and visit them. - String opens = readPackage(currentOffset, buffer); - int opensFlags = readUnsignedShort(currentOffset + 2); - int opensToCount = readUnsignedShort(currentOffset + 4); - currentOffset += 6; - String[] opensTo = null; - if (opensToCount != 0) { - opensTo = new String[opensToCount]; - for (int i = 0; i < opensToCount; ++i) { - opensTo[i] = readModule(currentOffset, buffer); - currentOffset += 2; - } - } - moduleVisitor.visitOpen(opens, opensFlags, opensTo); - } - - // Read the 'uses_count' and 'uses' fields. - int usesCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (usesCount-- > 0) { - moduleVisitor.visitUse(readClass(currentOffset, buffer)); - currentOffset += 2; - } - - // Read the 'provides_count' and 'provides' fields. - int providesCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (providesCount-- > 0) { - // Read the provides_index, provides_with_count and provides_with_index fields and visit them. - String provides = readClass(currentOffset, buffer); - int providesWithCount = readUnsignedShort(currentOffset + 2); - currentOffset += 4; - String[] providesWith = new String[providesWithCount]; - for (int i = 0; i < providesWithCount; ++i) { - providesWith[i] = readClass(currentOffset, buffer); - currentOffset += 2; - } - moduleVisitor.visitProvide(provides, providesWith); - } - - // Visit the end of the module attributes. - moduleVisitor.visitEnd(); - } - - /** - * Reads a JVMS field_info structure and makes the given visitor visit it. - * - * @param classVisitor the visitor that must visit the field. - * @param context information about the class being parsed. - * @param fieldInfoOffset the start offset of the field_info structure. - * @return the offset of the first byte following the field_info structure. - */ - private int readField( - final ClassVisitor classVisitor, final Context context, final int fieldInfoOffset) { - char[] charBuffer = context.charBuffer; - - // Read the access_flags, name_index and descriptor_index fields. - int currentOffset = fieldInfoOffset; - int accessFlags = readUnsignedShort(currentOffset); - String name = readUTF8(currentOffset + 2, charBuffer); - String descriptor = readUTF8(currentOffset + 4, charBuffer); - currentOffset += 6; - - // Read the field attributes (the variables are ordered as in Section 4.7 of the JVMS). - // Attribute offsets exclude the attribute_name_index and attribute_length fields. - // - The value corresponding to the ConstantValue attribute, or null. - Object constantValue = null; - // - The string corresponding to the Signature attribute, or null. - String signature = null; - // - The offset of the RuntimeVisibleAnnotations attribute, or 0. - int runtimeVisibleAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. - int runtimeInvisibleAnnotationsOffset = 0; - // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. - int runtimeVisibleTypeAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. - int runtimeInvisibleTypeAnnotationsOffset = 0; - // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). - // This list in the reverse order or their order in the ClassFile structure. - Attribute attributes = null; - - int attributesCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (attributesCount-- > 0) { - // Read the attribute_info's attribute_name and attribute_length fields. - String attributeName = readUTF8(currentOffset, charBuffer); - int attributeLength = readInt(currentOffset + 2); - currentOffset += 6; - // The tests are sorted in decreasing frequency order (based on frequencies observed on - // typical classes). - if (Constants.CONSTANT_VALUE.equals(attributeName)) { - int constantvalueIndex = readUnsignedShort(currentOffset); - constantValue = constantvalueIndex == 0 ? null : readConst(constantvalueIndex, charBuffer); - } else if (Constants.SIGNATURE.equals(attributeName)) { - signature = readUTF8(currentOffset, charBuffer); - } else if (Constants.DEPRECATED.equals(attributeName)) { - accessFlags |= Opcodes.ACC_DEPRECATED; - } else if (Constants.SYNTHETIC.equals(attributeName)) { - accessFlags |= Opcodes.ACC_SYNTHETIC; - } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleTypeAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleTypeAnnotationsOffset = currentOffset; - } else { - Attribute attribute = - readAttribute( - context.attributePrototypes, - attributeName, - currentOffset, - attributeLength, - charBuffer, - -1, - null); - attribute.nextAttribute = attributes; - attributes = attribute; - } - currentOffset += attributeLength; - } - - // Visit the field declaration. - FieldVisitor fieldVisitor = - classVisitor.visitField(accessFlags, name, descriptor, signature, constantValue); - if (fieldVisitor == null) { - return currentOffset; - } - - // Visit the RuntimeVisibleAnnotations attribute. - if (runtimeVisibleAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset); - int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeInvisibleAnnotations attribute. - if (runtimeInvisibleAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset); - int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeVisibleTypeAnnotations attribute. - if (runtimeVisibleTypeAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset); - int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the target_type, target_info and target_path fields. - currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - fieldVisitor.visitTypeAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeInvisibleTypeAnnotations attribute. - if (runtimeInvisibleTypeAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset); - int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the target_type, target_info and target_path fields. - currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - fieldVisitor.visitTypeAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the non standard attributes. - while (attributes != null) { - // Copy and reset the nextAttribute field so that it can also be used in FieldWriter. - Attribute nextAttribute = attributes.nextAttribute; - attributes.nextAttribute = null; - fieldVisitor.visitAttribute(attributes); - attributes = nextAttribute; - } - - // Visit the end of the field. - fieldVisitor.visitEnd(); - return currentOffset; - } - - /** - * Reads a JVMS method_info structure and makes the given visitor visit it. - * - * @param classVisitor the visitor that must visit the method. - * @param context information about the class being parsed. - * @param methodInfoOffset the start offset of the method_info structure. - * @return the offset of the first byte following the method_info structure. - */ - private int readMethod( - final ClassVisitor classVisitor, final Context context, final int methodInfoOffset) { - char[] charBuffer = context.charBuffer; - - // Read the access_flags, name_index and descriptor_index fields. - int currentOffset = methodInfoOffset; - context.currentMethodAccessFlags = readUnsignedShort(currentOffset); - context.currentMethodName = readUTF8(currentOffset + 2, charBuffer); - context.currentMethodDescriptor = readUTF8(currentOffset + 4, charBuffer); - currentOffset += 6; - - // Read the method attributes (the variables are ordered as in Section 4.7 of the JVMS). - // Attribute offsets exclude the attribute_name_index and attribute_length fields. - // - The offset of the Code attribute, or 0. - int codeOffset = 0; - // - The offset of the Exceptions attribute, or 0. - int exceptionsOffset = 0; - // - The strings corresponding to the Exceptions attribute, or null. - String[] exceptions = null; - // - Whether the method has a Synthetic attribute. - boolean synthetic = false; - // - The constant pool index contained in the Signature attribute, or 0. - int signatureIndex = 0; - // - The offset of the RuntimeVisibleAnnotations attribute, or 0. - int runtimeVisibleAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. - int runtimeInvisibleAnnotationsOffset = 0; - // - The offset of the RuntimeVisibleParameterAnnotations attribute, or 0. - int runtimeVisibleParameterAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleParameterAnnotations attribute, or 0. - int runtimeInvisibleParameterAnnotationsOffset = 0; - // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. - int runtimeVisibleTypeAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. - int runtimeInvisibleTypeAnnotationsOffset = 0; - // - The offset of the AnnotationDefault attribute, or 0. - int annotationDefaultOffset = 0; - // - The offset of the MethodParameters attribute, or 0. - int methodParametersOffset = 0; - // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). - // This list in the reverse order or their order in the ClassFile structure. - Attribute attributes = null; - - int attributesCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (attributesCount-- > 0) { - // Read the attribute_info's attribute_name and attribute_length fields. - String attributeName = readUTF8(currentOffset, charBuffer); - int attributeLength = readInt(currentOffset + 2); - currentOffset += 6; - // The tests are sorted in decreasing frequency order (based on frequencies observed on - // typical classes). - if (Constants.CODE.equals(attributeName)) { - if ((context.parsingOptions & SKIP_CODE) == 0) { - codeOffset = currentOffset; - } - } else if (Constants.EXCEPTIONS.equals(attributeName)) { - exceptionsOffset = currentOffset; - exceptions = new String[readUnsignedShort(exceptionsOffset)]; - int currentExceptionOffset = exceptionsOffset + 2; - for (int i = 0; i < exceptions.length; ++i) { - exceptions[i] = readClass(currentExceptionOffset, charBuffer); - currentExceptionOffset += 2; - } - } else if (Constants.SIGNATURE.equals(attributeName)) { - signatureIndex = readUnsignedShort(currentOffset); - } else if (Constants.DEPRECATED.equals(attributeName)) { - context.currentMethodAccessFlags |= Opcodes.ACC_DEPRECATED; - } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleTypeAnnotationsOffset = currentOffset; - } else if (Constants.ANNOTATION_DEFAULT.equals(attributeName)) { - annotationDefaultOffset = currentOffset; - } else if (Constants.SYNTHETIC.equals(attributeName)) { - synthetic = true; - context.currentMethodAccessFlags |= Opcodes.ACC_SYNTHETIC; - } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleTypeAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleParameterAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleParameterAnnotationsOffset = currentOffset; - } else if (Constants.METHOD_PARAMETERS.equals(attributeName)) { - methodParametersOffset = currentOffset; - } else { - Attribute attribute = - readAttribute( - context.attributePrototypes, - attributeName, - currentOffset, - attributeLength, - charBuffer, - -1, - null); - attribute.nextAttribute = attributes; - attributes = attribute; - } - currentOffset += attributeLength; - } - - // Visit the method declaration. - MethodVisitor methodVisitor = - classVisitor.visitMethod( - context.currentMethodAccessFlags, - context.currentMethodName, - context.currentMethodDescriptor, - signatureIndex == 0 ? null : readUtf(signatureIndex, charBuffer), - exceptions); - if (methodVisitor == null) { - return currentOffset; - } - - // If the returned MethodVisitor is in fact a MethodWriter, it means there is no method - // adapter between the reader and the writer. In this case, it might be possible to copy - // the method attributes directly into the writer. If so, return early without visiting - // the content of these attributes. - if (methodVisitor instanceof MethodWriter) { - MethodWriter methodWriter = (MethodWriter) methodVisitor; - if (methodWriter.canCopyMethodAttributes( - this, - synthetic, - (context.currentMethodAccessFlags & Opcodes.ACC_DEPRECATED) != 0, - readUnsignedShort(methodInfoOffset + 4), - signatureIndex, - exceptionsOffset)) { - methodWriter.setMethodAttributesSource(methodInfoOffset, currentOffset - methodInfoOffset); - return currentOffset; - } - } - - // Visit the MethodParameters attribute. - if (methodParametersOffset != 0) { - int parametersCount = readByte(methodParametersOffset); - int currentParameterOffset = methodParametersOffset + 1; - while (parametersCount-- > 0) { - // Read the name_index and access_flags fields and visit them. - methodVisitor.visitParameter( - readUTF8(currentParameterOffset, charBuffer), - readUnsignedShort(currentParameterOffset + 2)); - currentParameterOffset += 4; - } - } - - // Visit the AnnotationDefault attribute. - if (annotationDefaultOffset != 0) { - AnnotationVisitor annotationVisitor = methodVisitor.visitAnnotationDefault(); - readElementValue(annotationVisitor, annotationDefaultOffset, null, charBuffer); - if (annotationVisitor != null) { - annotationVisitor.visitEnd(); - } - } - - // Visit the RuntimeVisibleAnnotations attribute. - if (runtimeVisibleAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset); - int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeInvisibleAnnotations attribute. - if (runtimeInvisibleAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset); - int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeVisibleTypeAnnotations attribute. - if (runtimeVisibleTypeAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset); - int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the target_type, target_info and target_path fields. - currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - methodVisitor.visitTypeAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeInvisibleTypeAnnotations attribute. - if (runtimeInvisibleTypeAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset); - int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the target_type, target_info and target_path fields. - currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - methodVisitor.visitTypeAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeVisibleParameterAnnotations attribute. - if (runtimeVisibleParameterAnnotationsOffset != 0) { - readParameterAnnotations( - methodVisitor, context, runtimeVisibleParameterAnnotationsOffset, /* visible = */ true); - } - - // Visit the RuntimeInvisibleParameterAnnotations attribute. - if (runtimeInvisibleParameterAnnotationsOffset != 0) { - readParameterAnnotations( - methodVisitor, - context, - runtimeInvisibleParameterAnnotationsOffset, - /* visible = */ false); - } - - // Visit the non standard attributes. - while (attributes != null) { - // Copy and reset the nextAttribute field so that it can also be used in MethodWriter. - Attribute nextAttribute = attributes.nextAttribute; - attributes.nextAttribute = null; - methodVisitor.visitAttribute(attributes); - attributes = nextAttribute; - } - - // Visit the Code attribute. - if (codeOffset != 0) { - methodVisitor.visitCode(); - readCode(methodVisitor, context, codeOffset); - } - - // Visit the end of the method. - methodVisitor.visitEnd(); - return currentOffset; - } - - // ---------------------------------------------------------------------------------------------- - // Methods to parse a Code attribute - // ---------------------------------------------------------------------------------------------- - - /** - * Reads a JVMS 'Code' attribute and makes the given visitor visit it. - * - * @param methodVisitor the visitor that must visit the Code attribute. - * @param context information about the class being parsed. - * @param codeOffset the start offset in {@link #classFileBuffer} of the Code attribute, excluding - * its attribute_name_index and attribute_length fields. - */ - private void readCode( - final MethodVisitor methodVisitor, final Context context, final int codeOffset) { - int currentOffset = codeOffset; - - // Read the max_stack, max_locals and code_length fields. - final byte[] classBuffer = classFileBuffer; - final char[] charBuffer = context.charBuffer; - final int maxStack = readUnsignedShort(currentOffset); - final int maxLocals = readUnsignedShort(currentOffset + 2); - final int codeLength = readInt(currentOffset + 4); - currentOffset += 8; - - // Read the bytecode 'code' array to create a label for each referenced instruction. - final int bytecodeStartOffset = currentOffset; - final int bytecodeEndOffset = currentOffset + codeLength; - final Label[] labels = context.currentMethodLabels = new Label[codeLength + 1]; - while (currentOffset < bytecodeEndOffset) { - final int bytecodeOffset = currentOffset - bytecodeStartOffset; - final int opcode = classBuffer[currentOffset] & 0xFF; - switch (opcode) { - case Constants.NOP: - case Constants.ACONST_NULL: - case Constants.ICONST_M1: - case Constants.ICONST_0: - case Constants.ICONST_1: - case Constants.ICONST_2: - case Constants.ICONST_3: - case Constants.ICONST_4: - case Constants.ICONST_5: - case Constants.LCONST_0: - case Constants.LCONST_1: - case Constants.FCONST_0: - case Constants.FCONST_1: - case Constants.FCONST_2: - case Constants.DCONST_0: - case Constants.DCONST_1: - case Constants.IALOAD: - case Constants.LALOAD: - case Constants.FALOAD: - case Constants.DALOAD: - case Constants.AALOAD: - case Constants.BALOAD: - case Constants.CALOAD: - case Constants.SALOAD: - case Constants.IASTORE: - case Constants.LASTORE: - case Constants.FASTORE: - case Constants.DASTORE: - case Constants.AASTORE: - case Constants.BASTORE: - case Constants.CASTORE: - case Constants.SASTORE: - case Constants.POP: - case Constants.POP2: - case Constants.DUP: - case Constants.DUP_X1: - case Constants.DUP_X2: - case Constants.DUP2: - case Constants.DUP2_X1: - case Constants.DUP2_X2: - case Constants.SWAP: - case Constants.IADD: - case Constants.LADD: - case Constants.FADD: - case Constants.DADD: - case Constants.ISUB: - case Constants.LSUB: - case Constants.FSUB: - case Constants.DSUB: - case Constants.IMUL: - case Constants.LMUL: - case Constants.FMUL: - case Constants.DMUL: - case Constants.IDIV: - case Constants.LDIV: - case Constants.FDIV: - case Constants.DDIV: - case Constants.IREM: - case Constants.LREM: - case Constants.FREM: - case Constants.DREM: - case Constants.INEG: - case Constants.LNEG: - case Constants.FNEG: - case Constants.DNEG: - case Constants.ISHL: - case Constants.LSHL: - case Constants.ISHR: - case Constants.LSHR: - case Constants.IUSHR: - case Constants.LUSHR: - case Constants.IAND: - case Constants.LAND: - case Constants.IOR: - case Constants.LOR: - case Constants.IXOR: - case Constants.LXOR: - case Constants.I2L: - case Constants.I2F: - case Constants.I2D: - case Constants.L2I: - case Constants.L2F: - case Constants.L2D: - case Constants.F2I: - case Constants.F2L: - case Constants.F2D: - case Constants.D2I: - case Constants.D2L: - case Constants.D2F: - case Constants.I2B: - case Constants.I2C: - case Constants.I2S: - case Constants.LCMP: - case Constants.FCMPL: - case Constants.FCMPG: - case Constants.DCMPL: - case Constants.DCMPG: - case Constants.IRETURN: - case Constants.LRETURN: - case Constants.FRETURN: - case Constants.DRETURN: - case Constants.ARETURN: - case Constants.RETURN: - case Constants.ARRAYLENGTH: - case Constants.ATHROW: - case Constants.MONITORENTER: - case Constants.MONITOREXIT: - case Constants.ILOAD_0: - case Constants.ILOAD_1: - case Constants.ILOAD_2: - case Constants.ILOAD_3: - case Constants.LLOAD_0: - case Constants.LLOAD_1: - case Constants.LLOAD_2: - case Constants.LLOAD_3: - case Constants.FLOAD_0: - case Constants.FLOAD_1: - case Constants.FLOAD_2: - case Constants.FLOAD_3: - case Constants.DLOAD_0: - case Constants.DLOAD_1: - case Constants.DLOAD_2: - case Constants.DLOAD_3: - case Constants.ALOAD_0: - case Constants.ALOAD_1: - case Constants.ALOAD_2: - case Constants.ALOAD_3: - case Constants.ISTORE_0: - case Constants.ISTORE_1: - case Constants.ISTORE_2: - case Constants.ISTORE_3: - case Constants.LSTORE_0: - case Constants.LSTORE_1: - case Constants.LSTORE_2: - case Constants.LSTORE_3: - case Constants.FSTORE_0: - case Constants.FSTORE_1: - case Constants.FSTORE_2: - case Constants.FSTORE_3: - case Constants.DSTORE_0: - case Constants.DSTORE_1: - case Constants.DSTORE_2: - case Constants.DSTORE_3: - case Constants.ASTORE_0: - case Constants.ASTORE_1: - case Constants.ASTORE_2: - case Constants.ASTORE_3: - currentOffset += 1; - break; - case Constants.IFEQ: - case Constants.IFNE: - case Constants.IFLT: - case Constants.IFGE: - case Constants.IFGT: - case Constants.IFLE: - case Constants.IF_ICMPEQ: - case Constants.IF_ICMPNE: - case Constants.IF_ICMPLT: - case Constants.IF_ICMPGE: - case Constants.IF_ICMPGT: - case Constants.IF_ICMPLE: - case Constants.IF_ACMPEQ: - case Constants.IF_ACMPNE: - case Constants.GOTO: - case Constants.JSR: - case Constants.IFNULL: - case Constants.IFNONNULL: - createLabel(bytecodeOffset + readShort(currentOffset + 1), labels); - currentOffset += 3; - break; - case Constants.ASM_IFEQ: - case Constants.ASM_IFNE: - case Constants.ASM_IFLT: - case Constants.ASM_IFGE: - case Constants.ASM_IFGT: - case Constants.ASM_IFLE: - case Constants.ASM_IF_ICMPEQ: - case Constants.ASM_IF_ICMPNE: - case Constants.ASM_IF_ICMPLT: - case Constants.ASM_IF_ICMPGE: - case Constants.ASM_IF_ICMPGT: - case Constants.ASM_IF_ICMPLE: - case Constants.ASM_IF_ACMPEQ: - case Constants.ASM_IF_ACMPNE: - case Constants.ASM_GOTO: - case Constants.ASM_JSR: - case Constants.ASM_IFNULL: - case Constants.ASM_IFNONNULL: - createLabel(bytecodeOffset + readUnsignedShort(currentOffset + 1), labels); - currentOffset += 3; - break; - case Constants.GOTO_W: - case Constants.JSR_W: - case Constants.ASM_GOTO_W: - createLabel(bytecodeOffset + readInt(currentOffset + 1), labels); - currentOffset += 5; - break; - case Constants.WIDE: - switch (classBuffer[currentOffset + 1] & 0xFF) { - case Constants.ILOAD: - case Constants.FLOAD: - case Constants.ALOAD: - case Constants.LLOAD: - case Constants.DLOAD: - case Constants.ISTORE: - case Constants.FSTORE: - case Constants.ASTORE: - case Constants.LSTORE: - case Constants.DSTORE: - case Constants.RET: - currentOffset += 4; - break; - case Constants.IINC: - currentOffset += 6; - break; - default: - throw new IllegalArgumentException(); - } - break; - case Constants.TABLESWITCH: - // Skip 0 to 3 padding bytes. - currentOffset += 4 - (bytecodeOffset & 3); - // Read the default label and the number of table entries. - createLabel(bytecodeOffset + readInt(currentOffset), labels); - int numTableEntries = readInt(currentOffset + 8) - readInt(currentOffset + 4) + 1; - currentOffset += 12; - // Read the table labels. - while (numTableEntries-- > 0) { - createLabel(bytecodeOffset + readInt(currentOffset), labels); - currentOffset += 4; - } - break; - case Constants.LOOKUPSWITCH: - // Skip 0 to 3 padding bytes. - currentOffset += 4 - (bytecodeOffset & 3); - // Read the default label and the number of switch cases. - createLabel(bytecodeOffset + readInt(currentOffset), labels); - int numSwitchCases = readInt(currentOffset + 4); - currentOffset += 8; - // Read the switch labels. - while (numSwitchCases-- > 0) { - createLabel(bytecodeOffset + readInt(currentOffset + 4), labels); - currentOffset += 8; - } - break; - case Constants.ILOAD: - case Constants.LLOAD: - case Constants.FLOAD: - case Constants.DLOAD: - case Constants.ALOAD: - case Constants.ISTORE: - case Constants.LSTORE: - case Constants.FSTORE: - case Constants.DSTORE: - case Constants.ASTORE: - case Constants.RET: - case Constants.BIPUSH: - case Constants.NEWARRAY: - case Constants.LDC: - currentOffset += 2; - break; - case Constants.SIPUSH: - case Constants.LDC_W: - case Constants.LDC2_W: - case Constants.GETSTATIC: - case Constants.PUTSTATIC: - case Constants.GETFIELD: - case Constants.PUTFIELD: - case Constants.INVOKEVIRTUAL: - case Constants.INVOKESPECIAL: - case Constants.INVOKESTATIC: - case Constants.NEW: - case Constants.ANEWARRAY: - case Constants.CHECKCAST: - case Constants.INSTANCEOF: - case Constants.IINC: - currentOffset += 3; - break; - case Constants.INVOKEINTERFACE: - case Constants.INVOKEDYNAMIC: - currentOffset += 5; - break; - case Constants.MULTIANEWARRAY: - currentOffset += 4; - break; - default: - throw new IllegalArgumentException(); - } - } - - // Read the 'exception_table_length' and 'exception_table' field to create a label for each - // referenced instruction, and to make methodVisitor visit the corresponding try catch blocks. - int exceptionTableLength = readUnsignedShort(currentOffset); - currentOffset += 2; - while (exceptionTableLength-- > 0) { - Label start = createLabel(readUnsignedShort(currentOffset), labels); - Label end = createLabel(readUnsignedShort(currentOffset + 2), labels); - Label handler = createLabel(readUnsignedShort(currentOffset + 4), labels); - String catchType = readUTF8(cpInfoOffsets[readUnsignedShort(currentOffset + 6)], charBuffer); - currentOffset += 8; - methodVisitor.visitTryCatchBlock(start, end, handler, catchType); - } - - // Read the Code attributes to create a label for each referenced instruction (the variables - // are ordered as in Section 4.7 of the JVMS). Attribute offsets exclude the - // attribute_name_index and attribute_length fields. - // - The offset of the current 'stack_map_frame' in the StackMap[Table] attribute, or 0. - // Initially, this is the offset of the first 'stack_map_frame' entry. Then this offset is - // updated after each stack_map_frame is read. - int stackMapFrameOffset = 0; - // - The end offset of the StackMap[Table] attribute, or 0. - int stackMapTableEndOffset = 0; - // - Whether the stack map frames are compressed (i.e. in a StackMapTable) or not. - boolean compressedFrames = true; - // - The offset of the LocalVariableTable attribute, or 0. - int localVariableTableOffset = 0; - // - The offset of the LocalVariableTypeTable attribute, or 0. - int localVariableTypeTableOffset = 0; - // - The offset of each 'type_annotation' entry in the RuntimeVisibleTypeAnnotations - // attribute, or null. - int[] visibleTypeAnnotationOffsets = null; - // - The offset of each 'type_annotation' entry in the RuntimeInvisibleTypeAnnotations - // attribute, or null. - int[] invisibleTypeAnnotationOffsets = null; - // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). - // This list in the reverse order or their order in the ClassFile structure. - Attribute attributes = null; - - int attributesCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (attributesCount-- > 0) { - // Read the attribute_info's attribute_name and attribute_length fields. - String attributeName = readUTF8(currentOffset, charBuffer); - int attributeLength = readInt(currentOffset + 2); - currentOffset += 6; - if (Constants.LOCAL_VARIABLE_TABLE.equals(attributeName)) { - if ((context.parsingOptions & SKIP_DEBUG) == 0) { - localVariableTableOffset = currentOffset; - // Parse the attribute to find the corresponding (debug only) labels. - int currentLocalVariableTableOffset = currentOffset; - int localVariableTableLength = readUnsignedShort(currentLocalVariableTableOffset); - currentLocalVariableTableOffset += 2; - while (localVariableTableLength-- > 0) { - int startPc = readUnsignedShort(currentLocalVariableTableOffset); - createDebugLabel(startPc, labels); - int length = readUnsignedShort(currentLocalVariableTableOffset + 2); - createDebugLabel(startPc + length, labels); - // Skip the name_index, descriptor_index and index fields (2 bytes each). - currentLocalVariableTableOffset += 10; - } - } - } else if (Constants.LOCAL_VARIABLE_TYPE_TABLE.equals(attributeName)) { - localVariableTypeTableOffset = currentOffset; - // Here we do not extract the labels corresponding to the attribute content. We assume they - // are the same or a subset of those of the LocalVariableTable attribute. - } else if (Constants.LINE_NUMBER_TABLE.equals(attributeName)) { - if ((context.parsingOptions & SKIP_DEBUG) == 0) { - // Parse the attribute to find the corresponding (debug only) labels. - int currentLineNumberTableOffset = currentOffset; - int lineNumberTableLength = readUnsignedShort(currentLineNumberTableOffset); - currentLineNumberTableOffset += 2; - while (lineNumberTableLength-- > 0) { - int startPc = readUnsignedShort(currentLineNumberTableOffset); - int lineNumber = readUnsignedShort(currentLineNumberTableOffset + 2); - currentLineNumberTableOffset += 4; - createDebugLabel(startPc, labels); - labels[startPc].addLineNumber(lineNumber); - } - } - } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - visibleTypeAnnotationOffsets = - readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ true); - // Here we do not extract the labels corresponding to the attribute content. This would - // require a full parsing of the attribute, which would need to be repeated when parsing - // the bytecode instructions (see below). Instead, the content of the attribute is read one - // type annotation at a time (i.e. after a type annotation has been visited, the next type - // annotation is read), and the labels it contains are also extracted one annotation at a - // time. This assumes that type annotations are ordered by increasing bytecode offset. - } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - invisibleTypeAnnotationOffsets = - readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ false); - // Same comment as above for the RuntimeVisibleTypeAnnotations attribute. - } else if (Constants.STACK_MAP_TABLE.equals(attributeName)) { - if ((context.parsingOptions & SKIP_FRAMES) == 0) { - stackMapFrameOffset = currentOffset + 2; - stackMapTableEndOffset = currentOffset + attributeLength; - } - // Here we do not extract the labels corresponding to the attribute content. This would - // require a full parsing of the attribute, which would need to be repeated when parsing - // the bytecode instructions (see below). Instead, the content of the attribute is read one - // frame at a time (i.e. after a frame has been visited, the next frame is read), and the - // labels it contains are also extracted one frame at a time. Thanks to the ordering of - // frames, having only a "one frame lookahead" is not a problem, i.e. it is not possible to - // see an offset smaller than the offset of the current instruction and for which no Label - // exist. Except for UNINITIALIZED type offsets. We solve this by parsing the stack map - // table without a full decoding (see below). - } else if ("StackMap".equals(attributeName)) { - if ((context.parsingOptions & SKIP_FRAMES) == 0) { - stackMapFrameOffset = currentOffset + 2; - stackMapTableEndOffset = currentOffset + attributeLength; - compressedFrames = false; - } - // IMPORTANT! Here we assume that the frames are ordered, as in the StackMapTable attribute, - // although this is not guaranteed by the attribute format. This allows an incremental - // extraction of the labels corresponding to this attribute (see the comment above for the - // StackMapTable attribute). - } else { - Attribute attribute = - readAttribute( - context.attributePrototypes, - attributeName, - currentOffset, - attributeLength, - charBuffer, - codeOffset, - labels); - attribute.nextAttribute = attributes; - attributes = attribute; - } - currentOffset += attributeLength; - } - - // Initialize the context fields related to stack map frames, and generate the first - // (implicit) stack map frame, if needed. - final boolean expandFrames = (context.parsingOptions & EXPAND_FRAMES) != 0; - if (stackMapFrameOffset != 0) { - // The bytecode offset of the first explicit frame is not offset_delta + 1 but only - // offset_delta. Setting the implicit frame offset to -1 allows us to use of the - // "offset_delta + 1" rule in all cases. - context.currentFrameOffset = -1; - context.currentFrameType = 0; - context.currentFrameLocalCount = 0; - context.currentFrameLocalCountDelta = 0; - context.currentFrameLocalTypes = new Object[maxLocals]; - context.currentFrameStackCount = 0; - context.currentFrameStackTypes = new Object[maxStack]; - if (expandFrames) { - computeImplicitFrame(context); - } - // Find the labels for UNINITIALIZED frame types. Instead of decoding each element of the - // stack map table, we look for 3 consecutive bytes that "look like" an UNINITIALIZED type - // (tag ITEM_Uninitialized, offset within bytecode bounds, NEW instruction at this offset). - // We may find false positives (i.e. not real UNINITIALIZED types), but this should be rare, - // and the only consequence will be the creation of an unneeded label. This is better than - // creating a label for each NEW instruction, and faster than fully decoding the whole stack - // map table. - for (int offset = stackMapFrameOffset; offset < stackMapTableEndOffset - 2; ++offset) { - if (classBuffer[offset] == Frame.ITEM_UNINITIALIZED) { - int potentialBytecodeOffset = readUnsignedShort(offset + 1); - if (potentialBytecodeOffset >= 0 - && potentialBytecodeOffset < codeLength - && (classBuffer[bytecodeStartOffset + potentialBytecodeOffset] & 0xFF) - == Opcodes.NEW) { - createLabel(potentialBytecodeOffset, labels); - } - } - } - } - if (expandFrames && (context.parsingOptions & EXPAND_ASM_INSNS) != 0) { - // Expanding the ASM specific instructions can introduce F_INSERT frames, even if the method - // does not currently have any frame. These inserted frames must be computed by simulating the - // effect of the bytecode instructions, one by one, starting from the implicit first frame. - // For this, MethodWriter needs to know maxLocals before the first instruction is visited. To - // ensure this, we visit the implicit first frame here (passing only maxLocals - the rest is - // computed in MethodWriter). - methodVisitor.visitFrame(Opcodes.F_NEW, maxLocals, null, 0, null); - } - - // Visit the bytecode instructions. First, introduce state variables for the incremental parsing - // of the type annotations. - - // Index of the next runtime visible type annotation to read (in the - // visibleTypeAnnotationOffsets array). - int currentVisibleTypeAnnotationIndex = 0; - // The bytecode offset of the next runtime visible type annotation to read, or -1. - int currentVisibleTypeAnnotationBytecodeOffset = - getTypeAnnotationBytecodeOffset(visibleTypeAnnotationOffsets, 0); - // Index of the next runtime invisible type annotation to read (in the - // invisibleTypeAnnotationOffsets array). - int currentInvisibleTypeAnnotationIndex = 0; - // The bytecode offset of the next runtime invisible type annotation to read, or -1. - int currentInvisibleTypeAnnotationBytecodeOffset = - getTypeAnnotationBytecodeOffset(invisibleTypeAnnotationOffsets, 0); - - // Whether a F_INSERT stack map frame must be inserted before the current instruction. - boolean insertFrame = false; - - // The delta to subtract from a goto_w or jsr_w opcode to get the corresponding goto or jsr - // opcode, or 0 if goto_w and jsr_w must be left unchanged (i.e. when expanding ASM specific - // instructions). - final int wideJumpOpcodeDelta = - (context.parsingOptions & EXPAND_ASM_INSNS) == 0 ? Constants.WIDE_JUMP_OPCODE_DELTA : 0; - - currentOffset = bytecodeStartOffset; - while (currentOffset < bytecodeEndOffset) { - final int currentBytecodeOffset = currentOffset - bytecodeStartOffset; - - // Visit the label and the line number(s) for this bytecode offset, if any. - Label currentLabel = labels[currentBytecodeOffset]; - if (currentLabel != null) { - currentLabel.accept(methodVisitor, (context.parsingOptions & SKIP_DEBUG) == 0); - } - - // Visit the stack map frame for this bytecode offset, if any. - while (stackMapFrameOffset != 0 - && (context.currentFrameOffset == currentBytecodeOffset - || context.currentFrameOffset == -1)) { - // If there is a stack map frame for this offset, make methodVisitor visit it, and read the - // next stack map frame if there is one. - if (context.currentFrameOffset != -1) { - if (!compressedFrames || expandFrames) { - methodVisitor.visitFrame( - Opcodes.F_NEW, - context.currentFrameLocalCount, - context.currentFrameLocalTypes, - context.currentFrameStackCount, - context.currentFrameStackTypes); - } else { - methodVisitor.visitFrame( - context.currentFrameType, - context.currentFrameLocalCountDelta, - context.currentFrameLocalTypes, - context.currentFrameStackCount, - context.currentFrameStackTypes); - } - // Since there is already a stack map frame for this bytecode offset, there is no need to - // insert a new one. - insertFrame = false; - } - if (stackMapFrameOffset < stackMapTableEndOffset) { - stackMapFrameOffset = - readStackMapFrame(stackMapFrameOffset, compressedFrames, expandFrames, context); - } else { - stackMapFrameOffset = 0; - } - } - - // Insert a stack map frame for this bytecode offset, if requested by setting insertFrame to - // true during the previous iteration. The actual frame content is computed in MethodWriter. - if (insertFrame) { - if ((context.parsingOptions & EXPAND_FRAMES) != 0) { - methodVisitor.visitFrame(Constants.F_INSERT, 0, null, 0, null); - } - insertFrame = false; - } - - // Visit the instruction at this bytecode offset. - int opcode = classBuffer[currentOffset] & 0xFF; - switch (opcode) { - case Constants.NOP: - case Constants.ACONST_NULL: - case Constants.ICONST_M1: - case Constants.ICONST_0: - case Constants.ICONST_1: - case Constants.ICONST_2: - case Constants.ICONST_3: - case Constants.ICONST_4: - case Constants.ICONST_5: - case Constants.LCONST_0: - case Constants.LCONST_1: - case Constants.FCONST_0: - case Constants.FCONST_1: - case Constants.FCONST_2: - case Constants.DCONST_0: - case Constants.DCONST_1: - case Constants.IALOAD: - case Constants.LALOAD: - case Constants.FALOAD: - case Constants.DALOAD: - case Constants.AALOAD: - case Constants.BALOAD: - case Constants.CALOAD: - case Constants.SALOAD: - case Constants.IASTORE: - case Constants.LASTORE: - case Constants.FASTORE: - case Constants.DASTORE: - case Constants.AASTORE: - case Constants.BASTORE: - case Constants.CASTORE: - case Constants.SASTORE: - case Constants.POP: - case Constants.POP2: - case Constants.DUP: - case Constants.DUP_X1: - case Constants.DUP_X2: - case Constants.DUP2: - case Constants.DUP2_X1: - case Constants.DUP2_X2: - case Constants.SWAP: - case Constants.IADD: - case Constants.LADD: - case Constants.FADD: - case Constants.DADD: - case Constants.ISUB: - case Constants.LSUB: - case Constants.FSUB: - case Constants.DSUB: - case Constants.IMUL: - case Constants.LMUL: - case Constants.FMUL: - case Constants.DMUL: - case Constants.IDIV: - case Constants.LDIV: - case Constants.FDIV: - case Constants.DDIV: - case Constants.IREM: - case Constants.LREM: - case Constants.FREM: - case Constants.DREM: - case Constants.INEG: - case Constants.LNEG: - case Constants.FNEG: - case Constants.DNEG: - case Constants.ISHL: - case Constants.LSHL: - case Constants.ISHR: - case Constants.LSHR: - case Constants.IUSHR: - case Constants.LUSHR: - case Constants.IAND: - case Constants.LAND: - case Constants.IOR: - case Constants.LOR: - case Constants.IXOR: - case Constants.LXOR: - case Constants.I2L: - case Constants.I2F: - case Constants.I2D: - case Constants.L2I: - case Constants.L2F: - case Constants.L2D: - case Constants.F2I: - case Constants.F2L: - case Constants.F2D: - case Constants.D2I: - case Constants.D2L: - case Constants.D2F: - case Constants.I2B: - case Constants.I2C: - case Constants.I2S: - case Constants.LCMP: - case Constants.FCMPL: - case Constants.FCMPG: - case Constants.DCMPL: - case Constants.DCMPG: - case Constants.IRETURN: - case Constants.LRETURN: - case Constants.FRETURN: - case Constants.DRETURN: - case Constants.ARETURN: - case Constants.RETURN: - case Constants.ARRAYLENGTH: - case Constants.ATHROW: - case Constants.MONITORENTER: - case Constants.MONITOREXIT: - methodVisitor.visitInsn(opcode); - currentOffset += 1; - break; - case Constants.ILOAD_0: - case Constants.ILOAD_1: - case Constants.ILOAD_2: - case Constants.ILOAD_3: - case Constants.LLOAD_0: - case Constants.LLOAD_1: - case Constants.LLOAD_2: - case Constants.LLOAD_3: - case Constants.FLOAD_0: - case Constants.FLOAD_1: - case Constants.FLOAD_2: - case Constants.FLOAD_3: - case Constants.DLOAD_0: - case Constants.DLOAD_1: - case Constants.DLOAD_2: - case Constants.DLOAD_3: - case Constants.ALOAD_0: - case Constants.ALOAD_1: - case Constants.ALOAD_2: - case Constants.ALOAD_3: - opcode -= Constants.ILOAD_0; - methodVisitor.visitVarInsn(Opcodes.ILOAD + (opcode >> 2), opcode & 0x3); - currentOffset += 1; - break; - case Constants.ISTORE_0: - case Constants.ISTORE_1: - case Constants.ISTORE_2: - case Constants.ISTORE_3: - case Constants.LSTORE_0: - case Constants.LSTORE_1: - case Constants.LSTORE_2: - case Constants.LSTORE_3: - case Constants.FSTORE_0: - case Constants.FSTORE_1: - case Constants.FSTORE_2: - case Constants.FSTORE_3: - case Constants.DSTORE_0: - case Constants.DSTORE_1: - case Constants.DSTORE_2: - case Constants.DSTORE_3: - case Constants.ASTORE_0: - case Constants.ASTORE_1: - case Constants.ASTORE_2: - case Constants.ASTORE_3: - opcode -= Constants.ISTORE_0; - methodVisitor.visitVarInsn(Opcodes.ISTORE + (opcode >> 2), opcode & 0x3); - currentOffset += 1; - break; - case Constants.IFEQ: - case Constants.IFNE: - case Constants.IFLT: - case Constants.IFGE: - case Constants.IFGT: - case Constants.IFLE: - case Constants.IF_ICMPEQ: - case Constants.IF_ICMPNE: - case Constants.IF_ICMPLT: - case Constants.IF_ICMPGE: - case Constants.IF_ICMPGT: - case Constants.IF_ICMPLE: - case Constants.IF_ACMPEQ: - case Constants.IF_ACMPNE: - case Constants.GOTO: - case Constants.JSR: - case Constants.IFNULL: - case Constants.IFNONNULL: - methodVisitor.visitJumpInsn( - opcode, labels[currentBytecodeOffset + readShort(currentOffset + 1)]); - currentOffset += 3; - break; - case Constants.GOTO_W: - case Constants.JSR_W: - methodVisitor.visitJumpInsn( - opcode - wideJumpOpcodeDelta, - labels[currentBytecodeOffset + readInt(currentOffset + 1)]); - currentOffset += 5; - break; - case Constants.ASM_IFEQ: - case Constants.ASM_IFNE: - case Constants.ASM_IFLT: - case Constants.ASM_IFGE: - case Constants.ASM_IFGT: - case Constants.ASM_IFLE: - case Constants.ASM_IF_ICMPEQ: - case Constants.ASM_IF_ICMPNE: - case Constants.ASM_IF_ICMPLT: - case Constants.ASM_IF_ICMPGE: - case Constants.ASM_IF_ICMPGT: - case Constants.ASM_IF_ICMPLE: - case Constants.ASM_IF_ACMPEQ: - case Constants.ASM_IF_ACMPNE: - case Constants.ASM_GOTO: - case Constants.ASM_JSR: - case Constants.ASM_IFNULL: - case Constants.ASM_IFNONNULL: - { - // A forward jump with an offset > 32767. In this case we automatically replace ASM_GOTO - // with GOTO_W, ASM_JSR with JSR_W and ASM_IFxxx with IFNOTxxx GOTO_W L:..., - // where IFNOTxxx is the "opposite" opcode of ASMS_IFxxx (e.g. IFNE for ASM_IFEQ) and - // where designates the instruction just after the GOTO_W. - // First, change the ASM specific opcodes ASM_IFEQ ... ASM_JSR, ASM_IFNULL and - // ASM_IFNONNULL to IFEQ ... JSR, IFNULL and IFNONNULL. - opcode = - opcode < Constants.ASM_IFNULL - ? opcode - Constants.ASM_OPCODE_DELTA - : opcode - Constants.ASM_IFNULL_OPCODE_DELTA; - Label target = labels[currentBytecodeOffset + readUnsignedShort(currentOffset + 1)]; - if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { - // Replace GOTO with GOTO_W and JSR with JSR_W. - methodVisitor.visitJumpInsn(opcode + Constants.WIDE_JUMP_OPCODE_DELTA, target); - } else { - // Compute the "opposite" of opcode. This can be done by flipping the least - // significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ - // (with a pre and post offset by 1). - opcode = opcode < Opcodes.GOTO ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1; - Label endif = createLabel(currentBytecodeOffset + 3, labels); - methodVisitor.visitJumpInsn(opcode, endif); - methodVisitor.visitJumpInsn(Constants.GOTO_W, target); - // endif designates the instruction just after GOTO_W, and is visited as part of the - // next instruction. Since it is a jump target, we need to insert a frame here. - insertFrame = true; - } - currentOffset += 3; - break; - } - case Constants.ASM_GOTO_W: - // Replace ASM_GOTO_W with GOTO_W. - methodVisitor.visitJumpInsn( - Constants.GOTO_W, labels[currentBytecodeOffset + readInt(currentOffset + 1)]); - // The instruction just after is a jump target (because ASM_GOTO_W is used in patterns - // IFNOTxxx ASM_GOTO_W L:..., see MethodWriter), so we need to insert a frame - // here. - insertFrame = true; - currentOffset += 5; - break; - case Constants.WIDE: - opcode = classBuffer[currentOffset + 1] & 0xFF; - if (opcode == Opcodes.IINC) { - methodVisitor.visitIincInsn( - readUnsignedShort(currentOffset + 2), readShort(currentOffset + 4)); - currentOffset += 6; - } else { - methodVisitor.visitVarInsn(opcode, readUnsignedShort(currentOffset + 2)); - currentOffset += 4; - } - break; - case Constants.TABLESWITCH: - { - // Skip 0 to 3 padding bytes. - currentOffset += 4 - (currentBytecodeOffset & 3); - // Read the instruction. - Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)]; - int low = readInt(currentOffset + 4); - int high = readInt(currentOffset + 8); - currentOffset += 12; - Label[] table = new Label[high - low + 1]; - for (int i = 0; i < table.length; ++i) { - table[i] = labels[currentBytecodeOffset + readInt(currentOffset)]; - currentOffset += 4; - } - methodVisitor.visitTableSwitchInsn(low, high, defaultLabel, table); - break; - } - case Constants.LOOKUPSWITCH: - { - // Skip 0 to 3 padding bytes. - currentOffset += 4 - (currentBytecodeOffset & 3); - // Read the instruction. - Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)]; - int numPairs = readInt(currentOffset + 4); - currentOffset += 8; - int[] keys = new int[numPairs]; - Label[] values = new Label[numPairs]; - for (int i = 0; i < numPairs; ++i) { - keys[i] = readInt(currentOffset); - values[i] = labels[currentBytecodeOffset + readInt(currentOffset + 4)]; - currentOffset += 8; - } - methodVisitor.visitLookupSwitchInsn(defaultLabel, keys, values); - break; - } - case Constants.ILOAD: - case Constants.LLOAD: - case Constants.FLOAD: - case Constants.DLOAD: - case Constants.ALOAD: - case Constants.ISTORE: - case Constants.LSTORE: - case Constants.FSTORE: - case Constants.DSTORE: - case Constants.ASTORE: - case Constants.RET: - methodVisitor.visitVarInsn(opcode, classBuffer[currentOffset + 1] & 0xFF); - currentOffset += 2; - break; - case Constants.BIPUSH: - case Constants.NEWARRAY: - methodVisitor.visitIntInsn(opcode, classBuffer[currentOffset + 1]); - currentOffset += 2; - break; - case Constants.SIPUSH: - methodVisitor.visitIntInsn(opcode, readShort(currentOffset + 1)); - currentOffset += 3; - break; - case Constants.LDC: - methodVisitor.visitLdcInsn(readConst(classBuffer[currentOffset + 1] & 0xFF, charBuffer)); - currentOffset += 2; - break; - case Constants.LDC_W: - case Constants.LDC2_W: - methodVisitor.visitLdcInsn(readConst(readUnsignedShort(currentOffset + 1), charBuffer)); - currentOffset += 3; - break; - case Constants.GETSTATIC: - case Constants.PUTSTATIC: - case Constants.GETFIELD: - case Constants.PUTFIELD: - case Constants.INVOKEVIRTUAL: - case Constants.INVOKESPECIAL: - case Constants.INVOKESTATIC: - case Constants.INVOKEINTERFACE: - { - int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)]; - int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)]; - String owner = readClass(cpInfoOffset, charBuffer); - String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); - String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); - if (opcode < Opcodes.INVOKEVIRTUAL) { - methodVisitor.visitFieldInsn(opcode, owner, name, descriptor); - } else { - boolean isInterface = - classBuffer[cpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG; - methodVisitor.visitMethodInsn(opcode, owner, name, descriptor, isInterface); - } - if (opcode == Opcodes.INVOKEINTERFACE) { - currentOffset += 5; - } else { - currentOffset += 3; - } - break; - } - case Constants.INVOKEDYNAMIC: - { - int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)]; - int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)]; - String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); - String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); - int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)]; - Handle handle = - (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); - Object[] bootstrapMethodArguments = - new Object[readUnsignedShort(bootstrapMethodOffset + 2)]; - bootstrapMethodOffset += 4; - for (int i = 0; i < bootstrapMethodArguments.length; i++) { - bootstrapMethodArguments[i] = - readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); - bootstrapMethodOffset += 2; - } - methodVisitor.visitInvokeDynamicInsn( - name, descriptor, handle, bootstrapMethodArguments); - currentOffset += 5; - break; - } - case Constants.NEW: - case Constants.ANEWARRAY: - case Constants.CHECKCAST: - case Constants.INSTANCEOF: - methodVisitor.visitTypeInsn(opcode, readClass(currentOffset + 1, charBuffer)); - currentOffset += 3; - break; - case Constants.IINC: - methodVisitor.visitIincInsn( - classBuffer[currentOffset + 1] & 0xFF, classBuffer[currentOffset + 2]); - currentOffset += 3; - break; - case Constants.MULTIANEWARRAY: - methodVisitor.visitMultiANewArrayInsn( - readClass(currentOffset + 1, charBuffer), classBuffer[currentOffset + 3] & 0xFF); - currentOffset += 4; - break; - default: - throw new AssertionError(); - } - - // Visit the runtime visible instruction annotations, if any. - while (visibleTypeAnnotationOffsets != null - && currentVisibleTypeAnnotationIndex < visibleTypeAnnotationOffsets.length - && currentVisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) { - if (currentVisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) { - // Parse the target_type, target_info and target_path fields. - int currentAnnotationOffset = - readTypeAnnotationTarget( - context, visibleTypeAnnotationOffsets[currentVisibleTypeAnnotationIndex]); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - readElementValues( - methodVisitor.visitInsnAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - currentVisibleTypeAnnotationBytecodeOffset = - getTypeAnnotationBytecodeOffset( - visibleTypeAnnotationOffsets, ++currentVisibleTypeAnnotationIndex); - } - - // Visit the runtime invisible instruction annotations, if any. - while (invisibleTypeAnnotationOffsets != null - && currentInvisibleTypeAnnotationIndex < invisibleTypeAnnotationOffsets.length - && currentInvisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) { - if (currentInvisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) { - // Parse the target_type, target_info and target_path fields. - int currentAnnotationOffset = - readTypeAnnotationTarget( - context, invisibleTypeAnnotationOffsets[currentInvisibleTypeAnnotationIndex]); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - readElementValues( - methodVisitor.visitInsnAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - currentInvisibleTypeAnnotationBytecodeOffset = - getTypeAnnotationBytecodeOffset( - invisibleTypeAnnotationOffsets, ++currentInvisibleTypeAnnotationIndex); - } - } - if (labels[codeLength] != null) { - methodVisitor.visitLabel(labels[codeLength]); - } - - // Visit LocalVariableTable and LocalVariableTypeTable attributes. - if (localVariableTableOffset != 0 && (context.parsingOptions & SKIP_DEBUG) == 0) { - // The (start_pc, index, signature_index) fields of each entry of the LocalVariableTypeTable. - int[] typeTable = null; - if (localVariableTypeTableOffset != 0) { - typeTable = new int[readUnsignedShort(localVariableTypeTableOffset) * 3]; - currentOffset = localVariableTypeTableOffset + 2; - int typeTableIndex = typeTable.length; - while (typeTableIndex > 0) { - // Store the offset of 'signature_index', and the value of 'index' and 'start_pc'. - typeTable[--typeTableIndex] = currentOffset + 6; - typeTable[--typeTableIndex] = readUnsignedShort(currentOffset + 8); - typeTable[--typeTableIndex] = readUnsignedShort(currentOffset); - currentOffset += 10; - } - } - int localVariableTableLength = readUnsignedShort(localVariableTableOffset); - currentOffset = localVariableTableOffset + 2; - while (localVariableTableLength-- > 0) { - int startPc = readUnsignedShort(currentOffset); - int length = readUnsignedShort(currentOffset + 2); - String name = readUTF8(currentOffset + 4, charBuffer); - String descriptor = readUTF8(currentOffset + 6, charBuffer); - int index = readUnsignedShort(currentOffset + 8); - currentOffset += 10; - String signature = null; - if (typeTable != null) { - for (int i = 0; i < typeTable.length; i += 3) { - if (typeTable[i] == startPc && typeTable[i + 1] == index) { - signature = readUTF8(typeTable[i + 2], charBuffer); - break; - } - } - } - methodVisitor.visitLocalVariable( - name, descriptor, signature, labels[startPc], labels[startPc + length], index); - } - } - - // Visit the local variable type annotations of the RuntimeVisibleTypeAnnotations attribute. - if (visibleTypeAnnotationOffsets != null) { - for (int typeAnnotationOffset : visibleTypeAnnotationOffsets) { - int targetType = readByte(typeAnnotationOffset); - if (targetType == TypeReference.LOCAL_VARIABLE - || targetType == TypeReference.RESOURCE_VARIABLE) { - // Parse the target_type, target_info and target_path fields. - currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentOffset, charBuffer); - currentOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - readElementValues( - methodVisitor.visitLocalVariableAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - context.currentLocalVariableAnnotationRangeStarts, - context.currentLocalVariableAnnotationRangeEnds, - context.currentLocalVariableAnnotationRangeIndices, - annotationDescriptor, - /* visible = */ true), - currentOffset, - /* named = */ true, - charBuffer); - } - } - } - - // Visit the local variable type annotations of the RuntimeInvisibleTypeAnnotations attribute. - if (invisibleTypeAnnotationOffsets != null) { - for (int typeAnnotationOffset : invisibleTypeAnnotationOffsets) { - int targetType = readByte(typeAnnotationOffset); - if (targetType == TypeReference.LOCAL_VARIABLE - || targetType == TypeReference.RESOURCE_VARIABLE) { - // Parse the target_type, target_info and target_path fields. - currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentOffset, charBuffer); - currentOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - readElementValues( - methodVisitor.visitLocalVariableAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - context.currentLocalVariableAnnotationRangeStarts, - context.currentLocalVariableAnnotationRangeEnds, - context.currentLocalVariableAnnotationRangeIndices, - annotationDescriptor, - /* visible = */ false), - currentOffset, - /* named = */ true, - charBuffer); - } - } - } - - // Visit the non standard attributes. - while (attributes != null) { - // Copy and reset the nextAttribute field so that it can also be used in MethodWriter. - Attribute nextAttribute = attributes.nextAttribute; - attributes.nextAttribute = null; - methodVisitor.visitAttribute(attributes); - attributes = nextAttribute; - } - - // Visit the max stack and max locals values. - methodVisitor.visitMaxs(maxStack, maxLocals); - } - - /** - * Returns the label corresponding to the given bytecode offset. The default implementation of - * this method creates a label for the given offset if it has not been already created. - * - * @param bytecodeOffset a bytecode offset in a method. - * @param labels the already created labels, indexed by their offset. If a label already exists - * for bytecodeOffset this method must not create a new one. Otherwise it must store the new - * label in this array. - * @return a non null Label, which must be equal to labels[bytecodeOffset]. - */ - protected Label readLabel(final int bytecodeOffset, final Label[] labels) { - if (labels[bytecodeOffset] == null) { - labels[bytecodeOffset] = new Label(); - } - return labels[bytecodeOffset]; - } - - /** - * Creates a label without the {@link Label#FLAG_DEBUG_ONLY} flag set, for the given bytecode - * offset. The label is created with a call to {@link #readLabel} and its {@link - * Label#FLAG_DEBUG_ONLY} flag is cleared. - * - * @param bytecodeOffset a bytecode offset in a method. - * @param labels the already created labels, indexed by their offset. - * @return a Label without the {@link Label#FLAG_DEBUG_ONLY} flag set. - */ - private Label createLabel(final int bytecodeOffset, final Label[] labels) { - Label label = readLabel(bytecodeOffset, labels); - label.flags &= ~Label.FLAG_DEBUG_ONLY; - return label; - } - - /** - * Creates a label with the {@link Label#FLAG_DEBUG_ONLY} flag set, if there is no already - * existing label for the given bytecode offset (otherwise does nothing). The label is created - * with a call to {@link #readLabel}. - * - * @param bytecodeOffset a bytecode offset in a method. - * @param labels the already created labels, indexed by their offset. - */ - private void createDebugLabel(final int bytecodeOffset, final Label[] labels) { - if (labels[bytecodeOffset] == null) { - readLabel(bytecodeOffset, labels).flags |= Label.FLAG_DEBUG_ONLY; - } - } - - // ---------------------------------------------------------------------------------------------- - // Methods to parse annotations, type annotations and parameter annotations - // ---------------------------------------------------------------------------------------------- - - /** - * Parses a Runtime[In]VisibleTypeAnnotations attribute to find the offset of each type_annotation - * entry it contains, to find the corresponding labels, and to visit the try catch block - * annotations. - * - * @param methodVisitor the method visitor to be used to visit the try catch block annotations. - * @param context information about the class being parsed. - * @param runtimeTypeAnnotationsOffset the start offset of a Runtime[In]VisibleTypeAnnotations - * attribute, excluding the attribute_info's attribute_name_index and attribute_length fields. - * @param visible true if the attribute to parse is a RuntimeVisibleTypeAnnotations attribute, - * false it is a RuntimeInvisibleTypeAnnotations attribute. - * @return the start offset of each entry of the Runtime[In]VisibleTypeAnnotations_attribute's - * 'annotations' array field. - */ - private int[] readTypeAnnotations( - final MethodVisitor methodVisitor, - final Context context, - final int runtimeTypeAnnotationsOffset, - final boolean visible) { - char[] charBuffer = context.charBuffer; - int currentOffset = runtimeTypeAnnotationsOffset; - // Read the num_annotations field and create an array to store the type_annotation offsets. - int[] typeAnnotationsOffsets = new int[readUnsignedShort(currentOffset)]; - currentOffset += 2; - // Parse the 'annotations' array field. - for (int i = 0; i < typeAnnotationsOffsets.length; ++i) { - typeAnnotationsOffsets[i] = currentOffset; - // Parse the type_annotation's target_type and the target_info fields. The size of the - // target_info field depends on the value of target_type. - int targetType = readInt(currentOffset); - switch (targetType >>> 24) { - case TypeReference.LOCAL_VARIABLE: - case TypeReference.RESOURCE_VARIABLE: - // A localvar_target has a variable size, which depends on the value of their table_length - // field. It also references bytecode offsets, for which we need labels. - int tableLength = readUnsignedShort(currentOffset + 1); - currentOffset += 3; - while (tableLength-- > 0) { - int startPc = readUnsignedShort(currentOffset); - int length = readUnsignedShort(currentOffset + 2); - // Skip the index field (2 bytes). - currentOffset += 6; - createLabel(startPc, context.currentMethodLabels); - createLabel(startPc + length, context.currentMethodLabels); - } - break; - case TypeReference.CAST: - case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: - case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT: - case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: - case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT: - currentOffset += 4; - break; - case TypeReference.CLASS_EXTENDS: - case TypeReference.CLASS_TYPE_PARAMETER_BOUND: - case TypeReference.METHOD_TYPE_PARAMETER_BOUND: - case TypeReference.THROWS: - case TypeReference.EXCEPTION_PARAMETER: - case TypeReference.INSTANCEOF: - case TypeReference.NEW: - case TypeReference.CONSTRUCTOR_REFERENCE: - case TypeReference.METHOD_REFERENCE: - currentOffset += 3; - break; - case TypeReference.CLASS_TYPE_PARAMETER: - case TypeReference.METHOD_TYPE_PARAMETER: - case TypeReference.METHOD_FORMAL_PARAMETER: - case TypeReference.FIELD: - case TypeReference.METHOD_RETURN: - case TypeReference.METHOD_RECEIVER: - default: - // TypeReference type which can't be used in Code attribute, or which is unknown. - throw new IllegalArgumentException(); - } - // Parse the rest of the type_annotation structure, starting with the target_path structure - // (whose size depends on its path_length field). - int pathLength = readByte(currentOffset); - if ((targetType >>> 24) == TypeReference.EXCEPTION_PARAMETER) { - // Parse the target_path structure and create a corresponding TypePath. - TypePath path = pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset); - currentOffset += 1 + 2 * pathLength; - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentOffset, charBuffer); - currentOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentOffset = - readElementValues( - methodVisitor.visitTryCatchAnnotation( - targetType & 0xFFFFFF00, path, annotationDescriptor, visible), - currentOffset, - /* named = */ true, - charBuffer); - } else { - // We don't want to visit the other target_type annotations, so we just skip them (which - // requires some parsing because the element_value_pairs array has a variable size). First, - // skip the target_path structure: - currentOffset += 3 + 2 * pathLength; - // Then skip the num_element_value_pairs and element_value_pairs fields (by reading them - // with a null AnnotationVisitor). - currentOffset = - readElementValues( - /* annotationVisitor = */ null, currentOffset, /* named = */ true, charBuffer); - } - } - return typeAnnotationsOffsets; - } - - /** - * Returns the bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or - * -1 if there is no such type_annotation of if it does not have a bytecode offset. - * - * @param typeAnnotationOffsets the offset of each 'type_annotation' entry in a - * Runtime[In]VisibleTypeAnnotations attribute, or null. - * @param typeAnnotationIndex the index a 'type_annotation' entry in typeAnnotationOffsets. - * @return bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or -1 - * if there is no such type_annotation of if it does not have a bytecode offset. - */ - private int getTypeAnnotationBytecodeOffset( - final int[] typeAnnotationOffsets, final int typeAnnotationIndex) { - if (typeAnnotationOffsets == null - || typeAnnotationIndex >= typeAnnotationOffsets.length - || readByte(typeAnnotationOffsets[typeAnnotationIndex]) < TypeReference.INSTANCEOF) { - return -1; - } - return readUnsignedShort(typeAnnotationOffsets[typeAnnotationIndex] + 1); - } - - /** - * Parses the header of a JVMS type_annotation structure to extract its target_type, target_info - * and target_path (the result is stored in the given context), and returns the start offset of - * the rest of the type_annotation structure. - * - * @param context information about the class being parsed. This is where the extracted - * target_type and target_path must be stored. - * @param typeAnnotationOffset the start offset of a type_annotation structure. - * @return the start offset of the rest of the type_annotation structure. - */ - private int readTypeAnnotationTarget(final Context context, final int typeAnnotationOffset) { - int currentOffset = typeAnnotationOffset; - // Parse and store the target_type structure. - int targetType = readInt(typeAnnotationOffset); - switch (targetType >>> 24) { - case TypeReference.CLASS_TYPE_PARAMETER: - case TypeReference.METHOD_TYPE_PARAMETER: - case TypeReference.METHOD_FORMAL_PARAMETER: - targetType &= 0xFFFF0000; - currentOffset += 2; - break; - case TypeReference.FIELD: - case TypeReference.METHOD_RETURN: - case TypeReference.METHOD_RECEIVER: - targetType &= 0xFF000000; - currentOffset += 1; - break; - case TypeReference.LOCAL_VARIABLE: - case TypeReference.RESOURCE_VARIABLE: - targetType &= 0xFF000000; - int tableLength = readUnsignedShort(currentOffset + 1); - currentOffset += 3; - context.currentLocalVariableAnnotationRangeStarts = new Label[tableLength]; - context.currentLocalVariableAnnotationRangeEnds = new Label[tableLength]; - context.currentLocalVariableAnnotationRangeIndices = new int[tableLength]; - for (int i = 0; i < tableLength; ++i) { - int startPc = readUnsignedShort(currentOffset); - int length = readUnsignedShort(currentOffset + 2); - int index = readUnsignedShort(currentOffset + 4); - currentOffset += 6; - context.currentLocalVariableAnnotationRangeStarts[i] = - createLabel(startPc, context.currentMethodLabels); - context.currentLocalVariableAnnotationRangeEnds[i] = - createLabel(startPc + length, context.currentMethodLabels); - context.currentLocalVariableAnnotationRangeIndices[i] = index; - } - break; - case TypeReference.CAST: - case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: - case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT: - case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: - case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT: - targetType &= 0xFF0000FF; - currentOffset += 4; - break; - case TypeReference.CLASS_EXTENDS: - case TypeReference.CLASS_TYPE_PARAMETER_BOUND: - case TypeReference.METHOD_TYPE_PARAMETER_BOUND: - case TypeReference.THROWS: - case TypeReference.EXCEPTION_PARAMETER: - targetType &= 0xFFFFFF00; - currentOffset += 3; - break; - case TypeReference.INSTANCEOF: - case TypeReference.NEW: - case TypeReference.CONSTRUCTOR_REFERENCE: - case TypeReference.METHOD_REFERENCE: - targetType &= 0xFF000000; - currentOffset += 3; - break; - default: - throw new IllegalArgumentException(); - } - context.currentTypeAnnotationTarget = targetType; - // Parse and store the target_path structure. - int pathLength = readByte(currentOffset); - context.currentTypeAnnotationTargetPath = - pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset); - // Return the start offset of the rest of the type_annotation structure. - return currentOffset + 1 + 2 * pathLength; - } - - /** - * Reads a Runtime[In]VisibleParameterAnnotations attribute and makes the given visitor visit it. - * - * @param methodVisitor the visitor that must visit the parameter annotations. - * @param context information about the class being parsed. - * @param runtimeParameterAnnotationsOffset the start offset of a - * Runtime[In]VisibleParameterAnnotations attribute, excluding the attribute_info's - * attribute_name_index and attribute_length fields. - * @param visible true if the attribute to parse is a RuntimeVisibleParameterAnnotations - * attribute, false it is a RuntimeInvisibleParameterAnnotations attribute. - */ - private void readParameterAnnotations( - final MethodVisitor methodVisitor, - final Context context, - final int runtimeParameterAnnotationsOffset, - final boolean visible) { - int currentOffset = runtimeParameterAnnotationsOffset; - int numParameters = classFileBuffer[currentOffset++] & 0xFF; - methodVisitor.visitAnnotableParameterCount(numParameters, visible); - char[] charBuffer = context.charBuffer; - for (int i = 0; i < numParameters; ++i) { - int numAnnotations = readUnsignedShort(currentOffset); - currentOffset += 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentOffset, charBuffer); - currentOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentOffset = - readElementValues( - methodVisitor.visitParameterAnnotation(i, annotationDescriptor, visible), - currentOffset, - /* named = */ true, - charBuffer); - } - } - } - - /** - * Reads the element values of a JVMS 'annotation' structure and makes the given visitor visit - * them. This method can also be used to read the values of the JVMS 'array_value' field of an - * annotation's 'element_value'. - * - * @param annotationVisitor the visitor that must visit the values. - * @param annotationOffset the start offset of an 'annotation' structure (excluding its type_index - * field) or of an 'array_value' structure. - * @param named if the annotation values are named or not. This should be true to parse the values - * of a JVMS 'annotation' structure, and false to parse the JVMS 'array_value' of an - * annotation's element_value. - * @param charBuffer the buffer used to read strings in the constant pool. - * @return the end offset of the JVMS 'annotation' or 'array_value' structure. - */ - private int readElementValues( - final AnnotationVisitor annotationVisitor, - final int annotationOffset, - final boolean named, - final char[] charBuffer) { - int currentOffset = annotationOffset; - // Read the num_element_value_pairs field (or num_values field for an array_value). - int numElementValuePairs = readUnsignedShort(currentOffset); - currentOffset += 2; - if (named) { - // Parse the element_value_pairs array. - while (numElementValuePairs-- > 0) { - String elementName = readUTF8(currentOffset, charBuffer); - currentOffset = - readElementValue(annotationVisitor, currentOffset + 2, elementName, charBuffer); - } - } else { - // Parse the array_value array. - while (numElementValuePairs-- > 0) { - currentOffset = - readElementValue(annotationVisitor, currentOffset, /* named = */ null, charBuffer); - } - } - if (annotationVisitor != null) { - annotationVisitor.visitEnd(); - } - return currentOffset; - } - - /** - * Reads a JVMS 'element_value' structure and makes the given visitor visit it. - * - * @param annotationVisitor the visitor that must visit the element_value structure. - * @param elementValueOffset the start offset in {@link #classFileBuffer} of the element_value - * structure to be read. - * @param elementName the name of the element_value structure to be read, or {@literal null}. - * @param charBuffer the buffer used to read strings in the constant pool. - * @return the end offset of the JVMS 'element_value' structure. - */ - private int readElementValue( - final AnnotationVisitor annotationVisitor, - final int elementValueOffset, - final String elementName, - final char[] charBuffer) { - int currentOffset = elementValueOffset; - if (annotationVisitor == null) { - switch (classFileBuffer[currentOffset] & 0xFF) { - case 'e': // enum_const_value - return currentOffset + 5; - case '@': // annotation_value - return readElementValues(null, currentOffset + 3, /* named = */ true, charBuffer); - case '[': // array_value - return readElementValues(null, currentOffset + 1, /* named = */ false, charBuffer); - default: - return currentOffset + 3; - } - } - switch (classFileBuffer[currentOffset++] & 0xFF) { - case 'B': // const_value_index, CONSTANT_Integer - annotationVisitor.visit( - elementName, (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)])); - currentOffset += 2; - break; - case 'C': // const_value_index, CONSTANT_Integer - annotationVisitor.visit( - elementName, (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)])); - currentOffset += 2; - break; - case 'D': // const_value_index, CONSTANT_Double - case 'F': // const_value_index, CONSTANT_Float - case 'I': // const_value_index, CONSTANT_Integer - case 'J': // const_value_index, CONSTANT_Long - annotationVisitor.visit( - elementName, readConst(readUnsignedShort(currentOffset), charBuffer)); - currentOffset += 2; - break; - case 'S': // const_value_index, CONSTANT_Integer - annotationVisitor.visit( - elementName, (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)])); - currentOffset += 2; - break; - - case 'Z': // const_value_index, CONSTANT_Integer - annotationVisitor.visit( - elementName, - readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]) == 0 - ? Boolean.FALSE - : Boolean.TRUE); - currentOffset += 2; - break; - case 's': // const_value_index, CONSTANT_Utf8 - annotationVisitor.visit(elementName, readUTF8(currentOffset, charBuffer)); - currentOffset += 2; - break; - case 'e': // enum_const_value - annotationVisitor.visitEnum( - elementName, - readUTF8(currentOffset, charBuffer), - readUTF8(currentOffset + 2, charBuffer)); - currentOffset += 4; - break; - case 'c': // class_info - annotationVisitor.visit(elementName, Type.getType(readUTF8(currentOffset, charBuffer))); - currentOffset += 2; - break; - case '@': // annotation_value - currentOffset = - readElementValues( - annotationVisitor.visitAnnotation(elementName, readUTF8(currentOffset, charBuffer)), - currentOffset + 2, - true, - charBuffer); - break; - case '[': // array_value - int numValues = readUnsignedShort(currentOffset); - currentOffset += 2; - if (numValues == 0) { - return readElementValues( - annotationVisitor.visitArray(elementName), - currentOffset - 2, - /* named = */ false, - charBuffer); - } - switch (classFileBuffer[currentOffset] & 0xFF) { - case 'B': - byte[] byteValues = new byte[numValues]; - for (int i = 0; i < numValues; i++) { - byteValues[i] = (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); - currentOffset += 3; - } - annotationVisitor.visit(elementName, byteValues); - break; - case 'Z': - boolean[] booleanValues = new boolean[numValues]; - for (int i = 0; i < numValues; i++) { - booleanValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]) != 0; - currentOffset += 3; - } - annotationVisitor.visit(elementName, booleanValues); - break; - case 'S': - short[] shortValues = new short[numValues]; - for (int i = 0; i < numValues; i++) { - shortValues[i] = (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); - currentOffset += 3; - } - annotationVisitor.visit(elementName, shortValues); - break; - case 'C': - char[] charValues = new char[numValues]; - for (int i = 0; i < numValues; i++) { - charValues[i] = (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); - currentOffset += 3; - } - annotationVisitor.visit(elementName, charValues); - break; - case 'I': - int[] intValues = new int[numValues]; - for (int i = 0; i < numValues; i++) { - intValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); - currentOffset += 3; - } - annotationVisitor.visit(elementName, intValues); - break; - case 'J': - long[] longValues = new long[numValues]; - for (int i = 0; i < numValues; i++) { - longValues[i] = readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); - currentOffset += 3; - } - annotationVisitor.visit(elementName, longValues); - break; - case 'F': - float[] floatValues = new float[numValues]; - for (int i = 0; i < numValues; i++) { - floatValues[i] = - Float.intBitsToFloat( - readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)])); - currentOffset += 3; - } - annotationVisitor.visit(elementName, floatValues); - break; - case 'D': - double[] doubleValues = new double[numValues]; - for (int i = 0; i < numValues; i++) { - doubleValues[i] = - Double.longBitsToDouble( - readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)])); - currentOffset += 3; - } - annotationVisitor.visit(elementName, doubleValues); - break; - default: - currentOffset = - readElementValues( - annotationVisitor.visitArray(elementName), - currentOffset - 2, - /* named = */ false, - charBuffer); - break; - } - break; - default: - throw new IllegalArgumentException(); - } - return currentOffset; - } - - // ---------------------------------------------------------------------------------------------- - // Methods to parse stack map frames - // ---------------------------------------------------------------------------------------------- - - /** - * Computes the implicit frame of the method currently being parsed (as defined in the given - * {@link Context}) and stores it in the given context. - * - * @param context information about the class being parsed. - */ - private void computeImplicitFrame(final Context context) { - String methodDescriptor = context.currentMethodDescriptor; - Object[] locals = context.currentFrameLocalTypes; - int numLocal = 0; - if ((context.currentMethodAccessFlags & Opcodes.ACC_STATIC) == 0) { - if ("".equals(context.currentMethodName)) { - locals[numLocal++] = Opcodes.UNINITIALIZED_THIS; - } else { - locals[numLocal++] = readClass(header + 2, context.charBuffer); - } - } - // Parse the method descriptor, one argument type descriptor at each iteration. Start by - // skipping the first method descriptor character, which is always '('. - int currentMethodDescritorOffset = 1; - while (true) { - int currentArgumentDescriptorStartOffset = currentMethodDescritorOffset; - switch (methodDescriptor.charAt(currentMethodDescritorOffset++)) { - case 'Z': - case 'C': - case 'B': - case 'S': - case 'I': - locals[numLocal++] = Opcodes.INTEGER; - break; - case 'F': - locals[numLocal++] = Opcodes.FLOAT; - break; - case 'J': - locals[numLocal++] = Opcodes.LONG; - break; - case 'D': - locals[numLocal++] = Opcodes.DOUBLE; - break; - case '[': - while (methodDescriptor.charAt(currentMethodDescritorOffset) == '[') { - ++currentMethodDescritorOffset; - } - if (methodDescriptor.charAt(currentMethodDescritorOffset) == 'L') { - ++currentMethodDescritorOffset; - while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') { - ++currentMethodDescritorOffset; - } - } - locals[numLocal++] = - methodDescriptor.substring( - currentArgumentDescriptorStartOffset, ++currentMethodDescritorOffset); - break; - case 'L': - while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') { - ++currentMethodDescritorOffset; - } - locals[numLocal++] = - methodDescriptor.substring( - currentArgumentDescriptorStartOffset + 1, currentMethodDescritorOffset++); - break; - default: - context.currentFrameLocalCount = numLocal; - return; - } - } - } - - /** - * Reads a JVMS 'stack_map_frame' structure and stores the result in the given {@link Context} - * object. This method can also be used to read a full_frame structure, excluding its frame_type - * field (this is used to parse the legacy StackMap attributes). - * - * @param stackMapFrameOffset the start offset in {@link #classFileBuffer} of the - * stack_map_frame_value structure to be read, or the start offset of a full_frame structure - * (excluding its frame_type field). - * @param compressed true to read a 'stack_map_frame' structure, false to read a 'full_frame' - * structure without its frame_type field. - * @param expand if the stack map frame must be expanded. See {@link #EXPAND_FRAMES}. - * @param context where the parsed stack map frame must be stored. - * @return the end offset of the JVMS 'stack_map_frame' or 'full_frame' structure. - */ - private int readStackMapFrame( - final int stackMapFrameOffset, - final boolean compressed, - final boolean expand, - final Context context) { - int currentOffset = stackMapFrameOffset; - final char[] charBuffer = context.charBuffer; - final Label[] labels = context.currentMethodLabels; - int frameType; - if (compressed) { - // Read the frame_type field. - frameType = classFileBuffer[currentOffset++] & 0xFF; - } else { - frameType = Frame.FULL_FRAME; - context.currentFrameOffset = -1; - } - int offsetDelta; - context.currentFrameLocalCountDelta = 0; - if (frameType < Frame.SAME_LOCALS_1_STACK_ITEM_FRAME) { - offsetDelta = frameType; - context.currentFrameType = Opcodes.F_SAME; - context.currentFrameStackCount = 0; - } else if (frameType < Frame.RESERVED) { - offsetDelta = frameType - Frame.SAME_LOCALS_1_STACK_ITEM_FRAME; - currentOffset = - readVerificationTypeInfo( - currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels); - context.currentFrameType = Opcodes.F_SAME1; - context.currentFrameStackCount = 1; - } else if (frameType >= Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { - offsetDelta = readUnsignedShort(currentOffset); - currentOffset += 2; - if (frameType == Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { - currentOffset = - readVerificationTypeInfo( - currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels); - context.currentFrameType = Opcodes.F_SAME1; - context.currentFrameStackCount = 1; - } else if (frameType >= Frame.CHOP_FRAME && frameType < Frame.SAME_FRAME_EXTENDED) { - context.currentFrameType = Opcodes.F_CHOP; - context.currentFrameLocalCountDelta = Frame.SAME_FRAME_EXTENDED - frameType; - context.currentFrameLocalCount -= context.currentFrameLocalCountDelta; - context.currentFrameStackCount = 0; - } else if (frameType == Frame.SAME_FRAME_EXTENDED) { - context.currentFrameType = Opcodes.F_SAME; - context.currentFrameStackCount = 0; - } else if (frameType < Frame.FULL_FRAME) { - int local = expand ? context.currentFrameLocalCount : 0; - for (int k = frameType - Frame.SAME_FRAME_EXTENDED; k > 0; k--) { - currentOffset = - readVerificationTypeInfo( - currentOffset, context.currentFrameLocalTypes, local++, charBuffer, labels); - } - context.currentFrameType = Opcodes.F_APPEND; - context.currentFrameLocalCountDelta = frameType - Frame.SAME_FRAME_EXTENDED; - context.currentFrameLocalCount += context.currentFrameLocalCountDelta; - context.currentFrameStackCount = 0; - } else { - final int numberOfLocals = readUnsignedShort(currentOffset); - currentOffset += 2; - context.currentFrameType = Opcodes.F_FULL; - context.currentFrameLocalCountDelta = numberOfLocals; - context.currentFrameLocalCount = numberOfLocals; - for (int local = 0; local < numberOfLocals; ++local) { - currentOffset = - readVerificationTypeInfo( - currentOffset, context.currentFrameLocalTypes, local, charBuffer, labels); - } - final int numberOfStackItems = readUnsignedShort(currentOffset); - currentOffset += 2; - context.currentFrameStackCount = numberOfStackItems; - for (int stack = 0; stack < numberOfStackItems; ++stack) { - currentOffset = - readVerificationTypeInfo( - currentOffset, context.currentFrameStackTypes, stack, charBuffer, labels); - } - } - } else { - throw new IllegalArgumentException(); - } - context.currentFrameOffset += offsetDelta + 1; - createLabel(context.currentFrameOffset, labels); - return currentOffset; - } - - /** - * Reads a JVMS 'verification_type_info' structure and stores it at the given index in the given - * array. - * - * @param verificationTypeInfoOffset the start offset of the 'verification_type_info' structure to - * read. - * @param frame the array where the parsed type must be stored. - * @param index the index in 'frame' where the parsed type must be stored. - * @param charBuffer the buffer used to read strings in the constant pool. - * @param labels the labels of the method currently being parsed, indexed by their offset. If the - * parsed type is an ITEM_Uninitialized, a new label for the corresponding NEW instruction is - * stored in this array if it does not already exist. - * @return the end offset of the JVMS 'verification_type_info' structure. - */ - private int readVerificationTypeInfo( - final int verificationTypeInfoOffset, - final Object[] frame, - final int index, - final char[] charBuffer, - final Label[] labels) { - int currentOffset = verificationTypeInfoOffset; - int tag = classFileBuffer[currentOffset++] & 0xFF; - switch (tag) { - case Frame.ITEM_TOP: - frame[index] = Opcodes.TOP; - break; - case Frame.ITEM_INTEGER: - frame[index] = Opcodes.INTEGER; - break; - case Frame.ITEM_FLOAT: - frame[index] = Opcodes.FLOAT; - break; - case Frame.ITEM_DOUBLE: - frame[index] = Opcodes.DOUBLE; - break; - case Frame.ITEM_LONG: - frame[index] = Opcodes.LONG; - break; - case Frame.ITEM_NULL: - frame[index] = Opcodes.NULL; - break; - case Frame.ITEM_UNINITIALIZED_THIS: - frame[index] = Opcodes.UNINITIALIZED_THIS; - break; - case Frame.ITEM_OBJECT: - frame[index] = readClass(currentOffset, charBuffer); - currentOffset += 2; - break; - case Frame.ITEM_UNINITIALIZED: - frame[index] = createLabel(readUnsignedShort(currentOffset), labels); - currentOffset += 2; - break; - default: - throw new IllegalArgumentException(); - } - return currentOffset; - } - - // ---------------------------------------------------------------------------------------------- - // Methods to parse attributes - // ---------------------------------------------------------------------------------------------- - - /** - * Returns the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array - * field entry. - * - * @return the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array - * field entry. - */ - final int getFirstAttributeOffset() { - // Skip the access_flags, this_class, super_class, and interfaces_count fields (using 2 bytes - // each), as well as the interfaces array field (2 bytes per interface). - int currentOffset = header + 8 + readUnsignedShort(header + 6) * 2; - - // Read the fields_count field. - int fieldsCount = readUnsignedShort(currentOffset); - currentOffset += 2; - // Skip the 'fields' array field. - while (fieldsCount-- > 0) { - // Invariant: currentOffset is the offset of a field_info structure. - // Skip the access_flags, name_index and descriptor_index fields (2 bytes each), and read the - // attributes_count field. - int attributesCount = readUnsignedShort(currentOffset + 6); - currentOffset += 8; - // Skip the 'attributes' array field. - while (attributesCount-- > 0) { - // Invariant: currentOffset is the offset of an attribute_info structure. - // Read the attribute_length field (2 bytes after the start of the attribute_info) and skip - // this many bytes, plus 6 for the attribute_name_index and attribute_length fields - // (yielding the total size of the attribute_info structure). - currentOffset += 6 + readInt(currentOffset + 2); - } - } - - // Skip the methods_count and 'methods' fields, using the same method as above. - int methodsCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (methodsCount-- > 0) { - int attributesCount = readUnsignedShort(currentOffset + 6); - currentOffset += 8; - while (attributesCount-- > 0) { - currentOffset += 6 + readInt(currentOffset + 2); - } - } - - // Skip the ClassFile's attributes_count field. - return currentOffset + 2; - } - - /** - * Reads the BootstrapMethods attribute to compute the offset of each bootstrap method. - * - * @param maxStringLength a conservative estimate of the maximum length of the strings contained - * in the constant pool of the class. - * @return the offsets of the bootstrap methods. - */ - private int[] readBootstrapMethodsAttribute(final int maxStringLength) { - char[] charBuffer = new char[maxStringLength]; - int currentAttributeOffset = getFirstAttributeOffset(); - int[] currentBootstrapMethodOffsets = null; - for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) { - // Read the attribute_info's attribute_name and attribute_length fields. - String attributeName = readUTF8(currentAttributeOffset, charBuffer); - int attributeLength = readInt(currentAttributeOffset + 2); - currentAttributeOffset += 6; - if (Constants.BOOTSTRAP_METHODS.equals(attributeName)) { - // Read the num_bootstrap_methods field and create an array of this size. - currentBootstrapMethodOffsets = new int[readUnsignedShort(currentAttributeOffset)]; - // Compute and store the offset of each 'bootstrap_methods' array field entry. - int currentBootstrapMethodOffset = currentAttributeOffset + 2; - for (int j = 0; j < currentBootstrapMethodOffsets.length; ++j) { - currentBootstrapMethodOffsets[j] = currentBootstrapMethodOffset; - // Skip the bootstrap_method_ref and num_bootstrap_arguments fields (2 bytes each), - // as well as the bootstrap_arguments array field (of size num_bootstrap_arguments * 2). - currentBootstrapMethodOffset += - 4 + readUnsignedShort(currentBootstrapMethodOffset + 2) * 2; - } - return currentBootstrapMethodOffsets; - } - currentAttributeOffset += attributeLength; - } - throw new IllegalArgumentException(); - } - - /** - * Reads a non standard JVMS 'attribute' structure in {@link #classFileBuffer}. - * - * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of - * the class. Any attribute whose type is not equal to the type of one the prototypes will not - * be parsed: its byte array value will be passed unchanged to the ClassWriter. - * @param type the type of the attribute. - * @param offset the start offset of the JVMS 'attribute' structure in {@link #classFileBuffer}. - * The 6 attribute header bytes (attribute_name_index and attribute_length) are not taken into - * account here. - * @param length the length of the attribute's content (excluding the 6 attribute header bytes). - * @param charBuffer the buffer to be used to read strings in the constant pool. - * @param codeAttributeOffset the start offset of the enclosing Code attribute in {@link - * #classFileBuffer}, or -1 if the attribute to be read is not a code attribute. The 6 - * attribute header bytes (attribute_name_index and attribute_length) are not taken into - * account here. - * @param labels the labels of the method's code, or {@literal null} if the attribute to be read - * is not a code attribute. - * @return the attribute that has been read. - */ - private Attribute readAttribute( - final Attribute[] attributePrototypes, - final String type, - final int offset, - final int length, - final char[] charBuffer, - final int codeAttributeOffset, - final Label[] labels) { - for (Attribute attributePrototype : attributePrototypes) { - if (attributePrototype.type.equals(type)) { - return attributePrototype.read( - this, offset, length, charBuffer, codeAttributeOffset, labels); - } - } - return new Attribute(type).read(this, offset, length, null, -1, null); - } - - // ----------------------------------------------------------------------------------------------- - // Utility methods: low level parsing - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the number of entries in the class's constant pool table. - * - * @return the number of entries in the class's constant pool table. - */ - public int getItemCount() { - return cpInfoOffsets.length; - } - - /** - * Returns the start offset in this {@link ClassReader} of a JVMS 'cp_info' structure (i.e. a - * constant pool entry), plus one. This method is intended for {@link Attribute} sub classes, - * and is normally not needed by class generators or adapters. - * - * @param constantPoolEntryIndex the index a constant pool entry in the class's constant pool - * table. - * @return the start offset in this {@link ClassReader} of the corresponding JVMS 'cp_info' - * structure, plus one. - */ - public int getItem(final int constantPoolEntryIndex) { - return cpInfoOffsets[constantPoolEntryIndex]; - } - - /** - * Returns a conservative estimate of the maximum length of the strings contained in the class's - * constant pool table. - * - * @return a conservative estimate of the maximum length of the strings contained in the class's - * constant pool table. - */ - public int getMaxStringLength() { - return maxStringLength; - } - - /** - * Reads a byte value in this {@link ClassReader}. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param offset the start offset of the value to be read in this {@link ClassReader}. - * @return the read value. - */ - public int readByte(final int offset) { - return classFileBuffer[offset] & 0xFF; - } - - /** - * Reads an unsigned short value in this {@link ClassReader}. This method is intended for - * {@link Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param offset the start index of the value to be read in this {@link ClassReader}. - * @return the read value. - */ - public int readUnsignedShort(final int offset) { - byte[] classBuffer = classFileBuffer; - return ((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF); - } - - /** - * Reads a signed short value in this {@link ClassReader}. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param offset the start offset of the value to be read in this {@link ClassReader}. - * @return the read value. - */ - public short readShort(final int offset) { - byte[] classBuffer = classFileBuffer; - return (short) (((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF)); - } - - /** - * Reads a signed int value in this {@link ClassReader}. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param offset the start offset of the value to be read in this {@link ClassReader}. - * @return the read value. - */ - public int readInt(final int offset) { - byte[] classBuffer = classFileBuffer; - return ((classBuffer[offset] & 0xFF) << 24) - | ((classBuffer[offset + 1] & 0xFF) << 16) - | ((classBuffer[offset + 2] & 0xFF) << 8) - | (classBuffer[offset + 3] & 0xFF); - } - - /** - * Reads a signed long value in this {@link ClassReader}. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param offset the start offset of the value to be read in this {@link ClassReader}. - * @return the read value. - */ - public long readLong(final int offset) { - long l1 = readInt(offset); - long l0 = readInt(offset + 4) & 0xFFFFFFFFL; - return (l1 << 32) | l0; - } - - /** - * Reads a CONSTANT_Utf8 constant pool entry in this {@link ClassReader}. This method is - * intended for {@link Attribute} sub classes, and is normally not needed by class generators or - * adapters. - * - * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose - * value is the index of a CONSTANT_Utf8 entry in the class's constant pool table. - * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified CONSTANT_Utf8 entry. - */ - // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility). - public String readUTF8(final int offset, final char[] charBuffer) { - int constantPoolEntryIndex = readUnsignedShort(offset); - if (offset == 0 || constantPoolEntryIndex == 0) { - return null; - } - return readUtf(constantPoolEntryIndex, charBuffer); - } - - /** - * Reads a CONSTANT_Utf8 constant pool entry in {@link #classFileBuffer}. - * - * @param constantPoolEntryIndex the index of a CONSTANT_Utf8 entry in the class's constant pool - * table. - * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified CONSTANT_Utf8 entry. - */ - final String readUtf(final int constantPoolEntryIndex, final char[] charBuffer) { - String value = constantUtf8Values[constantPoolEntryIndex]; - if (value != null) { - return value; - } - int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex]; - return constantUtf8Values[constantPoolEntryIndex] = - readUtf(cpInfoOffset + 2, readUnsignedShort(cpInfoOffset), charBuffer); - } - - /** - * Reads an UTF8 string in {@link #classFileBuffer}. - * - * @param utfOffset the start offset of the UTF8 string to be read. - * @param utfLength the length of the UTF8 string to be read. - * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified UTF8 string. - */ - private String readUtf(final int utfOffset, final int utfLength, final char[] charBuffer) { - int currentOffset = utfOffset; - int endOffset = currentOffset + utfLength; - int strLength = 0; - byte[] classBuffer = classFileBuffer; - while (currentOffset < endOffset) { - int currentByte = classBuffer[currentOffset++]; - if ((currentByte & 0x80) == 0) { - charBuffer[strLength++] = (char) (currentByte & 0x7F); - } else if ((currentByte & 0xE0) == 0xC0) { - charBuffer[strLength++] = - (char) (((currentByte & 0x1F) << 6) + (classBuffer[currentOffset++] & 0x3F)); - } else { - charBuffer[strLength++] = - (char) - (((currentByte & 0xF) << 12) - + ((classBuffer[currentOffset++] & 0x3F) << 6) - + (classBuffer[currentOffset++] & 0x3F)); - } - } - return new String(charBuffer, 0, strLength); - } - - /** - * Reads a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, CONSTANT_Module or - * CONSTANT_Package constant pool entry in {@link #classFileBuffer}. This method is intended - * for {@link Attribute} sub classes, and is normally not needed by class generators or - * adapters. - * - * @param offset the start offset of an unsigned short value in {@link #classFileBuffer}, whose - * value is the index of a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, - * CONSTANT_Module or CONSTANT_Package entry in class's constant pool table. - * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified constant pool entry. - */ - private String readStringish(final int offset, final char[] charBuffer) { - // Get the start offset of the cp_info structure (plus one), and read the CONSTANT_Utf8 entry - // designated by the first two bytes of this cp_info. - return readUTF8(cpInfoOffsets[readUnsignedShort(offset)], charBuffer); - } - - /** - * Reads a CONSTANT_Class constant pool entry in this {@link ClassReader}. This method is - * intended for {@link Attribute} sub classes, and is normally not needed by class generators or - * adapters. - * - * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose - * value is the index of a CONSTANT_Class entry in class's constant pool table. - * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified CONSTANT_Class entry. - */ - public String readClass(final int offset, final char[] charBuffer) { - return readStringish(offset, charBuffer); - } - - /** - * Reads a CONSTANT_Module constant pool entry in this {@link ClassReader}. This method is - * intended for {@link Attribute} sub classes, and is normally not needed by class generators or - * adapters. - * - * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose - * value is the index of a CONSTANT_Module entry in class's constant pool table. - * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified CONSTANT_Module entry. - */ - public String readModule(final int offset, final char[] charBuffer) { - return readStringish(offset, charBuffer); - } - - /** - * Reads a CONSTANT_Package constant pool entry in this {@link ClassReader}. This method is - * intended for {@link Attribute} sub classes, and is normally not needed by class generators or - * adapters. - * - * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose - * value is the index of a CONSTANT_Package entry in class's constant pool table. - * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified CONSTANT_Package entry. - */ - public String readPackage(final int offset, final char[] charBuffer) { - return readStringish(offset, charBuffer); - } - - /** - * Reads a CONSTANT_Dynamic constant pool entry in {@link #classFileBuffer}. - * - * @param constantPoolEntryIndex the index of a CONSTANT_Dynamic entry in the class's constant - * pool table. - * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the ConstantDynamic corresponding to the specified CONSTANT_Dynamic entry. - */ - private ConstantDynamic readConstantDynamic( - final int constantPoolEntryIndex, final char[] charBuffer) { - ConstantDynamic constantDynamic = constantDynamicValues[constantPoolEntryIndex]; - if (constantDynamic != null) { - return constantDynamic; - } - int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex]; - int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)]; - String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); - String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); - int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)]; - Handle handle = (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); - Object[] bootstrapMethodArguments = new Object[readUnsignedShort(bootstrapMethodOffset + 2)]; - bootstrapMethodOffset += 4; - for (int i = 0; i < bootstrapMethodArguments.length; i++) { - bootstrapMethodArguments[i] = readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); - bootstrapMethodOffset += 2; - } - return constantDynamicValues[constantPoolEntryIndex] = - new ConstantDynamic(name, descriptor, handle, bootstrapMethodArguments); - } - - /** - * Reads a numeric or string constant pool entry in this {@link ClassReader}. This method is - * intended for {@link Attribute} sub classes, and is normally not needed by class generators or - * adapters. - * - * @param constantPoolEntryIndex the index of a CONSTANT_Integer, CONSTANT_Float, CONSTANT_Long, - * CONSTANT_Double, CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, - * CONSTANT_MethodHandle or CONSTANT_Dynamic entry in the class's constant pool. - * @param charBuffer the buffer to be used to read strings. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the {@link Integer}, {@link Float}, {@link Long}, {@link Double}, {@link String}, - * {@link Type}, {@link Handle} or {@link ConstantDynamic} corresponding to the specified - * constant pool entry. - */ - public Object readConst(final int constantPoolEntryIndex, final char[] charBuffer) { - int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex]; - switch (classFileBuffer[cpInfoOffset - 1]) { - case Symbol.CONSTANT_INTEGER_TAG: - return readInt(cpInfoOffset); - case Symbol.CONSTANT_FLOAT_TAG: - return Float.intBitsToFloat(readInt(cpInfoOffset)); - case Symbol.CONSTANT_LONG_TAG: - return readLong(cpInfoOffset); - case Symbol.CONSTANT_DOUBLE_TAG: - return Double.longBitsToDouble(readLong(cpInfoOffset)); - case Symbol.CONSTANT_CLASS_TAG: - return Type.getObjectType(readUTF8(cpInfoOffset, charBuffer)); - case Symbol.CONSTANT_STRING_TAG: - return readUTF8(cpInfoOffset, charBuffer); - case Symbol.CONSTANT_METHOD_TYPE_TAG: - return Type.getMethodType(readUTF8(cpInfoOffset, charBuffer)); - case Symbol.CONSTANT_METHOD_HANDLE_TAG: - int referenceKind = readByte(cpInfoOffset); - int referenceCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 1)]; - int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(referenceCpInfoOffset + 2)]; - String owner = readClass(referenceCpInfoOffset, charBuffer); - String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); - String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); - boolean isInterface = - classFileBuffer[referenceCpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG; - return new Handle(referenceKind, owner, name, descriptor, isInterface); - case Symbol.CONSTANT_DYNAMIC_TAG: - return readConstantDynamic(constantPoolEntryIndex, charBuffer); - default: - throw new IllegalArgumentException(); - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/ClassTooLargeException.java b/jodd-proxetta/src/main/java/jodd/asm7/ClassTooLargeException.java deleted file mode 100644 index 89c09970a..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/ClassTooLargeException.java +++ /dev/null @@ -1,71 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * Exception thrown when the constant pool of a class produced by a {@link ClassWriter} is too - * large. - * - * @author Jason Zaugg - */ -public final class ClassTooLargeException extends IndexOutOfBoundsException { - private static final long serialVersionUID = 160715609518896765L; - - private final String className; - private final int constantPoolCount; - - /** - * Constructs a new {@link ClassTooLargeException}. - * - * @param className the internal name of the class. - * @param constantPoolCount the number of constant pool items of the class. - */ - public ClassTooLargeException(final String className, final int constantPoolCount) { - super("Class too large: " + className); - this.className = className; - this.constantPoolCount = constantPoolCount; - } - - /** - * Returns the internal name of the class. - * - * @return the internal name of the class. - */ - public String getClassName() { - return className; - } - - /** - * Returns the number of constant pool items of the class. - * - * @return the number of constant pool items of the class. - */ - public int getConstantPoolCount() { - return constantPoolCount; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/ClassVisitor.java b/jodd-proxetta/src/main/java/jodd/asm7/ClassVisitor.java deleted file mode 100644 index 1fc7afa99..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/ClassVisitor.java +++ /dev/null @@ -1,329 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * A visitor to visit a Java class. The methods of this class must be called in the following order: - * {@code visit} [ {@code visitSource} ] [ {@code visitModule} ][ {@code visitNestHost} ][ {@code - * visitOuterClass} ] ( {@code visitAnnotation} | {@code visitTypeAnnotation} | {@code - * visitAttribute} )* ( {@code visitNestMember} | {@code visitInnerClass} | {@code visitField} | - * {@code visitMethod} )* {@code visitEnd}. - * - * @author Eric Bruneton - */ -public abstract class ClassVisitor { - - /** - * The ASM API version implemented by this visitor. The value of this field must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - */ - protected final int api; - - /** The class visitor to which this visitor must delegate method calls. May be null. */ - protected ClassVisitor cv; - - /** - * Constructs a new {@link ClassVisitor}. - * - * @param api the ASM API version implemented by this visitor. Must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - */ - public ClassVisitor(final int api) { - this(api, null); - } - - /** - * Constructs a new {@link ClassVisitor}. - * - * @param api the ASM API version implemented by this visitor. Must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - * @param classVisitor the class visitor to which this visitor must delegate method calls. May be - * null. - */ - public ClassVisitor(final int api, final ClassVisitor classVisitor) { - if (api != Opcodes.ASM7 && api != Opcodes.ASM6 && api != Opcodes.ASM5 && api != Opcodes.ASM4) { - throw new IllegalArgumentException("Unsupported api " + api); - } - this.api = api; - this.cv = classVisitor; - } - - /** - * Visits the header of the class. - * - * @param version the class version. The minor version is stored in the 16 most significant bits, - * and the major version in the 16 least significant bits. - * @param access the class's access flags (see {@link Opcodes}). This parameter also indicates if - * the class is deprecated. - * @param name the internal name of the class (see {@link Type#getInternalName()}). - * @param signature the signature of this class. May be {@literal null} if the class is not a - * generic one, and does not extend or implement generic classes or interfaces. - * @param superName the internal of name of the super class (see {@link Type#getInternalName()}). - * For interfaces, the super class is {@link Object}. May be {@literal null}, but only for the - * {@link Object} class. - * @param interfaces the internal names of the class's interfaces (see {@link - * Type#getInternalName()}). May be {@literal null}. - */ - public void visit( - final int version, - final int access, - final String name, - final String signature, - final String superName, - final String[] interfaces) { - if (cv != null) { - cv.visit(version, access, name, signature, superName, interfaces); - } - } - - /** - * Visits the source of the class. - * - * @param source the name of the source file from which the class was compiled. May be {@literal - * null}. - * @param debug additional debug information to compute the correspondence between source and - * compiled elements of the class. May be {@literal null}. - */ - public void visitSource(final String source, final String debug) { - if (cv != null) { - cv.visitSource(source, debug); - } - } - - /** - * Visit the module corresponding to the class. - * - * @param name the fully qualified name (using dots) of the module. - * @param access the module access flags, among {@code ACC_OPEN}, {@code ACC_SYNTHETIC} and {@code - * ACC_MANDATED}. - * @param version the module version, or {@literal null}. - * @return a visitor to visit the module values, or {@literal null} if this visitor is not - * interested in visiting this module. - */ - public ModuleVisitor visitModule(final String name, final int access, final String version) { - if (api < Opcodes.ASM6) { - throw new UnsupportedOperationException("This feature requires ASM6"); - } - if (cv != null) { - return cv.visitModule(name, access, version); - } - return null; - } - - /** - * Visits the nest host class of the class. A nest is a set of classes of the same package that - * share access to their private members. One of these classes, called the host, lists the other - * members of the nest, which in turn should link to the host of their nest. This method must be - * called only once and only if the visited class is a non-host member of a nest. A class is - * implicitly its own nest, so it's invalid to call this method with the visited class name as - * argument. - * - * @param nestHost the internal name of the host class of the nest. - */ - public void visitNestHost(final String nestHost) { - if (api < Opcodes.ASM7) { - throw new UnsupportedOperationException("This feature requires ASM7"); - } - if (cv != null) { - cv.visitNestHost(nestHost); - } - } - - /** - * Visits the enclosing class of the class. This method must be called only if the class has an - * enclosing class. - * - * @param owner internal name of the enclosing class of the class. - * @param name the name of the method that contains the class, or {@literal null} if the class is - * not enclosed in a method of its enclosing class. - * @param descriptor the descriptor of the method that contains the class, or {@literal null} if - * the class is not enclosed in a method of its enclosing class. - */ - public void visitOuterClass(final String owner, final String name, final String descriptor) { - if (cv != null) { - cv.visitOuterClass(owner, name, descriptor); - } - } - - /** - * Visits an annotation of the class. - * - * @param descriptor the class descriptor of the annotation class. - * @param visible {@literal true} if the annotation is visible at runtime. - * @return a visitor to visit the annotation values, or {@literal null} if this visitor is not - * interested in visiting this annotation. - */ - public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) { - if (cv != null) { - return cv.visitAnnotation(descriptor, visible); - } - return null; - } - - /** - * Visits an annotation on a type in the class signature. - * - * @param typeRef a reference to the annotated type. The sort of this type reference must be - * {@link TypeReference#CLASS_TYPE_PARAMETER}, {@link - * TypeReference#CLASS_TYPE_PARAMETER_BOUND} or {@link TypeReference#CLASS_EXTENDS}. See - * {@link TypeReference}. - * @param typePath the path to the annotated type argument, wildcard bound, array element type, or - * static inner type within 'typeRef'. May be {@literal null} if the annotation targets - * 'typeRef' as a whole. - * @param descriptor the class descriptor of the annotation class. - * @param visible {@literal true} if the annotation is visible at runtime. - * @return a visitor to visit the annotation values, or {@literal null} if this visitor is not - * interested in visiting this annotation. - */ - public AnnotationVisitor visitTypeAnnotation( - final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { - if (api < Opcodes.ASM5) { - throw new UnsupportedOperationException("This feature requires ASM5"); - } - if (cv != null) { - return cv.visitTypeAnnotation(typeRef, typePath, descriptor, visible); - } - return null; - } - - /** - * Visits a non standard attribute of the class. - * - * @param attribute an attribute. - */ - public void visitAttribute(final Attribute attribute) { - if (cv != null) { - cv.visitAttribute(attribute); - } - } - - /** - * Visits a member of the nest. A nest is a set of classes of the same package that share access - * to their private members. One of these classes, called the host, lists the other members of the - * nest, which in turn should link to the host of their nest. This method must be called only if - * the visited class is the host of a nest. A nest host is implicitly a member of its own nest, so - * it's invalid to call this method with the visited class name as argument. - * - * @param nestMember the internal name of a nest member. - */ - public void visitNestMember(final String nestMember) { - if (api < Opcodes.ASM7) { - throw new UnsupportedOperationException("This feature requires ASM7"); - } - if (cv != null) { - cv.visitNestMember(nestMember); - } - } - - /** - * Visits information about an inner class. This inner class is not necessarily a member of the - * class being visited. - * - * @param name the internal name of an inner class (see {@link Type#getInternalName()}). - * @param outerName the internal name of the class to which the inner class belongs (see {@link - * Type#getInternalName()}). May be {@literal null} for not member classes. - * @param innerName the (simple) name of the inner class inside its enclosing class. May be - * {@literal null} for anonymous inner classes. - * @param access the access flags of the inner class as originally declared in the enclosing - * class. - */ - public void visitInnerClass( - final String name, final String outerName, final String innerName, final int access) { - if (cv != null) { - cv.visitInnerClass(name, outerName, innerName, access); - } - } - - /** - * Visits a field of the class. - * - * @param access the field's access flags (see {@link Opcodes}). This parameter also indicates if - * the field is synthetic and/or deprecated. - * @param name the field's name. - * @param descriptor the field's descriptor (see {@link Type}). - * @param signature the field's signature. May be {@literal null} if the field's type does not use - * generic types. - * @param value the field's initial value. This parameter, which may be {@literal null} if the - * field does not have an initial value, must be an {@link Integer}, a {@link Float}, a {@link - * Long}, a {@link Double} or a {@link String} (for {@code int}, {@code float}, {@code long} - * or {@code String} fields respectively). This parameter is only used for static - * fields. Its value is ignored for non static fields, which must be initialized through - * bytecode instructions in constructors or methods. - * @return a visitor to visit field annotations and attributes, or {@literal null} if this class - * visitor is not interested in visiting these annotations and attributes. - */ - public FieldVisitor visitField( - final int access, - final String name, - final String descriptor, - final String signature, - final Object value) { - if (cv != null) { - return cv.visitField(access, name, descriptor, signature, value); - } - return null; - } - - /** - * Visits a method of the class. This method must return a new {@link MethodVisitor} - * instance (or {@literal null}) each time it is called, i.e., it should not return a previously - * returned visitor. - * - * @param access the method's access flags (see {@link Opcodes}). This parameter also indicates if - * the method is synthetic and/or deprecated. - * @param name the method's name. - * @param descriptor the method's descriptor (see {@link Type}). - * @param signature the method's signature. May be {@literal null} if the method parameters, - * return type and exceptions do not use generic types. - * @param exceptions the internal names of the method's exception classes (see {@link - * Type#getInternalName()}). May be {@literal null}. - * @return an object to visit the byte code of the method, or {@literal null} if this class - * visitor is not interested in visiting the code of this method. - */ - public MethodVisitor visitMethod( - final int access, - final String name, - final String descriptor, - final String signature, - final String[] exceptions) { - if (cv != null) { - return cv.visitMethod(access, name, descriptor, signature, exceptions); - } - return null; - } - - /** - * Visits the end of the class. This method, which is the last one to be called, is used to inform - * the visitor that all the fields and methods of the class have been visited. - */ - public void visitEnd() { - if (cv != null) { - cv.visitEnd(); - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/ClassWriter.java b/jodd-proxetta/src/main/java/jodd/asm7/ClassWriter.java deleted file mode 100644 index 796c5831d..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/ClassWriter.java +++ /dev/null @@ -1,965 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * A {@link ClassVisitor} that generates a corresponding ClassFile structure, as defined in the Java - * Virtual Machine Specification (JVMS). It can be used alone, to generate a Java class "from - * scratch", or with one or more {@link ClassReader} and adapter {@link ClassVisitor} to generate a - * modified class from one or more existing Java classes. - * - * @see JVMS 4 - * @author Eric Bruneton - */ -public class ClassWriter extends ClassVisitor { - - /** - * A flag to automatically compute the maximum stack size and the maximum number of local - * variables of methods. If this flag is set, then the arguments of the {@link - * MethodVisitor#visitMaxs} method of the {@link MethodVisitor} returned by the {@link - * #visitMethod} method will be ignored, and computed automatically from the signature and the - * bytecode of each method. - * - *

Note: for classes whose version is {@link Opcodes#V1_7} of more, this option requires - * valid stack map frames. The maximum stack size is then computed from these frames, and from the - * bytecode instructions in between. If stack map frames are not present or must be recomputed, - * used {@link #COMPUTE_FRAMES} instead. - * - * @see #ClassWriter(int) - */ - public static final int COMPUTE_MAXS = 1; - - /** - * A flag to automatically compute the stack map frames of methods from scratch. If this flag is - * set, then the calls to the {@link MethodVisitor#visitFrame} method are ignored, and the stack - * map frames are recomputed from the methods bytecode. The arguments of the {@link - * MethodVisitor#visitMaxs} method are also ignored and recomputed from the bytecode. In other - * words, {@link #COMPUTE_FRAMES} implies {@link #COMPUTE_MAXS}. - * - * @see #ClassWriter(int) - */ - public static final int COMPUTE_FRAMES = 2; - - // Note: fields are ordered as in the ClassFile structure, and those related to attributes are - // ordered as in Section 4.7 of the JVMS. - - /** - * The minor_version and major_version fields of the JVMS ClassFile structure. minor_version is - * stored in the 16 most significant bits, and major_version in the 16 least significant bits. - */ - private int version; - - /** The symbol table for this class (contains the constant_pool and the BootstrapMethods). */ - private final SymbolTable symbolTable; - - /** - * The access_flags field of the JVMS ClassFile structure. This field can contain ASM specific - * access flags, such as {@link Opcodes#ACC_DEPRECATED}, which are removed when generating the - * ClassFile structure. - */ - private int accessFlags; - - /** The this_class field of the JVMS ClassFile structure. */ - private int thisClass; - - /** The super_class field of the JVMS ClassFile structure. */ - private int superClass; - - /** The interface_count field of the JVMS ClassFile structure. */ - private int interfaceCount; - - /** The 'interfaces' array of the JVMS ClassFile structure. */ - private int[] interfaces; - - /** - * The fields of this class, stored in a linked list of {@link FieldWriter} linked via their - * {@link FieldWriter#fv} field. This field stores the first element of this list. - */ - private FieldWriter firstField; - - /** - * The fields of this class, stored in a linked list of {@link FieldWriter} linked via their - * {@link FieldWriter#fv} field. This field stores the last element of this list. - */ - private FieldWriter lastField; - - /** - * The methods of this class, stored in a linked list of {@link MethodWriter} linked via their - * {@link MethodWriter#mv} field. This field stores the first element of this list. - */ - private MethodWriter firstMethod; - - /** - * The methods of this class, stored in a linked list of {@link MethodWriter} linked via their - * {@link MethodWriter#mv} field. This field stores the last element of this list. - */ - private MethodWriter lastMethod; - - /** The number_of_classes field of the InnerClasses attribute, or 0. */ - private int numberOfInnerClasses; - - /** The 'classes' array of the InnerClasses attribute, or {@literal null}. */ - private ByteVector innerClasses; - - /** The class_index field of the EnclosingMethod attribute, or 0. */ - private int enclosingClassIndex; - - /** The method_index field of the EnclosingMethod attribute. */ - private int enclosingMethodIndex; - - /** The signature_index field of the Signature attribute, or 0. */ - private int signatureIndex; - - /** The source_file_index field of the SourceFile attribute, or 0. */ - private int sourceFileIndex; - - /** The debug_extension field of the SourceDebugExtension attribute, or {@literal null}. */ - private ByteVector debugExtension; - - /** - * The last runtime visible annotation of this class. The previous ones can be accessed with the - * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeVisibleAnnotation; - - /** - * The last runtime invisible annotation of this class. The previous ones can be accessed with the - * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeInvisibleAnnotation; - - /** - * The last runtime visible type annotation of this class. The previous ones can be accessed with - * the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeVisibleTypeAnnotation; - - /** - * The last runtime invisible type annotation of this class. The previous ones can be accessed - * with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeInvisibleTypeAnnotation; - - /** The Module attribute of this class, or {@literal null}. */ - private ModuleWriter moduleWriter; - - /** The host_class_index field of the NestHost attribute, or 0. */ - private int nestHostClassIndex; - - /** The number_of_classes field of the NestMembers attribute, or 0. */ - private int numberOfNestMemberClasses; - - /** The 'classes' array of the NestMembers attribute, or {@literal null}. */ - private ByteVector nestMemberClasses; - - /** - * The first non standard attribute of this class. The next ones can be accessed with the {@link - * Attribute#nextAttribute} field. May be {@literal null}. - * - *

WARNING: this list stores the attributes in the reverse order of their visit. - * firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link - * #toByteArray} method writes the attributes in the order defined by this list, i.e. in the - * reverse order specified by the user. - */ - private Attribute firstAttribute; - - /** - * Indicates what must be automatically computed in {@link MethodWriter}. Must be one of {@link - * MethodWriter#COMPUTE_NOTHING}, {@link MethodWriter#COMPUTE_MAX_STACK_AND_LOCAL}, {@link - * MethodWriter#COMPUTE_INSERTED_FRAMES}, or {@link MethodWriter#COMPUTE_ALL_FRAMES}. - */ - private int compute; - - // ----------------------------------------------------------------------------------------------- - // Constructor - // ----------------------------------------------------------------------------------------------- - - /** - * Constructs a new {@link ClassWriter} object. - * - * @param flags option flags that can be used to modify the default behavior of this class. Must - * be zero or more of {@link #COMPUTE_MAXS} and {@link #COMPUTE_FRAMES}. - */ - public ClassWriter(final int flags) { - this(null, flags); - } - - /** - * Constructs a new {@link ClassWriter} object and enables optimizations for "mostly add" bytecode - * transformations. These optimizations are the following: - * - *

    - *
  • The constant pool and bootstrap methods from the original class are copied as is in the - * new class, which saves time. New constant pool entries and new bootstrap methods will be - * added at the end if necessary, but unused constant pool entries or bootstrap methods - * won't be removed. - *
  • Methods that are not transformed are copied as is in the new class, directly from the - * original class bytecode (i.e. without emitting visit events for all the method - * instructions), which saves a lot of time. Untransformed methods are detected by - * the fact that the {@link ClassReader} receives {@link MethodVisitor} objects that come - * from a {@link ClassWriter} (and not from any other {@link ClassVisitor} instance). - *
- * - * @param classReader the {@link ClassReader} used to read the original class. It will be used to - * copy the entire constant pool and bootstrap methods from the original class and also to - * copy other fragments of original bytecode where applicable. - * @param flags option flags that can be used to modify the default behavior of this class.Must be - * zero or more of {@link #COMPUTE_MAXS} and {@link #COMPUTE_FRAMES}. These option flags do - * not affect methods that are copied as is in the new class. This means that neither the - * maximum stack size nor the stack frames will be computed for these methods. - */ - public ClassWriter(final ClassReader classReader, final int flags) { - super(Opcodes.ASM7); - symbolTable = classReader == null ? new SymbolTable(this) : new SymbolTable(this, classReader); - if ((flags & COMPUTE_FRAMES) != 0) { - this.compute = MethodWriter.COMPUTE_ALL_FRAMES; - } else if ((flags & COMPUTE_MAXS) != 0) { - this.compute = MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL; - } else { - this.compute = MethodWriter.COMPUTE_NOTHING; - } - } - - // ----------------------------------------------------------------------------------------------- - // Implementation of the ClassVisitor abstract class - // ----------------------------------------------------------------------------------------------- - - @Override - public final void visit( - final int version, - final int access, - final String name, - final String signature, - final String superName, - final String[] interfaces) { - this.version = version; - this.accessFlags = access; - this.thisClass = symbolTable.setMajorVersionAndClassName(version & 0xFFFF, name); - if (signature != null) { - this.signatureIndex = symbolTable.addConstantUtf8(signature); - } - this.superClass = superName == null ? 0 : symbolTable.addConstantClass(superName).index; - if (interfaces != null && interfaces.length > 0) { - interfaceCount = interfaces.length; - this.interfaces = new int[interfaceCount]; - for (int i = 0; i < interfaceCount; ++i) { - this.interfaces[i] = symbolTable.addConstantClass(interfaces[i]).index; - } - } - if (compute == MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL && (version & 0xFFFF) >= Opcodes.V1_7) { - compute = MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES; - } - } - - @Override - public final void visitSource(final String file, final String debug) { - if (file != null) { - sourceFileIndex = symbolTable.addConstantUtf8(file); - } - if (debug != null) { - debugExtension = new ByteVector().encodeUtf8(debug, 0, Integer.MAX_VALUE); - } - } - - @Override - public final ModuleVisitor visitModule( - final String name, final int access, final String version) { - return moduleWriter = - new ModuleWriter( - symbolTable, - symbolTable.addConstantModule(name).index, - access, - version == null ? 0 : symbolTable.addConstantUtf8(version)); - } - - @Override - public void visitNestHost(final String nestHost) { - nestHostClassIndex = symbolTable.addConstantClass(nestHost).index; - } - - @Override - public final void visitOuterClass( - final String owner, final String name, final String descriptor) { - enclosingClassIndex = symbolTable.addConstantClass(owner).index; - if (name != null && descriptor != null) { - enclosingMethodIndex = symbolTable.addConstantNameAndType(name, descriptor); - } - } - - @Override - public final AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) { - if (visible) { - return lastRuntimeVisibleAnnotation = - AnnotationWriter.create(symbolTable, descriptor, lastRuntimeVisibleAnnotation); - } else { - return lastRuntimeInvisibleAnnotation = - AnnotationWriter.create(symbolTable, descriptor, lastRuntimeInvisibleAnnotation); - } - } - - @Override - public final AnnotationVisitor visitTypeAnnotation( - final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { - if (visible) { - return lastRuntimeVisibleTypeAnnotation = - AnnotationWriter.create( - symbolTable, typeRef, typePath, descriptor, lastRuntimeVisibleTypeAnnotation); - } else { - return lastRuntimeInvisibleTypeAnnotation = - AnnotationWriter.create( - symbolTable, typeRef, typePath, descriptor, lastRuntimeInvisibleTypeAnnotation); - } - } - - @Override - public final void visitAttribute(final Attribute attribute) { - // Store the attributes in the reverse order of their visit by this method. - attribute.nextAttribute = firstAttribute; - firstAttribute = attribute; - } - - @Override - public void visitNestMember(final String nestMember) { - if (nestMemberClasses == null) { - nestMemberClasses = new ByteVector(); - } - ++numberOfNestMemberClasses; - nestMemberClasses.putShort(symbolTable.addConstantClass(nestMember).index); - } - - @Override - public final void visitInnerClass( - final String name, final String outerName, final String innerName, final int access) { - if (innerClasses == null) { - innerClasses = new ByteVector(); - } - // Section 4.7.6 of the JVMS states "Every CONSTANT_Class_info entry in the constant_pool table - // which represents a class or interface C that is not a package member must have exactly one - // corresponding entry in the classes array". To avoid duplicates we keep track in the info - // field of the Symbol of each CONSTANT_Class_info entry C whether an inner class entry has - // already been added for C. If so, we store the index of this inner class entry (plus one) in - // the info field. This trick allows duplicate detection in O(1) time. - Symbol nameSymbol = symbolTable.addConstantClass(name); - if (nameSymbol.info == 0) { - ++numberOfInnerClasses; - innerClasses.putShort(nameSymbol.index); - innerClasses.putShort(outerName == null ? 0 : symbolTable.addConstantClass(outerName).index); - innerClasses.putShort(innerName == null ? 0 : symbolTable.addConstantUtf8(innerName)); - innerClasses.putShort(access); - nameSymbol.info = numberOfInnerClasses; - } - // Else, compare the inner classes entry nameSymbol.info - 1 with the arguments of this method - // and throw an exception if there is a difference? - } - - @Override - public final FieldVisitor visitField( - final int access, - final String name, - final String descriptor, - final String signature, - final Object value) { - FieldWriter fieldWriter = - new FieldWriter(symbolTable, access, name, descriptor, signature, value); - if (firstField == null) { - firstField = fieldWriter; - } else { - lastField.fv = fieldWriter; - } - return lastField = fieldWriter; - } - - @Override - public final MethodVisitor visitMethod( - final int access, - final String name, - final String descriptor, - final String signature, - final String[] exceptions) { - MethodWriter methodWriter = - new MethodWriter(symbolTable, access, name, descriptor, signature, exceptions, compute); - if (firstMethod == null) { - firstMethod = methodWriter; - } else { - lastMethod.mv = methodWriter; - } - return lastMethod = methodWriter; - } - - @Override - public final void visitEnd() { - // Nothing to do. - } - - // ----------------------------------------------------------------------------------------------- - // Other public methods - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the content of the class file that was built by this ClassWriter. - * - * @return the binary content of the JVMS ClassFile structure that was built by this ClassWriter. - * @throws ClassTooLargeException if the constant pool of the class is too large. - * @throws MethodTooLargeException if the Code attribute of a method is too large. - */ - public byte[] toByteArray() { - // First step: compute the size in bytes of the ClassFile structure. - // The magic field uses 4 bytes, 10 mandatory fields (minor_version, major_version, - // constant_pool_count, access_flags, this_class, super_class, interfaces_count, fields_count, - // methods_count and attributes_count) use 2 bytes each, and each interface uses 2 bytes too. - int size = 24 + 2 * interfaceCount; - int fieldsCount = 0; - FieldWriter fieldWriter = firstField; - while (fieldWriter != null) { - ++fieldsCount; - size += fieldWriter.computeFieldInfoSize(); - fieldWriter = (FieldWriter) fieldWriter.fv; - } - int methodsCount = 0; - MethodWriter methodWriter = firstMethod; - while (methodWriter != null) { - ++methodsCount; - size += methodWriter.computeMethodInfoSize(); - methodWriter = (MethodWriter) methodWriter.mv; - } - // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. - int attributesCount = 0; - if (innerClasses != null) { - ++attributesCount; - size += 8 + innerClasses.length; - symbolTable.addConstantUtf8(Constants.INNER_CLASSES); - } - if (enclosingClassIndex != 0) { - ++attributesCount; - size += 10; - symbolTable.addConstantUtf8(Constants.ENCLOSING_METHOD); - } - if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && (version & 0xFFFF) < Opcodes.V1_5) { - ++attributesCount; - size += 6; - symbolTable.addConstantUtf8(Constants.SYNTHETIC); - } - if (signatureIndex != 0) { - ++attributesCount; - size += 8; - symbolTable.addConstantUtf8(Constants.SIGNATURE); - } - if (sourceFileIndex != 0) { - ++attributesCount; - size += 8; - symbolTable.addConstantUtf8(Constants.SOURCE_FILE); - } - if (debugExtension != null) { - ++attributesCount; - size += 6 + debugExtension.length; - symbolTable.addConstantUtf8(Constants.SOURCE_DEBUG_EXTENSION); - } - if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) { - ++attributesCount; - size += 6; - symbolTable.addConstantUtf8(Constants.DEPRECATED); - } - if (lastRuntimeVisibleAnnotation != null) { - ++attributesCount; - size += - lastRuntimeVisibleAnnotation.computeAnnotationsSize( - Constants.RUNTIME_VISIBLE_ANNOTATIONS); - } - if (lastRuntimeInvisibleAnnotation != null) { - ++attributesCount; - size += - lastRuntimeInvisibleAnnotation.computeAnnotationsSize( - Constants.RUNTIME_INVISIBLE_ANNOTATIONS); - } - if (lastRuntimeVisibleTypeAnnotation != null) { - ++attributesCount; - size += - lastRuntimeVisibleTypeAnnotation.computeAnnotationsSize( - Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS); - } - if (lastRuntimeInvisibleTypeAnnotation != null) { - ++attributesCount; - size += - lastRuntimeInvisibleTypeAnnotation.computeAnnotationsSize( - Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS); - } - if (symbolTable.computeBootstrapMethodsSize() > 0) { - ++attributesCount; - size += symbolTable.computeBootstrapMethodsSize(); - } - if (moduleWriter != null) { - attributesCount += moduleWriter.getAttributeCount(); - size += moduleWriter.computeAttributesSize(); - } - if (nestHostClassIndex != 0) { - ++attributesCount; - size += 8; - symbolTable.addConstantUtf8(Constants.NEST_HOST); - } - if (nestMemberClasses != null) { - ++attributesCount; - size += 8 + nestMemberClasses.length; - symbolTable.addConstantUtf8(Constants.NEST_MEMBERS); - } - if (firstAttribute != null) { - attributesCount += firstAttribute.getAttributeCount(); - size += firstAttribute.computeAttributesSize(symbolTable); - } - // IMPORTANT: this must be the last part of the ClassFile size computation, because the previous - // statements can add attribute names to the constant pool, thereby changing its size! - size += symbolTable.getConstantPoolLength(); - int constantPoolCount = symbolTable.getConstantPoolCount(); - if (constantPoolCount > 0xFFFF) { - throw new ClassTooLargeException(symbolTable.getClassName(), constantPoolCount); - } - - // Second step: allocate a ByteVector of the correct size (in order to avoid any array copy in - // dynamic resizes) and fill it with the ClassFile content. - ByteVector result = new ByteVector(size); - result.putInt(0xCAFEBABE).putInt(version); - symbolTable.putConstantPool(result); - int mask = (version & 0xFFFF) < Opcodes.V1_5 ? Opcodes.ACC_SYNTHETIC : 0; - result.putShort(accessFlags & ~mask).putShort(thisClass).putShort(superClass); - result.putShort(interfaceCount); - for (int i = 0; i < interfaceCount; ++i) { - result.putShort(interfaces[i]); - } - result.putShort(fieldsCount); - fieldWriter = firstField; - while (fieldWriter != null) { - fieldWriter.putFieldInfo(result); - fieldWriter = (FieldWriter) fieldWriter.fv; - } - result.putShort(methodsCount); - boolean hasFrames = false; - boolean hasAsmInstructions = false; - methodWriter = firstMethod; - while (methodWriter != null) { - hasFrames |= methodWriter.hasFrames(); - hasAsmInstructions |= methodWriter.hasAsmInstructions(); - methodWriter.putMethodInfo(result); - methodWriter = (MethodWriter) methodWriter.mv; - } - // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. - result.putShort(attributesCount); - if (innerClasses != null) { - result - .putShort(symbolTable.addConstantUtf8(Constants.INNER_CLASSES)) - .putInt(innerClasses.length + 2) - .putShort(numberOfInnerClasses) - .putByteArray(innerClasses.data, 0, innerClasses.length); - } - if (enclosingClassIndex != 0) { - result - .putShort(symbolTable.addConstantUtf8(Constants.ENCLOSING_METHOD)) - .putInt(4) - .putShort(enclosingClassIndex) - .putShort(enclosingMethodIndex); - } - if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && (version & 0xFFFF) < Opcodes.V1_5) { - result.putShort(symbolTable.addConstantUtf8(Constants.SYNTHETIC)).putInt(0); - } - if (signatureIndex != 0) { - result - .putShort(symbolTable.addConstantUtf8(Constants.SIGNATURE)) - .putInt(2) - .putShort(signatureIndex); - } - if (sourceFileIndex != 0) { - result - .putShort(symbolTable.addConstantUtf8(Constants.SOURCE_FILE)) - .putInt(2) - .putShort(sourceFileIndex); - } - if (debugExtension != null) { - int length = debugExtension.length; - result - .putShort(symbolTable.addConstantUtf8(Constants.SOURCE_DEBUG_EXTENSION)) - .putInt(length) - .putByteArray(debugExtension.data, 0, length); - } - if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) { - result.putShort(symbolTable.addConstantUtf8(Constants.DEPRECATED)).putInt(0); - } - AnnotationWriter.putAnnotations( - symbolTable, - lastRuntimeVisibleAnnotation, - lastRuntimeInvisibleAnnotation, - lastRuntimeVisibleTypeAnnotation, - lastRuntimeInvisibleTypeAnnotation, - result); - symbolTable.putBootstrapMethods(result); - if (moduleWriter != null) { - moduleWriter.putAttributes(result); - } - if (nestHostClassIndex != 0) { - result - .putShort(symbolTable.addConstantUtf8(Constants.NEST_HOST)) - .putInt(2) - .putShort(nestHostClassIndex); - } - if (nestMemberClasses != null) { - result - .putShort(symbolTable.addConstantUtf8(Constants.NEST_MEMBERS)) - .putInt(nestMemberClasses.length + 2) - .putShort(numberOfNestMemberClasses) - .putByteArray(nestMemberClasses.data, 0, nestMemberClasses.length); - } - if (firstAttribute != null) { - firstAttribute.putAttributes(symbolTable, result); - } - - // Third step: replace the ASM specific instructions, if any. - if (hasAsmInstructions) { - return replaceAsmInstructions(result.data, hasFrames); - } else { - return result.data; - } - } - - /** - * Returns the equivalent of the given class file, with the ASM specific instructions replaced - * with standard ones. This is done with a ClassReader -> ClassWriter round trip. - * - * @param classFile a class file containing ASM specific instructions, generated by this - * ClassWriter. - * @param hasFrames whether there is at least one stack map frames in 'classFile'. - * @return an equivalent of 'classFile', with the ASM specific instructions replaced with standard - * ones. - */ - private byte[] replaceAsmInstructions(final byte[] classFile, final boolean hasFrames) { - final Attribute[] attributes = getAttributePrototypes(); - firstField = null; - lastField = null; - firstMethod = null; - lastMethod = null; - lastRuntimeVisibleAnnotation = null; - lastRuntimeInvisibleAnnotation = null; - lastRuntimeVisibleTypeAnnotation = null; - lastRuntimeInvisibleTypeAnnotation = null; - moduleWriter = null; - nestHostClassIndex = 0; - numberOfNestMemberClasses = 0; - nestMemberClasses = null; - firstAttribute = null; - compute = hasFrames ? MethodWriter.COMPUTE_INSERTED_FRAMES : MethodWriter.COMPUTE_NOTHING; - new ClassReader(classFile, 0, /* checkClassVersion = */ false) - .accept( - this, - attributes, - (hasFrames ? ClassReader.EXPAND_FRAMES : 0) | ClassReader.EXPAND_ASM_INSNS); - return toByteArray(); - } - - /** - * Returns the prototypes of the attributes used by this class, its fields and its methods. - * - * @return the prototypes of the attributes used by this class, its fields and its methods. - */ - private Attribute[] getAttributePrototypes() { - Attribute.Set attributePrototypes = new Attribute.Set(); - attributePrototypes.addAttributes(firstAttribute); - FieldWriter fieldWriter = firstField; - while (fieldWriter != null) { - fieldWriter.collectAttributePrototypes(attributePrototypes); - fieldWriter = (FieldWriter) fieldWriter.fv; - } - MethodWriter methodWriter = firstMethod; - while (methodWriter != null) { - methodWriter.collectAttributePrototypes(attributePrototypes); - methodWriter = (MethodWriter) methodWriter.mv; - } - return attributePrototypes.toArray(); - } - - // ----------------------------------------------------------------------------------------------- - // Utility methods: constant pool management for Attribute sub classes - // ----------------------------------------------------------------------------------------------- - - /** - * Adds a number or string constant to the constant pool of the class being build. Does nothing if - * the constant pool already contains a similar item. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param value the value of the constant to be added to the constant pool. This parameter must be - * an {@link Integer}, a {@link Float}, a {@link Long}, a {@link Double} or a {@link String}. - * @return the index of a new or already existing constant item with the given value. - */ - public int newConst(final Object value) { - return symbolTable.addConstant(value).index; - } - - /** - * Adds an UTF8 string to the constant pool of the class being build. Does nothing if the constant - * pool already contains a similar item. This method is intended for {@link Attribute} sub - * classes, and is normally not needed by class generators or adapters. - * - * @param value the String value. - * @return the index of a new or already existing UTF8 item. - */ - // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility). - public int newUTF8(final String value) { - return symbolTable.addConstantUtf8(value); - } - - /** - * Adds a class reference to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param value the internal name of the class. - * @return the index of a new or already existing class reference item. - */ - public int newClass(final String value) { - return symbolTable.addConstantClass(value).index; - } - - /** - * Adds a method type reference to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param methodDescriptor method descriptor of the method type. - * @return the index of a new or already existing method type reference item. - */ - public int newMethodType(final String methodDescriptor) { - return symbolTable.addConstantMethodType(methodDescriptor).index; - } - - /** - * Adds a module reference to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param moduleName name of the module. - * @return the index of a new or already existing module reference item. - */ - public int newModule(final String moduleName) { - return symbolTable.addConstantModule(moduleName).index; - } - - /** - * Adds a package reference to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param packageName name of the package in its internal form. - * @return the index of a new or already existing module reference item. - */ - public int newPackage(final String packageName) { - return symbolTable.addConstantPackage(packageName).index; - } - - /** - * Adds a handle to the constant pool of the class being build. Does nothing if the constant pool - * already contains a similar item. This method is intended for {@link Attribute} sub classes, - * and is normally not needed by class generators or adapters. - * - * @param tag the kind of this handle. Must be {@link Opcodes#H_GETFIELD}, {@link - * Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link - * Opcodes#H_INVOKEVIRTUAL}, {@link Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, - * {@link Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}. - * @param owner the internal name of the field or method owner class. - * @param name the name of the field or method. - * @param descriptor the descriptor of the field or method. - * @return the index of a new or already existing method type reference item. - * @deprecated this method is superseded by {@link #newHandle(int, String, String, String, - * boolean)}. - */ - @Deprecated - public int newHandle( - final int tag, final String owner, final String name, final String descriptor) { - return newHandle(tag, owner, name, descriptor, tag == Opcodes.H_INVOKEINTERFACE); - } - - /** - * Adds a handle to the constant pool of the class being build. Does nothing if the constant pool - * already contains a similar item. This method is intended for {@link Attribute} sub classes, - * and is normally not needed by class generators or adapters. - * - * @param tag the kind of this handle. Must be {@link Opcodes#H_GETFIELD}, {@link - * Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link - * Opcodes#H_INVOKEVIRTUAL}, {@link Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, - * {@link Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}. - * @param owner the internal name of the field or method owner class. - * @param name the name of the field or method. - * @param descriptor the descriptor of the field or method. - * @param isInterface true if the owner is an interface. - * @return the index of a new or already existing method type reference item. - */ - public int newHandle( - final int tag, - final String owner, - final String name, - final String descriptor, - final boolean isInterface) { - return symbolTable.addConstantMethodHandle(tag, owner, name, descriptor, isInterface).index; - } - - /** - * Adds a dynamic constant reference to the constant pool of the class being build. Does nothing - * if the constant pool already contains a similar item. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param name name of the invoked method. - * @param descriptor field descriptor of the constant type. - * @param bootstrapMethodHandle the bootstrap method. - * @param bootstrapMethodArguments the bootstrap method constant arguments. - * @return the index of a new or already existing dynamic constant reference item. - */ - public int newConstantDynamic( - final String name, - final String descriptor, - final Handle bootstrapMethodHandle, - final Object... bootstrapMethodArguments) { - return symbolTable.addConstantDynamic( - name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments) - .index; - } - - /** - * Adds an invokedynamic reference to the constant pool of the class being build. Does nothing if - * the constant pool already contains a similar item. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param name name of the invoked method. - * @param descriptor descriptor of the invoke method. - * @param bootstrapMethodHandle the bootstrap method. - * @param bootstrapMethodArguments the bootstrap method constant arguments. - * @return the index of a new or already existing invokedynamic reference item. - */ - public int newInvokeDynamic( - final String name, - final String descriptor, - final Handle bootstrapMethodHandle, - final Object... bootstrapMethodArguments) { - return symbolTable.addConstantInvokeDynamic( - name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments) - .index; - } - - /** - * Adds a field reference to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param owner the internal name of the field's owner class. - * @param name the field's name. - * @param descriptor the field's descriptor. - * @return the index of a new or already existing field reference item. - */ - public int newField(final String owner, final String name, final String descriptor) { - return symbolTable.addConstantFieldref(owner, name, descriptor).index; - } - - /** - * Adds a method reference to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param owner the internal name of the method's owner class. - * @param name the method's name. - * @param descriptor the method's descriptor. - * @param isInterface {@literal true} if {@code owner} is an interface. - * @return the index of a new or already existing method reference item. - */ - public int newMethod( - final String owner, final String name, final String descriptor, final boolean isInterface) { - return symbolTable.addConstantMethodref(owner, name, descriptor, isInterface).index; - } - - /** - * Adds a name and type to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param name a name. - * @param descriptor a type descriptor. - * @return the index of a new or already existing name and type item. - */ - public int newNameType(final String name, final String descriptor) { - return symbolTable.addConstantNameAndType(name, descriptor); - } - - // ----------------------------------------------------------------------------------------------- - // Default method to compute common super classes when computing stack map frames - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the common super type of the two given types. The default implementation of this method - * loads the two given classes and uses the java.lang.Class methods to find the common - * super class. It can be overridden to compute this common super type in other ways, in - * particular without actually loading any class, or to take into account the class that is - * currently being generated by this ClassWriter, which can of course not be loaded since it is - * under construction. - * - * @param type1 the internal name of a class. - * @param type2 the internal name of another class. - * @return the internal name of the common super class of the two given classes. - */ - protected String getCommonSuperClass(final String type1, final String type2) { - ClassLoader classLoader = getClassLoader(); - Class class1; - try { - class1 = Class.forName(type1.replace('/', '.'), false, classLoader); - } catch (ClassNotFoundException e) { - throw new TypeNotPresentException(type1, e); - } - Class class2; - try { - class2 = Class.forName(type2.replace('/', '.'), false, classLoader); - } catch (ClassNotFoundException e) { - throw new TypeNotPresentException(type2, e); - } - if (class1.isAssignableFrom(class2)) { - return type1; - } - if (class2.isAssignableFrom(class1)) { - return type2; - } - if (class1.isInterface() || class2.isInterface()) { - return "java/lang/Object"; - } else { - do { - class1 = class1.getSuperclass(); - } while (!class1.isAssignableFrom(class2)); - return class1.getName().replace('.', '/'); - } - } - - /** - * Returns the {@link ClassLoader} to be used by the default implementation of {@link - * #getCommonSuperClass(String, String)}, that of this {@link ClassWriter}'s runtime type by - * default. - * - * @return ClassLoader - */ - protected ClassLoader getClassLoader() { - return getClass().getClassLoader(); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/ConstantDynamic.java b/jodd-proxetta/src/main/java/jodd/asm7/ConstantDynamic.java deleted file mode 100644 index 9ac365b97..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/ConstantDynamic.java +++ /dev/null @@ -1,183 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -import java.util.Arrays; - -/** - * A constant whose value is computed at runtime, with a bootstrap method. - * - * @author Remi Forax - */ -public final class ConstantDynamic { - - /** The constant name (can be arbitrary). */ - private final String name; - - /** The constant type (must be a field descriptor). */ - private final String descriptor; - - /** The bootstrap method to use to compute the constant value at runtime. */ - private final Handle bootstrapMethod; - - /** - * The arguments to pass to the bootstrap method, in order to compute the constant value at - * runtime. - */ - private final Object[] bootstrapMethodArguments; - - /** - * Constructs a new {@link ConstantDynamic}. - * - * @param name the constant name (can be arbitrary). - * @param descriptor the constant type (must be a field descriptor). - * @param bootstrapMethod the bootstrap method to use to compute the constant value at runtime. - * @param bootstrapMethodArguments the arguments to pass to the bootstrap method, in order to - * compute the constant value at runtime. - */ - public ConstantDynamic( - final String name, - final String descriptor, - final Handle bootstrapMethod, - final Object... bootstrapMethodArguments) { - this.name = name; - this.descriptor = descriptor; - this.bootstrapMethod = bootstrapMethod; - this.bootstrapMethodArguments = bootstrapMethodArguments; - } - - /** - * Returns the name of this constant. - * - * @return the name of this constant. - */ - public String getName() { - return name; - } - - /** - * Returns the type of this constant. - * - * @return the type of this constant, as a field descriptor. - */ - public String getDescriptor() { - return descriptor; - } - - /** - * Returns the bootstrap method used to compute the value of this constant. - * - * @return the bootstrap method used to compute the value of this constant. - */ - public Handle getBootstrapMethod() { - return bootstrapMethod; - } - - /** - * Returns the number of arguments passed to the bootstrap method, in order to compute the value - * of this constant. - * - * @return the number of arguments passed to the bootstrap method, in order to compute the value - * of this constant. - */ - public int getBootstrapMethodArgumentCount() { - return bootstrapMethodArguments.length; - } - - /** - * Returns an argument passed to the bootstrap method, in order to compute the value of this - * constant. - * - * @param index an argument index, between 0 and {@link #getBootstrapMethodArgumentCount()} - * (exclusive). - * @return the argument passed to the bootstrap method, with the given index. - */ - public Object getBootstrapMethodArgument(final int index) { - return bootstrapMethodArguments[index]; - } - - /** - * Returns the arguments to pass to the bootstrap method, in order to compute the value of this - * constant. WARNING: this array must not be modified, and must not be returned to the user. - * - * @return the arguments to pass to the bootstrap method, in order to compute the value of this - * constant. - */ - Object[] getBootstrapMethodArgumentsUnsafe() { - return bootstrapMethodArguments; - } - - /** - * Returns the size of this constant. - * - * @return the size of this constant, i.e., 2 for {@code long} and {@code double}, 1 otherwise. - */ - public int getSize() { - char firstCharOfDescriptor = descriptor.charAt(0); - return (firstCharOfDescriptor == 'J' || firstCharOfDescriptor == 'D') ? 2 : 1; - } - - void accept(final MethodVisitor methodVisitor) { - methodVisitor.visitInvokeDynamicInsn( - name, descriptor, bootstrapMethod, bootstrapMethodArguments); - } - - @Override - public boolean equals(final Object object) { - if (object == this) { - return true; - } - if (!(object instanceof ConstantDynamic)) { - return false; - } - ConstantDynamic constantDynamic = (ConstantDynamic) object; - return name.equals(constantDynamic.name) - && descriptor.equals(constantDynamic.descriptor) - && bootstrapMethod.equals(constantDynamic.bootstrapMethod) - && Arrays.equals(bootstrapMethodArguments, constantDynamic.bootstrapMethodArguments); - } - - @Override - public int hashCode() { - return name.hashCode() - ^ Integer.rotateLeft(descriptor.hashCode(), 8) - ^ Integer.rotateLeft(bootstrapMethod.hashCode(), 16) - ^ Integer.rotateLeft(Arrays.hashCode(bootstrapMethodArguments), 24); - } - - @Override - public String toString() { - return name - + " : " - + descriptor - + ' ' - + bootstrapMethod - + ' ' - + Arrays.toString(bootstrapMethodArguments); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/Constants.java b/jodd-proxetta/src/main/java/jodd/asm7/Constants.java deleted file mode 100644 index 695da6865..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/Constants.java +++ /dev/null @@ -1,177 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * Defines additional JVM opcodes, access flags and constants which are not part of the ASM public - * API. - * - * @see JVMS 6 - * @author Eric Bruneton - */ -final class Constants implements Opcodes { - - // The ClassFile attribute names, in the order they are defined in - // https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-4.html#jvms-4.7-300. - - static final String CONSTANT_VALUE = "ConstantValue"; - static final String CODE = "Code"; - static final String STACK_MAP_TABLE = "StackMapTable"; - static final String EXCEPTIONS = "Exceptions"; - static final String INNER_CLASSES = "InnerClasses"; - static final String ENCLOSING_METHOD = "EnclosingMethod"; - static final String SYNTHETIC = "Synthetic"; - static final String SIGNATURE = "Signature"; - static final String SOURCE_FILE = "SourceFile"; - static final String SOURCE_DEBUG_EXTENSION = "SourceDebugExtension"; - static final String LINE_NUMBER_TABLE = "LineNumberTable"; - static final String LOCAL_VARIABLE_TABLE = "LocalVariableTable"; - static final String LOCAL_VARIABLE_TYPE_TABLE = "LocalVariableTypeTable"; - static final String DEPRECATED = "Deprecated"; - static final String RUNTIME_VISIBLE_ANNOTATIONS = "RuntimeVisibleAnnotations"; - static final String RUNTIME_INVISIBLE_ANNOTATIONS = "RuntimeInvisibleAnnotations"; - static final String RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS = "RuntimeVisibleParameterAnnotations"; - static final String RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS = - "RuntimeInvisibleParameterAnnotations"; - static final String RUNTIME_VISIBLE_TYPE_ANNOTATIONS = "RuntimeVisibleTypeAnnotations"; - static final String RUNTIME_INVISIBLE_TYPE_ANNOTATIONS = "RuntimeInvisibleTypeAnnotations"; - static final String ANNOTATION_DEFAULT = "AnnotationDefault"; - static final String BOOTSTRAP_METHODS = "BootstrapMethods"; - static final String METHOD_PARAMETERS = "MethodParameters"; - static final String MODULE = "Module"; - static final String MODULE_PACKAGES = "ModulePackages"; - static final String MODULE_MAIN_CLASS = "ModuleMainClass"; - static final String NEST_HOST = "NestHost"; - static final String NEST_MEMBERS = "NestMembers"; - - // ASM specific access flags. - // WARNING: the 16 least significant bits must NOT be used, to avoid conflicts with standard - // access flags, and also to make sure that these flags are automatically filtered out when - // written in class files (because access flags are stored using 16 bits only). - - static final int ACC_CONSTRUCTOR = 0x40000; // method access flag. - - // ASM specific stack map frame types, used in {@link ClassVisitor#visitFrame}. - - /** - * A frame inserted between already existing frames. This internal stack map frame type (in - * addition to the ones declared in {@link Opcodes}) can only be used if the frame content can be - * computed from the previous existing frame and from the instructions between this existing frame - * and the inserted one, without any knowledge of the type hierarchy. This kind of frame is only - * used when an unconditional jump is inserted in a method while expanding an ASM specific - * instruction. Keep in sync with Opcodes.java. - */ - static final int F_INSERT = 256; - - // The JVM opcode values which are not part of the ASM public API. - // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-6.html. - - static final int LDC_W = 19; - static final int LDC2_W = 20; - static final int ILOAD_0 = 26; - static final int ILOAD_1 = 27; - static final int ILOAD_2 = 28; - static final int ILOAD_3 = 29; - static final int LLOAD_0 = 30; - static final int LLOAD_1 = 31; - static final int LLOAD_2 = 32; - static final int LLOAD_3 = 33; - static final int FLOAD_0 = 34; - static final int FLOAD_1 = 35; - static final int FLOAD_2 = 36; - static final int FLOAD_3 = 37; - static final int DLOAD_0 = 38; - static final int DLOAD_1 = 39; - static final int DLOAD_2 = 40; - static final int DLOAD_3 = 41; - static final int ALOAD_0 = 42; - static final int ALOAD_1 = 43; - static final int ALOAD_2 = 44; - static final int ALOAD_3 = 45; - static final int ISTORE_0 = 59; - static final int ISTORE_1 = 60; - static final int ISTORE_2 = 61; - static final int ISTORE_3 = 62; - static final int LSTORE_0 = 63; - static final int LSTORE_1 = 64; - static final int LSTORE_2 = 65; - static final int LSTORE_3 = 66; - static final int FSTORE_0 = 67; - static final int FSTORE_1 = 68; - static final int FSTORE_2 = 69; - static final int FSTORE_3 = 70; - static final int DSTORE_0 = 71; - static final int DSTORE_1 = 72; - static final int DSTORE_2 = 73; - static final int DSTORE_3 = 74; - static final int ASTORE_0 = 75; - static final int ASTORE_1 = 76; - static final int ASTORE_2 = 77; - static final int ASTORE_3 = 78; - static final int WIDE = 196; - static final int GOTO_W = 200; - static final int JSR_W = 201; - - // Constants to convert between normal and wide jump instructions. - - // The delta between the GOTO_W and JSR_W opcodes and GOTO and JUMP. - static final int WIDE_JUMP_OPCODE_DELTA = GOTO_W - GOTO; - - // Constants to convert JVM opcodes to the equivalent ASM specific opcodes, and vice versa. - - // The delta between the ASM_IFEQ, ..., ASM_IF_ACMPNE, ASM_GOTO and ASM_JSR opcodes - // and IFEQ, ..., IF_ACMPNE, GOTO and JSR. - static final int ASM_OPCODE_DELTA = 49; - - // The delta between the ASM_IFNULL and ASM_IFNONNULL opcodes and IFNULL and IFNONNULL. - static final int ASM_IFNULL_OPCODE_DELTA = 20; - - // ASM specific opcodes, used for long forward jump instructions. - - static final int ASM_IFEQ = IFEQ + ASM_OPCODE_DELTA; - static final int ASM_IFNE = IFNE + ASM_OPCODE_DELTA; - static final int ASM_IFLT = IFLT + ASM_OPCODE_DELTA; - static final int ASM_IFGE = IFGE + ASM_OPCODE_DELTA; - static final int ASM_IFGT = IFGT + ASM_OPCODE_DELTA; - static final int ASM_IFLE = IFLE + ASM_OPCODE_DELTA; - static final int ASM_IF_ICMPEQ = IF_ICMPEQ + ASM_OPCODE_DELTA; - static final int ASM_IF_ICMPNE = IF_ICMPNE + ASM_OPCODE_DELTA; - static final int ASM_IF_ICMPLT = IF_ICMPLT + ASM_OPCODE_DELTA; - static final int ASM_IF_ICMPGE = IF_ICMPGE + ASM_OPCODE_DELTA; - static final int ASM_IF_ICMPGT = IF_ICMPGT + ASM_OPCODE_DELTA; - static final int ASM_IF_ICMPLE = IF_ICMPLE + ASM_OPCODE_DELTA; - static final int ASM_IF_ACMPEQ = IF_ACMPEQ + ASM_OPCODE_DELTA; - static final int ASM_IF_ACMPNE = IF_ACMPNE + ASM_OPCODE_DELTA; - static final int ASM_GOTO = GOTO + ASM_OPCODE_DELTA; - static final int ASM_JSR = JSR + ASM_OPCODE_DELTA; - static final int ASM_IFNULL = IFNULL + ASM_IFNULL_OPCODE_DELTA; - static final int ASM_IFNONNULL = IFNONNULL + ASM_IFNULL_OPCODE_DELTA; - static final int ASM_GOTO_W = 220; - - private Constants() {} -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/Context.java b/jodd-proxetta/src/main/java/jodd/asm7/Context.java deleted file mode 100644 index 94b758043..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/Context.java +++ /dev/null @@ -1,137 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. - -package jodd.asm7; - -/** - * Information about a class being parsed in a {@link ClassReader}. - * - * @author Eric Bruneton - */ -final class Context { - - /** The prototypes of the attributes that must be parsed in this class. */ - Attribute[] attributePrototypes; - - /** - * The options used to parse this class. One or more of {@link ClassReader#SKIP_CODE}, {@link - * ClassReader#SKIP_DEBUG}, {@link ClassReader#SKIP_FRAMES}, {@link ClassReader#EXPAND_FRAMES} or - * {@link ClassReader#EXPAND_ASM_INSNS}. - */ - int parsingOptions; - - /** The buffer used to read strings in the constant pool. */ - char[] charBuffer; - - // Information about the current method, i.e. the one read in the current (or latest) call - // to {@link ClassReader#readMethod()}. - - /** The access flags of the current method. */ - int currentMethodAccessFlags; - - /** The name of the current method. */ - String currentMethodName; - - /** The descriptor of the current method. */ - String currentMethodDescriptor; - - /** - * The labels of the current method, indexed by bytecode offset (only bytecode offsets for which a - * label is needed have a non null associated Label). - */ - Label[] currentMethodLabels; - - // Information about the current type annotation target, i.e. the one read in the current - // (or latest) call to {@link ClassReader#readAnnotationTarget()}. - - /** - * The target_type and target_info of the current type annotation target, encoded as described in - * {@link TypeReference}. - */ - int currentTypeAnnotationTarget; - - /** The target_path of the current type annotation target. */ - TypePath currentTypeAnnotationTargetPath; - - /** The start of each local variable range in the current local variable annotation. */ - Label[] currentLocalVariableAnnotationRangeStarts; - - /** The end of each local variable range in the current local variable annotation. */ - Label[] currentLocalVariableAnnotationRangeEnds; - - /** - * The local variable index of each local variable range in the current local variable annotation. - */ - int[] currentLocalVariableAnnotationRangeIndices; - - // Information about the current stack map frame, i.e. the one read in the current (or latest) - // call to {@link ClassReader#readFrame()}. - - /** The bytecode offset of the current stack map frame. */ - int currentFrameOffset; - - /** - * The type of the current stack map frame. One of {@link Opcodes#F_FULL}, {@link - * Opcodes#F_APPEND}, {@link Opcodes#F_CHOP}, {@link Opcodes#F_SAME} or {@link Opcodes#F_SAME1}. - */ - int currentFrameType; - - /** - * The number of local variable types in the current stack map frame. Each type is represented - * with a single array element (even long and double). - */ - int currentFrameLocalCount; - - /** - * The delta number of local variable types in the current stack map frame (each type is - * represented with a single array element - even long and double). This is the number of local - * variable types in this frame, minus the number of local variable types in the previous frame. - */ - int currentFrameLocalCountDelta; - - /** - * The types of the local variables in the current stack map frame. Each type is represented with - * a single array element (even long and double), using the format described in {@link - * MethodVisitor#visitFrame}. Depending on {@link #currentFrameType}, this contains the types of - * all the local variables, or only those of the additional ones (compared to the previous frame). - */ - Object[] currentFrameLocalTypes; - - /** - * The number stack element types in the current stack map frame. Each type is represented with a - * single array element (even long and double). - */ - int currentFrameStackCount; - - /** - * The types of the stack elements in the current stack map frame. Each type is represented with a - * single array element (even long and double), using the format described in {@link - * MethodVisitor#visitFrame}. - */ - Object[] currentFrameStackTypes; -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/CurrentFrame.java b/jodd-proxetta/src/main/java/jodd/asm7/CurrentFrame.java deleted file mode 100644 index 2fecd1679..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/CurrentFrame.java +++ /dev/null @@ -1,56 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. - -package jodd.asm7; - -/** - * Information about the input stack map frame at the "current" instruction of a method. This is - * implemented as a Frame subclass for a "basic block" containing only one instruction. - * - * @author Eric Bruneton - */ -final class CurrentFrame extends Frame { - - CurrentFrame(final Label owner) { - super(owner); - } - - /** - * Sets this CurrentFrame to the input stack map frame of the next "current" instruction, i.e. the - * instruction just after the given one. It is assumed that the value of this object when this - * method is called is the stack map frame status just before the given instruction is executed. - */ - @Override - void execute( - final int opcode, final int arg, final Symbol symbolArg, final SymbolTable symbolTable) { - super.execute(opcode, arg, symbolArg, symbolTable); - Frame successor = new Frame(null); - merge(symbolTable, successor, 0); - copyFrom(successor); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/Edge.java b/jodd-proxetta/src/main/java/jodd/asm7/Edge.java deleted file mode 100644 index add45ec2d..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/Edge.java +++ /dev/null @@ -1,91 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * An edge in the control flow graph of a method. Each node of this graph is a basic block, - * represented with the Label corresponding to its first instruction. Each edge goes from one node - * to another, i.e. from one basic block to another (called the predecessor and successor blocks, - * respectively). An edge corresponds either to a jump or ret instruction or to an exception - * handler. - * - * @see Label - * @author Eric Bruneton - */ -final class Edge { - - /** - * A control flow graph edge corresponding to a jump or ret instruction. Only used with {@link - * ClassWriter#COMPUTE_FRAMES}. - */ - static final int JUMP = 0; - - /** - * A control flow graph edge corresponding to an exception handler. Only used with {@link - * ClassWriter#COMPUTE_MAXS}. - */ - static final int EXCEPTION = 0x7FFFFFFF; - - /** - * Information about this control flow graph edge. - * - *
    - *
  • If {@link ClassWriter#COMPUTE_MAXS} is used, this field contains either a stack size - * delta (for an edge corresponding to a jump instruction), or the value EXCEPTION (for an - * edge corresponding to an exception handler). The stack size delta is the stack size just - * after the jump instruction, minus the stack size at the beginning of the predecessor - * basic block, i.e. the one containing the jump instruction. - *
  • If {@link ClassWriter#COMPUTE_FRAMES} is used, this field contains either the value JUMP - * (for an edge corresponding to a jump instruction), or the index, in the {@link - * ClassWriter} type table, of the exception type that is handled (for an edge corresponding - * to an exception handler). - *
- */ - final int info; - - /** The successor block of this control flow graph edge. */ - final Label successor; - - /** - * The next edge in the list of outgoing edges of a basic block. See {@link Label#outgoingEdges}. - */ - Edge nextEdge; - - /** - * Constructs a new Edge. - * - * @param info see {@link #info}. - * @param successor see {@link #successor}. - * @param nextEdge see {@link #nextEdge}. - */ - Edge(final int info, final Label successor, final Edge nextEdge) { - this.info = info; - this.successor = successor; - this.nextEdge = nextEdge; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/FieldVisitor.java b/jodd-proxetta/src/main/java/jodd/asm7/FieldVisitor.java deleted file mode 100644 index be00f93b4..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/FieldVisitor.java +++ /dev/null @@ -1,133 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * A visitor to visit a Java field. The methods of this class must be called in the following order: - * ( {@code visitAnnotation} | {@code visitTypeAnnotation} | {@code visitAttribute} )* {@code - * visitEnd}. - * - * @author Eric Bruneton - */ -public abstract class FieldVisitor { - - /** - * The ASM API version implemented by this visitor. The value of this field must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - */ - protected final int api; - - /** The field visitor to which this visitor must delegate method calls. May be null. */ - protected FieldVisitor fv; - - /** - * Constructs a new {@link FieldVisitor}. - * - * @param api the ASM API version implemented by this visitor. Must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - */ - public FieldVisitor(final int api) { - this(api, null); - } - - /** - * Constructs a new {@link FieldVisitor}. - * - * @param api the ASM API version implemented by this visitor. Must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - * @param fieldVisitor the field visitor to which this visitor must delegate method calls. May be - * null. - */ - public FieldVisitor(final int api, final FieldVisitor fieldVisitor) { - if (api != Opcodes.ASM7 && api != Opcodes.ASM6 && api != Opcodes.ASM5 && api != Opcodes.ASM4) { - throw new IllegalArgumentException("Unsupported api " + api); - } - this.api = api; - this.fv = fieldVisitor; - } - - /** - * Visits an annotation of the field. - * - * @param descriptor the class descriptor of the annotation class. - * @param visible {@literal true} if the annotation is visible at runtime. - * @return a visitor to visit the annotation values, or {@literal null} if this visitor is not - * interested in visiting this annotation. - */ - public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) { - if (fv != null) { - return fv.visitAnnotation(descriptor, visible); - } - return null; - } - - /** - * Visits an annotation on the type of the field. - * - * @param typeRef a reference to the annotated type. The sort of this type reference must be - * {@link TypeReference#FIELD}. See {@link TypeReference}. - * @param typePath the path to the annotated type argument, wildcard bound, array element type, or - * static inner type within 'typeRef'. May be {@literal null} if the annotation targets - * 'typeRef' as a whole. - * @param descriptor the class descriptor of the annotation class. - * @param visible {@literal true} if the annotation is visible at runtime. - * @return a visitor to visit the annotation values, or {@literal null} if this visitor is not - * interested in visiting this annotation. - */ - public AnnotationVisitor visitTypeAnnotation( - final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { - if (api < Opcodes.ASM5) { - throw new UnsupportedOperationException("This feature requires ASM5"); - } - if (fv != null) { - return fv.visitTypeAnnotation(typeRef, typePath, descriptor, visible); - } - return null; - } - - /** - * Visits a non standard attribute of the field. - * - * @param attribute an attribute. - */ - public void visitAttribute(final Attribute attribute) { - if (fv != null) { - fv.visitAttribute(attribute); - } - } - - /** - * Visits the end of the field. This method, which is the last one to be called, is used to inform - * the visitor that all the annotations and attributes of the field have been visited. - */ - public void visitEnd() { - if (fv != null) { - fv.visitEnd(); - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/FieldWriter.java b/jodd-proxetta/src/main/java/jodd/asm7/FieldWriter.java deleted file mode 100644 index 4a721dd7d..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/FieldWriter.java +++ /dev/null @@ -1,284 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * A {@link FieldVisitor} that generates a corresponding 'field_info' structure, as defined in the - * Java Virtual Machine Specification (JVMS). - * - * @see JVMS - * 4.5 - * @author Eric Bruneton - */ -final class FieldWriter extends FieldVisitor { - - /** Where the constants used in this FieldWriter must be stored. */ - private final SymbolTable symbolTable; - - // Note: fields are ordered as in the field_info structure, and those related to attributes are - // ordered as in Section 4.7 of the JVMS. - - /** - * The access_flags field of the field_info JVMS structure. This field can contain ASM specific - * access flags, such as {@link Opcodes#ACC_DEPRECATED}, which are removed when generating the - * ClassFile structure. - */ - private final int accessFlags; - - /** The name_index field of the field_info JVMS structure. */ - private final int nameIndex; - - /** The descriptor_index field of the field_info JVMS structure. */ - private final int descriptorIndex; - - /** - * The signature_index field of the Signature attribute of this field_info, or 0 if there is no - * Signature attribute. - */ - private int signatureIndex; - - /** - * The constantvalue_index field of the ConstantValue attribute of this field_info, or 0 if there - * is no ConstantValue attribute. - */ - private int constantValueIndex; - - /** - * The last runtime visible annotation of this field. The previous ones can be accessed with the - * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeVisibleAnnotation; - - /** - * The last runtime invisible annotation of this field. The previous ones can be accessed with the - * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeInvisibleAnnotation; - - /** - * The last runtime visible type annotation of this field. The previous ones can be accessed with - * the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeVisibleTypeAnnotation; - - /** - * The last runtime invisible type annotation of this field. The previous ones can be accessed - * with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeInvisibleTypeAnnotation; - - /** - * The first non standard attribute of this field. The next ones can be accessed with the {@link - * Attribute#nextAttribute} field. May be {@literal null}. - * - *

WARNING: this list stores the attributes in the reverse order of their visit. - * firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link - * #putFieldInfo} method writes the attributes in the order defined by this list, i.e. in the - * reverse order specified by the user. - */ - private Attribute firstAttribute; - - // ----------------------------------------------------------------------------------------------- - // Constructor - // ----------------------------------------------------------------------------------------------- - - /** - * Constructs a new {@link FieldWriter}. - * - * @param symbolTable where the constants used in this FieldWriter must be stored. - * @param access the field's access flags (see {@link Opcodes}). - * @param name the field's name. - * @param descriptor the field's descriptor (see {@link Type}). - * @param signature the field's signature. May be {@literal null}. - * @param constantValue the field's constant value. May be {@literal null}. - */ - FieldWriter( - final SymbolTable symbolTable, - final int access, - final String name, - final String descriptor, - final String signature, - final Object constantValue) { - super(Opcodes.ASM7); - this.symbolTable = symbolTable; - this.accessFlags = access; - this.nameIndex = symbolTable.addConstantUtf8(name); - this.descriptorIndex = symbolTable.addConstantUtf8(descriptor); - if (signature != null) { - this.signatureIndex = symbolTable.addConstantUtf8(signature); - } - if (constantValue != null) { - this.constantValueIndex = symbolTable.addConstant(constantValue).index; - } - } - - // ----------------------------------------------------------------------------------------------- - // Implementation of the FieldVisitor abstract class - // ----------------------------------------------------------------------------------------------- - - @Override - public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) { - if (visible) { - return lastRuntimeVisibleAnnotation = - AnnotationWriter.create(symbolTable, descriptor, lastRuntimeVisibleAnnotation); - } else { - return lastRuntimeInvisibleAnnotation = - AnnotationWriter.create(symbolTable, descriptor, lastRuntimeInvisibleAnnotation); - } - } - - @Override - public AnnotationVisitor visitTypeAnnotation( - final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { - if (visible) { - return lastRuntimeVisibleTypeAnnotation = - AnnotationWriter.create( - symbolTable, typeRef, typePath, descriptor, lastRuntimeVisibleTypeAnnotation); - } else { - return lastRuntimeInvisibleTypeAnnotation = - AnnotationWriter.create( - symbolTable, typeRef, typePath, descriptor, lastRuntimeInvisibleTypeAnnotation); - } - } - - @Override - public void visitAttribute(final Attribute attribute) { - // Store the attributes in the reverse order of their visit by this method. - attribute.nextAttribute = firstAttribute; - firstAttribute = attribute; - } - - @Override - public void visitEnd() { - // Nothing to do. - } - - // ----------------------------------------------------------------------------------------------- - // Utility methods - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the size of the field_info JVMS structure generated by this FieldWriter. Also adds the - * names of the attributes of this field in the constant pool. - * - * @return the size in bytes of the field_info JVMS structure. - */ - int computeFieldInfoSize() { - // The access_flags, name_index, descriptor_index and attributes_count fields use 8 bytes. - int size = 8; - // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. - if (constantValueIndex != 0) { - // ConstantValue attributes always use 8 bytes. - symbolTable.addConstantUtf8(Constants.CONSTANT_VALUE); - size += 8; - } - size += Attribute.computeAttributesSize(symbolTable, accessFlags, signatureIndex); - size += - AnnotationWriter.computeAnnotationsSize( - lastRuntimeVisibleAnnotation, - lastRuntimeInvisibleAnnotation, - lastRuntimeVisibleTypeAnnotation, - lastRuntimeInvisibleTypeAnnotation); - if (firstAttribute != null) { - size += firstAttribute.computeAttributesSize(symbolTable); - } - return size; - } - - /** - * Puts the content of the field_info JVMS structure generated by this FieldWriter into the given - * ByteVector. - * - * @param output where the field_info structure must be put. - */ - void putFieldInfo(final ByteVector output) { - boolean useSyntheticAttribute = symbolTable.getMajorVersion() < Opcodes.V1_5; - // Put the access_flags, name_index and descriptor_index fields. - int mask = useSyntheticAttribute ? Opcodes.ACC_SYNTHETIC : 0; - output.putShort(accessFlags & ~mask).putShort(nameIndex).putShort(descriptorIndex); - // Compute and put the attributes_count field. - // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. - int attributesCount = 0; - if (constantValueIndex != 0) { - ++attributesCount; - } - if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && useSyntheticAttribute) { - ++attributesCount; - } - if (signatureIndex != 0) { - ++attributesCount; - } - if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) { - ++attributesCount; - } - if (lastRuntimeVisibleAnnotation != null) { - ++attributesCount; - } - if (lastRuntimeInvisibleAnnotation != null) { - ++attributesCount; - } - if (lastRuntimeVisibleTypeAnnotation != null) { - ++attributesCount; - } - if (lastRuntimeInvisibleTypeAnnotation != null) { - ++attributesCount; - } - if (firstAttribute != null) { - attributesCount += firstAttribute.getAttributeCount(); - } - output.putShort(attributesCount); - // Put the field_info attributes. - // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. - if (constantValueIndex != 0) { - output - .putShort(symbolTable.addConstantUtf8(Constants.CONSTANT_VALUE)) - .putInt(2) - .putShort(constantValueIndex); - } - Attribute.putAttributes(symbolTable, accessFlags, signatureIndex, output); - AnnotationWriter.putAnnotations( - symbolTable, - lastRuntimeVisibleAnnotation, - lastRuntimeInvisibleAnnotation, - lastRuntimeVisibleTypeAnnotation, - lastRuntimeInvisibleTypeAnnotation, - output); - if (firstAttribute != null) { - firstAttribute.putAttributes(symbolTable, output); - } - } - - /** - * Collects the attributes of this field into the given set of attribute prototypes. - * - * @param attributePrototypes a set of attribute prototypes. - */ - final void collectAttributePrototypes(final Attribute.Set attributePrototypes) { - attributePrototypes.addAttributes(firstAttribute); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/Frame.java b/jodd-proxetta/src/main/java/jodd/asm7/Frame.java deleted file mode 100644 index 4efed3ffc..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/Frame.java +++ /dev/null @@ -1,1473 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * The input and output stack map frames of a basic block. - * - *

Stack map frames are computed in two steps: - * - *

    - *
  • During the visit of each instruction in MethodWriter, the state of the frame at the end of - * the current basic block is updated by simulating the action of the instruction on the - * previous state of this so called "output frame". - *
  • After all instructions have been visited, a fix point algorithm is used in MethodWriter to - * compute the "input frame" of each basic block (i.e. the stack map frame at the beginning of - * the basic block). See {@link MethodWriter#computeAllFrames}. - *
- * - *

Output stack map frames are computed relatively to the input frame of the basic block, which - * is not yet known when output frames are computed. It is therefore necessary to be able to - * represent abstract types such as "the type at position x in the input frame locals" or "the type - * at position x from the top of the input frame stack" or even "the type at position x in the input - * frame, with y more (or less) array dimensions". This explains the rather complicated type format - * used in this class, explained below. - * - *

The local variables and the operand stack of input and output frames contain values called - * "abstract types" hereafter. An abstract type is represented with 4 fields named DIM, KIND, FLAGS - * and VALUE, packed in a single int value for better performance and memory efficiency: - * - *

- *   =====================================
- *   |...DIM|KIND|.F|...............VALUE|
- *   =====================================
- * 
- * - *
    - *
  • the DIM field, stored in the 6 most significant bits, is a signed number of array - * dimensions (from -32 to 31, included). It can be retrieved with {@link #DIM_MASK} and a - * right shift of {@link #DIM_SHIFT}. - *
  • the KIND field, stored in 4 bits, indicates the kind of VALUE used. These 4 bits can be - * retrieved with {@link #KIND_MASK} and, without any shift, must be equal to {@link - * #CONSTANT_KIND}, {@link #REFERENCE_KIND}, {@link #UNINITIALIZED_KIND}, {@link #LOCAL_KIND} - * or {@link #STACK_KIND}. - *
  • the FLAGS field, stored in 2 bits, contains up to 2 boolean flags. Currently only one flag - * is defined, namely {@link #TOP_IF_LONG_OR_DOUBLE_FLAG}. - *
  • the VALUE field, stored in the remaining 20 bits, contains either - *
      - *
    • one of the constants {@link #ITEM_TOP}, {@link #ITEM_ASM_BOOLEAN}, {@link - * #ITEM_ASM_BYTE}, {@link #ITEM_ASM_CHAR} or {@link #ITEM_ASM_SHORT}, {@link - * #ITEM_INTEGER}, {@link #ITEM_FLOAT}, {@link #ITEM_LONG}, {@link #ITEM_DOUBLE}, {@link - * #ITEM_NULL} or {@link #ITEM_UNINITIALIZED_THIS}, if KIND is equal to {@link - * #CONSTANT_KIND}. - *
    • the index of a {@link Symbol#TYPE_TAG} {@link Symbol} in the type table of a {@link - * SymbolTable}, if KIND is equal to {@link #REFERENCE_KIND}. - *
    • the index of an {@link Symbol#UNINITIALIZED_TYPE_TAG} {@link Symbol} in the type - * table of a SymbolTable, if KIND is equal to {@link #UNINITIALIZED_KIND}. - *
    • the index of a local variable in the input stack frame, if KIND is equal to {@link - * #LOCAL_KIND}. - *
    • a position relatively to the top of the stack of the input stack frame, if KIND is - * equal to {@link #STACK_KIND}, - *
    - *
- * - *

Output frames can contain abstract types of any kind and with a positive or negative array - * dimension (and even unassigned types, represented by 0 - which does not correspond to any valid - * abstract type value). Input frames can only contain CONSTANT_KIND, REFERENCE_KIND or - * UNINITIALIZED_KIND abstract types of positive or null array dimension. In all cases the type - * table contains only internal type names (array type descriptors are forbidden - array dimensions - * must be represented through the DIM field). - * - *

The LONG and DOUBLE types are always represented by using two slots (LONG + TOP or DOUBLE + - * TOP), for local variables as well as in the operand stack. This is necessary to be able to - * simulate DUPx_y instructions, whose effect would be dependent on the concrete types represented - * by the abstract types in the stack (which are not always known). - * - * @author Eric Bruneton - */ -class Frame { - - // Constants used in the StackMapTable attribute. - // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.4. - - static final int SAME_FRAME = 0; - static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64; - static final int RESERVED = 128; - static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247; - static final int CHOP_FRAME = 248; - static final int SAME_FRAME_EXTENDED = 251; - static final int APPEND_FRAME = 252; - static final int FULL_FRAME = 255; - - static final int ITEM_TOP = 0; - static final int ITEM_INTEGER = 1; - static final int ITEM_FLOAT = 2; - static final int ITEM_DOUBLE = 3; - static final int ITEM_LONG = 4; - static final int ITEM_NULL = 5; - static final int ITEM_UNINITIALIZED_THIS = 6; - static final int ITEM_OBJECT = 7; - static final int ITEM_UNINITIALIZED = 8; - // Additional, ASM specific constants used in abstract types below. - private static final int ITEM_ASM_BOOLEAN = 9; - private static final int ITEM_ASM_BYTE = 10; - private static final int ITEM_ASM_CHAR = 11; - private static final int ITEM_ASM_SHORT = 12; - - // The size and offset in bits of each field of an abstract type. - - private static final int DIM_SIZE = 6; - private static final int KIND_SIZE = 4; - private static final int FLAGS_SIZE = 2; - private static final int VALUE_SIZE = 32 - DIM_SIZE - KIND_SIZE - FLAGS_SIZE; - - private static final int DIM_SHIFT = KIND_SIZE + FLAGS_SIZE + VALUE_SIZE; - private static final int KIND_SHIFT = FLAGS_SIZE + VALUE_SIZE; - private static final int FLAGS_SHIFT = VALUE_SIZE; - - // Bitmasks to get each field of an abstract type. - - private static final int DIM_MASK = ((1 << DIM_SIZE) - 1) << DIM_SHIFT; - private static final int KIND_MASK = ((1 << KIND_SIZE) - 1) << KIND_SHIFT; - private static final int VALUE_MASK = (1 << VALUE_SIZE) - 1; - - // Constants to manipulate the DIM field of an abstract type. - - /** The constant to be added to an abstract type to get one with one more array dimension. */ - private static final int ARRAY_OF = +1 << DIM_SHIFT; - - /** The constant to be added to an abstract type to get one with one less array dimension. */ - private static final int ELEMENT_OF = -1 << DIM_SHIFT; - - // Possible values for the KIND field of an abstract type. - - private static final int CONSTANT_KIND = 1 << KIND_SHIFT; - private static final int REFERENCE_KIND = 2 << KIND_SHIFT; - private static final int UNINITIALIZED_KIND = 3 << KIND_SHIFT; - private static final int LOCAL_KIND = 4 << KIND_SHIFT; - private static final int STACK_KIND = 5 << KIND_SHIFT; - - // Possible flags for the FLAGS field of an abstract type. - - /** - * A flag used for LOCAL_KIND and STACK_KIND abstract types, indicating that if the resolved, - * concrete type is LONG or DOUBLE, TOP should be used instead (because the value has been - * partially overridden with an xSTORE instruction). - */ - private static final int TOP_IF_LONG_OR_DOUBLE_FLAG = 1 << FLAGS_SHIFT; - - // Useful predefined abstract types (all the possible CONSTANT_KIND types). - - private static final int TOP = CONSTANT_KIND | ITEM_TOP; - private static final int BOOLEAN = CONSTANT_KIND | ITEM_ASM_BOOLEAN; - private static final int BYTE = CONSTANT_KIND | ITEM_ASM_BYTE; - private static final int CHAR = CONSTANT_KIND | ITEM_ASM_CHAR; - private static final int SHORT = CONSTANT_KIND | ITEM_ASM_SHORT; - private static final int INTEGER = CONSTANT_KIND | ITEM_INTEGER; - private static final int FLOAT = CONSTANT_KIND | ITEM_FLOAT; - private static final int LONG = CONSTANT_KIND | ITEM_LONG; - private static final int DOUBLE = CONSTANT_KIND | ITEM_DOUBLE; - private static final int NULL = CONSTANT_KIND | ITEM_NULL; - private static final int UNINITIALIZED_THIS = CONSTANT_KIND | ITEM_UNINITIALIZED_THIS; - - // ----------------------------------------------------------------------------------------------- - // Instance fields - // ----------------------------------------------------------------------------------------------- - - /** The basic block to which these input and output stack map frames correspond. */ - Label owner; - - /** The input stack map frame locals. This is an array of abstract types. */ - private int[] inputLocals; - - /** The input stack map frame stack. This is an array of abstract types. */ - private int[] inputStack; - - /** The output stack map frame locals. This is an array of abstract types. */ - private int[] outputLocals; - - /** The output stack map frame stack. This is an array of abstract types. */ - private int[] outputStack; - - /** - * The start of the output stack, relatively to the input stack. This offset is always negative or - * null. A null offset means that the output stack must be appended to the input stack. A -n - * offset means that the first n output stack elements must replace the top n input stack - * elements, and that the other elements must be appended to the input stack. - */ - private short outputStackStart; - - /** The index of the top stack element in {@link #outputStack}. */ - private short outputStackTop; - - /** The number of types that are initialized in the basic block. See {@link #initializations}. */ - private int initializationCount; - - /** - * The abstract types that are initialized in the basic block. A constructor invocation on an - * UNINITIALIZED or UNINITIALIZED_THIS abstract type must replace every occurrence of this - * type in the local variables and in the operand stack. This cannot be done during the first step - * of the algorithm since, during this step, the local variables and the operand stack types are - * still abstract. It is therefore necessary to store the abstract types of the constructors which - * are invoked in the basic block, in order to do this replacement during the second step of the - * algorithm, where the frames are fully computed. Note that this array can contain abstract types - * that are relative to the input locals or to the input stack. - */ - private int[] initializations; - - // ----------------------------------------------------------------------------------------------- - // Constructor - // ----------------------------------------------------------------------------------------------- - - /** - * Constructs a new Frame. - * - * @param owner the basic block to which these input and output stack map frames correspond. - */ - Frame(final Label owner) { - this.owner = owner; - } - - /** - * Sets this frame to the value of the given frame. - * - *

WARNING: after this method is called the two frames share the same data structures. It is - * recommended to discard the given frame to avoid unexpected side effects. - * - * @param frame The new frame value. - */ - final void copyFrom(final Frame frame) { - inputLocals = frame.inputLocals; - inputStack = frame.inputStack; - outputStackStart = 0; - outputLocals = frame.outputLocals; - outputStack = frame.outputStack; - outputStackTop = frame.outputStackTop; - initializationCount = frame.initializationCount; - initializations = frame.initializations; - } - - // ----------------------------------------------------------------------------------------------- - // Static methods to get abstract types from other type formats - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the abstract type corresponding to the given public API frame element type. - * - * @param symbolTable the type table to use to lookup and store type {@link Symbol}. - * @param type a frame element type described using the same format as in {@link - * MethodVisitor#visitFrame}, i.e. either {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, {@link - * Opcodes#FLOAT}, {@link Opcodes#LONG}, {@link Opcodes#DOUBLE}, {@link Opcodes#NULL}, or - * {@link Opcodes#UNINITIALIZED_THIS}, or the internal name of a class, or a Label designating - * a NEW instruction (for uninitialized types). - * @return the abstract type corresponding to the given frame element type. - */ - static int getAbstractTypeFromApiFormat(final SymbolTable symbolTable, final Object type) { - if (type instanceof Integer) { - return CONSTANT_KIND | ((Integer) type).intValue(); - } else if (type instanceof String) { - String descriptor = Type.getObjectType((String) type).getDescriptor(); - return getAbstractTypeFromDescriptor(symbolTable, descriptor, 0); - } else { - return UNINITIALIZED_KIND - | symbolTable.addUninitializedType("", ((Label) type).bytecodeOffset); - } - } - - /** - * Returns the abstract type corresponding to the internal name of a class. - * - * @param symbolTable the type table to use to lookup and store type {@link Symbol}. - * @param internalName the internal name of a class. This must not be an array type - * descriptor. - * @return the abstract type value corresponding to the given internal name. - */ - static int getAbstractTypeFromInternalName( - final SymbolTable symbolTable, final String internalName) { - return REFERENCE_KIND | symbolTable.addType(internalName); - } - - /** - * Returns the abstract type corresponding to the given type descriptor. - * - * @param symbolTable the type table to use to lookup and store type {@link Symbol}. - * @param buffer a string ending with a type descriptor. - * @param offset the start offset of the type descriptor in buffer. - * @return the abstract type corresponding to the given type descriptor. - */ - private static int getAbstractTypeFromDescriptor( - final SymbolTable symbolTable, final String buffer, final int offset) { - String internalName; - switch (buffer.charAt(offset)) { - case 'V': - return 0; - case 'Z': - case 'C': - case 'B': - case 'S': - case 'I': - return INTEGER; - case 'F': - return FLOAT; - case 'J': - return LONG; - case 'D': - return DOUBLE; - case 'L': - internalName = buffer.substring(offset + 1, buffer.length() - 1); - return REFERENCE_KIND | symbolTable.addType(internalName); - case '[': - int elementDescriptorOffset = offset + 1; - while (buffer.charAt(elementDescriptorOffset) == '[') { - ++elementDescriptorOffset; - } - int typeValue; - switch (buffer.charAt(elementDescriptorOffset)) { - case 'Z': - typeValue = BOOLEAN; - break; - case 'C': - typeValue = CHAR; - break; - case 'B': - typeValue = BYTE; - break; - case 'S': - typeValue = SHORT; - break; - case 'I': - typeValue = INTEGER; - break; - case 'F': - typeValue = FLOAT; - break; - case 'J': - typeValue = LONG; - break; - case 'D': - typeValue = DOUBLE; - break; - case 'L': - internalName = buffer.substring(elementDescriptorOffset + 1, buffer.length() - 1); - typeValue = REFERENCE_KIND | symbolTable.addType(internalName); - break; - default: - throw new IllegalArgumentException(); - } - return ((elementDescriptorOffset - offset) << DIM_SHIFT) | typeValue; - default: - throw new IllegalArgumentException(); - } - } - - // ----------------------------------------------------------------------------------------------- - // Methods related to the input frame - // ----------------------------------------------------------------------------------------------- - - /** - * Sets the input frame from the given method description. This method is used to initialize the - * first frame of a method, which is implicit (i.e. not stored explicitly in the StackMapTable - * attribute). - * - * @param symbolTable the type table to use to lookup and store type {@link Symbol}. - * @param access the method's access flags. - * @param descriptor the method descriptor. - * @param maxLocals the maximum number of local variables of the method. - */ - final void setInputFrameFromDescriptor( - final SymbolTable symbolTable, - final int access, - final String descriptor, - final int maxLocals) { - inputLocals = new int[maxLocals]; - inputStack = new int[0]; - int inputLocalIndex = 0; - if ((access & Opcodes.ACC_STATIC) == 0) { - if ((access & Constants.ACC_CONSTRUCTOR) == 0) { - inputLocals[inputLocalIndex++] = - REFERENCE_KIND | symbolTable.addType(symbolTable.getClassName()); - } else { - inputLocals[inputLocalIndex++] = UNINITIALIZED_THIS; - } - } - for (Type argumentType : Type.getArgumentTypes(descriptor)) { - int abstractType = - getAbstractTypeFromDescriptor(symbolTable, argumentType.getDescriptor(), 0); - inputLocals[inputLocalIndex++] = abstractType; - if (abstractType == LONG || abstractType == DOUBLE) { - inputLocals[inputLocalIndex++] = TOP; - } - } - while (inputLocalIndex < maxLocals) { - inputLocals[inputLocalIndex++] = TOP; - } - } - - /** - * Sets the input frame from the given public API frame description. - * - * @param symbolTable the type table to use to lookup and store type {@link Symbol}. - * @param numLocal the number of local variables. - * @param local the local variable types, described using the same format as in {@link - * MethodVisitor#visitFrame}. - * @param numStack the number of operand stack elements. - * @param stack the operand stack types, described using the same format as in {@link - * MethodVisitor#visitFrame}. - */ - final void setInputFrameFromApiFormat( - final SymbolTable symbolTable, - final int numLocal, - final Object[] local, - final int numStack, - final Object[] stack) { - int inputLocalIndex = 0; - for (int i = 0; i < numLocal; ++i) { - inputLocals[inputLocalIndex++] = getAbstractTypeFromApiFormat(symbolTable, local[i]); - if (local[i] == Opcodes.LONG || local[i] == Opcodes.DOUBLE) { - inputLocals[inputLocalIndex++] = TOP; - } - } - while (inputLocalIndex < inputLocals.length) { - inputLocals[inputLocalIndex++] = TOP; - } - int numStackTop = 0; - for (int i = 0; i < numStack; ++i) { - if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) { - ++numStackTop; - } - } - inputStack = new int[numStack + numStackTop]; - int inputStackIndex = 0; - for (int i = 0; i < numStack; ++i) { - inputStack[inputStackIndex++] = getAbstractTypeFromApiFormat(symbolTable, stack[i]); - if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) { - inputStack[inputStackIndex++] = TOP; - } - } - outputStackTop = 0; - initializationCount = 0; - } - - final int getInputStackSize() { - return inputStack.length; - } - - // ----------------------------------------------------------------------------------------------- - // Methods related to the output frame - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the abstract type stored at the given local variable index in the output frame. - * - * @param localIndex the index of the local variable whose value must be returned. - * @return the abstract type stored at the given local variable index in the output frame. - */ - private int getLocal(final int localIndex) { - if (outputLocals == null || localIndex >= outputLocals.length) { - // If this local has never been assigned in this basic block, it is still equal to its value - // in the input frame. - return LOCAL_KIND | localIndex; - } else { - int abstractType = outputLocals[localIndex]; - if (abstractType == 0) { - // If this local has never been assigned in this basic block, so it is still equal to its - // value in the input frame. - abstractType = outputLocals[localIndex] = LOCAL_KIND | localIndex; - } - return abstractType; - } - } - - /** - * Replaces the abstract type stored at the given local variable index in the output frame. - * - * @param localIndex the index of the output frame local variable that must be set. - * @param abstractType the value that must be set. - */ - private void setLocal(final int localIndex, final int abstractType) { - // Create and/or resize the output local variables array if necessary. - if (outputLocals == null) { - outputLocals = new int[10]; - } - int outputLocalsLength = outputLocals.length; - if (localIndex >= outputLocalsLength) { - int[] newOutputLocals = new int[Math.max(localIndex + 1, 2 * outputLocalsLength)]; - System.arraycopy(outputLocals, 0, newOutputLocals, 0, outputLocalsLength); - outputLocals = newOutputLocals; - } - // Set the local variable. - outputLocals[localIndex] = abstractType; - } - - /** - * Pushes the given abstract type on the output frame stack. - * - * @param abstractType an abstract type. - */ - private void push(final int abstractType) { - // Create and/or resize the output stack array if necessary. - if (outputStack == null) { - outputStack = new int[10]; - } - int outputStackLength = outputStack.length; - if (outputStackTop >= outputStackLength) { - int[] newOutputStack = new int[Math.max(outputStackTop + 1, 2 * outputStackLength)]; - System.arraycopy(outputStack, 0, newOutputStack, 0, outputStackLength); - outputStack = newOutputStack; - } - // Pushes the abstract type on the output stack. - outputStack[outputStackTop++] = abstractType; - // Updates the maximum size reached by the output stack, if needed (note that this size is - // relative to the input stack size, which is not known yet). - short outputStackSize = (short) (outputStackStart + outputStackTop); - if (outputStackSize > owner.outputStackMax) { - owner.outputStackMax = outputStackSize; - } - } - - /** - * Pushes the abstract type corresponding to the given descriptor on the output frame stack. - * - * @param symbolTable the type table to use to lookup and store type {@link Symbol}. - * @param descriptor a type or method descriptor (in which case its return type is pushed). - */ - private void push(final SymbolTable symbolTable, final String descriptor) { - int typeDescriptorOffset = - descriptor.charAt(0) == '(' ? Type.getReturnTypeOffset(descriptor) : 0; - int abstractType = getAbstractTypeFromDescriptor(symbolTable, descriptor, typeDescriptorOffset); - if (abstractType != 0) { - push(abstractType); - if (abstractType == LONG || abstractType == DOUBLE) { - push(TOP); - } - } - } - - /** - * Pops an abstract type from the output frame stack and returns its value. - * - * @return the abstract type that has been popped from the output frame stack. - */ - private int pop() { - if (outputStackTop > 0) { - return outputStack[--outputStackTop]; - } else { - // If the output frame stack is empty, pop from the input stack. - return STACK_KIND | -(--outputStackStart); - } - } - - /** - * Pops the given number of abstract types from the output frame stack. - * - * @param elements the number of abstract types that must be popped. - */ - private void pop(final int elements) { - if (outputStackTop >= elements) { - outputStackTop -= elements; - } else { - // If the number of elements to be popped is greater than the number of elements in the output - // stack, clear it, and pop the remaining elements from the input stack. - outputStackStart -= elements - outputStackTop; - outputStackTop = 0; - } - } - - /** - * Pops as many abstract types from the output frame stack as described by the given descriptor. - * - * @param descriptor a type or method descriptor (in which case its argument types are popped). - */ - private void pop(final String descriptor) { - char firstDescriptorChar = descriptor.charAt(0); - if (firstDescriptorChar == '(') { - pop((Type.getArgumentsAndReturnSizes(descriptor) >> 2) - 1); - } else if (firstDescriptorChar == 'J' || firstDescriptorChar == 'D') { - pop(2); - } else { - pop(1); - } - } - - // ----------------------------------------------------------------------------------------------- - // Methods to handle uninitialized types - // ----------------------------------------------------------------------------------------------- - - /** - * Adds an abstract type to the list of types on which a constructor is invoked in the basic - * block. - * - * @param abstractType an abstract type on a which a constructor is invoked. - */ - private void addInitializedType(final int abstractType) { - // Create and/or resize the initializations array if necessary. - if (initializations == null) { - initializations = new int[2]; - } - int initializationsLength = initializations.length; - if (initializationCount >= initializationsLength) { - int[] newInitializations = - new int[Math.max(initializationCount + 1, 2 * initializationsLength)]; - System.arraycopy(initializations, 0, newInitializations, 0, initializationsLength); - initializations = newInitializations; - } - // Store the abstract type. - initializations[initializationCount++] = abstractType; - } - - /** - * Returns the "initialized" abstract type corresponding to the given abstract type. - * - * @param symbolTable the type table to use to lookup and store type {@link Symbol}. - * @param abstractType an abstract type. - * @return the REFERENCE_KIND abstract type corresponding to abstractType if it is - * UNINITIALIZED_THIS or an UNINITIALIZED_KIND abstract type for one of the types on which a - * constructor is invoked in the basic block. Otherwise returns abstractType. - */ - private int getInitializedType(final SymbolTable symbolTable, final int abstractType) { - if (abstractType == UNINITIALIZED_THIS - || (abstractType & (DIM_MASK | KIND_MASK)) == UNINITIALIZED_KIND) { - for (int i = 0; i < initializationCount; ++i) { - int initializedType = initializations[i]; - int dim = initializedType & DIM_MASK; - int kind = initializedType & KIND_MASK; - int value = initializedType & VALUE_MASK; - if (kind == LOCAL_KIND) { - initializedType = dim + inputLocals[value]; - } else if (kind == STACK_KIND) { - initializedType = dim + inputStack[inputStack.length - value]; - } - if (abstractType == initializedType) { - if (abstractType == UNINITIALIZED_THIS) { - return REFERENCE_KIND | symbolTable.addType(symbolTable.getClassName()); - } else { - return REFERENCE_KIND - | symbolTable.addType(symbolTable.getType(abstractType & VALUE_MASK).value); - } - } - } - } - return abstractType; - } - - // ----------------------------------------------------------------------------------------------- - // Main method, to simulate the execution of each instruction on the output frame - // ----------------------------------------------------------------------------------------------- - - /** - * Simulates the action of the given instruction on the output stack frame. - * - * @param opcode the opcode of the instruction. - * @param arg the numeric operand of the instruction, if any. - * @param argSymbol the Symbol operand of the instruction, if any. - * @param symbolTable the type table to use to lookup and store type {@link Symbol}. - */ - void execute( - final int opcode, final int arg, final Symbol argSymbol, final SymbolTable symbolTable) { - // Abstract types popped from the stack or read from local variables. - int abstractType1; - int abstractType2; - int abstractType3; - int abstractType4; - switch (opcode) { - case Opcodes.NOP: - case Opcodes.INEG: - case Opcodes.LNEG: - case Opcodes.FNEG: - case Opcodes.DNEG: - case Opcodes.I2B: - case Opcodes.I2C: - case Opcodes.I2S: - case Opcodes.GOTO: - case Opcodes.RETURN: - break; - case Opcodes.ACONST_NULL: - push(NULL); - break; - case Opcodes.ICONST_M1: - case Opcodes.ICONST_0: - case Opcodes.ICONST_1: - case Opcodes.ICONST_2: - case Opcodes.ICONST_3: - case Opcodes.ICONST_4: - case Opcodes.ICONST_5: - case Opcodes.BIPUSH: - case Opcodes.SIPUSH: - case Opcodes.ILOAD: - push(INTEGER); - break; - case Opcodes.LCONST_0: - case Opcodes.LCONST_1: - case Opcodes.LLOAD: - push(LONG); - push(TOP); - break; - case Opcodes.FCONST_0: - case Opcodes.FCONST_1: - case Opcodes.FCONST_2: - case Opcodes.FLOAD: - push(FLOAT); - break; - case Opcodes.DCONST_0: - case Opcodes.DCONST_1: - case Opcodes.DLOAD: - push(DOUBLE); - push(TOP); - break; - case Opcodes.LDC: - switch (argSymbol.tag) { - case Symbol.CONSTANT_INTEGER_TAG: - push(INTEGER); - break; - case Symbol.CONSTANT_LONG_TAG: - push(LONG); - push(TOP); - break; - case Symbol.CONSTANT_FLOAT_TAG: - push(FLOAT); - break; - case Symbol.CONSTANT_DOUBLE_TAG: - push(DOUBLE); - push(TOP); - break; - case Symbol.CONSTANT_CLASS_TAG: - push(REFERENCE_KIND | symbolTable.addType("java/lang/Class")); - break; - case Symbol.CONSTANT_STRING_TAG: - push(REFERENCE_KIND | symbolTable.addType("java/lang/String")); - break; - case Symbol.CONSTANT_METHOD_TYPE_TAG: - push(REFERENCE_KIND | symbolTable.addType("java/lang/invoke/MethodType")); - break; - case Symbol.CONSTANT_METHOD_HANDLE_TAG: - push(REFERENCE_KIND | symbolTable.addType("java/lang/invoke/MethodHandle")); - break; - case Symbol.CONSTANT_DYNAMIC_TAG: - push(symbolTable, argSymbol.value); - break; - default: - throw new AssertionError(); - } - break; - case Opcodes.ALOAD: - push(getLocal(arg)); - break; - case Opcodes.LALOAD: - case Opcodes.D2L: - pop(2); - push(LONG); - push(TOP); - break; - case Opcodes.DALOAD: - case Opcodes.L2D: - pop(2); - push(DOUBLE); - push(TOP); - break; - case Opcodes.AALOAD: - pop(1); - abstractType1 = pop(); - push(abstractType1 == NULL ? abstractType1 : ELEMENT_OF + abstractType1); - break; - case Opcodes.ISTORE: - case Opcodes.FSTORE: - case Opcodes.ASTORE: - abstractType1 = pop(); - setLocal(arg, abstractType1); - if (arg > 0) { - int previousLocalType = getLocal(arg - 1); - if (previousLocalType == LONG || previousLocalType == DOUBLE) { - setLocal(arg - 1, TOP); - } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND - || (previousLocalType & KIND_MASK) == STACK_KIND) { - // The type of the previous local variable is not known yet, but if it later appears - // to be LONG or DOUBLE, we should then use TOP instead. - setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG); - } - } - break; - case Opcodes.LSTORE: - case Opcodes.DSTORE: - pop(1); - abstractType1 = pop(); - setLocal(arg, abstractType1); - setLocal(arg + 1, TOP); - if (arg > 0) { - int previousLocalType = getLocal(arg - 1); - if (previousLocalType == LONG || previousLocalType == DOUBLE) { - setLocal(arg - 1, TOP); - } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND - || (previousLocalType & KIND_MASK) == STACK_KIND) { - // The type of the previous local variable is not known yet, but if it later appears - // to be LONG or DOUBLE, we should then use TOP instead. - setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG); - } - } - break; - case Opcodes.IASTORE: - case Opcodes.BASTORE: - case Opcodes.CASTORE: - case Opcodes.SASTORE: - case Opcodes.FASTORE: - case Opcodes.AASTORE: - pop(3); - break; - case Opcodes.LASTORE: - case Opcodes.DASTORE: - pop(4); - break; - case Opcodes.POP: - case Opcodes.IFEQ: - case Opcodes.IFNE: - case Opcodes.IFLT: - case Opcodes.IFGE: - case Opcodes.IFGT: - case Opcodes.IFLE: - case Opcodes.IRETURN: - case Opcodes.FRETURN: - case Opcodes.ARETURN: - case Opcodes.TABLESWITCH: - case Opcodes.LOOKUPSWITCH: - case Opcodes.ATHROW: - case Opcodes.MONITORENTER: - case Opcodes.MONITOREXIT: - case Opcodes.IFNULL: - case Opcodes.IFNONNULL: - pop(1); - break; - case Opcodes.POP2: - case Opcodes.IF_ICMPEQ: - case Opcodes.IF_ICMPNE: - case Opcodes.IF_ICMPLT: - case Opcodes.IF_ICMPGE: - case Opcodes.IF_ICMPGT: - case Opcodes.IF_ICMPLE: - case Opcodes.IF_ACMPEQ: - case Opcodes.IF_ACMPNE: - case Opcodes.LRETURN: - case Opcodes.DRETURN: - pop(2); - break; - case Opcodes.DUP: - abstractType1 = pop(); - push(abstractType1); - push(abstractType1); - break; - case Opcodes.DUP_X1: - abstractType1 = pop(); - abstractType2 = pop(); - push(abstractType1); - push(abstractType2); - push(abstractType1); - break; - case Opcodes.DUP_X2: - abstractType1 = pop(); - abstractType2 = pop(); - abstractType3 = pop(); - push(abstractType1); - push(abstractType3); - push(abstractType2); - push(abstractType1); - break; - case Opcodes.DUP2: - abstractType1 = pop(); - abstractType2 = pop(); - push(abstractType2); - push(abstractType1); - push(abstractType2); - push(abstractType1); - break; - case Opcodes.DUP2_X1: - abstractType1 = pop(); - abstractType2 = pop(); - abstractType3 = pop(); - push(abstractType2); - push(abstractType1); - push(abstractType3); - push(abstractType2); - push(abstractType1); - break; - case Opcodes.DUP2_X2: - abstractType1 = pop(); - abstractType2 = pop(); - abstractType3 = pop(); - abstractType4 = pop(); - push(abstractType2); - push(abstractType1); - push(abstractType4); - push(abstractType3); - push(abstractType2); - push(abstractType1); - break; - case Opcodes.SWAP: - abstractType1 = pop(); - abstractType2 = pop(); - push(abstractType1); - push(abstractType2); - break; - case Opcodes.IALOAD: - case Opcodes.BALOAD: - case Opcodes.CALOAD: - case Opcodes.SALOAD: - case Opcodes.IADD: - case Opcodes.ISUB: - case Opcodes.IMUL: - case Opcodes.IDIV: - case Opcodes.IREM: - case Opcodes.IAND: - case Opcodes.IOR: - case Opcodes.IXOR: - case Opcodes.ISHL: - case Opcodes.ISHR: - case Opcodes.IUSHR: - case Opcodes.L2I: - case Opcodes.D2I: - case Opcodes.FCMPL: - case Opcodes.FCMPG: - pop(2); - push(INTEGER); - break; - case Opcodes.LADD: - case Opcodes.LSUB: - case Opcodes.LMUL: - case Opcodes.LDIV: - case Opcodes.LREM: - case Opcodes.LAND: - case Opcodes.LOR: - case Opcodes.LXOR: - pop(4); - push(LONG); - push(TOP); - break; - case Opcodes.FALOAD: - case Opcodes.FADD: - case Opcodes.FSUB: - case Opcodes.FMUL: - case Opcodes.FDIV: - case Opcodes.FREM: - case Opcodes.L2F: - case Opcodes.D2F: - pop(2); - push(FLOAT); - break; - case Opcodes.DADD: - case Opcodes.DSUB: - case Opcodes.DMUL: - case Opcodes.DDIV: - case Opcodes.DREM: - pop(4); - push(DOUBLE); - push(TOP); - break; - case Opcodes.LSHL: - case Opcodes.LSHR: - case Opcodes.LUSHR: - pop(3); - push(LONG); - push(TOP); - break; - case Opcodes.IINC: - setLocal(arg, INTEGER); - break; - case Opcodes.I2L: - case Opcodes.F2L: - pop(1); - push(LONG); - push(TOP); - break; - case Opcodes.I2F: - pop(1); - push(FLOAT); - break; - case Opcodes.I2D: - case Opcodes.F2D: - pop(1); - push(DOUBLE); - push(TOP); - break; - case Opcodes.F2I: - case Opcodes.ARRAYLENGTH: - case Opcodes.INSTANCEOF: - pop(1); - push(INTEGER); - break; - case Opcodes.LCMP: - case Opcodes.DCMPL: - case Opcodes.DCMPG: - pop(4); - push(INTEGER); - break; - case Opcodes.JSR: - case Opcodes.RET: - throw new IllegalArgumentException("JSR/RET are not supported with computeFrames option"); - case Opcodes.GETSTATIC: - push(symbolTable, argSymbol.value); - break; - case Opcodes.PUTSTATIC: - pop(argSymbol.value); - break; - case Opcodes.GETFIELD: - pop(1); - push(symbolTable, argSymbol.value); - break; - case Opcodes.PUTFIELD: - pop(argSymbol.value); - pop(); - break; - case Opcodes.INVOKEVIRTUAL: - case Opcodes.INVOKESPECIAL: - case Opcodes.INVOKESTATIC: - case Opcodes.INVOKEINTERFACE: - pop(argSymbol.value); - if (opcode != Opcodes.INVOKESTATIC) { - abstractType1 = pop(); - if (opcode == Opcodes.INVOKESPECIAL && argSymbol.name.charAt(0) == '<') { - addInitializedType(abstractType1); - } - } - push(symbolTable, argSymbol.value); - break; - case Opcodes.INVOKEDYNAMIC: - pop(argSymbol.value); - push(symbolTable, argSymbol.value); - break; - case Opcodes.NEW: - push(UNINITIALIZED_KIND | symbolTable.addUninitializedType(argSymbol.value, arg)); - break; - case Opcodes.NEWARRAY: - pop(); - switch (arg) { - case Opcodes.T_BOOLEAN: - push(ARRAY_OF | BOOLEAN); - break; - case Opcodes.T_CHAR: - push(ARRAY_OF | CHAR); - break; - case Opcodes.T_BYTE: - push(ARRAY_OF | BYTE); - break; - case Opcodes.T_SHORT: - push(ARRAY_OF | SHORT); - break; - case Opcodes.T_INT: - push(ARRAY_OF | INTEGER); - break; - case Opcodes.T_FLOAT: - push(ARRAY_OF | FLOAT); - break; - case Opcodes.T_DOUBLE: - push(ARRAY_OF | DOUBLE); - break; - case Opcodes.T_LONG: - push(ARRAY_OF | LONG); - break; - default: - throw new IllegalArgumentException(); - } - break; - case Opcodes.ANEWARRAY: - String arrayElementType = argSymbol.value; - pop(); - if (arrayElementType.charAt(0) == '[') { - push(symbolTable, '[' + arrayElementType); - } else { - push(ARRAY_OF | REFERENCE_KIND | symbolTable.addType(arrayElementType)); - } - break; - case Opcodes.CHECKCAST: - String castType = argSymbol.value; - pop(); - if (castType.charAt(0) == '[') { - push(symbolTable, castType); - } else { - push(REFERENCE_KIND | symbolTable.addType(castType)); - } - break; - case Opcodes.MULTIANEWARRAY: - pop(arg); - push(symbolTable, argSymbol.value); - break; - default: - throw new IllegalArgumentException(); - } - } - - // ----------------------------------------------------------------------------------------------- - // Frame merging methods, used in the second step of the stack map frame computation algorithm - // ----------------------------------------------------------------------------------------------- - - /** - * Computes the concrete output type corresponding to a given abstract output type. - * - * @param abstractOutputType an abstract output type. - * @param numStack the size of the input stack, used to resolve abstract output types of - * STACK_KIND kind. - * @return the concrete output type corresponding to 'abstractOutputType'. - */ - private int getConcreteOutputType(final int abstractOutputType, final int numStack) { - int dim = abstractOutputType & DIM_MASK; - int kind = abstractOutputType & KIND_MASK; - if (kind == LOCAL_KIND) { - // By definition, a LOCAL_KIND type designates the concrete type of a local variable at - // the beginning of the basic block corresponding to this frame (which is known when - // this method is called, but was not when the abstract type was computed). - int concreteOutputType = dim + inputLocals[abstractOutputType & VALUE_MASK]; - if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0 - && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) { - concreteOutputType = TOP; - } - return concreteOutputType; - } else if (kind == STACK_KIND) { - // By definition, a STACK_KIND type designates the concrete type of a local variable at - // the beginning of the basic block corresponding to this frame (which is known when - // this method is called, but was not when the abstract type was computed). - int concreteOutputType = dim + inputStack[numStack - (abstractOutputType & VALUE_MASK)]; - if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0 - && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) { - concreteOutputType = TOP; - } - return concreteOutputType; - } else { - return abstractOutputType; - } - } - - /** - * Merges the input frame of the given {@link Frame} with the input and output frames of this - * {@link Frame}. Returns {@literal true} if the given frame has been changed by this operation - * (the input and output frames of this {@link Frame} are never changed). - * - * @param symbolTable the type table to use to lookup and store type {@link Symbol}. - * @param dstFrame the {@link Frame} whose input frame must be updated. This should be the frame - * of a successor, in the control flow graph, of the basic block corresponding to this frame. - * @param catchTypeIndex if 'frame' corresponds to an exception handler basic block, the type - * table index of the caught exception type, otherwise 0. - * @return {@literal true} if the input frame of 'frame' has been changed by this operation. - */ - final boolean merge( - final SymbolTable symbolTable, final Frame dstFrame, final int catchTypeIndex) { - boolean frameChanged = false; - - // Compute the concrete types of the local variables at the end of the basic block corresponding - // to this frame, by resolving its abstract output types, and merge these concrete types with - // those of the local variables in the input frame of dstFrame. - int numLocal = inputLocals.length; - int numStack = inputStack.length; - if (dstFrame.inputLocals == null) { - dstFrame.inputLocals = new int[numLocal]; - frameChanged = true; - } - for (int i = 0; i < numLocal; ++i) { - int concreteOutputType; - if (outputLocals != null && i < outputLocals.length) { - int abstractOutputType = outputLocals[i]; - if (abstractOutputType == 0) { - // If the local variable has never been assigned in this basic block, it is equal to its - // value at the beginning of the block. - concreteOutputType = inputLocals[i]; - } else { - concreteOutputType = getConcreteOutputType(abstractOutputType, numStack); - } - } else { - // If the local variable has never been assigned in this basic block, it is equal to its - // value at the beginning of the block. - concreteOutputType = inputLocals[i]; - } - // concreteOutputType might be an uninitialized type from the input locals or from the input - // stack. However, if a constructor has been called for this class type in the basic block, - // then this type is no longer uninitialized at the end of basic block. - if (initializations != null) { - concreteOutputType = getInitializedType(symbolTable, concreteOutputType); - } - frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputLocals, i); - } - - // If dstFrame is an exception handler block, it can be reached from any instruction of the - // basic block corresponding to this frame, in particular from the first one. Therefore, the - // input locals of dstFrame should be compatible (i.e. merged) with the input locals of this - // frame (and the input stack of dstFrame should be compatible, i.e. merged, with a one - // element stack containing the caught exception type). - if (catchTypeIndex > 0) { - for (int i = 0; i < numLocal; ++i) { - frameChanged |= merge(symbolTable, inputLocals[i], dstFrame.inputLocals, i); - } - if (dstFrame.inputStack == null) { - dstFrame.inputStack = new int[1]; - frameChanged = true; - } - frameChanged |= merge(symbolTable, catchTypeIndex, dstFrame.inputStack, 0); - return frameChanged; - } - - // Compute the concrete types of the stack operands at the end of the basic block corresponding - // to this frame, by resolving its abstract output types, and merge these concrete types with - // those of the stack operands in the input frame of dstFrame. - int numInputStack = inputStack.length + outputStackStart; - if (dstFrame.inputStack == null) { - dstFrame.inputStack = new int[numInputStack + outputStackTop]; - frameChanged = true; - } - // First, do this for the stack operands that have not been popped in the basic block - // corresponding to this frame, and which are therefore equal to their value in the input - // frame (except for uninitialized types, which may have been initialized). - for (int i = 0; i < numInputStack; ++i) { - int concreteOutputType = inputStack[i]; - if (initializations != null) { - concreteOutputType = getInitializedType(symbolTable, concreteOutputType); - } - frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputStack, i); - } - // Then, do this for the stack operands that have pushed in the basic block (this code is the - // same as the one above for local variables). - for (int i = 0; i < outputStackTop; ++i) { - int abstractOutputType = outputStack[i]; - int concreteOutputType = getConcreteOutputType(abstractOutputType, numStack); - if (initializations != null) { - concreteOutputType = getInitializedType(symbolTable, concreteOutputType); - } - frameChanged |= - merge(symbolTable, concreteOutputType, dstFrame.inputStack, numInputStack + i); - } - return frameChanged; - } - - /** - * Merges the type at the given index in the given abstract type array with the given type. - * Returns {@literal true} if the type array has been modified by this operation. - * - * @param symbolTable the type table to use to lookup and store type {@link Symbol}. - * @param sourceType the abstract type with which the abstract type array element must be merged. - * This type should be of {@link #CONSTANT_KIND}, {@link #REFERENCE_KIND} or {@link - * #UNINITIALIZED_KIND} kind, with positive or null array dimensions. - * @param dstTypes an array of abstract types. These types should be of {@link #CONSTANT_KIND}, - * {@link #REFERENCE_KIND} or {@link #UNINITIALIZED_KIND} kind, with positive or null array - * dimensions. - * @param dstIndex the index of the type that must be merged in dstTypes. - * @return {@literal true} if the type array has been modified by this operation. - */ - private static boolean merge( - final SymbolTable symbolTable, - final int sourceType, - final int[] dstTypes, - final int dstIndex) { - int dstType = dstTypes[dstIndex]; - if (dstType == sourceType) { - // If the types are equal, merge(sourceType, dstType) = dstType, so there is no change. - return false; - } - int srcType = sourceType; - if ((sourceType & ~DIM_MASK) == NULL) { - if (dstType == NULL) { - return false; - } - srcType = NULL; - } - if (dstType == 0) { - // If dstTypes[dstIndex] has never been assigned, merge(srcType, dstType) = srcType. - dstTypes[dstIndex] = srcType; - return true; - } - int mergedType; - if ((dstType & DIM_MASK) != 0 || (dstType & KIND_MASK) == REFERENCE_KIND) { - // If dstType is a reference type of any array dimension. - if (srcType == NULL) { - // If srcType is the NULL type, merge(srcType, dstType) = dstType, so there is no change. - return false; - } else if ((srcType & (DIM_MASK | KIND_MASK)) == (dstType & (DIM_MASK | KIND_MASK))) { - // If srcType has the same array dimension and the same kind as dstType. - if ((dstType & KIND_MASK) == REFERENCE_KIND) { - // If srcType and dstType are reference types with the same array dimension, - // merge(srcType, dstType) = dim(srcType) | common super class of srcType and dstType. - mergedType = - (srcType & DIM_MASK) - | REFERENCE_KIND - | symbolTable.addMergedType(srcType & VALUE_MASK, dstType & VALUE_MASK); - } else { - // If srcType and dstType are array types of equal dimension but different element types, - // merge(srcType, dstType) = dim(srcType) - 1 | java/lang/Object. - int mergedDim = ELEMENT_OF + (srcType & DIM_MASK); - mergedType = mergedDim | REFERENCE_KIND | symbolTable.addType("java/lang/Object"); - } - } else if ((srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND) { - // If srcType is any other reference or array type, - // merge(srcType, dstType) = min(srcDdim, dstDim) | java/lang/Object - // where srcDim is the array dimension of srcType, minus 1 if srcType is an array type - // with a non reference element type (and similarly for dstDim). - int srcDim = srcType & DIM_MASK; - if (srcDim != 0 && (srcType & KIND_MASK) != REFERENCE_KIND) { - srcDim = ELEMENT_OF + srcDim; - } - int dstDim = dstType & DIM_MASK; - if (dstDim != 0 && (dstType & KIND_MASK) != REFERENCE_KIND) { - dstDim = ELEMENT_OF + dstDim; - } - mergedType = - Math.min(srcDim, dstDim) | REFERENCE_KIND | symbolTable.addType("java/lang/Object"); - } else { - // If srcType is any other type, merge(srcType, dstType) = TOP. - mergedType = TOP; - } - } else if (dstType == NULL) { - // If dstType is the NULL type, merge(srcType, dstType) = srcType, or TOP if srcType is not a - // an array type or a reference type. - mergedType = - (srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND ? srcType : TOP; - } else { - // If dstType is any other type, merge(srcType, dstType) = TOP whatever srcType. - mergedType = TOP; - } - if (mergedType != dstType) { - dstTypes[dstIndex] = mergedType; - return true; - } - return false; - } - - // ----------------------------------------------------------------------------------------------- - // Frame output methods, to generate StackMapFrame attributes - // ----------------------------------------------------------------------------------------------- - - /** - * Makes the given {@link MethodWriter} visit the input frame of this {@link Frame}. The visit is - * done with the {@link MethodWriter#visitFrameStart}, {@link MethodWriter#visitAbstractType} and - * {@link MethodWriter#visitFrameEnd} methods. - * - * @param methodWriter the {@link MethodWriter} that should visit the input frame of this {@link - * Frame}. - */ - final void accept(final MethodWriter methodWriter) { - // Compute the number of locals, ignoring TOP types that are just after a LONG or a DOUBLE, and - // all trailing TOP types. - int[] localTypes = inputLocals; - int numLocal = 0; - int numTrailingTop = 0; - int i = 0; - while (i < localTypes.length) { - int localType = localTypes[i]; - i += (localType == LONG || localType == DOUBLE) ? 2 : 1; - if (localType == TOP) { - numTrailingTop++; - } else { - numLocal += numTrailingTop + 1; - numTrailingTop = 0; - } - } - // Compute the stack size, ignoring TOP types that are just after a LONG or a DOUBLE. - int[] stackTypes = inputStack; - int numStack = 0; - i = 0; - while (i < stackTypes.length) { - int stackType = stackTypes[i]; - i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1; - numStack++; - } - // Visit the frame and its content. - int frameIndex = methodWriter.visitFrameStart(owner.bytecodeOffset, numLocal, numStack); - i = 0; - while (numLocal-- > 0) { - int localType = localTypes[i]; - i += (localType == LONG || localType == DOUBLE) ? 2 : 1; - methodWriter.visitAbstractType(frameIndex++, localType); - } - i = 0; - while (numStack-- > 0) { - int stackType = stackTypes[i]; - i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1; - methodWriter.visitAbstractType(frameIndex++, stackType); - } - methodWriter.visitFrameEnd(); - } - - /** - * Put the given abstract type in the given ByteVector, using the JVMS verification_type_info - * format used in StackMapTable attributes. - * - * @param symbolTable the type table to use to lookup and store type {@link Symbol}. - * @param abstractType an abstract type, restricted to {@link Frame#CONSTANT_KIND}, {@link - * Frame#REFERENCE_KIND} or {@link Frame#UNINITIALIZED_KIND} types. - * @param output where the abstract type must be put. - * @see JVMS - * 4.7.4 - */ - static void putAbstractType( - final SymbolTable symbolTable, final int abstractType, final ByteVector output) { - int arrayDimensions = (abstractType & Frame.DIM_MASK) >> DIM_SHIFT; - if (arrayDimensions == 0) { - int typeValue = abstractType & VALUE_MASK; - switch (abstractType & KIND_MASK) { - case CONSTANT_KIND: - output.putByte(typeValue); - break; - case REFERENCE_KIND: - output - .putByte(ITEM_OBJECT) - .putShort(symbolTable.addConstantClass(symbolTable.getType(typeValue).value).index); - break; - case UNINITIALIZED_KIND: - output.putByte(ITEM_UNINITIALIZED).putShort((int) symbolTable.getType(typeValue).data); - break; - default: - throw new AssertionError(); - } - } else { - // Case of an array type, we need to build its descriptor first. - StringBuilder typeDescriptor = new StringBuilder(); - while (arrayDimensions-- > 0) { - typeDescriptor.append('['); - } - if ((abstractType & KIND_MASK) == REFERENCE_KIND) { - typeDescriptor - .append('L') - .append(symbolTable.getType(abstractType & VALUE_MASK).value) - .append(';'); - } else { - switch (abstractType & VALUE_MASK) { - case Frame.ITEM_ASM_BOOLEAN: - typeDescriptor.append('Z'); - break; - case Frame.ITEM_ASM_BYTE: - typeDescriptor.append('B'); - break; - case Frame.ITEM_ASM_CHAR: - typeDescriptor.append('C'); - break; - case Frame.ITEM_ASM_SHORT: - typeDescriptor.append('S'); - break; - case Frame.ITEM_INTEGER: - typeDescriptor.append('I'); - break; - case Frame.ITEM_FLOAT: - typeDescriptor.append('F'); - break; - case Frame.ITEM_LONG: - typeDescriptor.append('J'); - break; - case Frame.ITEM_DOUBLE: - typeDescriptor.append('D'); - break; - default: - throw new AssertionError(); - } - } - output - .putByte(ITEM_OBJECT) - .putShort(symbolTable.addConstantClass(typeDescriptor.toString()).index); - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/Handle.java b/jodd-proxetta/src/main/java/jodd/asm7/Handle.java deleted file mode 100644 index 2e6288653..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/Handle.java +++ /dev/null @@ -1,189 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. - -package jodd.asm7; - -/** - * A reference to a field or a method. - * - * @author Remi Forax - * @author Eric Bruneton - */ -public final class Handle { - - /** - * The kind of field or method designated by this Handle. Should be {@link Opcodes#H_GETFIELD}, - * {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link - * Opcodes#H_INVOKEVIRTUAL}, {@link Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, - * {@link Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}. - */ - private final int tag; - - /** The internal name of the class that owns the field or method designated by this handle. */ - private final String owner; - - /** The name of the field or method designated by this handle. */ - private final String name; - - /** The descriptor of the field or method designated by this handle. */ - private final String descriptor; - - /** Whether the owner is an interface or not. */ - private final boolean isInterface; - - /** - * Constructs a new field or method handle. - * - * @param tag the kind of field or method designated by this Handle. Must be {@link - * Opcodes#H_GETFIELD}, {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, {@link - * Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL}, {@link Opcodes#H_INVOKESTATIC}, - * {@link Opcodes#H_INVOKESPECIAL}, {@link Opcodes#H_NEWINVOKESPECIAL} or {@link - * Opcodes#H_INVOKEINTERFACE}. - * @param owner the internal name of the class that owns the field or method designated by this - * handle. - * @param name the name of the field or method designated by this handle. - * @param descriptor the descriptor of the field or method designated by this handle. - * @deprecated this constructor has been superseded by {@link #Handle(int, String, String, String, - * boolean)}. - */ - @Deprecated - public Handle(final int tag, final String owner, final String name, final String descriptor) { - this(tag, owner, name, descriptor, tag == Opcodes.H_INVOKEINTERFACE); - } - - /** - * Constructs a new field or method handle. - * - * @param tag the kind of field or method designated by this Handle. Must be {@link - * Opcodes#H_GETFIELD}, {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, {@link - * Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL}, {@link Opcodes#H_INVOKESTATIC}, - * {@link Opcodes#H_INVOKESPECIAL}, {@link Opcodes#H_NEWINVOKESPECIAL} or {@link - * Opcodes#H_INVOKEINTERFACE}. - * @param owner the internal name of the class that owns the field or method designated by this - * handle. - * @param name the name of the field or method designated by this handle. - * @param descriptor the descriptor of the field or method designated by this handle. - * @param isInterface whether the owner is an interface or not. - */ - public Handle( - final int tag, - final String owner, - final String name, - final String descriptor, - final boolean isInterface) { - this.tag = tag; - this.owner = owner; - this.name = name; - this.descriptor = descriptor; - this.isInterface = isInterface; - } - - /** - * Returns the kind of field or method designated by this handle. - * - * @return {@link Opcodes#H_GETFIELD}, {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, - * {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL}, {@link - * Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, {@link - * Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}. - */ - public int getTag() { - return tag; - } - - /** - * Returns the internal name of the class that owns the field or method designated by this handle. - * - * @return the internal name of the class that owns the field or method designated by this handle. - */ - public String getOwner() { - return owner; - } - - /** - * Returns the name of the field or method designated by this handle. - * - * @return the name of the field or method designated by this handle. - */ - public String getName() { - return name; - } - - /** - * Returns the descriptor of the field or method designated by this handle. - * - * @return the descriptor of the field or method designated by this handle. - */ - public String getDesc() { - return descriptor; - } - - /** - * Returns true if the owner of the field or method designated by this handle is an interface. - * - * @return true if the owner of the field or method designated by this handle is an interface. - */ - public boolean isInterface() { - return isInterface; - } - - @Override - public boolean equals(final Object object) { - if (object == this) { - return true; - } - if (!(object instanceof Handle)) { - return false; - } - Handle handle = (Handle) object; - return tag == handle.tag - && isInterface == handle.isInterface - && owner.equals(handle.owner) - && name.equals(handle.name) - && descriptor.equals(handle.descriptor); - } - - @Override - public int hashCode() { - return tag - + (isInterface ? 64 : 0) - + owner.hashCode() * name.hashCode() * descriptor.hashCode(); - } - - /** - * Returns the textual representation of this handle. The textual representation is: - * - *

    - *
  • for a reference to a class: owner "." name descriptor " (" tag ")", - *
  • for a reference to an interface: owner "." name descriptor " (" tag " itf)". - *
- */ - @Override - public String toString() { - return owner + '.' + name + descriptor + " (" + tag + (isInterface ? " itf" : "") + ')'; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/Handler.java b/jodd-proxetta/src/main/java/jodd/asm7/Handler.java deleted file mode 100644 index 92c9334b5..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/Handler.java +++ /dev/null @@ -1,198 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * Information about an exception handler. Corresponds to an element of the exception_table array of - * a Code attribute, as defined in the Java Virtual Machine Specification (JVMS). Handler instances - * can be chained together, with their {@link #nextHandler} field, to describe a full JVMS - * exception_table array. - * - * @see JVMS - * 4.7.3 - * @author Eric Bruneton - */ -final class Handler { - - /** - * The start_pc field of this JVMS exception_table entry. Corresponds to the beginning of the - * exception handler's scope (inclusive). - */ - final Label startPc; - - /** - * The end_pc field of this JVMS exception_table entry. Corresponds to the end of the exception - * handler's scope (exclusive). - */ - final Label endPc; - - /** - * The handler_pc field of this JVMS exception_table entry. Corresponding to the beginning of the - * exception handler's code. - */ - final Label handlerPc; - - /** - * The catch_type field of this JVMS exception_table entry. This is the constant pool index of the - * internal name of the type of exceptions handled by this handler, or 0 to catch any exceptions. - */ - final int catchType; - - /** - * The internal name of the type of exceptions handled by this handler, or {@literal null} to - * catch any exceptions. - */ - final String catchTypeDescriptor; - - /** The next exception handler. */ - Handler nextHandler; - - /** - * Constructs a new Handler. - * - * @param startPc the start_pc field of this JVMS exception_table entry. - * @param endPc the end_pc field of this JVMS exception_table entry. - * @param handlerPc the handler_pc field of this JVMS exception_table entry. - * @param catchType The catch_type field of this JVMS exception_table entry. - * @param catchTypeDescriptor The internal name of the type of exceptions handled by this handler, - * or {@literal null} to catch any exceptions. - */ - Handler( - final Label startPc, - final Label endPc, - final Label handlerPc, - final int catchType, - final String catchTypeDescriptor) { - this.startPc = startPc; - this.endPc = endPc; - this.handlerPc = handlerPc; - this.catchType = catchType; - this.catchTypeDescriptor = catchTypeDescriptor; - } - - /** - * Constructs a new Handler from the given one, with a different scope. - * - * @param handler an existing Handler. - * @param startPc the start_pc field of this JVMS exception_table entry. - * @param endPc the end_pc field of this JVMS exception_table entry. - */ - Handler(final Handler handler, final Label startPc, final Label endPc) { - this(startPc, endPc, handler.handlerPc, handler.catchType, handler.catchTypeDescriptor); - this.nextHandler = handler.nextHandler; - } - - /** - * Removes the range between start and end from the Handler list that begins with the given - * element. - * - * @param firstHandler the beginning of a Handler list. May be {@literal null}. - * @param start the start of the range to be removed. - * @param end the end of the range to be removed. Maybe {@literal null}. - * @return the exception handler list with the start-end range removed. - */ - static Handler removeRange(final Handler firstHandler, final Label start, final Label end) { - if (firstHandler == null) { - return null; - } else { - firstHandler.nextHandler = removeRange(firstHandler.nextHandler, start, end); - } - int handlerStart = firstHandler.startPc.bytecodeOffset; - int handlerEnd = firstHandler.endPc.bytecodeOffset; - int rangeStart = start.bytecodeOffset; - int rangeEnd = end == null ? Integer.MAX_VALUE : end.bytecodeOffset; - // Return early if [handlerStart,handlerEnd[ and [rangeStart,rangeEnd[ don't intersect. - if (rangeStart >= handlerEnd || rangeEnd <= handlerStart) { - return firstHandler; - } - if (rangeStart <= handlerStart) { - if (rangeEnd >= handlerEnd) { - // If [handlerStart,handlerEnd[ is included in [rangeStart,rangeEnd[, remove firstHandler. - return firstHandler.nextHandler; - } else { - // [handlerStart,handlerEnd[ - [rangeStart,rangeEnd[ = [rangeEnd,handlerEnd[ - return new Handler(firstHandler, end, firstHandler.endPc); - } - } else if (rangeEnd >= handlerEnd) { - // [handlerStart,handlerEnd[ - [rangeStart,rangeEnd[ = [handlerStart,rangeStart[ - return new Handler(firstHandler, firstHandler.startPc, start); - } else { - // [handlerStart,handlerEnd[ - [rangeStart,rangeEnd[ = - // [handlerStart,rangeStart[ + [rangeEnd,handerEnd[ - firstHandler.nextHandler = new Handler(firstHandler, end, firstHandler.endPc); - return new Handler(firstHandler, firstHandler.startPc, start); - } - } - - /** - * Returns the number of elements of the Handler list that begins with the given element. - * - * @param firstHandler the beginning of a Handler list. May be {@literal null}. - * @return the number of elements of the Handler list that begins with 'handler'. - */ - static int getExceptionTableLength(final Handler firstHandler) { - int length = 0; - Handler handler = firstHandler; - while (handler != null) { - length++; - handler = handler.nextHandler; - } - return length; - } - - /** - * Returns the size in bytes of the JVMS exception_table corresponding to the Handler list that - * begins with the given element. This includes the exception_table_length field. - * - * @param firstHandler the beginning of a Handler list. May be {@literal null}. - * @return the size in bytes of the exception_table_length and exception_table structures. - */ - static int getExceptionTableSize(final Handler firstHandler) { - return 2 + 8 * getExceptionTableLength(firstHandler); - } - - /** - * Puts the JVMS exception_table corresponding to the Handler list that begins with the given - * element. This includes the exception_table_length field. - * - * @param firstHandler the beginning of a Handler list. May be {@literal null}. - * @param output where the exception_table_length and exception_table structures must be put. - */ - static void putExceptionTable(final Handler firstHandler, final ByteVector output) { - output.putShort(getExceptionTableLength(firstHandler)); - Handler handler = firstHandler; - while (handler != null) { - output - .putShort(handler.startPc.bytecodeOffset) - .putShort(handler.endPc.bytecodeOffset) - .putShort(handler.handlerPc.bytecodeOffset) - .putShort(handler.catchType); - handler = handler.nextHandler; - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/Label.java b/jodd-proxetta/src/main/java/jodd/asm7/Label.java deleted file mode 100644 index a8ae741c3..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/Label.java +++ /dev/null @@ -1,621 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * A position in the bytecode of a method. Labels are used for jump, goto, and switch instructions, - * and for try catch blocks. A label designates the instruction that is just after. Note - * however that there can be other elements between a label and the instruction it designates (such - * as other labels, stack map frames, line numbers, etc.). - * - * @author Eric Bruneton - */ -public class Label { - - /** - * A flag indicating that a label is only used for debug attributes. Such a label is not the start - * of a basic block, the target of a jump instruction, or an exception handler. It can be safely - * ignored in control flow graph analysis algorithms (for optimization purposes). - */ - static final int FLAG_DEBUG_ONLY = 1; - - /** - * A flag indicating that a label is the target of a jump instruction, or the start of an - * exception handler. - */ - static final int FLAG_JUMP_TARGET = 2; - - /** A flag indicating that the bytecode offset of a label is known. */ - static final int FLAG_RESOLVED = 4; - - /** A flag indicating that a label corresponds to a reachable basic block. */ - static final int FLAG_REACHABLE = 8; - - /** - * A flag indicating that the basic block corresponding to a label ends with a subroutine call. By - * construction in {@link MethodWriter#visitJumpInsn}, labels with this flag set have at least two - * outgoing edges: - * - *
    - *
  • the first one corresponds to the instruction that follows the jsr instruction in the - * bytecode, i.e. where execution continues when it returns from the jsr call. This is a - * virtual control flow edge, since execution never goes directly from the jsr to the next - * instruction. Instead, it goes to the subroutine and eventually returns to the instruction - * following the jsr. This virtual edge is used to compute the real outgoing edges of the - * basic blocks ending with a ret instruction, in {@link #addSubroutineRetSuccessors}. - *
  • the second one corresponds to the target of the jsr instruction, - *
- */ - static final int FLAG_SUBROUTINE_CALLER = 16; - - /** - * A flag indicating that the basic block corresponding to a label is the start of a subroutine. - */ - static final int FLAG_SUBROUTINE_START = 32; - - /** A flag indicating that the basic block corresponding to a label is the end of a subroutine. */ - static final int FLAG_SUBROUTINE_END = 64; - - /** - * The number of elements to add to the {@link #otherLineNumbers} array when it needs to be - * resized to store a new source line number. - */ - static final int LINE_NUMBERS_CAPACITY_INCREMENT = 4; - - /** - * The number of elements to add to the {@link #forwardReferences} array when it needs to be - * resized to store a new forward reference. - */ - static final int FORWARD_REFERENCES_CAPACITY_INCREMENT = 6; - - /** - * The bit mask to extract the type of a forward reference to this label. The extracted type is - * either {@link #FORWARD_REFERENCE_TYPE_SHORT} or {@link #FORWARD_REFERENCE_TYPE_WIDE}. - * - * @see #forwardReferences - */ - static final int FORWARD_REFERENCE_TYPE_MASK = 0xF0000000; - - /** - * The type of forward references stored with two bytes in the bytecode. This is the case, for - * instance, of a forward reference from an ifnull instruction. - */ - static final int FORWARD_REFERENCE_TYPE_SHORT = 0x10000000; - - /** - * The type of forward references stored in four bytes in the bytecode. This is the case, for - * instance, of a forward reference from a lookupswitch instruction. - */ - static final int FORWARD_REFERENCE_TYPE_WIDE = 0x20000000; - - /** - * The bit mask to extract the 'handle' of a forward reference to this label. The extracted handle - * is the bytecode offset where the forward reference value is stored (using either 2 or 4 bytes, - * as indicated by the {@link #FORWARD_REFERENCE_TYPE_MASK}). - * - * @see #forwardReferences - */ - static final int FORWARD_REFERENCE_HANDLE_MASK = 0x0FFFFFFF; - - /** - * A sentinel element used to indicate the end of a list of labels. - * - * @see #nextListElement - */ - static final Label EMPTY_LIST = new Label(); - - /** - * A user managed state associated with this label. Warning: this field is used by the ASM tree - * package. In order to use it with the ASM tree package you must override the getLabelNode method - * in MethodNode. - */ - public Object info; - - /** - * The type and status of this label or its corresponding basic block. Must be zero or more of - * {@link #FLAG_DEBUG_ONLY}, {@link #FLAG_JUMP_TARGET}, {@link #FLAG_RESOLVED}, {@link - * #FLAG_REACHABLE}, {@link #FLAG_SUBROUTINE_CALLER}, {@link #FLAG_SUBROUTINE_START}, {@link - * #FLAG_SUBROUTINE_END}. - */ - short flags; - - /** - * The source line number corresponding to this label, or 0. If there are several source line - * numbers corresponding to this label, the first one is stored in this field, and the remaining - * ones are stored in {@link #otherLineNumbers}. - */ - private short lineNumber; - - /** - * The source line numbers corresponding to this label, in addition to {@link #lineNumber}, or - * null. The first element of this array is the number n of source line numbers it contains, which - * are stored between indices 1 and n (inclusive). - */ - private int[] otherLineNumbers; - - /** - * The offset of this label in the bytecode of its method, in bytes. This value is set if and only - * if the {@link #FLAG_RESOLVED} flag is set. - */ - int bytecodeOffset; - - /** - * The forward references to this label. The first element is the number of forward references, - * times 2 (this corresponds to the index of the last element actually used in this array). Then, - * each forward reference is described with two consecutive integers noted - * 'sourceInsnBytecodeOffset' and 'reference': - * - *
    - *
  • 'sourceInsnBytecodeOffset' is the bytecode offset of the instruction that contains the - * forward reference, - *
  • 'reference' contains the type and the offset in the bytecode where the forward reference - * value must be stored, which can be extracted with {@link #FORWARD_REFERENCE_TYPE_MASK} - * and {@link #FORWARD_REFERENCE_HANDLE_MASK}. - *
- * - *

For instance, for an ifnull instruction at bytecode offset x, 'sourceInsnBytecodeOffset' is - * equal to x, and 'reference' is of type {@link #FORWARD_REFERENCE_TYPE_SHORT} with value x + 1 - * (because the ifnull instruction uses a 2 bytes bytecode offset operand stored one byte after - * the start of the instruction itself). For the default case of a lookupswitch instruction at - * bytecode offset x, 'sourceInsnBytecodeOffset' is equal to x, and 'reference' is of type {@link - * #FORWARD_REFERENCE_TYPE_WIDE} with value between x + 1 and x + 4 (because the lookupswitch - * instruction uses a 4 bytes bytecode offset operand stored one to four bytes after the start of - * the instruction itself). - */ - private int[] forwardReferences; - - // ----------------------------------------------------------------------------------------------- - - // Fields for the control flow and data flow graph analysis algorithms (used to compute the - // maximum stack size or the stack map frames). A control flow graph contains one node per "basic - // block", and one edge per "jump" from one basic block to another. Each node (i.e., each basic - // block) is represented with the Label object that corresponds to the first instruction of this - // basic block. Each node also stores the list of its successors in the graph, as a linked list of - // Edge objects. - // - // The control flow analysis algorithms used to compute the maximum stack size or the stack map - // frames are similar and use two steps. The first step, during the visit of each instruction, - // builds information about the state of the local variables and the operand stack at the end of - // each basic block, called the "output frame", relatively to the frame state at the - // beginning of the basic block, which is called the "input frame", and which is unknown - // during this step. The second step, in {@link MethodWriter#computeAllFrames} and {@link - // MethodWriter#computeMaxStackAndLocal}, is a fix point algorithm - // that computes information about the input frame of each basic block, from the input state of - // the first basic block (known from the method signature), and by the using the previously - // computed relative output frames. - // - // The algorithm used to compute the maximum stack size only computes the relative output and - // absolute input stack heights, while the algorithm used to compute stack map frames computes - // relative output frames and absolute input frames. - - /** - * The number of elements in the input stack of the basic block corresponding to this label. This - * field is computed in {@link MethodWriter#computeMaxStackAndLocal}. - */ - short inputStackSize; - - /** - * The number of elements in the output stack, at the end of the basic block corresponding to this - * label. This field is only computed for basic blocks that end with a RET instruction. - */ - short outputStackSize; - - /** - * The maximum height reached by the output stack, relatively to the top of the input stack, in - * the basic block corresponding to this label. This maximum is always positive or null. - */ - short outputStackMax; - - /** - * The id of the subroutine to which this basic block belongs, or 0. If the basic block belongs to - * several subroutines, this is the id of the "oldest" subroutine that contains it (with the - * convention that a subroutine calling another one is "older" than the callee). This field is - * computed in {@link MethodWriter#computeMaxStackAndLocal}, if the method contains JSR - * instructions. - */ - short subroutineId; - - /** - * The input and output stack map frames of the basic block corresponding to this label. This - * field is only used when the {@link MethodWriter#COMPUTE_ALL_FRAMES} or {@link - * MethodWriter#COMPUTE_INSERTED_FRAMES} option is used. - */ - Frame frame; - - /** - * The successor of this label, in the order they are visited in {@link MethodVisitor#visitLabel}. - * This linked list does not include labels used for debug info only. If the {@link - * MethodWriter#COMPUTE_ALL_FRAMES} or {@link MethodWriter#COMPUTE_INSERTED_FRAMES} option is used - * then it does not contain either successive labels that denote the same bytecode offset (in this - * case only the first label appears in this list). - */ - Label nextBasicBlock; - - /** - * The outgoing edges of the basic block corresponding to this label, in the control flow graph of - * its method. These edges are stored in a linked list of {@link Edge} objects, linked to each - * other by their {@link Edge#nextEdge} field. - */ - Edge outgoingEdges; - - /** - * The next element in the list of labels to which this label belongs, or null if it does not - * belong to any list. All lists of labels must end with the {@link #EMPTY_LIST} sentinel, in - * order to ensure that this field is null if and only if this label does not belong to a list of - * labels. Note that there can be several lists of labels at the same time, but that a label can - * belong to at most one list at a time (unless some lists share a common tail, but this is not - * used in practice). - * - *

List of labels are used in {@link MethodWriter#computeAllFrames} and {@link - * MethodWriter#computeMaxStackAndLocal} to compute stack map frames and the maximum stack size, - * respectively, as well as in {@link #markSubroutine} and {@link #addSubroutineRetSuccessors} to - * compute the basic blocks belonging to subroutines and their outgoing edges. Outside of these - * methods, this field should be null (this property is a precondition and a postcondition of - * these methods). - */ - Label nextListElement; - - // ----------------------------------------------------------------------------------------------- - // Constructor and accessors - // ----------------------------------------------------------------------------------------------- - - /** Constructs a new label. */ - public Label() { - // Nothing to do. - } - - /** - * Returns the bytecode offset corresponding to this label. This offset is computed from the start - * of the method's bytecode. This method is intended for {@link Attribute} sub classes, and is - * normally not needed by class generators or adapters. - * - * @return the bytecode offset corresponding to this label. - * @throws IllegalStateException if this label is not resolved yet. - */ - public int getOffset() { - if ((flags & FLAG_RESOLVED) == 0) { - throw new IllegalStateException("Label offset position has not been resolved yet"); - } - return bytecodeOffset; - } - - /** - * Returns the "canonical" {@link Label} instance corresponding to this label's bytecode offset, - * if known, otherwise the label itself. The canonical instance is the first label (in the order - * of their visit by {@link MethodVisitor#visitLabel}) corresponding to this bytecode offset. It - * cannot be known for labels which have not been visited yet. - * - *

This method should only be used when the {@link MethodWriter#COMPUTE_ALL_FRAMES} option - * is used. - * - * @return the label itself if {@link #frame} is null, otherwise the Label's frame owner. This - * corresponds to the "canonical" label instance described above thanks to the way the label - * frame is set in {@link MethodWriter#visitLabel}. - */ - final Label getCanonicalInstance() { - return frame == null ? this : frame.owner; - } - - // ----------------------------------------------------------------------------------------------- - // Methods to manage line numbers - // ----------------------------------------------------------------------------------------------- - - /** - * Adds a source line number corresponding to this label. - * - * @param lineNumber a source line number (which should be strictly positive). - */ - final void addLineNumber(final int lineNumber) { - if (this.lineNumber == 0) { - this.lineNumber = (short) lineNumber; - } else { - if (otherLineNumbers == null) { - otherLineNumbers = new int[LINE_NUMBERS_CAPACITY_INCREMENT]; - } - int otherLineNumberIndex = ++otherLineNumbers[0]; - if (otherLineNumberIndex >= otherLineNumbers.length) { - int[] newLineNumbers = new int[otherLineNumbers.length + LINE_NUMBERS_CAPACITY_INCREMENT]; - System.arraycopy(otherLineNumbers, 0, newLineNumbers, 0, otherLineNumbers.length); - otherLineNumbers = newLineNumbers; - } - otherLineNumbers[otherLineNumberIndex] = lineNumber; - } - } - - /** - * Makes the given visitor visit this label and its source line numbers, if applicable. - * - * @param methodVisitor a method visitor. - * @param visitLineNumbers whether to visit of the label's source line numbers, if any. - */ - final void accept(final MethodVisitor methodVisitor, final boolean visitLineNumbers) { - methodVisitor.visitLabel(this); - if (visitLineNumbers && lineNumber != 0) { - methodVisitor.visitLineNumber(lineNumber & 0xFFFF, this); - if (otherLineNumbers != null) { - for (int i = 1; i <= otherLineNumbers[0]; ++i) { - methodVisitor.visitLineNumber(otherLineNumbers[i], this); - } - } - } - } - - // ----------------------------------------------------------------------------------------------- - // Methods to compute offsets and to manage forward references - // ----------------------------------------------------------------------------------------------- - - /** - * Puts a reference to this label in the bytecode of a method. If the bytecode offset of the label - * is known, the relative bytecode offset between the label and the instruction referencing it is - * computed and written directly. Otherwise, a null relative offset is written and a new forward - * reference is declared for this label. - * - * @param code the bytecode of the method. This is where the reference is appended. - * @param sourceInsnBytecodeOffset the bytecode offset of the instruction that contains the - * reference to be appended. - * @param wideReference whether the reference must be stored in 4 bytes (instead of 2 bytes). - */ - final void put( - final ByteVector code, final int sourceInsnBytecodeOffset, final boolean wideReference) { - if ((flags & FLAG_RESOLVED) == 0) { - if (wideReference) { - addForwardReference(sourceInsnBytecodeOffset, FORWARD_REFERENCE_TYPE_WIDE, code.length); - code.putInt(-1); - } else { - addForwardReference(sourceInsnBytecodeOffset, FORWARD_REFERENCE_TYPE_SHORT, code.length); - code.putShort(-1); - } - } else { - if (wideReference) { - code.putInt(bytecodeOffset - sourceInsnBytecodeOffset); - } else { - code.putShort(bytecodeOffset - sourceInsnBytecodeOffset); - } - } - } - - /** - * Adds a forward reference to this label. This method must be called only for a true forward - * reference, i.e. only if this label is not resolved yet. For backward references, the relative - * bytecode offset of the reference can be, and must be, computed and stored directly. - * - * @param sourceInsnBytecodeOffset the bytecode offset of the instruction that contains the - * reference stored at referenceHandle. - * @param referenceType either {@link #FORWARD_REFERENCE_TYPE_SHORT} or {@link - * #FORWARD_REFERENCE_TYPE_WIDE}. - * @param referenceHandle the offset in the bytecode where the forward reference value must be - * stored. - */ - private void addForwardReference( - final int sourceInsnBytecodeOffset, final int referenceType, final int referenceHandle) { - if (forwardReferences == null) { - forwardReferences = new int[FORWARD_REFERENCES_CAPACITY_INCREMENT]; - } - int lastElementIndex = forwardReferences[0]; - if (lastElementIndex + 2 >= forwardReferences.length) { - int[] newValues = new int[forwardReferences.length + FORWARD_REFERENCES_CAPACITY_INCREMENT]; - System.arraycopy(forwardReferences, 0, newValues, 0, forwardReferences.length); - forwardReferences = newValues; - } - forwardReferences[++lastElementIndex] = sourceInsnBytecodeOffset; - forwardReferences[++lastElementIndex] = referenceType | referenceHandle; - forwardReferences[0] = lastElementIndex; - } - - /** - * Sets the bytecode offset of this label to the given value and resolves the forward references - * to this label, if any. This method must be called when this label is added to the bytecode of - * the method, i.e. when its bytecode offset becomes known. This method fills in the blanks that - * where left in the bytecode by each forward reference previously added to this label. - * - * @param code the bytecode of the method. - * @param bytecodeOffset the bytecode offset of this label. - * @return {@literal true} if a blank that was left for this label was too small to store the - * offset. In such a case the corresponding jump instruction is replaced with an equivalent - * ASM specific instruction using an unsigned two bytes offset. These ASM specific - * instructions are later replaced with standard bytecode instructions with wider offsets (4 - * bytes instead of 2), in ClassReader. - */ - final boolean resolve(final byte[] code, final int bytecodeOffset) { - this.flags |= FLAG_RESOLVED; - this.bytecodeOffset = bytecodeOffset; - if (forwardReferences == null) { - return false; - } - boolean hasAsmInstructions = false; - for (int i = forwardReferences[0]; i > 0; i -= 2) { - final int sourceInsnBytecodeOffset = forwardReferences[i - 1]; - final int reference = forwardReferences[i]; - final int relativeOffset = bytecodeOffset - sourceInsnBytecodeOffset; - int handle = reference & FORWARD_REFERENCE_HANDLE_MASK; - if ((reference & FORWARD_REFERENCE_TYPE_MASK) == FORWARD_REFERENCE_TYPE_SHORT) { - if (relativeOffset < Short.MIN_VALUE || relativeOffset > Short.MAX_VALUE) { - // Change the opcode of the jump instruction, in order to be able to find it later in - // ClassReader. These ASM specific opcodes are similar to jump instruction opcodes, except - // that the 2 bytes offset is unsigned (and can therefore represent values from 0 to - // 65535, which is sufficient since the size of a method is limited to 65535 bytes). - int opcode = code[sourceInsnBytecodeOffset] & 0xFF; - if (opcode < Opcodes.IFNULL) { - // Change IFEQ ... JSR to ASM_IFEQ ... ASM_JSR. - code[sourceInsnBytecodeOffset] = (byte) (opcode + Constants.ASM_OPCODE_DELTA); - } else { - // Change IFNULL and IFNONNULL to ASM_IFNULL and ASM_IFNONNULL. - code[sourceInsnBytecodeOffset] = (byte) (opcode + Constants.ASM_IFNULL_OPCODE_DELTA); - } - hasAsmInstructions = true; - } - code[handle++] = (byte) (relativeOffset >>> 8); - code[handle] = (byte) relativeOffset; - } else { - code[handle++] = (byte) (relativeOffset >>> 24); - code[handle++] = (byte) (relativeOffset >>> 16); - code[handle++] = (byte) (relativeOffset >>> 8); - code[handle] = (byte) relativeOffset; - } - } - return hasAsmInstructions; - } - - // ----------------------------------------------------------------------------------------------- - // Methods related to subroutines - // ----------------------------------------------------------------------------------------------- - - /** - * Finds the basic blocks that belong to the subroutine starting with the basic block - * corresponding to this label, and marks these blocks as belonging to this subroutine. This - * method follows the control flow graph to find all the blocks that are reachable from the - * current basic block WITHOUT following any jsr target. - * - *

Note: a precondition and postcondition of this method is that all labels must have a null - * {@link #nextListElement}. - * - * @param subroutineId the id of the subroutine starting with the basic block corresponding to - * this label. - */ - final void markSubroutine(final short subroutineId) { - // Data flow algorithm: put this basic block in a list of blocks to process (which are blocks - // belonging to subroutine subroutineId) and, while there are blocks to process, remove one from - // the list, mark it as belonging to the subroutine, and add its successor basic blocks in the - // control flow graph to the list of blocks to process (if not already done). - Label listOfBlocksToProcess = this; - listOfBlocksToProcess.nextListElement = EMPTY_LIST; - while (listOfBlocksToProcess != EMPTY_LIST) { - // Remove a basic block from the list of blocks to process. - Label basicBlock = listOfBlocksToProcess; - listOfBlocksToProcess = listOfBlocksToProcess.nextListElement; - basicBlock.nextListElement = null; - - // If it is not already marked as belonging to a subroutine, mark it as belonging to - // subroutineId and add its successors to the list of blocks to process (unless already done). - if (basicBlock.subroutineId == 0) { - basicBlock.subroutineId = subroutineId; - listOfBlocksToProcess = basicBlock.pushSuccessors(listOfBlocksToProcess); - } - } - } - - /** - * Finds the basic blocks that end a subroutine starting with the basic block corresponding to - * this label and, for each one of them, adds an outgoing edge to the basic block following the - * given subroutine call. In other words, completes the control flow graph by adding the edges - * corresponding to the return from this subroutine, when called from the given caller basic - * block. - * - *

Note: a precondition and postcondition of this method is that all labels must have a null - * {@link #nextListElement}. - * - * @param subroutineCaller a basic block that ends with a jsr to the basic block corresponding to - * this label. This label is supposed to correspond to the start of a subroutine. - */ - final void addSubroutineRetSuccessors(final Label subroutineCaller) { - // Data flow algorithm: put this basic block in a list blocks to process (which are blocks - // belonging to a subroutine starting with this label) and, while there are blocks to process, - // remove one from the list, put it in a list of blocks that have been processed, add a return - // edge to the successor of subroutineCaller if applicable, and add its successor basic blocks - // in the control flow graph to the list of blocks to process (if not already done). - Label listOfProcessedBlocks = EMPTY_LIST; - Label listOfBlocksToProcess = this; - listOfBlocksToProcess.nextListElement = EMPTY_LIST; - while (listOfBlocksToProcess != EMPTY_LIST) { - // Move a basic block from the list of blocks to process to the list of processed blocks. - Label basicBlock = listOfBlocksToProcess; - listOfBlocksToProcess = basicBlock.nextListElement; - basicBlock.nextListElement = listOfProcessedBlocks; - listOfProcessedBlocks = basicBlock; - - // Add an edge from this block to the successor of the caller basic block, if this block is - // the end of a subroutine and if this block and subroutineCaller do not belong to the same - // subroutine. - if ((basicBlock.flags & FLAG_SUBROUTINE_END) != 0 - && basicBlock.subroutineId != subroutineCaller.subroutineId) { - basicBlock.outgoingEdges = - new Edge( - basicBlock.outputStackSize, - // By construction, the first outgoing edge of a basic block that ends with a jsr - // instruction leads to the jsr continuation block, i.e. where execution continues - // when ret is called (see {@link #FLAG_SUBROUTINE_CALLER}). - subroutineCaller.outgoingEdges.successor, - basicBlock.outgoingEdges); - } - // Add its successors to the list of blocks to process. Note that {@link #pushSuccessors} does - // not push basic blocks which are already in a list. Here this means either in the list of - // blocks to process, or in the list of already processed blocks. This second list is - // important to make sure we don't reprocess an already processed block. - listOfBlocksToProcess = basicBlock.pushSuccessors(listOfBlocksToProcess); - } - // Reset the {@link #nextListElement} of all the basic blocks that have been processed to null, - // so that this method can be called again with a different subroutine or subroutine caller. - while (listOfProcessedBlocks != EMPTY_LIST) { - Label newListOfProcessedBlocks = listOfProcessedBlocks.nextListElement; - listOfProcessedBlocks.nextListElement = null; - listOfProcessedBlocks = newListOfProcessedBlocks; - } - } - - /** - * Adds the successors of this label in the method's control flow graph (except those - * corresponding to a jsr target, and those already in a list of labels) to the given list of - * blocks to process, and returns the new list. - * - * @param listOfLabelsToProcess a list of basic blocks to process, linked together with their - * {@link #nextListElement} field. - * @return the new list of blocks to process. - */ - private Label pushSuccessors(final Label listOfLabelsToProcess) { - Label newListOfLabelsToProcess = listOfLabelsToProcess; - Edge outgoingEdge = outgoingEdges; - while (outgoingEdge != null) { - // By construction, the second outgoing edge of a basic block that ends with a jsr instruction - // leads to the jsr target (see {@link #FLAG_SUBROUTINE_CALLER}). - boolean isJsrTarget = - (flags & Label.FLAG_SUBROUTINE_CALLER) != 0 && outgoingEdge == outgoingEdges.nextEdge; - if (!isJsrTarget && outgoingEdge.successor.nextListElement == null) { - // Add this successor to the list of blocks to process, if it does not already belong to a - // list of labels. - outgoingEdge.successor.nextListElement = newListOfLabelsToProcess; - newListOfLabelsToProcess = outgoingEdge.successor; - } - outgoingEdge = outgoingEdge.nextEdge; - } - return newListOfLabelsToProcess; - } - - // ----------------------------------------------------------------------------------------------- - // Overridden Object methods - // ----------------------------------------------------------------------------------------------- - - /** - * Returns a string representation of this label. - * - * @return a string representation of this label. - */ - @Override - public String toString() { - return "L" + System.identityHashCode(this); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/MethodTooLargeException.java b/jodd-proxetta/src/main/java/jodd/asm7/MethodTooLargeException.java deleted file mode 100644 index 7817acfc3..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/MethodTooLargeException.java +++ /dev/null @@ -1,99 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * Exception thrown when the Code attribute of a method produced by a {@link ClassWriter} is too - * large. - * - * @author Jason Zaugg - */ -public final class MethodTooLargeException extends IndexOutOfBoundsException { - private static final long serialVersionUID = 6807380416709738314L; - - private final String className; - private final String methodName; - private final String descriptor; - private final int codeSize; - - /** - * Constructs a new {@link MethodTooLargeException}. - * - * @param className the internal name of the owner class. - * @param methodName the name of the method. - * @param descriptor the descriptor of the method. - * @param codeSize the size of the method's Code attribute, in bytes. - */ - public MethodTooLargeException( - final String className, - final String methodName, - final String descriptor, - final int codeSize) { - super("Method too large: " + className + "." + methodName + " " + descriptor); - this.className = className; - this.methodName = methodName; - this.descriptor = descriptor; - this.codeSize = codeSize; - } - - /** - * Returns the internal name of the owner class. - * - * @return the internal name of the owner class. - */ - public String getClassName() { - return className; - } - - /** - * Returns the name of the method. - * - * @return the name of the method. - */ - public String getMethodName() { - return methodName; - } - - /** - * Returns the descriptor of the method. - * - * @return the descriptor of the method. - */ - public String getDescriptor() { - return descriptor; - } - - /** - * Returns the size of the method's Code attribute, in bytes. - * - * @return the size of the method's Code attribute, in bytes. - */ - public int getCodeSize() { - return codeSize; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/MethodVisitor.java b/jodd-proxetta/src/main/java/jodd/asm7/MethodVisitor.java deleted file mode 100644 index 12d3e13c6..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/MethodVisitor.java +++ /dev/null @@ -1,775 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * A visitor to visit a Java method. The methods of this class must be called in the following - * order: ( {@code visitParameter} )* [ {@code visitAnnotationDefault} ] ( {@code visitAnnotation} | - * {@code visitAnnotableParameterCount} | {@code visitParameterAnnotation} {@code - * visitTypeAnnotation} | {@code visitAttribute} )* [ {@code visitCode} ( {@code visitFrame} | - * {@code visitXInsn} | {@code visitLabel} | {@code visitInsnAnnotation} | {@code - * visitTryCatchBlock} | {@code visitTryCatchAnnotation} | {@code visitLocalVariable} | {@code - * visitLocalVariableAnnotation} | {@code visitLineNumber} )* {@code visitMaxs} ] {@code visitEnd}. - * In addition, the {@code visitXInsn} and {@code visitLabel} methods must be called in the - * sequential order of the bytecode instructions of the visited code, {@code visitInsnAnnotation} - * must be called after the annotated instruction, {@code visitTryCatchBlock} must be called - * before the labels passed as arguments have been visited, {@code - * visitTryCatchBlockAnnotation} must be called after the corresponding try catch block has - * been visited, and the {@code visitLocalVariable}, {@code visitLocalVariableAnnotation} and {@code - * visitLineNumber} methods must be called after the labels passed as arguments have been - * visited. - * - * @author Eric Bruneton - */ -public abstract class MethodVisitor { - - private static final String REQUIRES_ASM5 = "This feature requires ASM5"; - - /** - * The ASM API version implemented by this visitor. The value of this field must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - */ - protected final int api; - - /** The method visitor to which this visitor must delegate method calls. May be null. */ - protected MethodVisitor mv; - - /** - * Constructs a new {@link MethodVisitor}. - * - * @param api the ASM API version implemented by this visitor. Must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - */ - public MethodVisitor(final int api) { - this(api, null); - } - - /** - * Constructs a new {@link MethodVisitor}. - * - * @param api the ASM API version implemented by this visitor. Must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - * @param methodVisitor the method visitor to which this visitor must delegate method calls. May - * be null. - */ - public MethodVisitor(final int api, final MethodVisitor methodVisitor) { - if (api != Opcodes.ASM7 && api != Opcodes.ASM6 && api != Opcodes.ASM5 && api != Opcodes.ASM4) { - throw new IllegalArgumentException("Unsupported api " + api); - } - this.api = api; - this.mv = methodVisitor; - } - - // ----------------------------------------------------------------------------------------------- - // Parameters, annotations and non standard attributes - // ----------------------------------------------------------------------------------------------- - - /** - * Visits a parameter of this method. - * - * @param name parameter name or null if none is provided. - * @param access the parameter's access flags, only {@code ACC_FINAL}, {@code ACC_SYNTHETIC} - * or/and {@code ACC_MANDATED} are allowed (see {@link Opcodes}). - */ - public void visitParameter(final String name, final int access) { - if (api < Opcodes.ASM5) { - throw new UnsupportedOperationException(REQUIRES_ASM5); - } - if (mv != null) { - mv.visitParameter(name, access); - } - } - - /** - * Visits the default value of this annotation interface method. - * - * @return a visitor to the visit the actual default value of this annotation interface method, or - * {@literal null} if this visitor is not interested in visiting this default value. The - * 'name' parameters passed to the methods of this annotation visitor are ignored. Moreover, - * exacly one visit method must be called on this annotation visitor, followed by visitEnd. - */ - public AnnotationVisitor visitAnnotationDefault() { - if (mv != null) { - return mv.visitAnnotationDefault(); - } - return null; - } - - /** - * Visits an annotation of this method. - * - * @param descriptor the class descriptor of the annotation class. - * @param visible {@literal true} if the annotation is visible at runtime. - * @return a visitor to visit the annotation values, or {@literal null} if this visitor is not - * interested in visiting this annotation. - */ - public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) { - if (mv != null) { - return mv.visitAnnotation(descriptor, visible); - } - return null; - } - - /** - * Visits an annotation on a type in the method signature. - * - * @param typeRef a reference to the annotated type. The sort of this type reference must be - * {@link TypeReference#METHOD_TYPE_PARAMETER}, {@link - * TypeReference#METHOD_TYPE_PARAMETER_BOUND}, {@link TypeReference#METHOD_RETURN}, {@link - * TypeReference#METHOD_RECEIVER}, {@link TypeReference#METHOD_FORMAL_PARAMETER} or {@link - * TypeReference#THROWS}. See {@link TypeReference}. - * @param typePath the path to the annotated type argument, wildcard bound, array element type, or - * static inner type within 'typeRef'. May be {@literal null} if the annotation targets - * 'typeRef' as a whole. - * @param descriptor the class descriptor of the annotation class. - * @param visible {@literal true} if the annotation is visible at runtime. - * @return a visitor to visit the annotation values, or {@literal null} if this visitor is not - * interested in visiting this annotation. - */ - public AnnotationVisitor visitTypeAnnotation( - final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { - if (api < Opcodes.ASM5) { - throw new UnsupportedOperationException(REQUIRES_ASM5); - } - if (mv != null) { - return mv.visitTypeAnnotation(typeRef, typePath, descriptor, visible); - } - return null; - } - - /** - * Visits the number of method parameters that can have annotations. By default (i.e. when this - * method is not called), all the method parameters defined by the method descriptor can have - * annotations. - * - * @param parameterCount the number of method parameters than can have annotations. This number - * must be less or equal than the number of parameter types in the method descriptor. It can - * be strictly less when a method has synthetic parameters and when these parameters are - * ignored when computing parameter indices for the purpose of parameter annotations (see - * https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.18). - * @param visible {@literal true} to define the number of method parameters that can have - * annotations visible at runtime, {@literal false} to define the number of method parameters - * that can have annotations invisible at runtime. - */ - public void visitAnnotableParameterCount(final int parameterCount, final boolean visible) { - if (mv != null) { - mv.visitAnnotableParameterCount(parameterCount, visible); - } - } - - /** - * Visits an annotation of a parameter this method. - * - * @param parameter the parameter index. This index must be strictly smaller than the number of - * parameters in the method descriptor, and strictly smaller than the parameter count - * specified in {@link #visitAnnotableParameterCount}. Important note: a parameter index i - * is not required to correspond to the i'th parameter descriptor in the method - * descriptor, in particular in case of synthetic parameters (see - * https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.18). - * @param descriptor the class descriptor of the annotation class. - * @param visible {@literal true} if the annotation is visible at runtime. - * @return a visitor to visit the annotation values, or {@literal null} if this visitor is not - * interested in visiting this annotation. - */ - public AnnotationVisitor visitParameterAnnotation( - final int parameter, final String descriptor, final boolean visible) { - if (mv != null) { - return mv.visitParameterAnnotation(parameter, descriptor, visible); - } - return null; - } - - /** - * Visits a non standard attribute of this method. - * - * @param attribute an attribute. - */ - public void visitAttribute(final Attribute attribute) { - if (mv != null) { - mv.visitAttribute(attribute); - } - } - - /** Starts the visit of the method's code, if any (i.e. non abstract method). */ - public void visitCode() { - if (mv != null) { - mv.visitCode(); - } - } - - /** - * Visits the current state of the local variables and operand stack elements. This method must(*) - * be called just before any instruction i that follows an unconditional branch - * instruction such as GOTO or THROW, that is the target of a jump instruction, or that starts an - * exception handler block. The visited types must describe the values of the local variables and - * of the operand stack elements just before i is executed.
- *
- * (*) this is mandatory only for classes whose version is greater than or equal to {@link - * Opcodes#V1_6}.
- *
- * The frames of a method must be given either in expanded form, or in compressed form (all frames - * must use the same format, i.e. you must not mix expanded and compressed frames within a single - * method): - * - *

    - *
  • In expanded form, all frames must have the F_NEW type. - *
  • In compressed form, frames are basically "deltas" from the state of the previous frame: - *
      - *
    • {@link Opcodes#F_SAME} representing frame with exactly the same locals as the - * previous frame and with the empty stack. - *
    • {@link Opcodes#F_SAME1} representing frame with exactly the same locals as the - * previous frame and with single value on the stack ( numStack is 1 and - * stack[0] contains value for the type of the stack item). - *
    • {@link Opcodes#F_APPEND} representing frame with current locals are the same as the - * locals in the previous frame, except that additional locals are defined ( - * numLocal is 1, 2 or 3 and local elements contains values - * representing added types). - *
    • {@link Opcodes#F_CHOP} representing frame with current locals are the same as the - * locals in the previous frame, except that the last 1-3 locals are absent and with - * the empty stack (numLocal is 1, 2 or 3). - *
    • {@link Opcodes#F_FULL} representing complete frame data. - *
    - *
- * - *
- * In both cases the first frame, corresponding to the method's parameters and access flags, is - * implicit and must not be visited. Also, it is illegal to visit two or more frames for the same - * code location (i.e., at least one instruction must be visited between two calls to visitFrame). - * - * @param type the type of this stack map frame. Must be {@link Opcodes#F_NEW} for expanded - * frames, or {@link Opcodes#F_FULL}, {@link Opcodes#F_APPEND}, {@link Opcodes#F_CHOP}, {@link - * Opcodes#F_SAME} or {@link Opcodes#F_APPEND}, {@link Opcodes#F_SAME1} for compressed frames. - * @param numLocal the number of local variables in the visited frame. - * @param local the local variable types in this frame. This array must not be modified. Primitive - * types are represented by {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, {@link - * Opcodes#FLOAT}, {@link Opcodes#LONG}, {@link Opcodes#DOUBLE}, {@link Opcodes#NULL} or - * {@link Opcodes#UNINITIALIZED_THIS} (long and double are represented by a single element). - * Reference types are represented by String objects (representing internal names), and - * uninitialized types by Label objects (this label designates the NEW instruction that - * created this uninitialized value). - * @param numStack the number of operand stack elements in the visited frame. - * @param stack the operand stack types in this frame. This array must not be modified. Its - * content has the same format as the "local" array. - * @throws IllegalStateException if a frame is visited just after another one, without any - * instruction between the two (unless this frame is a Opcodes#F_SAME frame, in which case it - * is silently ignored). - */ - public void visitFrame( - final int type, - final int numLocal, - final Object[] local, - final int numStack, - final Object[] stack) { - if (mv != null) { - mv.visitFrame(type, numLocal, local, numStack, stack); - } - } - - // ----------------------------------------------------------------------------------------------- - // Normal instructions - // ----------------------------------------------------------------------------------------------- - - /** - * Visits a zero operand instruction. - * - * @param opcode the opcode of the instruction to be visited. This opcode is either NOP, - * ACONST_NULL, ICONST_M1, ICONST_0, ICONST_1, ICONST_2, ICONST_3, ICONST_4, ICONST_5, - * LCONST_0, LCONST_1, FCONST_0, FCONST_1, FCONST_2, DCONST_0, DCONST_1, IALOAD, LALOAD, - * FALOAD, DALOAD, AALOAD, BALOAD, CALOAD, SALOAD, IASTORE, LASTORE, FASTORE, DASTORE, - * AASTORE, BASTORE, CASTORE, SASTORE, POP, POP2, DUP, DUP_X1, DUP_X2, DUP2, DUP2_X1, DUP2_X2, - * SWAP, IADD, LADD, FADD, DADD, ISUB, LSUB, FSUB, DSUB, IMUL, LMUL, FMUL, DMUL, IDIV, LDIV, - * FDIV, DDIV, IREM, LREM, FREM, DREM, INEG, LNEG, FNEG, DNEG, ISHL, LSHL, ISHR, LSHR, IUSHR, - * LUSHR, IAND, LAND, IOR, LOR, IXOR, LXOR, I2L, I2F, I2D, L2I, L2F, L2D, F2I, F2L, F2D, D2I, - * D2L, D2F, I2B, I2C, I2S, LCMP, FCMPL, FCMPG, DCMPL, DCMPG, IRETURN, LRETURN, FRETURN, - * DRETURN, ARETURN, RETURN, ARRAYLENGTH, ATHROW, MONITORENTER, or MONITOREXIT. - */ - public void visitInsn(final int opcode) { - if (mv != null) { - mv.visitInsn(opcode); - } - } - - /** - * Visits an instruction with a single int operand. - * - * @param opcode the opcode of the instruction to be visited. This opcode is either BIPUSH, SIPUSH - * or NEWARRAY. - * @param operand the operand of the instruction to be visited.
- * When opcode is BIPUSH, operand value should be between Byte.MIN_VALUE and Byte.MAX_VALUE. - *
- * When opcode is SIPUSH, operand value should be between Short.MIN_VALUE and Short.MAX_VALUE. - *
- * When opcode is NEWARRAY, operand value should be one of {@link Opcodes#T_BOOLEAN}, {@link - * Opcodes#T_CHAR}, {@link Opcodes#T_FLOAT}, {@link Opcodes#T_DOUBLE}, {@link Opcodes#T_BYTE}, - * {@link Opcodes#T_SHORT}, {@link Opcodes#T_INT} or {@link Opcodes#T_LONG}. - */ - public void visitIntInsn(final int opcode, final int operand) { - if (mv != null) { - mv.visitIntInsn(opcode, operand); - } - } - - /** - * Visits a local variable instruction. A local variable instruction is an instruction that loads - * or stores the value of a local variable. - * - * @param opcode the opcode of the local variable instruction to be visited. This opcode is either - * ILOAD, LLOAD, FLOAD, DLOAD, ALOAD, ISTORE, LSTORE, FSTORE, DSTORE, ASTORE or RET. - * @param var the operand of the instruction to be visited. This operand is the index of a local - * variable. - */ - public void visitVarInsn(final int opcode, final int var) { - if (mv != null) { - mv.visitVarInsn(opcode, var); - } - } - - /** - * Visits a type instruction. A type instruction is an instruction that takes the internal name of - * a class as parameter. - * - * @param opcode the opcode of the type instruction to be visited. This opcode is either NEW, - * ANEWARRAY, CHECKCAST or INSTANCEOF. - * @param type the operand of the instruction to be visited. This operand must be the internal - * name of an object or array class (see {@link Type#getInternalName()}). - */ - public void visitTypeInsn(final int opcode, final String type) { - if (mv != null) { - mv.visitTypeInsn(opcode, type); - } - } - - /** - * Visits a field instruction. A field instruction is an instruction that loads or stores the - * value of a field of an object. - * - * @param opcode the opcode of the type instruction to be visited. This opcode is either - * GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD. - * @param owner the internal name of the field's owner class (see {@link Type#getInternalName()}). - * @param name the field's name. - * @param descriptor the field's descriptor (see {@link Type}). - */ - public void visitFieldInsn( - final int opcode, final String owner, final String name, final String descriptor) { - if (mv != null) { - mv.visitFieldInsn(opcode, owner, name, descriptor); - } - } - - /** - * Visits a method instruction. A method instruction is an instruction that invokes a method. - * - * @param opcode the opcode of the type instruction to be visited. This opcode is either - * INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC or INVOKEINTERFACE. - * @param owner the internal name of the method's owner class (see {@link - * Type#getInternalName()}). - * @param name the method's name. - * @param descriptor the method's descriptor (see {@link Type}). - * @deprecated use {@link #visitMethodInsn(int, String, String, String, boolean)} instead. - */ - @Deprecated - public void visitMethodInsn( - final int opcode, final String owner, final String name, final String descriptor) { - int opcodeAndSource = opcode | (api < Opcodes.ASM5 ? Opcodes.SOURCE_DEPRECATED : 0); - visitMethodInsn(opcodeAndSource, owner, name, descriptor, opcode == Opcodes.INVOKEINTERFACE); - } - - /** - * Visits a method instruction. A method instruction is an instruction that invokes a method. - * - * @param opcode the opcode of the type instruction to be visited. This opcode is either - * INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC or INVOKEINTERFACE. - * @param owner the internal name of the method's owner class (see {@link - * Type#getInternalName()}). - * @param name the method's name. - * @param descriptor the method's descriptor (see {@link Type}). - * @param isInterface if the method's owner class is an interface. - */ - public void visitMethodInsn( - final int opcode, - final String owner, - final String name, - final String descriptor, - final boolean isInterface) { - if (api < Opcodes.ASM5 && (opcode & Opcodes.SOURCE_DEPRECATED) == 0) { - if (isInterface != (opcode == Opcodes.INVOKEINTERFACE)) { - throw new UnsupportedOperationException("INVOKESPECIAL/STATIC on interfaces requires ASM5"); - } - visitMethodInsn(opcode, owner, name, descriptor); - return; - } - if (mv != null) { - mv.visitMethodInsn(opcode & ~Opcodes.SOURCE_MASK, owner, name, descriptor, isInterface); - } - } - - /** - * Visits an invokedynamic instruction. - * - * @param name the method's name. - * @param descriptor the method's descriptor (see {@link Type}). - * @param bootstrapMethodHandle the bootstrap method. - * @param bootstrapMethodArguments the bootstrap method constant arguments. Each argument must be - * an {@link Integer}, {@link Float}, {@link Long}, {@link Double}, {@link String}, {@link - * Type}, {@link Handle} or {@link ConstantDynamic} value. This method is allowed to modify - * the content of the array so a caller should expect that this array may change. - */ - public void visitInvokeDynamicInsn( - final String name, - final String descriptor, - final Handle bootstrapMethodHandle, - final Object... bootstrapMethodArguments) { - if (api < Opcodes.ASM5) { - throw new UnsupportedOperationException(REQUIRES_ASM5); - } - if (mv != null) { - mv.visitInvokeDynamicInsn(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments); - } - } - - /** - * Visits a jump instruction. A jump instruction is an instruction that may jump to another - * instruction. - * - * @param opcode the opcode of the type instruction to be visited. This opcode is either IFEQ, - * IFNE, IFLT, IFGE, IFGT, IFLE, IF_ICMPEQ, IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, - * IF_ICMPLE, IF_ACMPEQ, IF_ACMPNE, GOTO, JSR, IFNULL or IFNONNULL. - * @param label the operand of the instruction to be visited. This operand is a label that - * designates the instruction to which the jump instruction may jump. - */ - public void visitJumpInsn(final int opcode, final Label label) { - if (mv != null) { - mv.visitJumpInsn(opcode, label); - } - } - - /** - * Visits a label. A label designates the instruction that will be visited just after it. - * - * @param label a {@link Label} object. - */ - public void visitLabel(final Label label) { - if (mv != null) { - mv.visitLabel(label); - } - } - - // ----------------------------------------------------------------------------------------------- - // Special instructions - // ----------------------------------------------------------------------------------------------- - - /** - * Visits a LDC instruction. Note that new constant types may be added in future versions of the - * Java Virtual Machine. To easily detect new constant types, implementations of this method - * should check for unexpected constant types, like this: - * - *
-   * if (cst instanceof Integer) {
-   *     // ...
-   * } else if (cst instanceof Float) {
-   *     // ...
-   * } else if (cst instanceof Long) {
-   *     // ...
-   * } else if (cst instanceof Double) {
-   *     // ...
-   * } else if (cst instanceof String) {
-   *     // ...
-   * } else if (cst instanceof Type) {
-   *     int sort = ((Type) cst).getSort();
-   *     if (sort == Type.OBJECT) {
-   *         // ...
-   *     } else if (sort == Type.ARRAY) {
-   *         // ...
-   *     } else if (sort == Type.METHOD) {
-   *         // ...
-   *     } else {
-   *         // throw an exception
-   *     }
-   * } else if (cst instanceof Handle) {
-   *     // ...
-   * } else if (cst instanceof ConstantDynamic) {
-   *     // ...
-   * } else {
-   *     // throw an exception
-   * }
-   * 
- * - * @param value the constant to be loaded on the stack. This parameter must be a non null {@link - * Integer}, a {@link Float}, a {@link Long}, a {@link Double}, a {@link String}, a {@link - * Type} of OBJECT or ARRAY sort for {@code .class} constants, for classes whose version is - * 49, a {@link Type} of METHOD sort for MethodType, a {@link Handle} for MethodHandle - * constants, for classes whose version is 51 or a {@link ConstantDynamic} for a constant - * dynamic for classes whose version is 55. - */ - public void visitLdcInsn(final Object value) { - if (api < Opcodes.ASM5 - && (value instanceof Handle - || (value instanceof Type && ((Type) value).getSort() == Type.METHOD))) { - throw new UnsupportedOperationException(REQUIRES_ASM5); - } - if (api != Opcodes.ASM7 && value instanceof ConstantDynamic) { - throw new UnsupportedOperationException("This feature requires ASM7"); - } - if (mv != null) { - mv.visitLdcInsn(value); - } - } - - /** - * Visits an IINC instruction. - * - * @param var index of the local variable to be incremented. - * @param increment amount to increment the local variable by. - */ - public void visitIincInsn(final int var, final int increment) { - if (mv != null) { - mv.visitIincInsn(var, increment); - } - } - - /** - * Visits a TABLESWITCH instruction. - * - * @param min the minimum key value. - * @param max the maximum key value. - * @param dflt beginning of the default handler block. - * @param labels beginnings of the handler blocks. {@code labels[i]} is the beginning of the - * handler block for the {@code min + i} key. - */ - public void visitTableSwitchInsn( - final int min, final int max, final Label dflt, final Label... labels) { - if (mv != null) { - mv.visitTableSwitchInsn(min, max, dflt, labels); - } - } - - /** - * Visits a LOOKUPSWITCH instruction. - * - * @param dflt beginning of the default handler block. - * @param keys the values of the keys. - * @param labels beginnings of the handler blocks. {@code labels[i]} is the beginning of the - * handler block for the {@code keys[i]} key. - */ - public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) { - if (mv != null) { - mv.visitLookupSwitchInsn(dflt, keys, labels); - } - } - - /** - * Visits a MULTIANEWARRAY instruction. - * - * @param descriptor an array type descriptor (see {@link Type}). - * @param numDimensions the number of dimensions of the array to allocate. - */ - public void visitMultiANewArrayInsn(final String descriptor, final int numDimensions) { - if (mv != null) { - mv.visitMultiANewArrayInsn(descriptor, numDimensions); - } - } - - /** - * Visits an annotation on an instruction. This method must be called just after the - * annotated instruction. It can be called several times for the same instruction. - * - * @param typeRef a reference to the annotated type. The sort of this type reference must be - * {@link TypeReference#INSTANCEOF}, {@link TypeReference#NEW}, {@link - * TypeReference#CONSTRUCTOR_REFERENCE}, {@link TypeReference#METHOD_REFERENCE}, {@link - * TypeReference#CAST}, {@link TypeReference#CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT}, {@link - * TypeReference#METHOD_INVOCATION_TYPE_ARGUMENT}, {@link - * TypeReference#CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT}, or {@link - * TypeReference#METHOD_REFERENCE_TYPE_ARGUMENT}. See {@link TypeReference}. - * @param typePath the path to the annotated type argument, wildcard bound, array element type, or - * static inner type within 'typeRef'. May be {@literal null} if the annotation targets - * 'typeRef' as a whole. - * @param descriptor the class descriptor of the annotation class. - * @param visible {@literal true} if the annotation is visible at runtime. - * @return a visitor to visit the annotation values, or {@literal null} if this visitor is not - * interested in visiting this annotation. - */ - public AnnotationVisitor visitInsnAnnotation( - final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { - if (api < Opcodes.ASM5) { - throw new UnsupportedOperationException(REQUIRES_ASM5); - } - if (mv != null) { - return mv.visitInsnAnnotation(typeRef, typePath, descriptor, visible); - } - return null; - } - - // ----------------------------------------------------------------------------------------------- - // Exceptions table entries, debug information, max stack and max locals - // ----------------------------------------------------------------------------------------------- - - /** - * Visits a try catch block. - * - * @param start the beginning of the exception handler's scope (inclusive). - * @param end the end of the exception handler's scope (exclusive). - * @param handler the beginning of the exception handler's code. - * @param type the internal name of the type of exceptions handled by the handler, or {@literal - * null} to catch any exceptions (for "finally" blocks). - * @throws IllegalArgumentException if one of the labels has already been visited by this visitor - * (by the {@link #visitLabel} method). - */ - public void visitTryCatchBlock( - final Label start, final Label end, final Label handler, final String type) { - if (mv != null) { - mv.visitTryCatchBlock(start, end, handler, type); - } - } - - /** - * Visits an annotation on an exception handler type. This method must be called after the - * {@link #visitTryCatchBlock} for the annotated exception handler. It can be called several times - * for the same exception handler. - * - * @param typeRef a reference to the annotated type. The sort of this type reference must be - * {@link TypeReference#EXCEPTION_PARAMETER}. See {@link TypeReference}. - * @param typePath the path to the annotated type argument, wildcard bound, array element type, or - * static inner type within 'typeRef'. May be {@literal null} if the annotation targets - * 'typeRef' as a whole. - * @param descriptor the class descriptor of the annotation class. - * @param visible {@literal true} if the annotation is visible at runtime. - * @return a visitor to visit the annotation values, or {@literal null} if this visitor is not - * interested in visiting this annotation. - */ - public AnnotationVisitor visitTryCatchAnnotation( - final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { - if (api < Opcodes.ASM5) { - throw new UnsupportedOperationException(REQUIRES_ASM5); - } - if (mv != null) { - return mv.visitTryCatchAnnotation(typeRef, typePath, descriptor, visible); - } - return null; - } - - /** - * Visits a local variable declaration. - * - * @param name the name of a local variable. - * @param descriptor the type descriptor of this local variable. - * @param signature the type signature of this local variable. May be {@literal null} if the local - * variable type does not use generic types. - * @param start the first instruction corresponding to the scope of this local variable - * (inclusive). - * @param end the last instruction corresponding to the scope of this local variable (exclusive). - * @param index the local variable's index. - * @throws IllegalArgumentException if one of the labels has not already been visited by this - * visitor (by the {@link #visitLabel} method). - */ - public void visitLocalVariable( - final String name, - final String descriptor, - final String signature, - final Label start, - final Label end, - final int index) { - if (mv != null) { - mv.visitLocalVariable(name, descriptor, signature, start, end, index); - } - } - - /** - * Visits an annotation on a local variable type. - * - * @param typeRef a reference to the annotated type. The sort of this type reference must be - * {@link TypeReference#LOCAL_VARIABLE} or {@link TypeReference#RESOURCE_VARIABLE}. See {@link - * TypeReference}. - * @param typePath the path to the annotated type argument, wildcard bound, array element type, or - * static inner type within 'typeRef'. May be {@literal null} if the annotation targets - * 'typeRef' as a whole. - * @param start the fist instructions corresponding to the continuous ranges that make the scope - * of this local variable (inclusive). - * @param end the last instructions corresponding to the continuous ranges that make the scope of - * this local variable (exclusive). This array must have the same size as the 'start' array. - * @param index the local variable's index in each range. This array must have the same size as - * the 'start' array. - * @param descriptor the class descriptor of the annotation class. - * @param visible {@literal true} if the annotation is visible at runtime. - * @return a visitor to visit the annotation values, or {@literal null} if this visitor is not - * interested in visiting this annotation. - */ - public AnnotationVisitor visitLocalVariableAnnotation( - final int typeRef, - final TypePath typePath, - final Label[] start, - final Label[] end, - final int[] index, - final String descriptor, - final boolean visible) { - if (api < Opcodes.ASM5) { - throw new UnsupportedOperationException(REQUIRES_ASM5); - } - if (mv != null) { - return mv.visitLocalVariableAnnotation( - typeRef, typePath, start, end, index, descriptor, visible); - } - return null; - } - - /** - * Visits a line number declaration. - * - * @param line a line number. This number refers to the source file from which the class was - * compiled. - * @param start the first instruction corresponding to this line number. - * @throws IllegalArgumentException if {@code start} has not already been visited by this visitor - * (by the {@link #visitLabel} method). - */ - public void visitLineNumber(final int line, final Label start) { - if (mv != null) { - mv.visitLineNumber(line, start); - } - } - - /** - * Visits the maximum stack size and the maximum number of local variables of the method. - * - * @param maxStack maximum stack size of the method. - * @param maxLocals maximum number of local variables for the method. - */ - public void visitMaxs(final int maxStack, final int maxLocals) { - if (mv != null) { - mv.visitMaxs(maxStack, maxLocals); - } - } - - /** - * Visits the end of the method. This method, which is the last one to be called, is used to - * inform the visitor that all the annotations and attributes of the method have been visited. - */ - public void visitEnd() { - if (mv != null) { - mv.visitEnd(); - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/MethodWriter.java b/jodd-proxetta/src/main/java/jodd/asm7/MethodWriter.java deleted file mode 100644 index 398b9207b..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/MethodWriter.java +++ /dev/null @@ -1,2390 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * A {@link MethodVisitor} that generates a corresponding 'method_info' structure, as defined in the - * Java Virtual Machine Specification (JVMS). - * - * @see JVMS - * 4.6 - * @author Eric Bruneton - * @author Eugene Kuleshov - */ -final class MethodWriter extends MethodVisitor { - - /** Indicates that nothing must be computed. */ - static final int COMPUTE_NOTHING = 0; - - /** - * Indicates that the maximum stack size and the maximum number of local variables must be - * computed, from scratch. - */ - static final int COMPUTE_MAX_STACK_AND_LOCAL = 1; - - /** - * Indicates that the maximum stack size and the maximum number of local variables must be - * computed, from the existing stack map frames. This can be done more efficiently than with the - * control flow graph algorithm used for {@link #COMPUTE_MAX_STACK_AND_LOCAL}, by using a linear - * scan of the bytecode instructions. - */ - static final int COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES = 2; - - /** - * Indicates that the stack map frames of type F_INSERT must be computed. The other frames are not - * computed. They should all be of type F_NEW and should be sufficient to compute the content of - * the F_INSERT frames, together with the bytecode instructions between a F_NEW and a F_INSERT - * frame - and without any knowledge of the type hierarchy (by definition of F_INSERT). - */ - static final int COMPUTE_INSERTED_FRAMES = 3; - - /** - * Indicates that all the stack map frames must be computed. In this case the maximum stack size - * and the maximum number of local variables is also computed. - */ - static final int COMPUTE_ALL_FRAMES = 4; - - /** Indicates that {@link #STACK_SIZE_DELTA} is not applicable (not constant or never used). */ - private static final int NA = 0; - - /** - * The stack size variation corresponding to each JVM opcode. The stack size variation for opcode - * 'o' is given by the array element at index 'o'. - * - * @see JVMS 6 - */ - private static final int[] STACK_SIZE_DELTA = { - 0, // nop = 0 (0x0) - 1, // aconst_null = 1 (0x1) - 1, // iconst_m1 = 2 (0x2) - 1, // iconst_0 = 3 (0x3) - 1, // iconst_1 = 4 (0x4) - 1, // iconst_2 = 5 (0x5) - 1, // iconst_3 = 6 (0x6) - 1, // iconst_4 = 7 (0x7) - 1, // iconst_5 = 8 (0x8) - 2, // lconst_0 = 9 (0x9) - 2, // lconst_1 = 10 (0xa) - 1, // fconst_0 = 11 (0xb) - 1, // fconst_1 = 12 (0xc) - 1, // fconst_2 = 13 (0xd) - 2, // dconst_0 = 14 (0xe) - 2, // dconst_1 = 15 (0xf) - 1, // bipush = 16 (0x10) - 1, // sipush = 17 (0x11) - 1, // ldc = 18 (0x12) - NA, // ldc_w = 19 (0x13) - NA, // ldc2_w = 20 (0x14) - 1, // iload = 21 (0x15) - 2, // lload = 22 (0x16) - 1, // fload = 23 (0x17) - 2, // dload = 24 (0x18) - 1, // aload = 25 (0x19) - NA, // iload_0 = 26 (0x1a) - NA, // iload_1 = 27 (0x1b) - NA, // iload_2 = 28 (0x1c) - NA, // iload_3 = 29 (0x1d) - NA, // lload_0 = 30 (0x1e) - NA, // lload_1 = 31 (0x1f) - NA, // lload_2 = 32 (0x20) - NA, // lload_3 = 33 (0x21) - NA, // fload_0 = 34 (0x22) - NA, // fload_1 = 35 (0x23) - NA, // fload_2 = 36 (0x24) - NA, // fload_3 = 37 (0x25) - NA, // dload_0 = 38 (0x26) - NA, // dload_1 = 39 (0x27) - NA, // dload_2 = 40 (0x28) - NA, // dload_3 = 41 (0x29) - NA, // aload_0 = 42 (0x2a) - NA, // aload_1 = 43 (0x2b) - NA, // aload_2 = 44 (0x2c) - NA, // aload_3 = 45 (0x2d) - -1, // iaload = 46 (0x2e) - 0, // laload = 47 (0x2f) - -1, // faload = 48 (0x30) - 0, // daload = 49 (0x31) - -1, // aaload = 50 (0x32) - -1, // baload = 51 (0x33) - -1, // caload = 52 (0x34) - -1, // saload = 53 (0x35) - -1, // istore = 54 (0x36) - -2, // lstore = 55 (0x37) - -1, // fstore = 56 (0x38) - -2, // dstore = 57 (0x39) - -1, // astore = 58 (0x3a) - NA, // istore_0 = 59 (0x3b) - NA, // istore_1 = 60 (0x3c) - NA, // istore_2 = 61 (0x3d) - NA, // istore_3 = 62 (0x3e) - NA, // lstore_0 = 63 (0x3f) - NA, // lstore_1 = 64 (0x40) - NA, // lstore_2 = 65 (0x41) - NA, // lstore_3 = 66 (0x42) - NA, // fstore_0 = 67 (0x43) - NA, // fstore_1 = 68 (0x44) - NA, // fstore_2 = 69 (0x45) - NA, // fstore_3 = 70 (0x46) - NA, // dstore_0 = 71 (0x47) - NA, // dstore_1 = 72 (0x48) - NA, // dstore_2 = 73 (0x49) - NA, // dstore_3 = 74 (0x4a) - NA, // astore_0 = 75 (0x4b) - NA, // astore_1 = 76 (0x4c) - NA, // astore_2 = 77 (0x4d) - NA, // astore_3 = 78 (0x4e) - -3, // iastore = 79 (0x4f) - -4, // lastore = 80 (0x50) - -3, // fastore = 81 (0x51) - -4, // dastore = 82 (0x52) - -3, // aastore = 83 (0x53) - -3, // bastore = 84 (0x54) - -3, // castore = 85 (0x55) - -3, // sastore = 86 (0x56) - -1, // pop = 87 (0x57) - -2, // pop2 = 88 (0x58) - 1, // dup = 89 (0x59) - 1, // dup_x1 = 90 (0x5a) - 1, // dup_x2 = 91 (0x5b) - 2, // dup2 = 92 (0x5c) - 2, // dup2_x1 = 93 (0x5d) - 2, // dup2_x2 = 94 (0x5e) - 0, // swap = 95 (0x5f) - -1, // iadd = 96 (0x60) - -2, // ladd = 97 (0x61) - -1, // fadd = 98 (0x62) - -2, // dadd = 99 (0x63) - -1, // isub = 100 (0x64) - -2, // lsub = 101 (0x65) - -1, // fsub = 102 (0x66) - -2, // dsub = 103 (0x67) - -1, // imul = 104 (0x68) - -2, // lmul = 105 (0x69) - -1, // fmul = 106 (0x6a) - -2, // dmul = 107 (0x6b) - -1, // idiv = 108 (0x6c) - -2, // ldiv = 109 (0x6d) - -1, // fdiv = 110 (0x6e) - -2, // ddiv = 111 (0x6f) - -1, // irem = 112 (0x70) - -2, // lrem = 113 (0x71) - -1, // frem = 114 (0x72) - -2, // drem = 115 (0x73) - 0, // ineg = 116 (0x74) - 0, // lneg = 117 (0x75) - 0, // fneg = 118 (0x76) - 0, // dneg = 119 (0x77) - -1, // ishl = 120 (0x78) - -1, // lshl = 121 (0x79) - -1, // ishr = 122 (0x7a) - -1, // lshr = 123 (0x7b) - -1, // iushr = 124 (0x7c) - -1, // lushr = 125 (0x7d) - -1, // iand = 126 (0x7e) - -2, // land = 127 (0x7f) - -1, // ior = 128 (0x80) - -2, // lor = 129 (0x81) - -1, // ixor = 130 (0x82) - -2, // lxor = 131 (0x83) - 0, // iinc = 132 (0x84) - 1, // i2l = 133 (0x85) - 0, // i2f = 134 (0x86) - 1, // i2d = 135 (0x87) - -1, // l2i = 136 (0x88) - -1, // l2f = 137 (0x89) - 0, // l2d = 138 (0x8a) - 0, // f2i = 139 (0x8b) - 1, // f2l = 140 (0x8c) - 1, // f2d = 141 (0x8d) - -1, // d2i = 142 (0x8e) - 0, // d2l = 143 (0x8f) - -1, // d2f = 144 (0x90) - 0, // i2b = 145 (0x91) - 0, // i2c = 146 (0x92) - 0, // i2s = 147 (0x93) - -3, // lcmp = 148 (0x94) - -1, // fcmpl = 149 (0x95) - -1, // fcmpg = 150 (0x96) - -3, // dcmpl = 151 (0x97) - -3, // dcmpg = 152 (0x98) - -1, // ifeq = 153 (0x99) - -1, // ifne = 154 (0x9a) - -1, // iflt = 155 (0x9b) - -1, // ifge = 156 (0x9c) - -1, // ifgt = 157 (0x9d) - -1, // ifle = 158 (0x9e) - -2, // if_icmpeq = 159 (0x9f) - -2, // if_icmpne = 160 (0xa0) - -2, // if_icmplt = 161 (0xa1) - -2, // if_icmpge = 162 (0xa2) - -2, // if_icmpgt = 163 (0xa3) - -2, // if_icmple = 164 (0xa4) - -2, // if_acmpeq = 165 (0xa5) - -2, // if_acmpne = 166 (0xa6) - 0, // goto = 167 (0xa7) - 1, // jsr = 168 (0xa8) - 0, // ret = 169 (0xa9) - -1, // tableswitch = 170 (0xaa) - -1, // lookupswitch = 171 (0xab) - -1, // ireturn = 172 (0xac) - -2, // lreturn = 173 (0xad) - -1, // freturn = 174 (0xae) - -2, // dreturn = 175 (0xaf) - -1, // areturn = 176 (0xb0) - 0, // return = 177 (0xb1) - NA, // getstatic = 178 (0xb2) - NA, // putstatic = 179 (0xb3) - NA, // getfield = 180 (0xb4) - NA, // putfield = 181 (0xb5) - NA, // invokevirtual = 182 (0xb6) - NA, // invokespecial = 183 (0xb7) - NA, // invokestatic = 184 (0xb8) - NA, // invokeinterface = 185 (0xb9) - NA, // invokedynamic = 186 (0xba) - 1, // new = 187 (0xbb) - 0, // newarray = 188 (0xbc) - 0, // anewarray = 189 (0xbd) - 0, // arraylength = 190 (0xbe) - NA, // athrow = 191 (0xbf) - 0, // checkcast = 192 (0xc0) - 0, // instanceof = 193 (0xc1) - -1, // monitorenter = 194 (0xc2) - -1, // monitorexit = 195 (0xc3) - NA, // wide = 196 (0xc4) - NA, // multianewarray = 197 (0xc5) - -1, // ifnull = 198 (0xc6) - -1, // ifnonnull = 199 (0xc7) - NA, // goto_w = 200 (0xc8) - NA // jsr_w = 201 (0xc9) - }; - - /** Where the constants used in this MethodWriter must be stored. */ - private final SymbolTable symbolTable; - - // Note: fields are ordered as in the method_info structure, and those related to attributes are - // ordered as in Section 4.7 of the JVMS. - - /** - * The access_flags field of the method_info JVMS structure. This field can contain ASM specific - * access flags, such as {@link Opcodes#ACC_DEPRECATED}, which are removed when generating the - * ClassFile structure. - */ - private final int accessFlags; - - /** The name_index field of the method_info JVMS structure. */ - private final int nameIndex; - - /** The name of this method. */ - private final String name; - - /** The descriptor_index field of the method_info JVMS structure. */ - private final int descriptorIndex; - - /** The descriptor of this method. */ - private final String descriptor; - - // Code attribute fields and sub attributes: - - /** The max_stack field of the Code attribute. */ - private int maxStack; - - /** The max_locals field of the Code attribute. */ - private int maxLocals; - - /** The 'code' field of the Code attribute. */ - private final ByteVector code = new ByteVector(); - - /** - * The first element in the exception handler list (used to generate the exception_table of the - * Code attribute). The next ones can be accessed with the {@link Handler#nextHandler} field. May - * be {@literal null}. - */ - private Handler firstHandler; - - /** - * The last element in the exception handler list (used to generate the exception_table of the - * Code attribute). The next ones can be accessed with the {@link Handler#nextHandler} field. May - * be {@literal null}. - */ - private Handler lastHandler; - - /** The line_number_table_length field of the LineNumberTable code attribute. */ - private int lineNumberTableLength; - - /** The line_number_table array of the LineNumberTable code attribute, or {@literal null}. */ - private ByteVector lineNumberTable; - - /** The local_variable_table_length field of the LocalVariableTable code attribute. */ - private int localVariableTableLength; - - /** - * The local_variable_table array of the LocalVariableTable code attribute, or {@literal null}. - */ - private ByteVector localVariableTable; - - /** The local_variable_type_table_length field of the LocalVariableTypeTable code attribute. */ - private int localVariableTypeTableLength; - - /** - * The local_variable_type_table array of the LocalVariableTypeTable code attribute, or {@literal - * null}. - */ - private ByteVector localVariableTypeTable; - - /** The number_of_entries field of the StackMapTable code attribute. */ - private int stackMapTableNumberOfEntries; - - /** The 'entries' array of the StackMapTable code attribute. */ - private ByteVector stackMapTableEntries; - - /** - * The last runtime visible type annotation of the Code attribute. The previous ones can be - * accessed with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastCodeRuntimeVisibleTypeAnnotation; - - /** - * The last runtime invisible type annotation of the Code attribute. The previous ones can be - * accessed with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastCodeRuntimeInvisibleTypeAnnotation; - - /** - * The first non standard attribute of the Code attribute. The next ones can be accessed with the - * {@link Attribute#nextAttribute} field. May be {@literal null}. - * - *

WARNING: this list stores the attributes in the reverse order of their visit. - * firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link - * #putMethodInfo} method writes the attributes in the order defined by this list, i.e. in the - * reverse order specified by the user. - */ - private Attribute firstCodeAttribute; - - // Other method_info attributes: - - /** The number_of_exceptions field of the Exceptions attribute. */ - private final int numberOfExceptions; - - /** The exception_index_table array of the Exceptions attribute, or {@literal null}. */ - private final int[] exceptionIndexTable; - - /** The signature_index field of the Signature attribute. */ - private final int signatureIndex; - - /** - * The last runtime visible annotation of this method. The previous ones can be accessed with the - * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeVisibleAnnotation; - - /** - * The last runtime invisible annotation of this method. The previous ones can be accessed with - * the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeInvisibleAnnotation; - - /** The number of method parameters that can have runtime visible annotations, or 0. */ - private int visibleAnnotableParameterCount; - - /** - * The runtime visible parameter annotations of this method. Each array element contains the last - * annotation of a parameter (which can be {@literal null} - the previous ones can be accessed - * with the {@link AnnotationWriter#previousAnnotation} field). May be {@literal null}. - */ - private AnnotationWriter[] lastRuntimeVisibleParameterAnnotations; - - /** The number of method parameters that can have runtime visible annotations, or 0. */ - private int invisibleAnnotableParameterCount; - - /** - * The runtime invisible parameter annotations of this method. Each array element contains the - * last annotation of a parameter (which can be {@literal null} - the previous ones can be - * accessed with the {@link AnnotationWriter#previousAnnotation} field). May be {@literal null}. - */ - private AnnotationWriter[] lastRuntimeInvisibleParameterAnnotations; - - /** - * The last runtime visible type annotation of this method. The previous ones can be accessed with - * the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeVisibleTypeAnnotation; - - /** - * The last runtime invisible type annotation of this method. The previous ones can be accessed - * with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeInvisibleTypeAnnotation; - - /** The default_value field of the AnnotationDefault attribute, or {@literal null}. */ - private ByteVector defaultValue; - - /** The parameters_count field of the MethodParameters attribute. */ - private int parametersCount; - - /** The 'parameters' array of the MethodParameters attribute, or {@literal null}. */ - private ByteVector parameters; - - /** - * The first non standard attribute of this method. The next ones can be accessed with the {@link - * Attribute#nextAttribute} field. May be {@literal null}. - * - *

WARNING: this list stores the attributes in the reverse order of their visit. - * firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link - * #putMethodInfo} method writes the attributes in the order defined by this list, i.e. in the - * reverse order specified by the user. - */ - private Attribute firstAttribute; - - // ----------------------------------------------------------------------------------------------- - // Fields used to compute the maximum stack size and number of locals, and the stack map frames - // ----------------------------------------------------------------------------------------------- - - /** - * Indicates what must be computed. Must be one of {@link #COMPUTE_ALL_FRAMES}, {@link - * #COMPUTE_INSERTED_FRAMES}, {@link #COMPUTE_MAX_STACK_AND_LOCAL} or {@link #COMPUTE_NOTHING}. - */ - private final int compute; - - /** - * The first basic block of the method. The next ones (in bytecode offset order) can be accessed - * with the {@link Label#nextBasicBlock} field. - */ - private Label firstBasicBlock; - - /** - * The last basic block of the method (in bytecode offset order). This field is updated each time - * a basic block is encountered, and is used to append it at the end of the basic block list. - */ - private Label lastBasicBlock; - - /** - * The current basic block, i.e. the basic block of the last visited instruction. When {@link - * #compute} is equal to {@link #COMPUTE_MAX_STACK_AND_LOCAL} or {@link #COMPUTE_ALL_FRAMES}, this - * field is {@literal null} for unreachable code. When {@link #compute} is equal to {@link - * #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES} or {@link #COMPUTE_INSERTED_FRAMES}, this field stays - * unchanged throughout the whole method (i.e. the whole code is seen as a single basic block; - * indeed, the existing frames are sufficient by hypothesis to compute any intermediate frame - - * and the maximum stack size as well - without using any control flow graph). - */ - private Label currentBasicBlock; - - /** - * The relative stack size after the last visited instruction. This size is relative to the - * beginning of {@link #currentBasicBlock}, i.e. the true stack size after the last visited - * instruction is equal to the {@link Label#inputStackSize} of the current basic block plus {@link - * #relativeStackSize}. When {@link #compute} is equal to {@link - * #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link #currentBasicBlock} is always the start of - * the method, so this relative size is also equal to the absolute stack size after the last - * visited instruction. - */ - private int relativeStackSize; - - /** - * The maximum relative stack size after the last visited instruction. This size is relative to - * the beginning of {@link #currentBasicBlock}, i.e. the true maximum stack size after the last - * visited instruction is equal to the {@link Label#inputStackSize} of the current basic block - * plus {@link #maxRelativeStackSize}.When {@link #compute} is equal to {@link - * #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link #currentBasicBlock} is always the start of - * the method, so this relative size is also equal to the absolute maximum stack size after the - * last visited instruction. - */ - private int maxRelativeStackSize; - - /** The number of local variables in the last visited stack map frame. */ - private int currentLocals; - - /** The bytecode offset of the last frame that was written in {@link #stackMapTableEntries}. */ - private int previousFrameOffset; - - /** - * The last frame that was written in {@link #stackMapTableEntries}. This field has the same - * format as {@link #currentFrame}. - */ - private int[] previousFrame; - - /** - * The current stack map frame. The first element contains the bytecode offset of the instruction - * to which the frame corresponds, the second element is the number of locals and the third one is - * the number of stack elements. The local variables start at index 3 and are followed by the - * operand stack elements. In summary frame[0] = offset, frame[1] = numLocal, frame[2] = numStack. - * Local variables and operand stack entries contain abstract types, as defined in {@link Frame}, - * but restricted to {@link Frame#CONSTANT_KIND}, {@link Frame#REFERENCE_KIND} or {@link - * Frame#UNINITIALIZED_KIND} abstract types. Long and double types use only one array entry. - */ - private int[] currentFrame; - - /** Whether this method contains subroutines. */ - private boolean hasSubroutines; - - // ----------------------------------------------------------------------------------------------- - // Other miscellaneous status fields - // ----------------------------------------------------------------------------------------------- - - /** Whether the bytecode of this method contains ASM specific instructions. */ - private boolean hasAsmInstructions; - - /** - * The start offset of the last visited instruction. Used to set the offset field of type - * annotations of type 'offset_target' (see JVMS - * 4.7.20.1). - */ - private int lastBytecodeOffset; - - /** - * The offset in bytes in {@link SymbolTable#getSource} from which the method_info for this method - * (excluding its first 6 bytes) must be copied, or 0. - */ - private int sourceOffset; - - /** - * The length in bytes in {@link SymbolTable#getSource} which must be copied to get the - * method_info for this method (excluding its first 6 bytes for access_flags, name_index and - * descriptor_index). - */ - private int sourceLength; - - // ----------------------------------------------------------------------------------------------- - // Constructor and accessors - // ----------------------------------------------------------------------------------------------- - - /** - * Constructs a new {@link MethodWriter}. - * - * @param symbolTable where the constants used in this AnnotationWriter must be stored. - * @param access the method's access flags (see {@link Opcodes}). - * @param name the method's name. - * @param descriptor the method's descriptor (see {@link Type}). - * @param signature the method's signature. May be {@literal null}. - * @param exceptions the internal names of the method's exceptions. May be {@literal null}. - * @param compute indicates what must be computed (see #compute). - */ - MethodWriter( - final SymbolTable symbolTable, - final int access, - final String name, - final String descriptor, - final String signature, - final String[] exceptions, - final int compute) { - super(Opcodes.ASM7); - this.symbolTable = symbolTable; - this.accessFlags = "".equals(name) ? access | Constants.ACC_CONSTRUCTOR : access; - this.nameIndex = symbolTable.addConstantUtf8(name); - this.name = name; - this.descriptorIndex = symbolTable.addConstantUtf8(descriptor); - this.descriptor = descriptor; - this.signatureIndex = signature == null ? 0 : symbolTable.addConstantUtf8(signature); - if (exceptions != null && exceptions.length > 0) { - numberOfExceptions = exceptions.length; - this.exceptionIndexTable = new int[numberOfExceptions]; - for (int i = 0; i < numberOfExceptions; ++i) { - this.exceptionIndexTable[i] = symbolTable.addConstantClass(exceptions[i]).index; - } - } else { - numberOfExceptions = 0; - this.exceptionIndexTable = null; - } - this.compute = compute; - if (compute != COMPUTE_NOTHING) { - // Update maxLocals and currentLocals. - int argumentsSize = Type.getArgumentsAndReturnSizes(descriptor) >> 2; - if ((access & Opcodes.ACC_STATIC) != 0) { - --argumentsSize; - } - maxLocals = argumentsSize; - currentLocals = argumentsSize; - // Create and visit the label for the first basic block. - firstBasicBlock = new Label(); - visitLabel(firstBasicBlock); - } - } - - boolean hasFrames() { - return stackMapTableNumberOfEntries > 0; - } - - boolean hasAsmInstructions() { - return hasAsmInstructions; - } - - // ----------------------------------------------------------------------------------------------- - // Implementation of the MethodVisitor abstract class - // ----------------------------------------------------------------------------------------------- - - @Override - public void visitParameter(final String name, final int access) { - if (parameters == null) { - parameters = new ByteVector(); - } - ++parametersCount; - parameters.putShort((name == null) ? 0 : symbolTable.addConstantUtf8(name)).putShort(access); - } - - @Override - public AnnotationVisitor visitAnnotationDefault() { - defaultValue = new ByteVector(); - return new AnnotationWriter(symbolTable, /* useNamedValues = */ false, defaultValue, null); - } - - @Override - public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) { - if (visible) { - return lastRuntimeVisibleAnnotation = - AnnotationWriter.create(symbolTable, descriptor, lastRuntimeVisibleAnnotation); - } else { - return lastRuntimeInvisibleAnnotation = - AnnotationWriter.create(symbolTable, descriptor, lastRuntimeInvisibleAnnotation); - } - } - - @Override - public AnnotationVisitor visitTypeAnnotation( - final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { - if (visible) { - return lastRuntimeVisibleTypeAnnotation = - AnnotationWriter.create( - symbolTable, typeRef, typePath, descriptor, lastRuntimeVisibleTypeAnnotation); - } else { - return lastRuntimeInvisibleTypeAnnotation = - AnnotationWriter.create( - symbolTable, typeRef, typePath, descriptor, lastRuntimeInvisibleTypeAnnotation); - } - } - - @Override - public void visitAnnotableParameterCount(final int parameterCount, final boolean visible) { - if (visible) { - visibleAnnotableParameterCount = parameterCount; - } else { - invisibleAnnotableParameterCount = parameterCount; - } - } - - @Override - public AnnotationVisitor visitParameterAnnotation( - final int parameter, final String annotationDescriptor, final boolean visible) { - if (visible) { - if (lastRuntimeVisibleParameterAnnotations == null) { - lastRuntimeVisibleParameterAnnotations = - new AnnotationWriter[Type.getArgumentTypes(descriptor).length]; - } - return lastRuntimeVisibleParameterAnnotations[parameter] = - AnnotationWriter.create( - symbolTable, annotationDescriptor, lastRuntimeVisibleParameterAnnotations[parameter]); - } else { - if (lastRuntimeInvisibleParameterAnnotations == null) { - lastRuntimeInvisibleParameterAnnotations = - new AnnotationWriter[Type.getArgumentTypes(descriptor).length]; - } - return lastRuntimeInvisibleParameterAnnotations[parameter] = - AnnotationWriter.create( - symbolTable, - annotationDescriptor, - lastRuntimeInvisibleParameterAnnotations[parameter]); - } - } - - @Override - public void visitAttribute(final Attribute attribute) { - // Store the attributes in the reverse order of their visit by this method. - if (attribute.isCodeAttribute()) { - attribute.nextAttribute = firstCodeAttribute; - firstCodeAttribute = attribute; - } else { - attribute.nextAttribute = firstAttribute; - firstAttribute = attribute; - } - } - - @Override - public void visitCode() { - // Nothing to do. - } - - @Override - public void visitFrame( - final int type, - final int numLocal, - final Object[] local, - final int numStack, - final Object[] stack) { - if (compute == COMPUTE_ALL_FRAMES) { - return; - } - - if (compute == COMPUTE_INSERTED_FRAMES) { - if (currentBasicBlock.frame == null) { - // This should happen only once, for the implicit first frame (which is explicitly visited - // in ClassReader if the EXPAND_ASM_INSNS option is used - and COMPUTE_INSERTED_FRAMES - // can't be set if EXPAND_ASM_INSNS is not used). - currentBasicBlock.frame = new CurrentFrame(currentBasicBlock); - currentBasicBlock.frame.setInputFrameFromDescriptor( - symbolTable, accessFlags, descriptor, numLocal); - currentBasicBlock.frame.accept(this); - } else { - if (type == Opcodes.F_NEW) { - currentBasicBlock.frame.setInputFrameFromApiFormat( - symbolTable, numLocal, local, numStack, stack); - } - // If type is not F_NEW then it is F_INSERT by hypothesis, and currentBlock.frame contains - // the stack map frame at the current instruction, computed from the last F_NEW frame and - // the bytecode instructions in between (via calls to CurrentFrame#execute). - currentBasicBlock.frame.accept(this); - } - } else if (type == Opcodes.F_NEW) { - if (previousFrame == null) { - int argumentsSize = Type.getArgumentsAndReturnSizes(descriptor) >> 2; - Frame implicitFirstFrame = new Frame(new Label()); - implicitFirstFrame.setInputFrameFromDescriptor( - symbolTable, accessFlags, descriptor, argumentsSize); - implicitFirstFrame.accept(this); - } - currentLocals = numLocal; - int frameIndex = visitFrameStart(code.length, numLocal, numStack); - for (int i = 0; i < numLocal; ++i) { - currentFrame[frameIndex++] = Frame.getAbstractTypeFromApiFormat(symbolTable, local[i]); - } - for (int i = 0; i < numStack; ++i) { - currentFrame[frameIndex++] = Frame.getAbstractTypeFromApiFormat(symbolTable, stack[i]); - } - visitFrameEnd(); - } else { - int offsetDelta; - if (stackMapTableEntries == null) { - stackMapTableEntries = new ByteVector(); - offsetDelta = code.length; - } else { - offsetDelta = code.length - previousFrameOffset - 1; - if (offsetDelta < 0) { - if (type == Opcodes.F_SAME) { - return; - } else { - throw new IllegalStateException(); - } - } - } - - switch (type) { - case Opcodes.F_FULL: - currentLocals = numLocal; - stackMapTableEntries.putByte(Frame.FULL_FRAME).putShort(offsetDelta).putShort(numLocal); - for (int i = 0; i < numLocal; ++i) { - putFrameType(local[i]); - } - stackMapTableEntries.putShort(numStack); - for (int i = 0; i < numStack; ++i) { - putFrameType(stack[i]); - } - break; - case Opcodes.F_APPEND: - currentLocals += numLocal; - stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED + numLocal).putShort(offsetDelta); - for (int i = 0; i < numLocal; ++i) { - putFrameType(local[i]); - } - break; - case Opcodes.F_CHOP: - currentLocals -= numLocal; - stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED - numLocal).putShort(offsetDelta); - break; - case Opcodes.F_SAME: - if (offsetDelta < 64) { - stackMapTableEntries.putByte(offsetDelta); - } else { - stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED).putShort(offsetDelta); - } - break; - case Opcodes.F_SAME1: - if (offsetDelta < 64) { - stackMapTableEntries.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME + offsetDelta); - } else { - stackMapTableEntries - .putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) - .putShort(offsetDelta); - } - putFrameType(stack[0]); - break; - default: - throw new IllegalArgumentException(); - } - - previousFrameOffset = code.length; - ++stackMapTableNumberOfEntries; - } - - if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) { - relativeStackSize = numStack; - for (int i = 0; i < numStack; ++i) { - if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) { - relativeStackSize++; - } - } - if (relativeStackSize > maxRelativeStackSize) { - maxRelativeStackSize = relativeStackSize; - } - } - - maxStack = Math.max(maxStack, numStack); - maxLocals = Math.max(maxLocals, currentLocals); - } - - @Override - public void visitInsn(final int opcode) { - lastBytecodeOffset = code.length; - // Add the instruction to the bytecode of the method. - code.putByte(opcode); - // If needed, update the maximum stack size and number of locals, and stack map frames. - if (currentBasicBlock != null) { - if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) { - currentBasicBlock.frame.execute(opcode, 0, null, null); - } else { - int size = relativeStackSize + STACK_SIZE_DELTA[opcode]; - if (size > maxRelativeStackSize) { - maxRelativeStackSize = size; - } - relativeStackSize = size; - } - if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN) || opcode == Opcodes.ATHROW) { - endCurrentBasicBlockWithNoSuccessor(); - } - } - } - - @Override - public void visitIntInsn(final int opcode, final int operand) { - lastBytecodeOffset = code.length; - // Add the instruction to the bytecode of the method. - if (opcode == Opcodes.SIPUSH) { - code.put12(opcode, operand); - } else { // BIPUSH or NEWARRAY - code.put11(opcode, operand); - } - // If needed, update the maximum stack size and number of locals, and stack map frames. - if (currentBasicBlock != null) { - if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) { - currentBasicBlock.frame.execute(opcode, operand, null, null); - } else if (opcode != Opcodes.NEWARRAY) { - // The stack size delta is 1 for BIPUSH or SIPUSH, and 0 for NEWARRAY. - int size = relativeStackSize + 1; - if (size > maxRelativeStackSize) { - maxRelativeStackSize = size; - } - relativeStackSize = size; - } - } - } - - @Override - public void visitVarInsn(final int opcode, final int var) { - lastBytecodeOffset = code.length; - // Add the instruction to the bytecode of the method. - if (var < 4 && opcode != Opcodes.RET) { - int optimizedOpcode; - if (opcode < Opcodes.ISTORE) { - optimizedOpcode = Constants.ILOAD_0 + ((opcode - Opcodes.ILOAD) << 2) + var; - } else { - optimizedOpcode = Constants.ISTORE_0 + ((opcode - Opcodes.ISTORE) << 2) + var; - } - code.putByte(optimizedOpcode); - } else if (var >= 256) { - code.putByte(Constants.WIDE).put12(opcode, var); - } else { - code.put11(opcode, var); - } - // If needed, update the maximum stack size and number of locals, and stack map frames. - if (currentBasicBlock != null) { - if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) { - currentBasicBlock.frame.execute(opcode, var, null, null); - } else { - if (opcode == Opcodes.RET) { - // No stack size delta. - currentBasicBlock.flags |= Label.FLAG_SUBROUTINE_END; - currentBasicBlock.outputStackSize = (short) relativeStackSize; - endCurrentBasicBlockWithNoSuccessor(); - } else { // xLOAD or xSTORE - int size = relativeStackSize + STACK_SIZE_DELTA[opcode]; - if (size > maxRelativeStackSize) { - maxRelativeStackSize = size; - } - relativeStackSize = size; - } - } - } - if (compute != COMPUTE_NOTHING) { - int currentMaxLocals; - if (opcode == Opcodes.LLOAD - || opcode == Opcodes.DLOAD - || opcode == Opcodes.LSTORE - || opcode == Opcodes.DSTORE) { - currentMaxLocals = var + 2; - } else { - currentMaxLocals = var + 1; - } - if (currentMaxLocals > maxLocals) { - maxLocals = currentMaxLocals; - } - } - if (opcode >= Opcodes.ISTORE && compute == COMPUTE_ALL_FRAMES && firstHandler != null) { - // If there are exception handler blocks, each instruction within a handler range is, in - // theory, a basic block (since execution can jump from this instruction to the exception - // handler). As a consequence, the local variable types at the beginning of the handler - // block should be the merge of the local variable types at all the instructions within the - // handler range. However, instead of creating a basic block for each instruction, we can - // get the same result in a more efficient way. Namely, by starting a new basic block after - // each xSTORE instruction, which is what we do here. - visitLabel(new Label()); - } - } - - @Override - public void visitTypeInsn(final int opcode, final String type) { - lastBytecodeOffset = code.length; - // Add the instruction to the bytecode of the method. - Symbol typeSymbol = symbolTable.addConstantClass(type); - code.put12(opcode, typeSymbol.index); - // If needed, update the maximum stack size and number of locals, and stack map frames. - if (currentBasicBlock != null) { - if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) { - currentBasicBlock.frame.execute(opcode, lastBytecodeOffset, typeSymbol, symbolTable); - } else if (opcode == Opcodes.NEW) { - // The stack size delta is 1 for NEW, and 0 for ANEWARRAY, CHECKCAST, or INSTANCEOF. - int size = relativeStackSize + 1; - if (size > maxRelativeStackSize) { - maxRelativeStackSize = size; - } - relativeStackSize = size; - } - } - } - - @Override - public void visitFieldInsn( - final int opcode, final String owner, final String name, final String descriptor) { - lastBytecodeOffset = code.length; - // Add the instruction to the bytecode of the method. - Symbol fieldrefSymbol = symbolTable.addConstantFieldref(owner, name, descriptor); - code.put12(opcode, fieldrefSymbol.index); - // If needed, update the maximum stack size and number of locals, and stack map frames. - if (currentBasicBlock != null) { - if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) { - currentBasicBlock.frame.execute(opcode, 0, fieldrefSymbol, symbolTable); - } else { - int size; - char firstDescChar = descriptor.charAt(0); - switch (opcode) { - case Opcodes.GETSTATIC: - size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? 2 : 1); - break; - case Opcodes.PUTSTATIC: - size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? -2 : -1); - break; - case Opcodes.GETFIELD: - size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? 1 : 0); - break; - case Opcodes.PUTFIELD: - default: - size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? -3 : -2); - break; - } - if (size > maxRelativeStackSize) { - maxRelativeStackSize = size; - } - relativeStackSize = size; - } - } - } - - @Override - public void visitMethodInsn( - final int opcode, - final String owner, - final String name, - final String descriptor, - final boolean isInterface) { - lastBytecodeOffset = code.length; - // Add the instruction to the bytecode of the method. - Symbol methodrefSymbol = symbolTable.addConstantMethodref(owner, name, descriptor, isInterface); - if (opcode == Opcodes.INVOKEINTERFACE) { - code.put12(Opcodes.INVOKEINTERFACE, methodrefSymbol.index) - .put11(methodrefSymbol.getArgumentsAndReturnSizes() >> 2, 0); - } else { - code.put12(opcode, methodrefSymbol.index); - } - // If needed, update the maximum stack size and number of locals, and stack map frames. - if (currentBasicBlock != null) { - if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) { - currentBasicBlock.frame.execute(opcode, 0, methodrefSymbol, symbolTable); - } else { - int argumentsAndReturnSize = methodrefSymbol.getArgumentsAndReturnSizes(); - int stackSizeDelta = (argumentsAndReturnSize & 3) - (argumentsAndReturnSize >> 2); - int size; - if (opcode == Opcodes.INVOKESTATIC) { - size = relativeStackSize + stackSizeDelta + 1; - } else { - size = relativeStackSize + stackSizeDelta; - } - if (size > maxRelativeStackSize) { - maxRelativeStackSize = size; - } - relativeStackSize = size; - } - } - } - - @Override - public void visitInvokeDynamicInsn( - final String name, - final String descriptor, - final Handle bootstrapMethodHandle, - final Object... bootstrapMethodArguments) { - lastBytecodeOffset = code.length; - // Add the instruction to the bytecode of the method. - Symbol invokeDynamicSymbol = - symbolTable.addConstantInvokeDynamic( - name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments); - code.put12(Opcodes.INVOKEDYNAMIC, invokeDynamicSymbol.index); - code.putShort(0); - // If needed, update the maximum stack size and number of locals, and stack map frames. - if (currentBasicBlock != null) { - if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) { - currentBasicBlock.frame.execute(Opcodes.INVOKEDYNAMIC, 0, invokeDynamicSymbol, symbolTable); - } else { - int argumentsAndReturnSize = invokeDynamicSymbol.getArgumentsAndReturnSizes(); - int stackSizeDelta = (argumentsAndReturnSize & 3) - (argumentsAndReturnSize >> 2) + 1; - int size = relativeStackSize + stackSizeDelta; - if (size > maxRelativeStackSize) { - maxRelativeStackSize = size; - } - relativeStackSize = size; - } - } - } - - @Override - public void visitJumpInsn(final int opcode, final Label label) { - lastBytecodeOffset = code.length; - // Add the instruction to the bytecode of the method. - // Compute the 'base' opcode, i.e. GOTO or JSR if opcode is GOTO_W or JSR_W, otherwise opcode. - int baseOpcode = - opcode >= Constants.GOTO_W ? opcode - Constants.WIDE_JUMP_OPCODE_DELTA : opcode; - boolean nextInsnIsJumpTarget = false; - if ((label.flags & Label.FLAG_RESOLVED) != 0 - && label.bytecodeOffset - code.length < Short.MIN_VALUE) { - // Case of a backward jump with an offset < -32768. In this case we automatically replace GOTO - // with GOTO_W, JSR with JSR_W and IFxxx with IFNOTxxx GOTO_W L:..., where - // IFNOTxxx is the "opposite" opcode of IFxxx (e.g. IFNE for IFEQ) and where designates - // the instruction just after the GOTO_W. - if (baseOpcode == Opcodes.GOTO) { - code.putByte(Constants.GOTO_W); - } else if (baseOpcode == Opcodes.JSR) { - code.putByte(Constants.JSR_W); - } else { - // Put the "opposite" opcode of baseOpcode. This can be done by flipping the least - // significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ (with a - // pre and post offset by 1). The jump offset is 8 bytes (3 for IFNOTxxx, 5 for GOTO_W). - code.putByte(baseOpcode >= Opcodes.IFNULL ? baseOpcode ^ 1 : ((baseOpcode + 1) ^ 1) - 1); - code.putShort(8); - // Here we could put a GOTO_W in theory, but if ASM specific instructions are used in this - // method or another one, and if the class has frames, we will need to insert a frame after - // this GOTO_W during the additional ClassReader -> ClassWriter round trip to remove the ASM - // specific instructions. To not miss this additional frame, we need to use an ASM_GOTO_W - // here, which has the unfortunate effect of forcing this additional round trip (which in - // some case would not have been really necessary, but we can't know this at this point). - code.putByte(Constants.ASM_GOTO_W); - hasAsmInstructions = true; - // The instruction after the GOTO_W becomes the target of the IFNOT instruction. - nextInsnIsJumpTarget = true; - } - label.put(code, code.length - 1, true); - } else if (baseOpcode != opcode) { - // Case of a GOTO_W or JSR_W specified by the user (normally ClassReader when used to remove - // ASM specific instructions). In this case we keep the original instruction. - code.putByte(opcode); - label.put(code, code.length - 1, true); - } else { - // Case of a jump with an offset >= -32768, or of a jump with an unknown offset. In these - // cases we store the offset in 2 bytes (which will be increased via a ClassReader -> - // ClassWriter round trip if it turns out that 2 bytes are not sufficient). - code.putByte(baseOpcode); - label.put(code, code.length - 1, false); - } - - // If needed, update the maximum stack size and number of locals, and stack map frames. - if (currentBasicBlock != null) { - Label nextBasicBlock = null; - if (compute == COMPUTE_ALL_FRAMES) { - currentBasicBlock.frame.execute(baseOpcode, 0, null, null); - // Record the fact that 'label' is the target of a jump instruction. - label.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET; - // Add 'label' as a successor of the current basic block. - addSuccessorToCurrentBasicBlock(Edge.JUMP, label); - if (baseOpcode != Opcodes.GOTO) { - // The next instruction starts a new basic block (except for GOTO: by default the code - // following a goto is unreachable - unless there is an explicit label for it - and we - // should not compute stack frame types for its instructions). - nextBasicBlock = new Label(); - } - } else if (compute == COMPUTE_INSERTED_FRAMES) { - currentBasicBlock.frame.execute(baseOpcode, 0, null, null); - } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) { - // No need to update maxRelativeStackSize (the stack size delta is always negative). - relativeStackSize += STACK_SIZE_DELTA[baseOpcode]; - } else { - if (baseOpcode == Opcodes.JSR) { - // Record the fact that 'label' designates a subroutine, if not already done. - if ((label.flags & Label.FLAG_SUBROUTINE_START) == 0) { - label.flags |= Label.FLAG_SUBROUTINE_START; - hasSubroutines = true; - } - currentBasicBlock.flags |= Label.FLAG_SUBROUTINE_CALLER; - // Note that, by construction in this method, a block which calls a subroutine has at - // least two successors in the control flow graph: the first one (added below) leads to - // the instruction after the JSR, while the second one (added here) leads to the JSR - // target. Note that the first successor is virtual (it does not correspond to a possible - // execution path): it is only used to compute the successors of the basic blocks ending - // with a ret, in {@link Label#addSubroutineRetSuccessors}. - addSuccessorToCurrentBasicBlock(relativeStackSize + 1, label); - // The instruction after the JSR starts a new basic block. - nextBasicBlock = new Label(); - } else { - // No need to update maxRelativeStackSize (the stack size delta is always negative). - relativeStackSize += STACK_SIZE_DELTA[baseOpcode]; - addSuccessorToCurrentBasicBlock(relativeStackSize, label); - } - } - // If the next instruction starts a new basic block, call visitLabel to add the label of this - // instruction as a successor of the current block, and to start a new basic block. - if (nextBasicBlock != null) { - if (nextInsnIsJumpTarget) { - nextBasicBlock.flags |= Label.FLAG_JUMP_TARGET; - } - visitLabel(nextBasicBlock); - } - if (baseOpcode == Opcodes.GOTO) { - endCurrentBasicBlockWithNoSuccessor(); - } - } - } - - @Override - public void visitLabel(final Label label) { - // Resolve the forward references to this label, if any. - hasAsmInstructions |= label.resolve(code.data, code.length); - // visitLabel starts a new basic block (except for debug only labels), so we need to update the - // previous and current block references and list of successors. - if ((label.flags & Label.FLAG_DEBUG_ONLY) != 0) { - return; - } - if (compute == COMPUTE_ALL_FRAMES) { - if (currentBasicBlock != null) { - if (label.bytecodeOffset == currentBasicBlock.bytecodeOffset) { - // We use {@link Label#getCanonicalInstance} to store the state of a basic block in only - // one place, but this does not work for labels which have not been visited yet. - // Therefore, when we detect here two labels having the same bytecode offset, we need to - // - consolidate the state scattered in these two instances into the canonical instance: - currentBasicBlock.flags |= (label.flags & Label.FLAG_JUMP_TARGET); - // - make sure the two instances share the same Frame instance (the implementation of - // {@link Label#getCanonicalInstance} relies on this property; here label.frame should be - // null): - label.frame = currentBasicBlock.frame; - // - and make sure to NOT assign 'label' into 'currentBasicBlock' or 'lastBasicBlock', so - // that they still refer to the canonical instance for this bytecode offset. - return; - } - // End the current basic block (with one new successor). - addSuccessorToCurrentBasicBlock(Edge.JUMP, label); - } - // Append 'label' at the end of the basic block list. - if (lastBasicBlock != null) { - if (label.bytecodeOffset == lastBasicBlock.bytecodeOffset) { - // Same comment as above. - lastBasicBlock.flags |= (label.flags & Label.FLAG_JUMP_TARGET); - // Here label.frame should be null. - label.frame = lastBasicBlock.frame; - currentBasicBlock = lastBasicBlock; - return; - } - lastBasicBlock.nextBasicBlock = label; - } - lastBasicBlock = label; - // Make it the new current basic block. - currentBasicBlock = label; - // Here label.frame should be null. - label.frame = new Frame(label); - } else if (compute == COMPUTE_INSERTED_FRAMES) { - if (currentBasicBlock == null) { - // This case should happen only once, for the visitLabel call in the constructor. Indeed, if - // compute is equal to COMPUTE_INSERTED_FRAMES, currentBasicBlock stays unchanged. - currentBasicBlock = label; - } else { - // Update the frame owner so that a correct frame offset is computed in Frame.accept(). - currentBasicBlock.frame.owner = label; - } - } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) { - if (currentBasicBlock != null) { - // End the current basic block (with one new successor). - currentBasicBlock.outputStackMax = (short) maxRelativeStackSize; - addSuccessorToCurrentBasicBlock(relativeStackSize, label); - } - // Start a new current basic block, and reset the current and maximum relative stack sizes. - currentBasicBlock = label; - relativeStackSize = 0; - maxRelativeStackSize = 0; - // Append the new basic block at the end of the basic block list. - if (lastBasicBlock != null) { - lastBasicBlock.nextBasicBlock = label; - } - lastBasicBlock = label; - } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES && currentBasicBlock == null) { - // This case should happen only once, for the visitLabel call in the constructor. Indeed, if - // compute is equal to COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES, currentBasicBlock stays - // unchanged. - currentBasicBlock = label; - } - } - - @Override - public void visitLdcInsn(final Object value) { - lastBytecodeOffset = code.length; - // Add the instruction to the bytecode of the method. - Symbol constantSymbol = symbolTable.addConstant(value); - int constantIndex = constantSymbol.index; - char firstDescriptorChar; - boolean isLongOrDouble = - constantSymbol.tag == Symbol.CONSTANT_LONG_TAG - || constantSymbol.tag == Symbol.CONSTANT_DOUBLE_TAG - || (constantSymbol.tag == Symbol.CONSTANT_DYNAMIC_TAG - && ((firstDescriptorChar = constantSymbol.value.charAt(0)) == 'J' - || firstDescriptorChar == 'D')); - if (isLongOrDouble) { - code.put12(Constants.LDC2_W, constantIndex); - } else if (constantIndex >= 256) { - code.put12(Constants.LDC_W, constantIndex); - } else { - code.put11(Opcodes.LDC, constantIndex); - } - // If needed, update the maximum stack size and number of locals, and stack map frames. - if (currentBasicBlock != null) { - if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) { - currentBasicBlock.frame.execute(Opcodes.LDC, 0, constantSymbol, symbolTable); - } else { - int size = relativeStackSize + (isLongOrDouble ? 2 : 1); - if (size > maxRelativeStackSize) { - maxRelativeStackSize = size; - } - relativeStackSize = size; - } - } - } - - @Override - public void visitIincInsn(final int var, final int increment) { - lastBytecodeOffset = code.length; - // Add the instruction to the bytecode of the method. - if ((var > 255) || (increment > 127) || (increment < -128)) { - code.putByte(Constants.WIDE).put12(Opcodes.IINC, var).putShort(increment); - } else { - code.putByte(Opcodes.IINC).put11(var, increment); - } - // If needed, update the maximum stack size and number of locals, and stack map frames. - if (currentBasicBlock != null - && (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES)) { - currentBasicBlock.frame.execute(Opcodes.IINC, var, null, null); - } - if (compute != COMPUTE_NOTHING) { - int currentMaxLocals = var + 1; - if (currentMaxLocals > maxLocals) { - maxLocals = currentMaxLocals; - } - } - } - - @Override - public void visitTableSwitchInsn( - final int min, final int max, final Label dflt, final Label... labels) { - lastBytecodeOffset = code.length; - // Add the instruction to the bytecode of the method. - code.putByte(Opcodes.TABLESWITCH).putByteArray(null, 0, (4 - code.length % 4) % 4); - dflt.put(code, lastBytecodeOffset, true); - code.putInt(min).putInt(max); - for (Label label : labels) { - label.put(code, lastBytecodeOffset, true); - } - // If needed, update the maximum stack size and number of locals, and stack map frames. - visitSwitchInsn(dflt, labels); - } - - @Override - public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) { - lastBytecodeOffset = code.length; - // Add the instruction to the bytecode of the method. - code.putByte(Opcodes.LOOKUPSWITCH).putByteArray(null, 0, (4 - code.length % 4) % 4); - dflt.put(code, lastBytecodeOffset, true); - code.putInt(labels.length); - for (int i = 0; i < labels.length; ++i) { - code.putInt(keys[i]); - labels[i].put(code, lastBytecodeOffset, true); - } - // If needed, update the maximum stack size and number of locals, and stack map frames. - visitSwitchInsn(dflt, labels); - } - - private void visitSwitchInsn(final Label dflt, final Label[] labels) { - if (currentBasicBlock != null) { - if (compute == COMPUTE_ALL_FRAMES) { - currentBasicBlock.frame.execute(Opcodes.LOOKUPSWITCH, 0, null, null); - // Add all the labels as successors of the current basic block. - addSuccessorToCurrentBasicBlock(Edge.JUMP, dflt); - dflt.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET; - for (Label label : labels) { - addSuccessorToCurrentBasicBlock(Edge.JUMP, label); - label.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET; - } - } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) { - // No need to update maxRelativeStackSize (the stack size delta is always negative). - --relativeStackSize; - // Add all the labels as successors of the current basic block. - addSuccessorToCurrentBasicBlock(relativeStackSize, dflt); - for (Label label : labels) { - addSuccessorToCurrentBasicBlock(relativeStackSize, label); - } - } - // End the current basic block. - endCurrentBasicBlockWithNoSuccessor(); - } - } - - @Override - public void visitMultiANewArrayInsn(final String descriptor, final int numDimensions) { - lastBytecodeOffset = code.length; - // Add the instruction to the bytecode of the method. - Symbol descSymbol = symbolTable.addConstantClass(descriptor); - code.put12(Opcodes.MULTIANEWARRAY, descSymbol.index).putByte(numDimensions); - // If needed, update the maximum stack size and number of locals, and stack map frames. - if (currentBasicBlock != null) { - if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) { - currentBasicBlock.frame.execute( - Opcodes.MULTIANEWARRAY, numDimensions, descSymbol, symbolTable); - } else { - // No need to update maxRelativeStackSize (the stack size delta is always negative). - relativeStackSize += 1 - numDimensions; - } - } - } - - @Override - public AnnotationVisitor visitInsnAnnotation( - final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { - if (visible) { - return lastCodeRuntimeVisibleTypeAnnotation = - AnnotationWriter.create( - symbolTable, - (typeRef & 0xFF0000FF) | (lastBytecodeOffset << 8), - typePath, - descriptor, - lastCodeRuntimeVisibleTypeAnnotation); - } else { - return lastCodeRuntimeInvisibleTypeAnnotation = - AnnotationWriter.create( - symbolTable, - (typeRef & 0xFF0000FF) | (lastBytecodeOffset << 8), - typePath, - descriptor, - lastCodeRuntimeInvisibleTypeAnnotation); - } - } - - @Override - public void visitTryCatchBlock( - final Label start, final Label end, final Label handler, final String type) { - Handler newHandler = - new Handler( - start, end, handler, type != null ? symbolTable.addConstantClass(type).index : 0, type); - if (firstHandler == null) { - firstHandler = newHandler; - } else { - lastHandler.nextHandler = newHandler; - } - lastHandler = newHandler; - } - - @Override - public AnnotationVisitor visitTryCatchAnnotation( - final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { - if (visible) { - return lastCodeRuntimeVisibleTypeAnnotation = - AnnotationWriter.create( - symbolTable, typeRef, typePath, descriptor, lastCodeRuntimeVisibleTypeAnnotation); - } else { - return lastCodeRuntimeInvisibleTypeAnnotation = - AnnotationWriter.create( - symbolTable, typeRef, typePath, descriptor, lastCodeRuntimeInvisibleTypeAnnotation); - } - } - - @Override - public void visitLocalVariable( - final String name, - final String descriptor, - final String signature, - final Label start, - final Label end, - final int index) { - if (signature != null) { - if (localVariableTypeTable == null) { - localVariableTypeTable = new ByteVector(); - } - ++localVariableTypeTableLength; - localVariableTypeTable - .putShort(start.bytecodeOffset) - .putShort(end.bytecodeOffset - start.bytecodeOffset) - .putShort(symbolTable.addConstantUtf8(name)) - .putShort(symbolTable.addConstantUtf8(signature)) - .putShort(index); - } - if (localVariableTable == null) { - localVariableTable = new ByteVector(); - } - ++localVariableTableLength; - localVariableTable - .putShort(start.bytecodeOffset) - .putShort(end.bytecodeOffset - start.bytecodeOffset) - .putShort(symbolTable.addConstantUtf8(name)) - .putShort(symbolTable.addConstantUtf8(descriptor)) - .putShort(index); - if (compute != COMPUTE_NOTHING) { - char firstDescChar = descriptor.charAt(0); - int currentMaxLocals = index + (firstDescChar == 'J' || firstDescChar == 'D' ? 2 : 1); - if (currentMaxLocals > maxLocals) { - maxLocals = currentMaxLocals; - } - } - } - - @Override - public AnnotationVisitor visitLocalVariableAnnotation( - final int typeRef, - final TypePath typePath, - final Label[] start, - final Label[] end, - final int[] index, - final String descriptor, - final boolean visible) { - // Create a ByteVector to hold a 'type_annotation' JVMS structure. - // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.20. - ByteVector typeAnnotation = new ByteVector(); - // Write target_type, target_info, and target_path. - typeAnnotation.putByte(typeRef >>> 24).putShort(start.length); - for (int i = 0; i < start.length; ++i) { - typeAnnotation - .putShort(start[i].bytecodeOffset) - .putShort(end[i].bytecodeOffset - start[i].bytecodeOffset) - .putShort(index[i]); - } - TypePath.put(typePath, typeAnnotation); - // Write type_index and reserve space for num_element_value_pairs. - typeAnnotation.putShort(symbolTable.addConstantUtf8(descriptor)).putShort(0); - if (visible) { - return lastCodeRuntimeVisibleTypeAnnotation = - new AnnotationWriter( - symbolTable, - /* useNamedValues = */ true, - typeAnnotation, - lastCodeRuntimeVisibleTypeAnnotation); - } else { - return lastCodeRuntimeInvisibleTypeAnnotation = - new AnnotationWriter( - symbolTable, - /* useNamedValues = */ true, - typeAnnotation, - lastCodeRuntimeInvisibleTypeAnnotation); - } - } - - @Override - public void visitLineNumber(final int line, final Label start) { - if (lineNumberTable == null) { - lineNumberTable = new ByteVector(); - } - ++lineNumberTableLength; - lineNumberTable.putShort(start.bytecodeOffset); - lineNumberTable.putShort(line); - } - - @Override - public void visitMaxs(final int maxStack, final int maxLocals) { - if (compute == COMPUTE_ALL_FRAMES) { - computeAllFrames(); - } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) { - computeMaxStackAndLocal(); - } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) { - this.maxStack = maxRelativeStackSize; - } else { - this.maxStack = maxStack; - this.maxLocals = maxLocals; - } - } - - /** Computes all the stack map frames of the method, from scratch. */ - private void computeAllFrames() { - // Complete the control flow graph with exception handler blocks. - Handler handler = firstHandler; - while (handler != null) { - String catchTypeDescriptor = - handler.catchTypeDescriptor == null ? "java/lang/Throwable" : handler.catchTypeDescriptor; - int catchType = Frame.getAbstractTypeFromInternalName(symbolTable, catchTypeDescriptor); - // Mark handlerBlock as an exception handler. - Label handlerBlock = handler.handlerPc.getCanonicalInstance(); - handlerBlock.flags |= Label.FLAG_JUMP_TARGET; - // Add handlerBlock as a successor of all the basic blocks in the exception handler range. - Label handlerRangeBlock = handler.startPc.getCanonicalInstance(); - Label handlerRangeEnd = handler.endPc.getCanonicalInstance(); - while (handlerRangeBlock != handlerRangeEnd) { - handlerRangeBlock.outgoingEdges = - new Edge(catchType, handlerBlock, handlerRangeBlock.outgoingEdges); - handlerRangeBlock = handlerRangeBlock.nextBasicBlock; - } - handler = handler.nextHandler; - } - - // Create and visit the first (implicit) frame. - Frame firstFrame = firstBasicBlock.frame; - firstFrame.setInputFrameFromDescriptor(symbolTable, accessFlags, descriptor, this.maxLocals); - firstFrame.accept(this); - - // Fix point algorithm: add the first basic block to a list of blocks to process (i.e. blocks - // whose stack map frame has changed) and, while there are blocks to process, remove one from - // the list and update the stack map frames of its successor blocks in the control flow graph - // (which might change them, in which case these blocks must be processed too, and are thus - // added to the list of blocks to process). Also compute the maximum stack size of the method, - // as a by-product. - Label listOfBlocksToProcess = firstBasicBlock; - listOfBlocksToProcess.nextListElement = Label.EMPTY_LIST; - int maxStackSize = 0; - while (listOfBlocksToProcess != Label.EMPTY_LIST) { - // Remove a basic block from the list of blocks to process. - Label basicBlock = listOfBlocksToProcess; - listOfBlocksToProcess = listOfBlocksToProcess.nextListElement; - basicBlock.nextListElement = null; - // By definition, basicBlock is reachable. - basicBlock.flags |= Label.FLAG_REACHABLE; - // Update the (absolute) maximum stack size. - int maxBlockStackSize = basicBlock.frame.getInputStackSize() + basicBlock.outputStackMax; - if (maxBlockStackSize > maxStackSize) { - maxStackSize = maxBlockStackSize; - } - // Update the successor blocks of basicBlock in the control flow graph. - Edge outgoingEdge = basicBlock.outgoingEdges; - while (outgoingEdge != null) { - Label successorBlock = outgoingEdge.successor.getCanonicalInstance(); - boolean successorBlockChanged = - basicBlock.frame.merge(symbolTable, successorBlock.frame, outgoingEdge.info); - if (successorBlockChanged && successorBlock.nextListElement == null) { - // If successorBlock has changed it must be processed. Thus, if it is not already in the - // list of blocks to process, add it to this list. - successorBlock.nextListElement = listOfBlocksToProcess; - listOfBlocksToProcess = successorBlock; - } - outgoingEdge = outgoingEdge.nextEdge; - } - } - - // Loop over all the basic blocks and visit the stack map frames that must be stored in the - // StackMapTable attribute. Also replace unreachable code with NOP* ATHROW, and remove it from - // exception handler ranges. - Label basicBlock = firstBasicBlock; - while (basicBlock != null) { - if ((basicBlock.flags & (Label.FLAG_JUMP_TARGET | Label.FLAG_REACHABLE)) - == (Label.FLAG_JUMP_TARGET | Label.FLAG_REACHABLE)) { - basicBlock.frame.accept(this); - } - if ((basicBlock.flags & Label.FLAG_REACHABLE) == 0) { - // Find the start and end bytecode offsets of this unreachable block. - Label nextBasicBlock = basicBlock.nextBasicBlock; - int startOffset = basicBlock.bytecodeOffset; - int endOffset = (nextBasicBlock == null ? code.length : nextBasicBlock.bytecodeOffset) - 1; - if (endOffset >= startOffset) { - // Replace its instructions with NOP ... NOP ATHROW. - for (int i = startOffset; i < endOffset; ++i) { - code.data[i] = Opcodes.NOP; - } - code.data[endOffset] = (byte) Opcodes.ATHROW; - // Emit a frame for this unreachable block, with no local and a Throwable on the stack - // (so that the ATHROW could consume this Throwable if it were reachable). - int frameIndex = visitFrameStart(startOffset, /* numLocal = */ 0, /* numStack = */ 1); - currentFrame[frameIndex] = - Frame.getAbstractTypeFromInternalName(symbolTable, "java/lang/Throwable"); - visitFrameEnd(); - // Remove this unreachable basic block from the exception handler ranges. - firstHandler = Handler.removeRange(firstHandler, basicBlock, nextBasicBlock); - // The maximum stack size is now at least one, because of the Throwable declared above. - maxStackSize = Math.max(maxStackSize, 1); - } - } - basicBlock = basicBlock.nextBasicBlock; - } - - this.maxStack = maxStackSize; - } - - /** Computes the maximum stack size of the method. */ - private void computeMaxStackAndLocal() { - // Complete the control flow graph with exception handler blocks. - Handler handler = firstHandler; - while (handler != null) { - Label handlerBlock = handler.handlerPc; - Label handlerRangeBlock = handler.startPc; - Label handlerRangeEnd = handler.endPc; - // Add handlerBlock as a successor of all the basic blocks in the exception handler range. - while (handlerRangeBlock != handlerRangeEnd) { - if ((handlerRangeBlock.flags & Label.FLAG_SUBROUTINE_CALLER) == 0) { - handlerRangeBlock.outgoingEdges = - new Edge(Edge.EXCEPTION, handlerBlock, handlerRangeBlock.outgoingEdges); - } else { - // If handlerRangeBlock is a JSR block, add handlerBlock after the first two outgoing - // edges to preserve the hypothesis about JSR block successors order (see - // {@link #visitJumpInsn}). - handlerRangeBlock.outgoingEdges.nextEdge.nextEdge = - new Edge( - Edge.EXCEPTION, handlerBlock, handlerRangeBlock.outgoingEdges.nextEdge.nextEdge); - } - handlerRangeBlock = handlerRangeBlock.nextBasicBlock; - } - handler = handler.nextHandler; - } - - // Complete the control flow graph with the successor blocks of subroutines, if needed. - if (hasSubroutines) { - // First step: find the subroutines. This step determines, for each basic block, to which - // subroutine(s) it belongs. Start with the main "subroutine": - short numSubroutines = 1; - firstBasicBlock.markSubroutine(numSubroutines); - // Then, mark the subroutines called by the main subroutine, then the subroutines called by - // those called by the main subroutine, etc. - for (short currentSubroutine = 1; currentSubroutine <= numSubroutines; ++currentSubroutine) { - Label basicBlock = firstBasicBlock; - while (basicBlock != null) { - if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0 - && basicBlock.subroutineId == currentSubroutine) { - Label jsrTarget = basicBlock.outgoingEdges.nextEdge.successor; - if (jsrTarget.subroutineId == 0) { - // If this subroutine has not been marked yet, find its basic blocks. - jsrTarget.markSubroutine(++numSubroutines); - } - } - basicBlock = basicBlock.nextBasicBlock; - } - } - // Second step: find the successors in the control flow graph of each subroutine basic block - // 'r' ending with a RET instruction. These successors are the virtual successors of the basic - // blocks ending with JSR instructions (see {@link #visitJumpInsn)} that can reach 'r'. - Label basicBlock = firstBasicBlock; - while (basicBlock != null) { - if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0) { - // By construction, jsr targets are stored in the second outgoing edge of basic blocks - // that ends with a jsr instruction (see {@link #FLAG_SUBROUTINE_CALLER}). - Label subroutine = basicBlock.outgoingEdges.nextEdge.successor; - subroutine.addSubroutineRetSuccessors(basicBlock); - } - basicBlock = basicBlock.nextBasicBlock; - } - } - - // Data flow algorithm: put the first basic block in a list of blocks to process (i.e. blocks - // whose input stack size has changed) and, while there are blocks to process, remove one - // from the list, update the input stack size of its successor blocks in the control flow - // graph, and add these blocks to the list of blocks to process (if not already done). - Label listOfBlocksToProcess = firstBasicBlock; - listOfBlocksToProcess.nextListElement = Label.EMPTY_LIST; - int maxStackSize = maxStack; - while (listOfBlocksToProcess != Label.EMPTY_LIST) { - // Remove a basic block from the list of blocks to process. Note that we don't reset - // basicBlock.nextListElement to null on purpose, to make sure we don't reprocess already - // processed basic blocks. - Label basicBlock = listOfBlocksToProcess; - listOfBlocksToProcess = listOfBlocksToProcess.nextListElement; - // Compute the (absolute) input stack size and maximum stack size of this block. - int inputStackTop = basicBlock.inputStackSize; - int maxBlockStackSize = inputStackTop + basicBlock.outputStackMax; - // Update the absolute maximum stack size of the method. - if (maxBlockStackSize > maxStackSize) { - maxStackSize = maxBlockStackSize; - } - // Update the input stack size of the successor blocks of basicBlock in the control flow - // graph, and add these blocks to the list of blocks to process, if not already done. - Edge outgoingEdge = basicBlock.outgoingEdges; - if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0) { - // Ignore the first outgoing edge of the basic blocks ending with a jsr: these are virtual - // edges which lead to the instruction just after the jsr, and do not correspond to a - // possible execution path (see {@link #visitJumpInsn} and - // {@link Label#FLAG_SUBROUTINE_CALLER}). - outgoingEdge = outgoingEdge.nextEdge; - } - while (outgoingEdge != null) { - Label successorBlock = outgoingEdge.successor; - if (successorBlock.nextListElement == null) { - successorBlock.inputStackSize = - (short) (outgoingEdge.info == Edge.EXCEPTION ? 1 : inputStackTop + outgoingEdge.info); - successorBlock.nextListElement = listOfBlocksToProcess; - listOfBlocksToProcess = successorBlock; - } - outgoingEdge = outgoingEdge.nextEdge; - } - } - this.maxStack = maxStackSize; - } - - @Override - public void visitEnd() { - // Nothing to do. - } - - // ----------------------------------------------------------------------------------------------- - // Utility methods: control flow analysis algorithm - // ----------------------------------------------------------------------------------------------- - - /** - * Adds a successor to {@link #currentBasicBlock} in the control flow graph. - * - * @param info information about the control flow edge to be added. - * @param successor the successor block to be added to the current basic block. - */ - private void addSuccessorToCurrentBasicBlock(final int info, final Label successor) { - currentBasicBlock.outgoingEdges = new Edge(info, successor, currentBasicBlock.outgoingEdges); - } - - /** - * Ends the current basic block. This method must be used in the case where the current basic - * block does not have any successor. - * - *

WARNING: this method must be called after the currently visited instruction has been put in - * {@link #code} (if frames are computed, this method inserts a new Label to start a new basic - * block after the current instruction). - */ - private void endCurrentBasicBlockWithNoSuccessor() { - if (compute == COMPUTE_ALL_FRAMES) { - Label nextBasicBlock = new Label(); - nextBasicBlock.frame = new Frame(nextBasicBlock); - nextBasicBlock.resolve(code.data, code.length); - lastBasicBlock.nextBasicBlock = nextBasicBlock; - lastBasicBlock = nextBasicBlock; - currentBasicBlock = null; - } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) { - currentBasicBlock.outputStackMax = (short) maxRelativeStackSize; - currentBasicBlock = null; - } - } - - // ----------------------------------------------------------------------------------------------- - // Utility methods: stack map frames - // ----------------------------------------------------------------------------------------------- - - /** - * Starts the visit of a new stack map frame, stored in {@link #currentFrame}. - * - * @param offset the bytecode offset of the instruction to which the frame corresponds. - * @param numLocal the number of local variables in the frame. - * @param numStack the number of stack elements in the frame. - * @return the index of the next element to be written in this frame. - */ - int visitFrameStart(final int offset, final int numLocal, final int numStack) { - int frameLength = 3 + numLocal + numStack; - if (currentFrame == null || currentFrame.length < frameLength) { - currentFrame = new int[frameLength]; - } - currentFrame[0] = offset; - currentFrame[1] = numLocal; - currentFrame[2] = numStack; - return 3; - } - - /** - * Sets an abstract type in {@link #currentFrame}. - * - * @param frameIndex the index of the element to be set in {@link #currentFrame}. - * @param abstractType an abstract type. - */ - void visitAbstractType(final int frameIndex, final int abstractType) { - currentFrame[frameIndex] = abstractType; - } - - /** - * Ends the visit of {@link #currentFrame} by writing it in the StackMapTable entries and by - * updating the StackMapTable number_of_entries (except if the current frame is the first one, - * which is implicit in StackMapTable). Then resets {@link #currentFrame} to {@literal null}. - */ - void visitFrameEnd() { - if (previousFrame != null) { - if (stackMapTableEntries == null) { - stackMapTableEntries = new ByteVector(); - } - putFrame(); - ++stackMapTableNumberOfEntries; - } - previousFrame = currentFrame; - currentFrame = null; - } - - /** Compresses and writes {@link #currentFrame} in a new StackMapTable entry. */ - private void putFrame() { - final int numLocal = currentFrame[1]; - final int numStack = currentFrame[2]; - if (symbolTable.getMajorVersion() < Opcodes.V1_6) { - // Generate a StackMap attribute entry, which are always uncompressed. - stackMapTableEntries.putShort(currentFrame[0]).putShort(numLocal); - putAbstractTypes(3, 3 + numLocal); - stackMapTableEntries.putShort(numStack); - putAbstractTypes(3 + numLocal, 3 + numLocal + numStack); - return; - } - final int offsetDelta = - stackMapTableNumberOfEntries == 0 - ? currentFrame[0] - : currentFrame[0] - previousFrame[0] - 1; - final int previousNumlocal = previousFrame[1]; - final int numLocalDelta = numLocal - previousNumlocal; - int type = Frame.FULL_FRAME; - if (numStack == 0) { - switch (numLocalDelta) { - case -3: - case -2: - case -1: - type = Frame.CHOP_FRAME; - break; - case 0: - type = offsetDelta < 64 ? Frame.SAME_FRAME : Frame.SAME_FRAME_EXTENDED; - break; - case 1: - case 2: - case 3: - type = Frame.APPEND_FRAME; - break; - default: - // Keep the FULL_FRAME type. - break; - } - } else if (numLocalDelta == 0 && numStack == 1) { - type = - offsetDelta < 63 - ? Frame.SAME_LOCALS_1_STACK_ITEM_FRAME - : Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED; - } - if (type != Frame.FULL_FRAME) { - // Verify if locals are the same as in the previous frame. - int frameIndex = 3; - for (int i = 0; i < previousNumlocal && i < numLocal; i++) { - if (currentFrame[frameIndex] != previousFrame[frameIndex]) { - type = Frame.FULL_FRAME; - break; - } - frameIndex++; - } - } - switch (type) { - case Frame.SAME_FRAME: - stackMapTableEntries.putByte(offsetDelta); - break; - case Frame.SAME_LOCALS_1_STACK_ITEM_FRAME: - stackMapTableEntries.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME + offsetDelta); - putAbstractTypes(3 + numLocal, 4 + numLocal); - break; - case Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED: - stackMapTableEntries - .putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) - .putShort(offsetDelta); - putAbstractTypes(3 + numLocal, 4 + numLocal); - break; - case Frame.SAME_FRAME_EXTENDED: - stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED).putShort(offsetDelta); - break; - case Frame.CHOP_FRAME: - stackMapTableEntries - .putByte(Frame.SAME_FRAME_EXTENDED + numLocalDelta) - .putShort(offsetDelta); - break; - case Frame.APPEND_FRAME: - stackMapTableEntries - .putByte(Frame.SAME_FRAME_EXTENDED + numLocalDelta) - .putShort(offsetDelta); - putAbstractTypes(3 + previousNumlocal, 3 + numLocal); - break; - case Frame.FULL_FRAME: - default: - stackMapTableEntries.putByte(Frame.FULL_FRAME).putShort(offsetDelta).putShort(numLocal); - putAbstractTypes(3, 3 + numLocal); - stackMapTableEntries.putShort(numStack); - putAbstractTypes(3 + numLocal, 3 + numLocal + numStack); - break; - } - } - - /** - * Puts some abstract types of {@link #currentFrame} in {@link #stackMapTableEntries} , using the - * JVMS verification_type_info format used in StackMapTable attributes. - * - * @param start index of the first type in {@link #currentFrame} to write. - * @param end index of last type in {@link #currentFrame} to write (exclusive). - */ - private void putAbstractTypes(final int start, final int end) { - for (int i = start; i < end; ++i) { - Frame.putAbstractType(symbolTable, currentFrame[i], stackMapTableEntries); - } - } - - /** - * Puts the given public API frame element type in {@link #stackMapTableEntries} , using the JVMS - * verification_type_info format used in StackMapTable attributes. - * - * @param type a frame element type described using the same format as in {@link - * MethodVisitor#visitFrame}, i.e. either {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, {@link - * Opcodes#FLOAT}, {@link Opcodes#LONG}, {@link Opcodes#DOUBLE}, {@link Opcodes#NULL}, or - * {@link Opcodes#UNINITIALIZED_THIS}, or the internal name of a class, or a Label designating - * a NEW instruction (for uninitialized types). - */ - private void putFrameType(final Object type) { - if (type instanceof Integer) { - stackMapTableEntries.putByte(((Integer) type).intValue()); - } else if (type instanceof String) { - stackMapTableEntries - .putByte(Frame.ITEM_OBJECT) - .putShort(symbolTable.addConstantClass((String) type).index); - } else { - stackMapTableEntries - .putByte(Frame.ITEM_UNINITIALIZED) - .putShort(((Label) type).bytecodeOffset); - } - } - - // ----------------------------------------------------------------------------------------------- - // Utility methods - // ----------------------------------------------------------------------------------------------- - - /** - * Returns whether the attributes of this method can be copied from the attributes of the given - * method (assuming there is no method visitor between the given ClassReader and this - * MethodWriter). This method should only be called just after this MethodWriter has been created, - * and before any content is visited. It returns true if the attributes corresponding to the - * constructor arguments (at most a Signature, an Exception, a Deprecated and a Synthetic - * attribute) are the same as the corresponding attributes in the given method. - * - * @param source the source ClassReader from which the attributes of this method might be copied. - * @param hasSyntheticAttribute whether the method_info JVMS structure from which the attributes - * of this method might be copied contains a Synthetic attribute. - * @param hasDeprecatedAttribute whether the method_info JVMS structure from which the attributes - * of this method might be copied contains a Deprecated attribute. - * @param descriptorIndex the descriptor_index field of the method_info JVMS structure from which - * the attributes of this method might be copied. - * @param signatureIndex the constant pool index contained in the Signature attribute of the - * method_info JVMS structure from which the attributes of this method might be copied, or 0. - * @param exceptionsOffset the offset in 'source.b' of the Exceptions attribute of the method_info - * JVMS structure from which the attributes of this method might be copied, or 0. - * @return whether the attributes of this method can be copied from the attributes of the - * method_info JVMS structure in 'source.b', between 'methodInfoOffset' and 'methodInfoOffset' - * + 'methodInfoLength'. - */ - boolean canCopyMethodAttributes( - final ClassReader source, - final boolean hasSyntheticAttribute, - final boolean hasDeprecatedAttribute, - final int descriptorIndex, - final int signatureIndex, - final int exceptionsOffset) { - // If the method descriptor has changed, with more locals than the max_locals field of the - // original Code attribute, if any, then the original method attributes can't be copied. A - // conservative check on the descriptor changes alone ensures this (being more precise is not - // worth the additional complexity, because these cases should be rare -- if a transform changes - // a method descriptor, most of the time it needs to change the method's code too). - if (source != symbolTable.getSource() - || descriptorIndex != this.descriptorIndex - || signatureIndex != this.signatureIndex - || hasDeprecatedAttribute != ((accessFlags & Opcodes.ACC_DEPRECATED) != 0)) { - return false; - } - boolean needSyntheticAttribute = - symbolTable.getMajorVersion() < Opcodes.V1_5 && (accessFlags & Opcodes.ACC_SYNTHETIC) != 0; - if (hasSyntheticAttribute != needSyntheticAttribute) { - return false; - } - if (exceptionsOffset == 0) { - if (numberOfExceptions != 0) { - return false; - } - } else if (source.readUnsignedShort(exceptionsOffset) == numberOfExceptions) { - int currentExceptionOffset = exceptionsOffset + 2; - for (int i = 0; i < numberOfExceptions; ++i) { - if (source.readUnsignedShort(currentExceptionOffset) != exceptionIndexTable[i]) { - return false; - } - currentExceptionOffset += 2; - } - } - return true; - } - - /** - * Sets the source from which the attributes of this method will be copied. - * - * @param methodInfoOffset the offset in 'symbolTable.getSource()' of the method_info JVMS - * structure from which the attributes of this method will be copied. - * @param methodInfoLength the length in 'symbolTable.getSource()' of the method_info JVMS - * structure from which the attributes of this method will be copied. - */ - void setMethodAttributesSource(final int methodInfoOffset, final int methodInfoLength) { - // Don't copy the attributes yet, instead store their location in the source class reader so - // they can be copied later, in {@link #putMethodInfo}. Note that we skip the 6 header bytes - // of the method_info JVMS structure. - this.sourceOffset = methodInfoOffset + 6; - this.sourceLength = methodInfoLength - 6; - } - - /** - * Returns the size of the method_info JVMS structure generated by this MethodWriter. Also add the - * names of the attributes of this method in the constant pool. - * - * @return the size in bytes of the method_info JVMS structure. - */ - int computeMethodInfoSize() { - // If this method_info must be copied from an existing one, the size computation is trivial. - if (sourceOffset != 0) { - // sourceLength excludes the first 6 bytes for access_flags, name_index and descriptor_index. - return 6 + sourceLength; - } - // 2 bytes each for access_flags, name_index, descriptor_index and attributes_count. - int size = 8; - // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. - if (code.length > 0) { - if (code.length > 65535) { - throw new MethodTooLargeException( - symbolTable.getClassName(), name, descriptor, code.length); - } - symbolTable.addConstantUtf8(Constants.CODE); - // The Code attribute has 6 header bytes, plus 2, 2, 4 and 2 bytes respectively for max_stack, - // max_locals, code_length and attributes_count, plus the bytecode and the exception table. - size += 16 + code.length + Handler.getExceptionTableSize(firstHandler); - if (stackMapTableEntries != null) { - boolean useStackMapTable = symbolTable.getMajorVersion() >= Opcodes.V1_6; - symbolTable.addConstantUtf8(useStackMapTable ? Constants.STACK_MAP_TABLE : "StackMap"); - // 6 header bytes and 2 bytes for number_of_entries. - size += 8 + stackMapTableEntries.length; - } - if (lineNumberTable != null) { - symbolTable.addConstantUtf8(Constants.LINE_NUMBER_TABLE); - // 6 header bytes and 2 bytes for line_number_table_length. - size += 8 + lineNumberTable.length; - } - if (localVariableTable != null) { - symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TABLE); - // 6 header bytes and 2 bytes for local_variable_table_length. - size += 8 + localVariableTable.length; - } - if (localVariableTypeTable != null) { - symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TYPE_TABLE); - // 6 header bytes and 2 bytes for local_variable_type_table_length. - size += 8 + localVariableTypeTable.length; - } - if (lastCodeRuntimeVisibleTypeAnnotation != null) { - size += - lastCodeRuntimeVisibleTypeAnnotation.computeAnnotationsSize( - Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS); - } - if (lastCodeRuntimeInvisibleTypeAnnotation != null) { - size += - lastCodeRuntimeInvisibleTypeAnnotation.computeAnnotationsSize( - Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS); - } - if (firstCodeAttribute != null) { - size += - firstCodeAttribute.computeAttributesSize( - symbolTable, code.data, code.length, maxStack, maxLocals); - } - } - if (numberOfExceptions > 0) { - symbolTable.addConstantUtf8(Constants.EXCEPTIONS); - size += 8 + 2 * numberOfExceptions; - } - size += Attribute.computeAttributesSize(symbolTable, accessFlags, signatureIndex); - size += - AnnotationWriter.computeAnnotationsSize( - lastRuntimeVisibleAnnotation, - lastRuntimeInvisibleAnnotation, - lastRuntimeVisibleTypeAnnotation, - lastRuntimeInvisibleTypeAnnotation); - if (lastRuntimeVisibleParameterAnnotations != null) { - size += - AnnotationWriter.computeParameterAnnotationsSize( - Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS, - lastRuntimeVisibleParameterAnnotations, - visibleAnnotableParameterCount == 0 - ? lastRuntimeVisibleParameterAnnotations.length - : visibleAnnotableParameterCount); - } - if (lastRuntimeInvisibleParameterAnnotations != null) { - size += - AnnotationWriter.computeParameterAnnotationsSize( - Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS, - lastRuntimeInvisibleParameterAnnotations, - invisibleAnnotableParameterCount == 0 - ? lastRuntimeInvisibleParameterAnnotations.length - : invisibleAnnotableParameterCount); - } - if (defaultValue != null) { - symbolTable.addConstantUtf8(Constants.ANNOTATION_DEFAULT); - size += 6 + defaultValue.length; - } - if (parameters != null) { - symbolTable.addConstantUtf8(Constants.METHOD_PARAMETERS); - // 6 header bytes and 1 byte for parameters_count. - size += 7 + parameters.length; - } - if (firstAttribute != null) { - size += firstAttribute.computeAttributesSize(symbolTable); - } - return size; - } - - /** - * Puts the content of the method_info JVMS structure generated by this MethodWriter into the - * given ByteVector. - * - * @param output where the method_info structure must be put. - */ - void putMethodInfo(final ByteVector output) { - boolean useSyntheticAttribute = symbolTable.getMajorVersion() < Opcodes.V1_5; - int mask = useSyntheticAttribute ? Opcodes.ACC_SYNTHETIC : 0; - output.putShort(accessFlags & ~mask).putShort(nameIndex).putShort(descriptorIndex); - // If this method_info must be copied from an existing one, copy it now and return early. - if (sourceOffset != 0) { - output.putByteArray(symbolTable.getSource().classFileBuffer, sourceOffset, sourceLength); - return; - } - // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. - int attributeCount = 0; - if (code.length > 0) { - ++attributeCount; - } - if (numberOfExceptions > 0) { - ++attributeCount; - } - if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && useSyntheticAttribute) { - ++attributeCount; - } - if (signatureIndex != 0) { - ++attributeCount; - } - if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) { - ++attributeCount; - } - if (lastRuntimeVisibleAnnotation != null) { - ++attributeCount; - } - if (lastRuntimeInvisibleAnnotation != null) { - ++attributeCount; - } - if (lastRuntimeVisibleParameterAnnotations != null) { - ++attributeCount; - } - if (lastRuntimeInvisibleParameterAnnotations != null) { - ++attributeCount; - } - if (lastRuntimeVisibleTypeAnnotation != null) { - ++attributeCount; - } - if (lastRuntimeInvisibleTypeAnnotation != null) { - ++attributeCount; - } - if (defaultValue != null) { - ++attributeCount; - } - if (parameters != null) { - ++attributeCount; - } - if (firstAttribute != null) { - attributeCount += firstAttribute.getAttributeCount(); - } - // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. - output.putShort(attributeCount); - if (code.length > 0) { - // 2, 2, 4 and 2 bytes respectively for max_stack, max_locals, code_length and - // attributes_count, plus the bytecode and the exception table. - int size = 10 + code.length + Handler.getExceptionTableSize(firstHandler); - int codeAttributeCount = 0; - if (stackMapTableEntries != null) { - // 6 header bytes and 2 bytes for number_of_entries. - size += 8 + stackMapTableEntries.length; - ++codeAttributeCount; - } - if (lineNumberTable != null) { - // 6 header bytes and 2 bytes for line_number_table_length. - size += 8 + lineNumberTable.length; - ++codeAttributeCount; - } - if (localVariableTable != null) { - // 6 header bytes and 2 bytes for local_variable_table_length. - size += 8 + localVariableTable.length; - ++codeAttributeCount; - } - if (localVariableTypeTable != null) { - // 6 header bytes and 2 bytes for local_variable_type_table_length. - size += 8 + localVariableTypeTable.length; - ++codeAttributeCount; - } - if (lastCodeRuntimeVisibleTypeAnnotation != null) { - size += - lastCodeRuntimeVisibleTypeAnnotation.computeAnnotationsSize( - Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS); - ++codeAttributeCount; - } - if (lastCodeRuntimeInvisibleTypeAnnotation != null) { - size += - lastCodeRuntimeInvisibleTypeAnnotation.computeAnnotationsSize( - Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS); - ++codeAttributeCount; - } - if (firstCodeAttribute != null) { - size += - firstCodeAttribute.computeAttributesSize( - symbolTable, code.data, code.length, maxStack, maxLocals); - codeAttributeCount += firstCodeAttribute.getAttributeCount(); - } - output - .putShort(symbolTable.addConstantUtf8(Constants.CODE)) - .putInt(size) - .putShort(maxStack) - .putShort(maxLocals) - .putInt(code.length) - .putByteArray(code.data, 0, code.length); - Handler.putExceptionTable(firstHandler, output); - output.putShort(codeAttributeCount); - if (stackMapTableEntries != null) { - boolean useStackMapTable = symbolTable.getMajorVersion() >= Opcodes.V1_6; - output - .putShort( - symbolTable.addConstantUtf8( - useStackMapTable ? Constants.STACK_MAP_TABLE : "StackMap")) - .putInt(2 + stackMapTableEntries.length) - .putShort(stackMapTableNumberOfEntries) - .putByteArray(stackMapTableEntries.data, 0, stackMapTableEntries.length); - } - if (lineNumberTable != null) { - output - .putShort(symbolTable.addConstantUtf8(Constants.LINE_NUMBER_TABLE)) - .putInt(2 + lineNumberTable.length) - .putShort(lineNumberTableLength) - .putByteArray(lineNumberTable.data, 0, lineNumberTable.length); - } - if (localVariableTable != null) { - output - .putShort(symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TABLE)) - .putInt(2 + localVariableTable.length) - .putShort(localVariableTableLength) - .putByteArray(localVariableTable.data, 0, localVariableTable.length); - } - if (localVariableTypeTable != null) { - output - .putShort(symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TYPE_TABLE)) - .putInt(2 + localVariableTypeTable.length) - .putShort(localVariableTypeTableLength) - .putByteArray(localVariableTypeTable.data, 0, localVariableTypeTable.length); - } - if (lastCodeRuntimeVisibleTypeAnnotation != null) { - lastCodeRuntimeVisibleTypeAnnotation.putAnnotations( - symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS), output); - } - if (lastCodeRuntimeInvisibleTypeAnnotation != null) { - lastCodeRuntimeInvisibleTypeAnnotation.putAnnotations( - symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS), output); - } - if (firstCodeAttribute != null) { - firstCodeAttribute.putAttributes( - symbolTable, code.data, code.length, maxStack, maxLocals, output); - } - } - if (numberOfExceptions > 0) { - output - .putShort(symbolTable.addConstantUtf8(Constants.EXCEPTIONS)) - .putInt(2 + 2 * numberOfExceptions) - .putShort(numberOfExceptions); - for (int exceptionIndex : exceptionIndexTable) { - output.putShort(exceptionIndex); - } - } - Attribute.putAttributes(symbolTable, accessFlags, signatureIndex, output); - AnnotationWriter.putAnnotations( - symbolTable, - lastRuntimeVisibleAnnotation, - lastRuntimeInvisibleAnnotation, - lastRuntimeVisibleTypeAnnotation, - lastRuntimeInvisibleTypeAnnotation, - output); - if (lastRuntimeVisibleParameterAnnotations != null) { - AnnotationWriter.putParameterAnnotations( - symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS), - lastRuntimeVisibleParameterAnnotations, - visibleAnnotableParameterCount == 0 - ? lastRuntimeVisibleParameterAnnotations.length - : visibleAnnotableParameterCount, - output); - } - if (lastRuntimeInvisibleParameterAnnotations != null) { - AnnotationWriter.putParameterAnnotations( - symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS), - lastRuntimeInvisibleParameterAnnotations, - invisibleAnnotableParameterCount == 0 - ? lastRuntimeInvisibleParameterAnnotations.length - : invisibleAnnotableParameterCount, - output); - } - if (defaultValue != null) { - output - .putShort(symbolTable.addConstantUtf8(Constants.ANNOTATION_DEFAULT)) - .putInt(defaultValue.length) - .putByteArray(defaultValue.data, 0, defaultValue.length); - } - if (parameters != null) { - output - .putShort(symbolTable.addConstantUtf8(Constants.METHOD_PARAMETERS)) - .putInt(1 + parameters.length) - .putByte(parametersCount) - .putByteArray(parameters.data, 0, parameters.length); - } - if (firstAttribute != null) { - firstAttribute.putAttributes(symbolTable, output); - } - } - - /** - * Collects the attributes of this method into the given set of attribute prototypes. - * - * @param attributePrototypes a set of attribute prototypes. - */ - final void collectAttributePrototypes(final Attribute.Set attributePrototypes) { - attributePrototypes.addAttributes(firstAttribute); - attributePrototypes.addAttributes(firstCodeAttribute); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/ModuleVisitor.java b/jodd-proxetta/src/main/java/jodd/asm7/ModuleVisitor.java deleted file mode 100644 index 95a8cc599..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/ModuleVisitor.java +++ /dev/null @@ -1,174 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * A visitor to visit a Java module. The methods of this class must be called in the following - * order: ( {@code visitMainClass} | ( {@code visitPackage} | {@code visitRequire} | {@code - * visitExport} | {@code visitOpen} | {@code visitUse} | {@code visitProvide} )* ) {@code visitEnd}. - * - * @author Remi Forax - * @author Eric Bruneton - */ -public abstract class ModuleVisitor { - /** - * The ASM API version implemented by this visitor. The value of this field must be one of {@link - * Opcodes#ASM6} or {@link Opcodes#ASM7}. - */ - protected final int api; - - /** The module visitor to which this visitor must delegate method calls. May be null. */ - protected ModuleVisitor mv; - - /** - * Constructs a new {@link ModuleVisitor}. - * - * @param api the ASM API version implemented by this visitor. Must be one of {@link Opcodes#ASM6} - * or {@link Opcodes#ASM7}. - */ - public ModuleVisitor(final int api) { - this(api, null); - } - - /** - * Constructs a new {@link ModuleVisitor}. - * - * @param api the ASM API version implemented by this visitor. Must be one of {@link Opcodes#ASM6} - * or {@link Opcodes#ASM7}. - * @param moduleVisitor the module visitor to which this visitor must delegate method calls. May - * be null. - */ - public ModuleVisitor(final int api, final ModuleVisitor moduleVisitor) { - if (api != Opcodes.ASM7 && api != Opcodes.ASM6) { - throw new IllegalArgumentException("Unsupported api " + api); - } - this.api = api; - this.mv = moduleVisitor; - } - - /** - * Visit the main class of the current module. - * - * @param mainClass the internal name of the main class of the current module. - */ - public void visitMainClass(final String mainClass) { - if (mv != null) { - mv.visitMainClass(mainClass); - } - } - - /** - * Visit a package of the current module. - * - * @param packaze the internal name of a package. - */ - public void visitPackage(final String packaze) { - if (mv != null) { - mv.visitPackage(packaze); - } - } - - /** - * Visits a dependence of the current module. - * - * @param module the fully qualified name (using dots) of the dependence. - * @param access the access flag of the dependence among {@code ACC_TRANSITIVE}, {@code - * ACC_STATIC_PHASE}, {@code ACC_SYNTHETIC} and {@code ACC_MANDATED}. - * @param version the module version at compile time, or {@literal null}. - */ - public void visitRequire(final String module, final int access, final String version) { - if (mv != null) { - mv.visitRequire(module, access, version); - } - } - - /** - * Visit an exported package of the current module. - * - * @param packaze the internal name of the exported package. - * @param access the access flag of the exported package, valid values are among {@code - * ACC_SYNTHETIC} and {@code ACC_MANDATED}. - * @param modules the fully qualified names (using dots) of the modules that can access the public - * classes of the exported package, or {@literal null}. - */ - public void visitExport(final String packaze, final int access, final String... modules) { - if (mv != null) { - mv.visitExport(packaze, access, modules); - } - } - - /** - * Visit an open package of the current module. - * - * @param packaze the internal name of the opened package. - * @param access the access flag of the opened package, valid values are among {@code - * ACC_SYNTHETIC} and {@code ACC_MANDATED}. - * @param modules the fully qualified names (using dots) of the modules that can use deep - * reflection to the classes of the open package, or {@literal null}. - */ - public void visitOpen(final String packaze, final int access, final String... modules) { - if (mv != null) { - mv.visitOpen(packaze, access, modules); - } - } - - /** - * Visit a service used by the current module. The name must be the internal name of an interface - * or a class. - * - * @param service the internal name of the service. - */ - public void visitUse(final String service) { - if (mv != null) { - mv.visitUse(service); - } - } - - /** - * Visit an implementation of a service. - * - * @param service the internal name of the service. - * @param providers the internal names of the implementations of the service (there is at least - * one provider). - */ - public void visitProvide(final String service, final String... providers) { - if (mv != null) { - mv.visitProvide(service, providers); - } - } - - /** - * Visits the end of the module. This method, which is the last one to be called, is used to - * inform the visitor that everything have been visited. - */ - public void visitEnd() { - if (mv != null) { - mv.visitEnd(); - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/ModuleWriter.java b/jodd-proxetta/src/main/java/jodd/asm7/ModuleWriter.java deleted file mode 100644 index da7a8de9d..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/ModuleWriter.java +++ /dev/null @@ -1,253 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * A {@link ModuleVisitor} that generates the corresponding Module, ModulePackages and - * ModuleMainClass attributes, as defined in the Java Virtual Machine Specification (JVMS). - * - * @see JVMS - * 4.7.25 - * @see JVMS - * 4.7.26 - * @see JVMS - * 4.7.27 - * @author Remi Forax - * @author Eric Bruneton - */ -final class ModuleWriter extends ModuleVisitor { - - /** Where the constants used in this AnnotationWriter must be stored. */ - private final SymbolTable symbolTable; - - /** The module_name_index field of the JVMS Module attribute. */ - private final int moduleNameIndex; - - /** The module_flags field of the JVMS Module attribute. */ - private final int moduleFlags; - - /** The module_version_index field of the JVMS Module attribute. */ - private final int moduleVersionIndex; - - /** The requires_count field of the JVMS Module attribute. */ - private int requiresCount; - - /** The binary content of the 'requires' array of the JVMS Module attribute. */ - private final ByteVector requires; - - /** The exports_count field of the JVMS Module attribute. */ - private int exportsCount; - - /** The binary content of the 'exports' array of the JVMS Module attribute. */ - private final ByteVector exports; - - /** The opens_count field of the JVMS Module attribute. */ - private int opensCount; - - /** The binary content of the 'opens' array of the JVMS Module attribute. */ - private final ByteVector opens; - - /** The uses_count field of the JVMS Module attribute. */ - private int usesCount; - - /** The binary content of the 'uses_index' array of the JVMS Module attribute. */ - private final ByteVector usesIndex; - - /** The provides_count field of the JVMS Module attribute. */ - private int providesCount; - - /** The binary content of the 'provides' array of the JVMS Module attribute. */ - private final ByteVector provides; - - /** The provides_count field of the JVMS ModulePackages attribute. */ - private int packageCount; - - /** The binary content of the 'package_index' array of the JVMS ModulePackages attribute. */ - private final ByteVector packageIndex; - - /** The main_class_index field of the JVMS ModuleMainClass attribute, or 0. */ - private int mainClassIndex; - - ModuleWriter(final SymbolTable symbolTable, final int name, final int access, final int version) { - super(Opcodes.ASM7); - this.symbolTable = symbolTable; - this.moduleNameIndex = name; - this.moduleFlags = access; - this.moduleVersionIndex = version; - this.requires = new ByteVector(); - this.exports = new ByteVector(); - this.opens = new ByteVector(); - this.usesIndex = new ByteVector(); - this.provides = new ByteVector(); - this.packageIndex = new ByteVector(); - } - - @Override - public void visitMainClass(final String mainClass) { - this.mainClassIndex = symbolTable.addConstantClass(mainClass).index; - } - - @Override - public void visitPackage(final String packaze) { - packageIndex.putShort(symbolTable.addConstantPackage(packaze).index); - packageCount++; - } - - @Override - public void visitRequire(final String module, final int access, final String version) { - requires - .putShort(symbolTable.addConstantModule(module).index) - .putShort(access) - .putShort(version == null ? 0 : symbolTable.addConstantUtf8(version)); - requiresCount++; - } - - @Override - public void visitExport(final String packaze, final int access, final String... modules) { - exports.putShort(symbolTable.addConstantPackage(packaze).index).putShort(access); - if (modules == null) { - exports.putShort(0); - } else { - exports.putShort(modules.length); - for (String module : modules) { - exports.putShort(symbolTable.addConstantModule(module).index); - } - } - exportsCount++; - } - - @Override - public void visitOpen(final String packaze, final int access, final String... modules) { - opens.putShort(symbolTable.addConstantPackage(packaze).index).putShort(access); - if (modules == null) { - opens.putShort(0); - } else { - opens.putShort(modules.length); - for (String module : modules) { - opens.putShort(symbolTable.addConstantModule(module).index); - } - } - opensCount++; - } - - @Override - public void visitUse(final String service) { - usesIndex.putShort(symbolTable.addConstantClass(service).index); - usesCount++; - } - - @Override - public void visitProvide(final String service, final String... providers) { - provides.putShort(symbolTable.addConstantClass(service).index); - provides.putShort(providers.length); - for (String provider : providers) { - provides.putShort(symbolTable.addConstantClass(provider).index); - } - providesCount++; - } - - @Override - public void visitEnd() { - // Nothing to do. - } - - /** - * Returns the number of Module, ModulePackages and ModuleMainClass attributes generated by this - * ModuleWriter. - * - * @return the number of Module, ModulePackages and ModuleMainClass attributes (between 1 and 3). - */ - int getAttributeCount() { - return 1 + (packageCount > 0 ? 1 : 0) + (mainClassIndex > 0 ? 1 : 0); - } - - /** - * Returns the size of the Module, ModulePackages and ModuleMainClass attributes generated by this - * ModuleWriter. Also add the names of these attributes in the constant pool. - * - * @return the size in bytes of the Module, ModulePackages and ModuleMainClass attributes. - */ - int computeAttributesSize() { - symbolTable.addConstantUtf8(Constants.MODULE); - // 6 attribute header bytes, 6 bytes for name, flags and version, and 5 * 2 bytes for counts. - int size = - 22 + requires.length + exports.length + opens.length + usesIndex.length + provides.length; - if (packageCount > 0) { - symbolTable.addConstantUtf8(Constants.MODULE_PACKAGES); - // 6 attribute header bytes, and 2 bytes for package_count. - size += 8 + packageIndex.length; - } - if (mainClassIndex > 0) { - symbolTable.addConstantUtf8(Constants.MODULE_MAIN_CLASS); - // 6 attribute header bytes, and 2 bytes for main_class_index. - size += 8; - } - return size; - } - - /** - * Puts the Module, ModulePackages and ModuleMainClass attributes generated by this ModuleWriter - * in the given ByteVector. - * - * @param output where the attributes must be put. - */ - void putAttributes(final ByteVector output) { - // 6 bytes for name, flags and version, and 5 * 2 bytes for counts. - int moduleAttributeLength = - 16 + requires.length + exports.length + opens.length + usesIndex.length + provides.length; - output - .putShort(symbolTable.addConstantUtf8(Constants.MODULE)) - .putInt(moduleAttributeLength) - .putShort(moduleNameIndex) - .putShort(moduleFlags) - .putShort(moduleVersionIndex) - .putShort(requiresCount) - .putByteArray(requires.data, 0, requires.length) - .putShort(exportsCount) - .putByteArray(exports.data, 0, exports.length) - .putShort(opensCount) - .putByteArray(opens.data, 0, opens.length) - .putShort(usesCount) - .putByteArray(usesIndex.data, 0, usesIndex.length) - .putShort(providesCount) - .putByteArray(provides.data, 0, provides.length); - if (packageCount > 0) { - output - .putShort(symbolTable.addConstantUtf8(Constants.MODULE_PACKAGES)) - .putInt(2 + packageIndex.length) - .putShort(packageCount) - .putByteArray(packageIndex.data, 0, packageIndex.length); - } - if (mainClassIndex > 0) { - output - .putShort(symbolTable.addConstantUtf8(Constants.MODULE_MAIN_CLASS)) - .putInt(2) - .putShort(mainClassIndex); - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/Opcodes.java b/jodd-proxetta/src/main/java/jodd/asm7/Opcodes.java deleted file mode 100644 index e59f14e75..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/Opcodes.java +++ /dev/null @@ -1,545 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * The JVM opcodes, access flags and array type codes. This interface does not define all the JVM - * opcodes because some opcodes are automatically handled. For example, the xLOAD and xSTORE opcodes - * are automatically replaced by xLOAD_n and xSTORE_n opcodes when possible. The xLOAD_n and - * xSTORE_n opcodes are therefore not defined in this interface. Likewise for LDC, automatically - * replaced by LDC_W or LDC2_W when necessary, WIDE, GOTO_W and JSR_W. - * - * @see JVMS 6 - * @author Eric Bruneton - * @author Eugene Kuleshov - */ -// DontCheck(InterfaceIsType): can't be fixed (for backward binary compatibility). -public interface Opcodes { - - // ASM API versions. - - int ASM4 = 4 << 16 | 0 << 8; - int ASM5 = 5 << 16 | 0 << 8; - int ASM6 = 6 << 16 | 0 << 8; - int ASM7 = 7 << 16 | 0 << 8; - - /* - * Internal flags used to redirect calls to deprecated methods. For instance, if a visitOldStuff - * method in API_OLD is deprecated and replaced with visitNewStuff in API_NEW, then the - * redirection should be done as follows: - * - *

-   * public class StuffVisitor {
-   *   ...
-   *
-   *   @Deprecated public void visitOldStuff(int arg, ...) {
-   *     // SOURCE_DEPRECATED means "a call from a deprecated method using the old 'api' value".
-   *     visitNewStuf(arg | (api < API_NEW ? SOURCE_DEPRECATED : 0), ...);
-   *   }
-   *
-   *   public void visitNewStuff(int argAndSource, ...) {
-   *     if (api < API_NEW && (argAndSource & SOURCE_DEPRECATED) == 0) {
-   *       visitOldStuff(argAndSource, ...);
-   *     } else {
-   *       int arg = argAndSource & ~SOURCE_MASK;
-   *       [ do stuff ]
-   *     }
-   *   }
-   * }
-   * 
- * - *

If 'api' is equal to API_NEW, there are two cases: - * - *

    - *
  • call visitNewStuff: the redirection test is skipped and 'do stuff' is executed directly. - *
  • call visitOldSuff: the source is not set to SOURCE_DEPRECATED before calling - * visitNewStuff, but the redirection test is skipped anyway in visitNewStuff, which - * directly executes 'do stuff'. - *
- * - *

If 'api' is equal to API_OLD, there are two cases: - * - *

    - *
  • call visitOldSuff: the source is set to SOURCE_DEPRECATED before calling visitNewStuff. - * Because of this visitNewStuff does not redirect back to visitOldStuff, and instead - * executes 'do stuff'. - *
  • call visitNewStuff: the call is redirected to visitOldStuff because the source is 0. - * visitOldStuff now sets the source to SOURCE_DEPRECATED and calls visitNewStuff back. This - * time visitNewStuff does not redirect the call, and instead executes 'do stuff'. - *
- * - *

User subclasses

- * - *

If a user subclass overrides one of these methods, there are only two cases: either 'api' is - * API_OLD and visitOldStuff is overridden (and visitNewStuff is not), or 'api' is API_NEW or - * more, and visitNewStuff is overridden (and visitOldStuff is not). Any other case is a user - * programming error. - * - *

If 'api' is equal to API_NEW, the class hierarchy is equivalent to - * - *

-   * public class StuffVisitor {
-   *   @Deprecated public void visitOldStuff(int arg, ...) { visitNewStuf(arg, ...); }
-   *   public void visitNewStuff(int arg, ...) { [ do stuff ] }
-   * }
-   * class UserStuffVisitor extends StuffVisitor {
-   *   @Override public void visitNewStuff(int arg, ...) {
-   *     super.visitNewStuff(int arg, ...); // optional
-   *     [ do user stuff ]
-   *   }
-   * }
-   * 
- * - *

It is then obvious that whether visitNewStuff or visitOldStuff is called, 'do stuff' and 'do - * user stuff' will be executed, in this order. - * - *

If 'api' is equal to API_OLD, the class hierarchy is equivalent to - * - *

-   * public class StuffVisitor {
-   *   @Deprecated public void visitOldStuff(int arg, ...) {
-   *     visitNewStuf(arg | SOURCE_DEPRECATED, ...);
-   *   }
-   *   public void visitNewStuff(int argAndSource...) {
-   *     if ((argAndSource & SOURCE_DEPRECATED) == 0) {
-   *       visitOldStuff(argAndSource, ...);
-   *     } else {
-   *       int arg = argAndSource & ~SOURCE_MASK;
-   *       [ do stuff ]
-   *     }
-   *   }
-   * }
-   * class UserStuffVisitor extends StuffVisitor {
-   *   @Override public void visitOldStuff(int arg, ...) {
-   *     super.visitOldStuff(int arg, ...); // optional
-   *     [ do user stuff ]
-   *   }
-   * }
-   * 
- * - *

and there are two cases: - * - *

    - *
  • call visitOldSuff: in the call to super.visitOldStuff, the source is set to - * SOURCE_DEPRECATED and visitNewStuff is called. Here 'do stuff' is run because the source - * was previously set to SOURCE_DEPRECATED, and execution eventually returns to - * UserStuffVisitor.visitOldStuff, where 'do user stuff' is run. - *
  • call visitNewStuff: the call is redirected to UserStuffVisitor.visitOldStuff because the - * source is 0. Execution continues as in the previous case, resulting in 'do stuff' and 'do - * user stuff' being executed, in this order. - *
- * - *

ASM subclasses

- * - *

In ASM packages, subclasses of StuffVisitor can typically be sub classed again by the user, - * and can be used with API_OLD or API_NEW. Because of this, if such a subclass must override - * visitNewStuff, it must do so in the following way (and must not override visitOldStuff): - * - *

-   * public class AsmStuffVisitor extends StuffVisitor {
-   *   @Override public void visitNewStuff(int argAndSource, ...) {
-   *     if (api < API_NEW && (argAndSource & SOURCE_DEPRECATED) == 0) {
-   *       super.visitNewStuff(argAndSource, ...);
-   *       return;
-   *     }
-   *     super.visitNewStuff(argAndSource, ...); // optional
-   *     int arg = argAndSource & ~SOURCE_MASK;
-   *     [ do other stuff ]
-   *   }
-   * }
-   * 
- * - *

If a user class extends this with 'api' equal to API_NEW, the class hierarchy is equivalent - * to - * - *

-   * public class StuffVisitor {
-   *   @Deprecated public void visitOldStuff(int arg, ...) { visitNewStuf(arg, ...); }
-   *   public void visitNewStuff(int arg, ...) { [ do stuff ] }
-   * }
-   * public class AsmStuffVisitor extends StuffVisitor {
-   *   @Override public void visitNewStuff(int arg, ...) {
-   *     super.visitNewStuff(arg, ...);
-   *     [ do other stuff ]
-   *   }
-   * }
-   * class UserStuffVisitor extends StuffVisitor {
-   *   @Override public void visitNewStuff(int arg, ...) {
-   *     super.visitNewStuff(int arg, ...);
-   *     [ do user stuff ]
-   *   }
-   * }
-   * 
- * - *

It is then obvious that whether visitNewStuff or visitOldStuff is called, 'do stuff', 'do - * other stuff' and 'do user stuff' will be executed, in this order. If, on the other hand, a user - * class extends AsmStuffVisitor with 'api' equal to API_OLD, the class hierarchy is equivalent to - * - *

-   * public class StuffVisitor {
-   *   @Deprecated public void visitOldStuff(int arg, ...) {
-   *     visitNewStuf(arg | SOURCE_DEPRECATED, ...);
-   *   }
-   *   public void visitNewStuff(int argAndSource, ...) {
-   *     if ((argAndSource & SOURCE_DEPRECATED) == 0) {
-   *       visitOldStuff(argAndSource, ...);
-   *     } else {
-   *       int arg = argAndSource & ~SOURCE_MASK;
-   *       [ do stuff ]
-   *     }
-   *   }
-   * }
-   * public class AsmStuffVisitor extends StuffVisitor {
-   *   @Override public void visitNewStuff(int argAndSource, ...) {
-   *     if ((argAndSource & SOURCE_DEPRECATED) == 0) {
-   *       super.visitNewStuff(argAndSource, ...);
-   *       return;
-   *     }
-   *     super.visitNewStuff(argAndSource, ...); // optional
-   *     int arg = argAndSource & ~SOURCE_MASK;
-   *     [ do other stuff ]
-   *   }
-   * }
-   * class UserStuffVisitor extends StuffVisitor {
-   *   @Override public void visitOldStuff(int arg, ...) {
-   *     super.visitOldStuff(arg, ...);
-   *     [ do user stuff ]
-   *   }
-   * }
-   * 
- * - *

and, here again, whether visitNewStuff or visitOldStuff is called, 'do stuff', 'do other - * stuff' and 'do user stuff' will be executed, in this order (exercise left to the reader). - * - *

Notes

- * - *
    - *
  • the SOURCE_DEPRECATED flag is set only if 'api' is API_OLD, just before calling - * visitNewStuff. By hypothesis, this method is not overridden by the user. Therefore, user - * classes can never see this flag. Only ASM subclasses must take care of extracting the - * actual argument value by clearing the source flags. - *
  • because the SOURCE_DEPRECATED flag is immediately cleared in the caller, the caller can - * call visitOldStuff or visitNewStuff (in 'do stuff' and 'do user stuff') on a delegate - * visitor without any risks (breaking the redirection logic, "leaking" the flag, etc). - *
  • all the scenarios discussed above are unit tested in MethodVisitorTest. - *
- */ - - int SOURCE_DEPRECATED = 0x100; - int SOURCE_MASK = SOURCE_DEPRECATED; - - // Java ClassFile versions (the minor version is stored in the 16 most significant bits, and the - // major version in the 16 least significant bits). - - int V1_1 = 3 << 16 | 45; - int V1_2 = 0 << 16 | 46; - int V1_3 = 0 << 16 | 47; - int V1_4 = 0 << 16 | 48; - int V1_5 = 0 << 16 | 49; - int V1_6 = 0 << 16 | 50; - int V1_7 = 0 << 16 | 51; - int V1_8 = 0 << 16 | 52; - int V9 = 0 << 16 | 53; - int V10 = 0 << 16 | 54; - int V11 = 0 << 16 | 55; - int V12 = 0 << 16 | 56; - int V13 = 0 << 16 | 57; - - /** - * Version flag indicating that the class is using 'preview' features. - * - *

{@code version & V_PREVIEW == V_PREVIEW} tests if a version is flagged with {@code - * V_PREVIEW}. - */ - int V_PREVIEW = 0xFFFF0000; - - // Access flags values, defined in - // - https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.1-200-E.1 - // - https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.5-200-A.1 - // - https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.6-200-A.1 - // - https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.25 - - int ACC_PUBLIC = 0x0001; // class, field, method - int ACC_PRIVATE = 0x0002; // class, field, method - int ACC_PROTECTED = 0x0004; // class, field, method - int ACC_STATIC = 0x0008; // field, method - int ACC_FINAL = 0x0010; // class, field, method, parameter - int ACC_SUPER = 0x0020; // class - int ACC_SYNCHRONIZED = 0x0020; // method - int ACC_OPEN = 0x0020; // module - int ACC_TRANSITIVE = 0x0020; // module requires - int ACC_VOLATILE = 0x0040; // field - int ACC_BRIDGE = 0x0040; // method - int ACC_STATIC_PHASE = 0x0040; // module requires - int ACC_VARARGS = 0x0080; // method - int ACC_TRANSIENT = 0x0080; // field - int ACC_NATIVE = 0x0100; // method - int ACC_INTERFACE = 0x0200; // class - int ACC_ABSTRACT = 0x0400; // class, method - int ACC_STRICT = 0x0800; // method - int ACC_SYNTHETIC = 0x1000; // class, field, method, parameter, module * - int ACC_ANNOTATION = 0x2000; // class - int ACC_ENUM = 0x4000; // class(?) field inner - int ACC_MANDATED = 0x8000; // parameter, module, module * - int ACC_MODULE = 0x8000; // class - - // ASM specific access flags. - // WARNING: the 16 least significant bits must NOT be used, to avoid conflicts with standard - // access flags, and also to make sure that these flags are automatically filtered out when - // written in class files (because access flags are stored using 16 bits only). - - int ACC_DEPRECATED = 0x20000; // class, field, method - - // Possible values for the type operand of the NEWARRAY instruction. - // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-6.html#jvms-6.5.newarray. - - int T_BOOLEAN = 4; - int T_CHAR = 5; - int T_FLOAT = 6; - int T_DOUBLE = 7; - int T_BYTE = 8; - int T_SHORT = 9; - int T_INT = 10; - int T_LONG = 11; - - // Possible values for the reference_kind field of CONSTANT_MethodHandle_info structures. - // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.4.8. - - int H_GETFIELD = 1; - int H_GETSTATIC = 2; - int H_PUTFIELD = 3; - int H_PUTSTATIC = 4; - int H_INVOKEVIRTUAL = 5; - int H_INVOKESTATIC = 6; - int H_INVOKESPECIAL = 7; - int H_NEWINVOKESPECIAL = 8; - int H_INVOKEINTERFACE = 9; - - // ASM specific stack map frame types, used in {@link ClassVisitor#visitFrame}. - - /** An expanded frame. See {@link ClassReader#EXPAND_FRAMES}. */ - int F_NEW = -1; - - /** A compressed frame with complete frame data. */ - int F_FULL = 0; - - /** - * A compressed frame where locals are the same as the locals in the previous frame, except that - * additional 1-3 locals are defined, and with an empty stack. - */ - int F_APPEND = 1; - - /** - * A compressed frame where locals are the same as the locals in the previous frame, except that - * the last 1-3 locals are absent and with an empty stack. - */ - int F_CHOP = 2; - - /** - * A compressed frame with exactly the same locals as the previous frame and with an empty stack. - */ - int F_SAME = 3; - - /** - * A compressed frame with exactly the same locals as the previous frame and with a single value - * on the stack. - */ - int F_SAME1 = 4; - - // Standard stack map frame element types, used in {@link ClassVisitor#visitFrame}. - - Integer TOP = Frame.ITEM_TOP; - Integer INTEGER = Frame.ITEM_INTEGER; - Integer FLOAT = Frame.ITEM_FLOAT; - Integer DOUBLE = Frame.ITEM_DOUBLE; - Integer LONG = Frame.ITEM_LONG; - Integer NULL = Frame.ITEM_NULL; - Integer UNINITIALIZED_THIS = Frame.ITEM_UNINITIALIZED_THIS; - - // The JVM opcode values (with the MethodVisitor method name used to visit them in comment, and - // where '-' means 'same method name as on the previous line'). - // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-6.html. - - int NOP = 0; // visitInsn - int ACONST_NULL = 1; // - - int ICONST_M1 = 2; // - - int ICONST_0 = 3; // - - int ICONST_1 = 4; // - - int ICONST_2 = 5; // - - int ICONST_3 = 6; // - - int ICONST_4 = 7; // - - int ICONST_5 = 8; // - - int LCONST_0 = 9; // - - int LCONST_1 = 10; // - - int FCONST_0 = 11; // - - int FCONST_1 = 12; // - - int FCONST_2 = 13; // - - int DCONST_0 = 14; // - - int DCONST_1 = 15; // - - int BIPUSH = 16; // visitIntInsn - int SIPUSH = 17; // - - int LDC = 18; // visitLdcInsn - int ILOAD = 21; // visitVarInsn - int LLOAD = 22; // - - int FLOAD = 23; // - - int DLOAD = 24; // - - int ALOAD = 25; // - - int IALOAD = 46; // visitInsn - int LALOAD = 47; // - - int FALOAD = 48; // - - int DALOAD = 49; // - - int AALOAD = 50; // - - int BALOAD = 51; // - - int CALOAD = 52; // - - int SALOAD = 53; // - - int ISTORE = 54; // visitVarInsn - int LSTORE = 55; // - - int FSTORE = 56; // - - int DSTORE = 57; // - - int ASTORE = 58; // - - int IASTORE = 79; // visitInsn - int LASTORE = 80; // - - int FASTORE = 81; // - - int DASTORE = 82; // - - int AASTORE = 83; // - - int BASTORE = 84; // - - int CASTORE = 85; // - - int SASTORE = 86; // - - int POP = 87; // - - int POP2 = 88; // - - int DUP = 89; // - - int DUP_X1 = 90; // - - int DUP_X2 = 91; // - - int DUP2 = 92; // - - int DUP2_X1 = 93; // - - int DUP2_X2 = 94; // - - int SWAP = 95; // - - int IADD = 96; // - - int LADD = 97; // - - int FADD = 98; // - - int DADD = 99; // - - int ISUB = 100; // - - int LSUB = 101; // - - int FSUB = 102; // - - int DSUB = 103; // - - int IMUL = 104; // - - int LMUL = 105; // - - int FMUL = 106; // - - int DMUL = 107; // - - int IDIV = 108; // - - int LDIV = 109; // - - int FDIV = 110; // - - int DDIV = 111; // - - int IREM = 112; // - - int LREM = 113; // - - int FREM = 114; // - - int DREM = 115; // - - int INEG = 116; // - - int LNEG = 117; // - - int FNEG = 118; // - - int DNEG = 119; // - - int ISHL = 120; // - - int LSHL = 121; // - - int ISHR = 122; // - - int LSHR = 123; // - - int IUSHR = 124; // - - int LUSHR = 125; // - - int IAND = 126; // - - int LAND = 127; // - - int IOR = 128; // - - int LOR = 129; // - - int IXOR = 130; // - - int LXOR = 131; // - - int IINC = 132; // visitIincInsn - int I2L = 133; // visitInsn - int I2F = 134; // - - int I2D = 135; // - - int L2I = 136; // - - int L2F = 137; // - - int L2D = 138; // - - int F2I = 139; // - - int F2L = 140; // - - int F2D = 141; // - - int D2I = 142; // - - int D2L = 143; // - - int D2F = 144; // - - int I2B = 145; // - - int I2C = 146; // - - int I2S = 147; // - - int LCMP = 148; // - - int FCMPL = 149; // - - int FCMPG = 150; // - - int DCMPL = 151; // - - int DCMPG = 152; // - - int IFEQ = 153; // visitJumpInsn - int IFNE = 154; // - - int IFLT = 155; // - - int IFGE = 156; // - - int IFGT = 157; // - - int IFLE = 158; // - - int IF_ICMPEQ = 159; // - - int IF_ICMPNE = 160; // - - int IF_ICMPLT = 161; // - - int IF_ICMPGE = 162; // - - int IF_ICMPGT = 163; // - - int IF_ICMPLE = 164; // - - int IF_ACMPEQ = 165; // - - int IF_ACMPNE = 166; // - - int GOTO = 167; // - - int JSR = 168; // - - int RET = 169; // visitVarInsn - int TABLESWITCH = 170; // visiTableSwitchInsn - int LOOKUPSWITCH = 171; // visitLookupSwitch - int IRETURN = 172; // visitInsn - int LRETURN = 173; // - - int FRETURN = 174; // - - int DRETURN = 175; // - - int ARETURN = 176; // - - int RETURN = 177; // - - int GETSTATIC = 178; // visitFieldInsn - int PUTSTATIC = 179; // - - int GETFIELD = 180; // - - int PUTFIELD = 181; // - - int INVOKEVIRTUAL = 182; // visitMethodInsn - int INVOKESPECIAL = 183; // - - int INVOKESTATIC = 184; // - - int INVOKEINTERFACE = 185; // - - int INVOKEDYNAMIC = 186; // visitInvokeDynamicInsn - int NEW = 187; // visitTypeInsn - int NEWARRAY = 188; // visitIntInsn - int ANEWARRAY = 189; // visitTypeInsn - int ARRAYLENGTH = 190; // visitInsn - int ATHROW = 191; // - - int CHECKCAST = 192; // visitTypeInsn - int INSTANCEOF = 193; // - - int MONITORENTER = 194; // visitInsn - int MONITOREXIT = 195; // - - int MULTIANEWARRAY = 197; // visitMultiANewArrayInsn - int IFNULL = 198; // visitJumpInsn - int IFNONNULL = 199; // - -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/Symbol.java b/jodd-proxetta/src/main/java/jodd/asm7/Symbol.java deleted file mode 100644 index 5c4aab3b7..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/Symbol.java +++ /dev/null @@ -1,243 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * An entry of the constant pool, of the BootstrapMethods attribute, or of the (ASM specific) type - * table of a class. - * - * @see JVMS - * 4.4 - * @see JVMS - * 4.7.23 - * @author Eric Bruneton - */ -abstract class Symbol { - - // Tag values for the constant pool entries (using the same order as in the JVMS). - - /** The tag value of CONSTANT_Class_info JVMS structures. */ - static final int CONSTANT_CLASS_TAG = 7; - - /** The tag value of CONSTANT_Fieldref_info JVMS structures. */ - static final int CONSTANT_FIELDREF_TAG = 9; - - /** The tag value of CONSTANT_Methodref_info JVMS structures. */ - static final int CONSTANT_METHODREF_TAG = 10; - - /** The tag value of CONSTANT_InterfaceMethodref_info JVMS structures. */ - static final int CONSTANT_INTERFACE_METHODREF_TAG = 11; - - /** The tag value of CONSTANT_String_info JVMS structures. */ - static final int CONSTANT_STRING_TAG = 8; - - /** The tag value of CONSTANT_Integer_info JVMS structures. */ - static final int CONSTANT_INTEGER_TAG = 3; - - /** The tag value of CONSTANT_Float_info JVMS structures. */ - static final int CONSTANT_FLOAT_TAG = 4; - - /** The tag value of CONSTANT_Long_info JVMS structures. */ - static final int CONSTANT_LONG_TAG = 5; - - /** The tag value of CONSTANT_Double_info JVMS structures. */ - static final int CONSTANT_DOUBLE_TAG = 6; - - /** The tag value of CONSTANT_NameAndType_info JVMS structures. */ - static final int CONSTANT_NAME_AND_TYPE_TAG = 12; - - /** The tag value of CONSTANT_Utf8_info JVMS structures. */ - static final int CONSTANT_UTF8_TAG = 1; - - /** The tag value of CONSTANT_MethodHandle_info JVMS structures. */ - static final int CONSTANT_METHOD_HANDLE_TAG = 15; - - /** The tag value of CONSTANT_MethodType_info JVMS structures. */ - static final int CONSTANT_METHOD_TYPE_TAG = 16; - - /** The tag value of CONSTANT_Dynamic_info JVMS structures. */ - static final int CONSTANT_DYNAMIC_TAG = 17; - - /** The tag value of CONSTANT_InvokeDynamic_info JVMS structures. */ - static final int CONSTANT_INVOKE_DYNAMIC_TAG = 18; - - /** The tag value of CONSTANT_Module_info JVMS structures. */ - static final int CONSTANT_MODULE_TAG = 19; - - /** The tag value of CONSTANT_Package_info JVMS structures. */ - static final int CONSTANT_PACKAGE_TAG = 20; - - // Tag values for the BootstrapMethods attribute entries (ASM specific tag). - - /** The tag value of the BootstrapMethods attribute entries. */ - static final int BOOTSTRAP_METHOD_TAG = 64; - - // Tag values for the type table entries (ASM specific tags). - - /** The tag value of a normal type entry in the (ASM specific) type table of a class. */ - static final int TYPE_TAG = 128; - - /** - * The tag value of an {@link Frame#ITEM_UNINITIALIZED} type entry in the type table of a class. - */ - static final int UNINITIALIZED_TYPE_TAG = 129; - - /** The tag value of a merged type entry in the (ASM specific) type table of a class. */ - static final int MERGED_TYPE_TAG = 130; - - // Instance fields. - - /** - * The index of this symbol in the constant pool, in the BootstrapMethods attribute, or in the - * (ASM specific) type table of a class (depending on the {@link #tag} value). - */ - final int index; - - /** - * A tag indicating the type of this symbol. Must be one of the static tag values defined in this - * class. - */ - final int tag; - - /** - * The internal name of the owner class of this symbol. Only used for {@link - * #CONSTANT_FIELDREF_TAG}, {@link #CONSTANT_METHODREF_TAG}, {@link - * #CONSTANT_INTERFACE_METHODREF_TAG}, and {@link #CONSTANT_METHOD_HANDLE_TAG} symbols. - */ - final String owner; - - /** - * The name of the class field or method corresponding to this symbol. Only used for {@link - * #CONSTANT_FIELDREF_TAG}, {@link #CONSTANT_METHODREF_TAG}, {@link - * #CONSTANT_INTERFACE_METHODREF_TAG}, {@link #CONSTANT_NAME_AND_TYPE_TAG}, {@link - * #CONSTANT_METHOD_HANDLE_TAG}, {@link #CONSTANT_DYNAMIC_TAG} and {@link - * #CONSTANT_INVOKE_DYNAMIC_TAG} symbols. - */ - final String name; - - /** - * The string value of this symbol. This is: - * - *

    - *
  • a field or method descriptor for {@link #CONSTANT_FIELDREF_TAG}, {@link - * #CONSTANT_METHODREF_TAG}, {@link #CONSTANT_INTERFACE_METHODREF_TAG}, {@link - * #CONSTANT_NAME_AND_TYPE_TAG}, {@link #CONSTANT_METHOD_HANDLE_TAG}, {@link - * #CONSTANT_METHOD_TYPE_TAG}, {@link #CONSTANT_DYNAMIC_TAG} and {@link - * #CONSTANT_INVOKE_DYNAMIC_TAG} symbols, - *
  • an arbitrary string for {@link #CONSTANT_UTF8_TAG} and {@link #CONSTANT_STRING_TAG} - * symbols, - *
  • an internal class name for {@link #CONSTANT_CLASS_TAG}, {@link #TYPE_TAG} and {@link - * #UNINITIALIZED_TYPE_TAG} symbols, - *
  • {@literal null} for the other types of symbol. - *
- */ - final String value; - - /** - * The numeric value of this symbol. This is: - * - *
    - *
  • the symbol's value for {@link #CONSTANT_INTEGER_TAG},{@link #CONSTANT_FLOAT_TAG}, {@link - * #CONSTANT_LONG_TAG}, {@link #CONSTANT_DOUBLE_TAG}, - *
  • the CONSTANT_MethodHandle_info reference_kind field value for {@link - * #CONSTANT_METHOD_HANDLE_TAG} symbols, - *
  • the CONSTANT_InvokeDynamic_info bootstrap_method_attr_index field value for {@link - * #CONSTANT_INVOKE_DYNAMIC_TAG} symbols, - *
  • the offset of a bootstrap method in the BootstrapMethods boostrap_methods array, for - * {@link #CONSTANT_DYNAMIC_TAG} or {@link #BOOTSTRAP_METHOD_TAG} symbols, - *
  • the bytecode offset of the NEW instruction that created an {@link - * Frame#ITEM_UNINITIALIZED} type for {@link #UNINITIALIZED_TYPE_TAG} symbols, - *
  • the indices (in the class' type table) of two {@link #TYPE_TAG} source types for {@link - * #MERGED_TYPE_TAG} symbols, - *
  • 0 for the other types of symbol. - *
- */ - final long data; - - /** - * Additional information about this symbol, generally computed lazily. Warning: the value of - * this field is ignored when comparing Symbol instances (to avoid duplicate entries in a - * SymbolTable). Therefore, this field should only contain data that can be computed from the - * other fields of this class. It contains: - * - *
    - *
  • the {@link Type#getArgumentsAndReturnSizes} of the symbol's method descriptor for {@link - * #CONSTANT_METHODREF_TAG}, {@link #CONSTANT_INTERFACE_METHODREF_TAG} and {@link - * #CONSTANT_INVOKE_DYNAMIC_TAG} symbols, - *
  • the index in the InnerClasses_attribute 'classes' array (plus one) corresponding to this - * class, for {@link #CONSTANT_CLASS_TAG} symbols, - *
  • the index (in the class' type table) of the merged type of the two source types for - * {@link #MERGED_TYPE_TAG} symbols, - *
  • 0 for the other types of symbol, or if this field has not been computed yet. - *
- */ - int info; - - /** - * Constructs a new Symbol. This constructor can't be used directly because the Symbol class is - * abstract. Instead, use the factory methods of the {@link SymbolTable} class. - * - * @param index the symbol index in the constant pool, in the BootstrapMethods attribute, or in - * the (ASM specific) type table of a class (depending on 'tag'). - * @param tag the symbol type. Must be one of the static tag values defined in this class. - * @param owner The internal name of the symbol's owner class. Maybe {@literal null}. - * @param name The name of the symbol's corresponding class field or method. Maybe {@literal - * null}. - * @param value The string value of this symbol. Maybe {@literal null}. - * @param data The numeric value of this symbol. - */ - Symbol( - final int index, - final int tag, - final String owner, - final String name, - final String value, - final long data) { - this.index = index; - this.tag = tag; - this.owner = owner; - this.name = name; - this.value = value; - this.data = data; - } - - /** - * Returns the result {@link Type#getArgumentsAndReturnSizes} on {@link #value}. - * - * @return the result {@link Type#getArgumentsAndReturnSizes} on {@link #value} (memoized in - * {@link #info} for efficiency). This should only be used for {@link - * #CONSTANT_METHODREF_TAG}, {@link #CONSTANT_INTERFACE_METHODREF_TAG} and {@link - * #CONSTANT_INVOKE_DYNAMIC_TAG} symbols. - */ - int getArgumentsAndReturnSizes() { - if (info == 0) { - info = Type.getArgumentsAndReturnSizes(value); - } - return info; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/SymbolTable.java b/jodd-proxetta/src/main/java/jodd/asm7/SymbolTable.java deleted file mode 100644 index 73ffdadb6..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/SymbolTable.java +++ /dev/null @@ -1,1320 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -/** - * The constant pool entries, the BootstrapMethods attribute entries and the (ASM specific) type - * table entries of a class. - * - * @see JVMS - * 4.4 - * @see JVMS - * 4.7.23 - * @author Eric Bruneton - */ -final class SymbolTable { - - /** - * The ClassWriter to which this SymbolTable belongs. This is only used to get access to {@link - * ClassWriter#getCommonSuperClass} and to serialize custom attributes with {@link - * Attribute#write}. - */ - final ClassWriter classWriter; - - /** - * The ClassReader from which this SymbolTable was constructed, or {@literal null} if it was - * constructed from scratch. - */ - private final ClassReader sourceClassReader; - - /** The major version number of the class to which this symbol table belongs. */ - private int majorVersion; - - /** The internal name of the class to which this symbol table belongs. */ - private String className; - - /** - * The total number of {@link Entry} instances in {@link #entries}. This includes entries that are - * accessible (recursively) via {@link Entry#next}. - */ - private int entryCount; - - /** - * A hash set of all the entries in this SymbolTable (this includes the constant pool entries, the - * bootstrap method entries and the type table entries). Each {@link Entry} instance is stored at - * the array index given by its hash code modulo the array size. If several entries must be stored - * at the same array index, they are linked together via their {@link Entry#next} field. The - * factory methods of this class make sure that this table does not contain duplicated entries. - */ - private Entry[] entries; - - /** - * The number of constant pool items in {@link #constantPool}, plus 1. The first constant pool - * item has index 1, and long and double items count for two items. - */ - private int constantPoolCount; - - /** - * The content of the ClassFile's constant_pool JVMS structure corresponding to this SymbolTable. - * The ClassFile's constant_pool_count field is not included. - */ - private ByteVector constantPool; - - /** - * The number of bootstrap methods in {@link #bootstrapMethods}. Corresponds to the - * BootstrapMethods_attribute's num_bootstrap_methods field value. - */ - private int bootstrapMethodCount; - - /** - * The content of the BootstrapMethods attribute 'bootstrap_methods' array corresponding to this - * SymbolTable. Note that the first 6 bytes of the BootstrapMethods_attribute, and its - * num_bootstrap_methods field, are not included. - */ - private ByteVector bootstrapMethods; - - /** - * The actual number of elements in {@link #typeTable}. These elements are stored from index 0 to - * typeCount (excluded). The other array entries are empty. - */ - private int typeCount; - - /** - * An ASM specific type table used to temporarily store internal names that will not necessarily - * be stored in the constant pool. This type table is used by the control flow and data flow - * analysis algorithm used to compute stack map frames from scratch. This array stores {@link - * Symbol#TYPE_TAG} and {@link Symbol#UNINITIALIZED_TYPE_TAG}) Symbol. The type symbol at index - * {@code i} has its {@link Symbol#index} equal to {@code i} (and vice versa). - */ - private Entry[] typeTable; - - /** - * Constructs a new, empty SymbolTable for the given ClassWriter. - * - * @param classWriter a ClassWriter. - */ - SymbolTable(final ClassWriter classWriter) { - this.classWriter = classWriter; - this.sourceClassReader = null; - this.entries = new Entry[256]; - this.constantPoolCount = 1; - this.constantPool = new ByteVector(); - } - - /** - * Constructs a new SymbolTable for the given ClassWriter, initialized with the constant pool and - * bootstrap methods of the given ClassReader. - * - * @param classWriter a ClassWriter. - * @param classReader the ClassReader whose constant pool and bootstrap methods must be copied to - * initialize the SymbolTable. - */ - SymbolTable(final ClassWriter classWriter, final ClassReader classReader) { - this.classWriter = classWriter; - this.sourceClassReader = classReader; - - // Copy the constant pool binary content. - byte[] inputBytes = classReader.classFileBuffer; - int constantPoolOffset = classReader.getItem(1) - 1; - int constantPoolLength = classReader.header - constantPoolOffset; - constantPoolCount = classReader.getItemCount(); - constantPool = new ByteVector(constantPoolLength); - constantPool.putByteArray(inputBytes, constantPoolOffset, constantPoolLength); - - // Add the constant pool items in the symbol table entries. Reserve enough space in 'entries' to - // avoid too many hash set collisions (entries is not dynamically resized by the addConstant* - // method calls below), and to account for bootstrap method entries. - entries = new Entry[constantPoolCount * 2]; - char[] charBuffer = new char[classReader.getMaxStringLength()]; - boolean hasBootstrapMethods = false; - int itemIndex = 1; - while (itemIndex < constantPoolCount) { - int itemOffset = classReader.getItem(itemIndex); - int itemTag = inputBytes[itemOffset - 1]; - int nameAndTypeItemOffset; - switch (itemTag) { - case Symbol.CONSTANT_FIELDREF_TAG: - case Symbol.CONSTANT_METHODREF_TAG: - case Symbol.CONSTANT_INTERFACE_METHODREF_TAG: - nameAndTypeItemOffset = - classReader.getItem(classReader.readUnsignedShort(itemOffset + 2)); - addConstantMemberReference( - itemIndex, - itemTag, - classReader.readClass(itemOffset, charBuffer), - classReader.readUTF8(nameAndTypeItemOffset, charBuffer), - classReader.readUTF8(nameAndTypeItemOffset + 2, charBuffer)); - break; - case Symbol.CONSTANT_INTEGER_TAG: - case Symbol.CONSTANT_FLOAT_TAG: - addConstantIntegerOrFloat(itemIndex, itemTag, classReader.readInt(itemOffset)); - break; - case Symbol.CONSTANT_NAME_AND_TYPE_TAG: - addConstantNameAndType( - itemIndex, - classReader.readUTF8(itemOffset, charBuffer), - classReader.readUTF8(itemOffset + 2, charBuffer)); - break; - case Symbol.CONSTANT_LONG_TAG: - case Symbol.CONSTANT_DOUBLE_TAG: - addConstantLongOrDouble(itemIndex, itemTag, classReader.readLong(itemOffset)); - break; - case Symbol.CONSTANT_UTF8_TAG: - addConstantUtf8(itemIndex, classReader.readUtf(itemIndex, charBuffer)); - break; - case Symbol.CONSTANT_METHOD_HANDLE_TAG: - int memberRefItemOffset = - classReader.getItem(classReader.readUnsignedShort(itemOffset + 1)); - nameAndTypeItemOffset = - classReader.getItem(classReader.readUnsignedShort(memberRefItemOffset + 2)); - addConstantMethodHandle( - itemIndex, - classReader.readByte(itemOffset), - classReader.readClass(memberRefItemOffset, charBuffer), - classReader.readUTF8(nameAndTypeItemOffset, charBuffer), - classReader.readUTF8(nameAndTypeItemOffset + 2, charBuffer)); - break; - case Symbol.CONSTANT_DYNAMIC_TAG: - case Symbol.CONSTANT_INVOKE_DYNAMIC_TAG: - hasBootstrapMethods = true; - nameAndTypeItemOffset = - classReader.getItem(classReader.readUnsignedShort(itemOffset + 2)); - addConstantDynamicOrInvokeDynamicReference( - itemTag, - itemIndex, - classReader.readUTF8(nameAndTypeItemOffset, charBuffer), - classReader.readUTF8(nameAndTypeItemOffset + 2, charBuffer), - classReader.readUnsignedShort(itemOffset)); - break; - case Symbol.CONSTANT_STRING_TAG: - case Symbol.CONSTANT_CLASS_TAG: - case Symbol.CONSTANT_METHOD_TYPE_TAG: - case Symbol.CONSTANT_MODULE_TAG: - case Symbol.CONSTANT_PACKAGE_TAG: - addConstantUtf8Reference( - itemIndex, itemTag, classReader.readUTF8(itemOffset, charBuffer)); - break; - default: - throw new IllegalArgumentException(); - } - itemIndex += - (itemTag == Symbol.CONSTANT_LONG_TAG || itemTag == Symbol.CONSTANT_DOUBLE_TAG) ? 2 : 1; - } - - // Copy the BootstrapMethods, if any. - if (hasBootstrapMethods) { - copyBootstrapMethods(classReader, charBuffer); - } - } - - /** - * Read the BootstrapMethods 'bootstrap_methods' array binary content and add them as entries of - * the SymbolTable. - * - * @param classReader the ClassReader whose bootstrap methods must be copied to initialize the - * SymbolTable. - * @param charBuffer a buffer used to read strings in the constant pool. - */ - private void copyBootstrapMethods(final ClassReader classReader, final char[] charBuffer) { - // Find attributOffset of the 'bootstrap_methods' array. - byte[] inputBytes = classReader.classFileBuffer; - int currentAttributeOffset = classReader.getFirstAttributeOffset(); - for (int i = classReader.readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) { - String attributeName = classReader.readUTF8(currentAttributeOffset, charBuffer); - if (Constants.BOOTSTRAP_METHODS.equals(attributeName)) { - bootstrapMethodCount = classReader.readUnsignedShort(currentAttributeOffset + 6); - break; - } - currentAttributeOffset += 6 + classReader.readInt(currentAttributeOffset + 2); - } - if (bootstrapMethodCount > 0) { - // Compute the offset and the length of the BootstrapMethods 'bootstrap_methods' array. - int bootstrapMethodsOffset = currentAttributeOffset + 8; - int bootstrapMethodsLength = classReader.readInt(currentAttributeOffset + 2) - 2; - bootstrapMethods = new ByteVector(bootstrapMethodsLength); - bootstrapMethods.putByteArray(inputBytes, bootstrapMethodsOffset, bootstrapMethodsLength); - - // Add each bootstrap method in the symbol table entries. - int currentOffset = bootstrapMethodsOffset; - for (int i = 0; i < bootstrapMethodCount; i++) { - int offset = currentOffset - bootstrapMethodsOffset; - int bootstrapMethodRef = classReader.readUnsignedShort(currentOffset); - currentOffset += 2; - int numBootstrapArguments = classReader.readUnsignedShort(currentOffset); - currentOffset += 2; - int hashCode = classReader.readConst(bootstrapMethodRef, charBuffer).hashCode(); - while (numBootstrapArguments-- > 0) { - int bootstrapArgument = classReader.readUnsignedShort(currentOffset); - currentOffset += 2; - hashCode ^= classReader.readConst(bootstrapArgument, charBuffer).hashCode(); - } - add(new Entry(i, Symbol.BOOTSTRAP_METHOD_TAG, offset, hashCode & 0x7FFFFFFF)); - } - } - } - - /** - * Returns the ClassReader from which this SymbolTable was constructed. - * - * @return the ClassReader from which this SymbolTable was constructed, or {@literal null} if it - * was constructed from scratch. - */ - ClassReader getSource() { - return sourceClassReader; - } - - /** - * Returns the major version of the class to which this symbol table belongs. - * - * @return the major version of the class to which this symbol table belongs. - */ - int getMajorVersion() { - return majorVersion; - } - - /** - * Returns the internal name of the class to which this symbol table belongs. - * - * @return the internal name of the class to which this symbol table belongs. - */ - String getClassName() { - return className; - } - - /** - * Sets the major version and the name of the class to which this symbol table belongs. Also adds - * the class name to the constant pool. - * - * @param majorVersion a major ClassFile version number. - * @param className an internal class name. - * @return the constant pool index of a new or already existing Symbol with the given class name. - */ - int setMajorVersionAndClassName(final int majorVersion, final String className) { - this.majorVersion = majorVersion; - this.className = className; - return addConstantClass(className).index; - } - - /** - * Returns the number of items in this symbol table's constant_pool array (plus 1). - * - * @return the number of items in this symbol table's constant_pool array (plus 1). - */ - int getConstantPoolCount() { - return constantPoolCount; - } - - /** - * Returns the length in bytes of this symbol table's constant_pool array. - * - * @return the length in bytes of this symbol table's constant_pool array. - */ - int getConstantPoolLength() { - return constantPool.length; - } - - /** - * Puts this symbol table's constant_pool array in the given ByteVector, preceded by the - * constant_pool_count value. - * - * @param output where the JVMS ClassFile's constant_pool array must be put. - */ - void putConstantPool(final ByteVector output) { - output.putShort(constantPoolCount).putByteArray(constantPool.data, 0, constantPool.length); - } - - /** - * Returns the size in bytes of this symbol table's BootstrapMethods attribute. Also adds the - * attribute name in the constant pool. - * - * @return the size in bytes of this symbol table's BootstrapMethods attribute. - */ - int computeBootstrapMethodsSize() { - if (bootstrapMethods != null) { - addConstantUtf8(Constants.BOOTSTRAP_METHODS); - return 8 + bootstrapMethods.length; - } else { - return 0; - } - } - - /** - * Puts this symbol table's BootstrapMethods attribute in the given ByteVector. This includes the - * 6 attribute header bytes and the num_bootstrap_methods value. - * - * @param output where the JVMS BootstrapMethods attribute must be put. - */ - void putBootstrapMethods(final ByteVector output) { - if (bootstrapMethods != null) { - output - .putShort(addConstantUtf8(Constants.BOOTSTRAP_METHODS)) - .putInt(bootstrapMethods.length + 2) - .putShort(bootstrapMethodCount) - .putByteArray(bootstrapMethods.data, 0, bootstrapMethods.length); - } - } - - // ----------------------------------------------------------------------------------------------- - // Generic symbol table entries management. - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the list of entries which can potentially have the given hash code. - * - * @param hashCode a {@link Entry#hashCode} value. - * @return the list of entries which can potentially have the given hash code. The list is stored - * via the {@link Entry#next} field. - */ - private Entry get(final int hashCode) { - return entries[hashCode % entries.length]; - } - - /** - * Puts the given entry in the {@link #entries} hash set. This method does not check - * whether {@link #entries} already contains a similar entry or not. {@link #entries} is resized - * if necessary to avoid hash collisions (multiple entries needing to be stored at the same {@link - * #entries} array index) as much as possible, with reasonable memory usage. - * - * @param entry an Entry (which must not already be contained in {@link #entries}). - * @return the given entry - */ - private Entry put(final Entry entry) { - if (entryCount > (entries.length * 3) / 4) { - int currentCapacity = entries.length; - int newCapacity = currentCapacity * 2 + 1; - Entry[] newEntries = new Entry[newCapacity]; - for (int i = currentCapacity - 1; i >= 0; --i) { - Entry currentEntry = entries[i]; - while (currentEntry != null) { - int newCurrentEntryIndex = currentEntry.hashCode % newCapacity; - Entry nextEntry = currentEntry.next; - currentEntry.next = newEntries[newCurrentEntryIndex]; - newEntries[newCurrentEntryIndex] = currentEntry; - currentEntry = nextEntry; - } - } - entries = newEntries; - } - entryCount++; - int index = entry.hashCode % entries.length; - entry.next = entries[index]; - return entries[index] = entry; - } - - /** - * Adds the given entry in the {@link #entries} hash set. This method does not check - * whether {@link #entries} already contains a similar entry or not, and does not resize - * {@link #entries} if necessary. - * - * @param entry an Entry (which must not already be contained in {@link #entries}). - */ - private void add(final Entry entry) { - entryCount++; - int index = entry.hashCode % entries.length; - entry.next = entries[index]; - entries[index] = entry; - } - - // ----------------------------------------------------------------------------------------------- - // Constant pool entries management. - // ----------------------------------------------------------------------------------------------- - - /** - * Adds a number or string constant to the constant pool of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param value the value of the constant to be added to the constant pool. This parameter must be - * an {@link Integer}, {@link Byte}, {@link Character}, {@link Short}, {@link Boolean}, {@link - * Float}, {@link Long}, {@link Double}, {@link String}, {@link Type} or {@link Handle}. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstant(final Object value) { - if (value instanceof Integer) { - return addConstantInteger(((Integer) value).intValue()); - } else if (value instanceof Byte) { - return addConstantInteger(((Byte) value).intValue()); - } else if (value instanceof Character) { - return addConstantInteger(((Character) value).charValue()); - } else if (value instanceof Short) { - return addConstantInteger(((Short) value).intValue()); - } else if (value instanceof Boolean) { - return addConstantInteger(((Boolean) value).booleanValue() ? 1 : 0); - } else if (value instanceof Float) { - return addConstantFloat(((Float) value).floatValue()); - } else if (value instanceof Long) { - return addConstantLong(((Long) value).longValue()); - } else if (value instanceof Double) { - return addConstantDouble(((Double) value).doubleValue()); - } else if (value instanceof String) { - return addConstantString((String) value); - } else if (value instanceof Type) { - Type type = (Type) value; - int typeSort = type.getSort(); - if (typeSort == Type.OBJECT) { - return addConstantClass(type.getInternalName()); - } else if (typeSort == Type.METHOD) { - return addConstantMethodType(type.getDescriptor()); - } else { // type is a primitive or array type. - return addConstantClass(type.getDescriptor()); - } - } else if (value instanceof Handle) { - Handle handle = (Handle) value; - return addConstantMethodHandle( - handle.getTag(), - handle.getOwner(), - handle.getName(), - handle.getDesc(), - handle.isInterface()); - } else if (value instanceof ConstantDynamic) { - ConstantDynamic constantDynamic = (ConstantDynamic) value; - return addConstantDynamic( - constantDynamic.getName(), - constantDynamic.getDescriptor(), - constantDynamic.getBootstrapMethod(), - constantDynamic.getBootstrapMethodArgumentsUnsafe()); - } else { - throw new IllegalArgumentException("value " + value); - } - } - - /** - * Adds a CONSTANT_Class_info to the constant pool of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param value the internal name of a class. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantClass(final String value) { - return addConstantUtf8Reference(Symbol.CONSTANT_CLASS_TAG, value); - } - - /** - * Adds a CONSTANT_Fieldref_info to the constant pool of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param owner the internal name of a class. - * @param name a field name. - * @param descriptor a field descriptor. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantFieldref(final String owner, final String name, final String descriptor) { - return addConstantMemberReference(Symbol.CONSTANT_FIELDREF_TAG, owner, name, descriptor); - } - - /** - * Adds a CONSTANT_Methodref_info or CONSTANT_InterfaceMethodref_info to the constant pool of this - * symbol table. Does nothing if the constant pool already contains a similar item. - * - * @param owner the internal name of a class. - * @param name a method name. - * @param descriptor a method descriptor. - * @param isInterface whether owner is an interface or not. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantMethodref( - final String owner, final String name, final String descriptor, final boolean isInterface) { - int tag = isInterface ? Symbol.CONSTANT_INTERFACE_METHODREF_TAG : Symbol.CONSTANT_METHODREF_TAG; - return addConstantMemberReference(tag, owner, name, descriptor); - } - - /** - * Adds a CONSTANT_Fieldref_info, CONSTANT_Methodref_info or CONSTANT_InterfaceMethodref_info to - * the constant pool of this symbol table. Does nothing if the constant pool already contains a - * similar item. - * - * @param tag one of {@link Symbol#CONSTANT_FIELDREF_TAG}, {@link Symbol#CONSTANT_METHODREF_TAG} - * or {@link Symbol#CONSTANT_INTERFACE_METHODREF_TAG}. - * @param owner the internal name of a class. - * @param name a field or method name. - * @param descriptor a field or method descriptor. - * @return a new or already existing Symbol with the given value. - */ - private Entry addConstantMemberReference( - final int tag, final String owner, final String name, final String descriptor) { - int hashCode = hash(tag, owner, name, descriptor); - Entry entry = get(hashCode); - while (entry != null) { - if (entry.tag == tag - && entry.hashCode == hashCode - && entry.owner.equals(owner) - && entry.name.equals(name) - && entry.value.equals(descriptor)) { - return entry; - } - entry = entry.next; - } - constantPool.put122( - tag, addConstantClass(owner).index, addConstantNameAndType(name, descriptor)); - return put(new Entry(constantPoolCount++, tag, owner, name, descriptor, 0, hashCode)); - } - - /** - * Adds a new CONSTANT_Fieldref_info, CONSTANT_Methodref_info or CONSTANT_InterfaceMethodref_info - * to the constant pool of this symbol table. - * - * @param index the constant pool index of the new Symbol. - * @param tag one of {@link Symbol#CONSTANT_FIELDREF_TAG}, {@link Symbol#CONSTANT_METHODREF_TAG} - * or {@link Symbol#CONSTANT_INTERFACE_METHODREF_TAG}. - * @param owner the internal name of a class. - * @param name a field or method name. - * @param descriptor a field or method descriptor. - */ - private void addConstantMemberReference( - final int index, - final int tag, - final String owner, - final String name, - final String descriptor) { - add(new Entry(index, tag, owner, name, descriptor, 0, hash(tag, owner, name, descriptor))); - } - - /** - * Adds a CONSTANT_String_info to the constant pool of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param value a string. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantString(final String value) { - return addConstantUtf8Reference(Symbol.CONSTANT_STRING_TAG, value); - } - - /** - * Adds a CONSTANT_Integer_info to the constant pool of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param value an int. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantInteger(final int value) { - return addConstantIntegerOrFloat(Symbol.CONSTANT_INTEGER_TAG, value); - } - - /** - * Adds a CONSTANT_Float_info to the constant pool of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param value a float. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantFloat(final float value) { - return addConstantIntegerOrFloat(Symbol.CONSTANT_FLOAT_TAG, Float.floatToRawIntBits(value)); - } - - /** - * Adds a CONSTANT_Integer_info or CONSTANT_Float_info to the constant pool of this symbol table. - * Does nothing if the constant pool already contains a similar item. - * - * @param tag one of {@link Symbol#CONSTANT_INTEGER_TAG} or {@link Symbol#CONSTANT_FLOAT_TAG}. - * @param value an int or float. - * @return a constant pool constant with the given tag and primitive values. - */ - private Symbol addConstantIntegerOrFloat(final int tag, final int value) { - int hashCode = hash(tag, value); - Entry entry = get(hashCode); - while (entry != null) { - if (entry.tag == tag && entry.hashCode == hashCode && entry.data == value) { - return entry; - } - entry = entry.next; - } - constantPool.putByte(tag).putInt(value); - return put(new Entry(constantPoolCount++, tag, value, hashCode)); - } - - /** - * Adds a new CONSTANT_Integer_info or CONSTANT_Float_info to the constant pool of this symbol - * table. - * - * @param index the constant pool index of the new Symbol. - * @param tag one of {@link Symbol#CONSTANT_INTEGER_TAG} or {@link Symbol#CONSTANT_FLOAT_TAG}. - * @param value an int or float. - */ - private void addConstantIntegerOrFloat(final int index, final int tag, final int value) { - add(new Entry(index, tag, value, hash(tag, value))); - } - - /** - * Adds a CONSTANT_Long_info to the constant pool of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param value a long. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantLong(final long value) { - return addConstantLongOrDouble(Symbol.CONSTANT_LONG_TAG, value); - } - - /** - * Adds a CONSTANT_Double_info to the constant pool of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param value a double. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantDouble(final double value) { - return addConstantLongOrDouble(Symbol.CONSTANT_DOUBLE_TAG, Double.doubleToRawLongBits(value)); - } - - /** - * Adds a CONSTANT_Long_info or CONSTANT_Double_info to the constant pool of this symbol table. - * Does nothing if the constant pool already contains a similar item. - * - * @param tag one of {@link Symbol#CONSTANT_LONG_TAG} or {@link Symbol#CONSTANT_DOUBLE_TAG}. - * @param value a long or double. - * @return a constant pool constant with the given tag and primitive values. - */ - private Symbol addConstantLongOrDouble(final int tag, final long value) { - int hashCode = hash(tag, value); - Entry entry = get(hashCode); - while (entry != null) { - if (entry.tag == tag && entry.hashCode == hashCode && entry.data == value) { - return entry; - } - entry = entry.next; - } - int index = constantPoolCount; - constantPool.putByte(tag).putLong(value); - constantPoolCount += 2; - return put(new Entry(index, tag, value, hashCode)); - } - - /** - * Adds a new CONSTANT_Long_info or CONSTANT_Double_info to the constant pool of this symbol - * table. - * - * @param index the constant pool index of the new Symbol. - * @param tag one of {@link Symbol#CONSTANT_LONG_TAG} or {@link Symbol#CONSTANT_DOUBLE_TAG}. - * @param value a long or double. - */ - private void addConstantLongOrDouble(final int index, final int tag, final long value) { - add(new Entry(index, tag, value, hash(tag, value))); - } - - /** - * Adds a CONSTANT_NameAndType_info to the constant pool of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param name a field or method name. - * @param descriptor a field or method descriptor. - * @return a new or already existing Symbol with the given value. - */ - int addConstantNameAndType(final String name, final String descriptor) { - final int tag = Symbol.CONSTANT_NAME_AND_TYPE_TAG; - int hashCode = hash(tag, name, descriptor); - Entry entry = get(hashCode); - while (entry != null) { - if (entry.tag == tag - && entry.hashCode == hashCode - && entry.name.equals(name) - && entry.value.equals(descriptor)) { - return entry.index; - } - entry = entry.next; - } - constantPool.put122(tag, addConstantUtf8(name), addConstantUtf8(descriptor)); - return put(new Entry(constantPoolCount++, tag, name, descriptor, hashCode)).index; - } - - /** - * Adds a new CONSTANT_NameAndType_info to the constant pool of this symbol table. - * - * @param index the constant pool index of the new Symbol. - * @param name a field or method name. - * @param descriptor a field or method descriptor. - */ - private void addConstantNameAndType(final int index, final String name, final String descriptor) { - final int tag = Symbol.CONSTANT_NAME_AND_TYPE_TAG; - add(new Entry(index, tag, name, descriptor, hash(tag, name, descriptor))); - } - - /** - * Adds a CONSTANT_Utf8_info to the constant pool of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param value a string. - * @return a new or already existing Symbol with the given value. - */ - int addConstantUtf8(final String value) { - int hashCode = hash(Symbol.CONSTANT_UTF8_TAG, value); - Entry entry = get(hashCode); - while (entry != null) { - if (entry.tag == Symbol.CONSTANT_UTF8_TAG - && entry.hashCode == hashCode - && entry.value.equals(value)) { - return entry.index; - } - entry = entry.next; - } - constantPool.putByte(Symbol.CONSTANT_UTF8_TAG).putUTF8(value); - return put(new Entry(constantPoolCount++, Symbol.CONSTANT_UTF8_TAG, value, hashCode)).index; - } - - /** - * Adds a new CONSTANT_String_info to the constant pool of this symbol table. - * - * @param index the constant pool index of the new Symbol. - * @param value a string. - */ - private void addConstantUtf8(final int index, final String value) { - add(new Entry(index, Symbol.CONSTANT_UTF8_TAG, value, hash(Symbol.CONSTANT_UTF8_TAG, value))); - } - - /** - * Adds a CONSTANT_MethodHandle_info to the constant pool of this symbol table. Does nothing if - * the constant pool already contains a similar item. - * - * @param referenceKind one of {@link Opcodes#H_GETFIELD}, {@link Opcodes#H_GETSTATIC}, {@link - * Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL}, {@link - * Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, {@link - * Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}. - * @param owner the internal name of a class of interface. - * @param name a field or method name. - * @param descriptor a field or method descriptor. - * @param isInterface whether owner is an interface or not. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantMethodHandle( - final int referenceKind, - final String owner, - final String name, - final String descriptor, - final boolean isInterface) { - final int tag = Symbol.CONSTANT_METHOD_HANDLE_TAG; - // Note that we don't need to include isInterface in the hash computation, because it is - // redundant with owner (we can't have the same owner with different isInterface values). - int hashCode = hash(tag, owner, name, descriptor, referenceKind); - Entry entry = get(hashCode); - while (entry != null) { - if (entry.tag == tag - && entry.hashCode == hashCode - && entry.data == referenceKind - && entry.owner.equals(owner) - && entry.name.equals(name) - && entry.value.equals(descriptor)) { - return entry; - } - entry = entry.next; - } - if (referenceKind <= Opcodes.H_PUTSTATIC) { - constantPool.put112(tag, referenceKind, addConstantFieldref(owner, name, descriptor).index); - } else { - constantPool.put112( - tag, referenceKind, addConstantMethodref(owner, name, descriptor, isInterface).index); - } - return put( - new Entry(constantPoolCount++, tag, owner, name, descriptor, referenceKind, hashCode)); - } - - /** - * Adds a new CONSTANT_MethodHandle_info to the constant pool of this symbol table. - * - * @param index the constant pool index of the new Symbol. - * @param referenceKind one of {@link Opcodes#H_GETFIELD}, {@link Opcodes#H_GETSTATIC}, {@link - * Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL}, {@link - * Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, {@link - * Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}. - * @param owner the internal name of a class of interface. - * @param name a field or method name. - * @param descriptor a field or method descriptor. - */ - private void addConstantMethodHandle( - final int index, - final int referenceKind, - final String owner, - final String name, - final String descriptor) { - final int tag = Symbol.CONSTANT_METHOD_HANDLE_TAG; - int hashCode = hash(tag, owner, name, descriptor, referenceKind); - add(new Entry(index, tag, owner, name, descriptor, referenceKind, hashCode)); - } - - /** - * Adds a CONSTANT_MethodType_info to the constant pool of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param methodDescriptor a method descriptor. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantMethodType(final String methodDescriptor) { - return addConstantUtf8Reference(Symbol.CONSTANT_METHOD_TYPE_TAG, methodDescriptor); - } - - /** - * Adds a CONSTANT_Dynamic_info to the constant pool of this symbol table. Also adds the related - * bootstrap method to the BootstrapMethods of this symbol table. Does nothing if the constant - * pool already contains a similar item. - * - * @param name a method name. - * @param descriptor a field descriptor. - * @param bootstrapMethodHandle a bootstrap method handle. - * @param bootstrapMethodArguments the bootstrap method arguments. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantDynamic( - final String name, - final String descriptor, - final Handle bootstrapMethodHandle, - final Object... bootstrapMethodArguments) { - Symbol bootstrapMethod = addBootstrapMethod(bootstrapMethodHandle, bootstrapMethodArguments); - return addConstantDynamicOrInvokeDynamicReference( - Symbol.CONSTANT_DYNAMIC_TAG, name, descriptor, bootstrapMethod.index); - } - - /** - * Adds a CONSTANT_InvokeDynamic_info to the constant pool of this symbol table. Also adds the - * related bootstrap method to the BootstrapMethods of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param name a method name. - * @param descriptor a method descriptor. - * @param bootstrapMethodHandle a bootstrap method handle. - * @param bootstrapMethodArguments the bootstrap method arguments. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantInvokeDynamic( - final String name, - final String descriptor, - final Handle bootstrapMethodHandle, - final Object... bootstrapMethodArguments) { - Symbol bootstrapMethod = addBootstrapMethod(bootstrapMethodHandle, bootstrapMethodArguments); - return addConstantDynamicOrInvokeDynamicReference( - Symbol.CONSTANT_INVOKE_DYNAMIC_TAG, name, descriptor, bootstrapMethod.index); - } - - /** - * Adds a CONSTANT_Dynamic or a CONSTANT_InvokeDynamic_info to the constant pool of this symbol - * table. Does nothing if the constant pool already contains a similar item. - * - * @param tag one of {@link Symbol#CONSTANT_DYNAMIC_TAG} or {@link - * Symbol#CONSTANT_INVOKE_DYNAMIC_TAG}. - * @param name a method name. - * @param descriptor a field descriptor for CONSTANT_DYNAMIC_TAG) or a method descriptor for - * CONSTANT_INVOKE_DYNAMIC_TAG. - * @param bootstrapMethodIndex the index of a bootstrap method in the BootstrapMethods attribute. - * @return a new or already existing Symbol with the given value. - */ - private Symbol addConstantDynamicOrInvokeDynamicReference( - final int tag, final String name, final String descriptor, final int bootstrapMethodIndex) { - int hashCode = hash(tag, name, descriptor, bootstrapMethodIndex); - Entry entry = get(hashCode); - while (entry != null) { - if (entry.tag == tag - && entry.hashCode == hashCode - && entry.data == bootstrapMethodIndex - && entry.name.equals(name) - && entry.value.equals(descriptor)) { - return entry; - } - entry = entry.next; - } - constantPool.put122(tag, bootstrapMethodIndex, addConstantNameAndType(name, descriptor)); - return put( - new Entry( - constantPoolCount++, tag, null, name, descriptor, bootstrapMethodIndex, hashCode)); - } - - /** - * Adds a new CONSTANT_Dynamic_info or CONSTANT_InvokeDynamic_info to the constant pool of this - * symbol table. - * - * @param tag one of {@link Symbol#CONSTANT_DYNAMIC_TAG} or {@link - * Symbol#CONSTANT_INVOKE_DYNAMIC_TAG}. - * @param index the constant pool index of the new Symbol. - * @param name a method name. - * @param descriptor a field descriptor for CONSTANT_DYNAMIC_TAG or a method descriptor for - * CONSTANT_INVOKE_DYNAMIC_TAG. - * @param bootstrapMethodIndex the index of a bootstrap method in the BootstrapMethods attribute. - */ - private void addConstantDynamicOrInvokeDynamicReference( - final int tag, - final int index, - final String name, - final String descriptor, - final int bootstrapMethodIndex) { - int hashCode = hash(tag, name, descriptor, bootstrapMethodIndex); - add(new Entry(index, tag, null, name, descriptor, bootstrapMethodIndex, hashCode)); - } - - /** - * Adds a CONSTANT_Module_info to the constant pool of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param moduleName a fully qualified name (using dots) of a module. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantModule(final String moduleName) { - return addConstantUtf8Reference(Symbol.CONSTANT_MODULE_TAG, moduleName); - } - - /** - * Adds a CONSTANT_Package_info to the constant pool of this symbol table. Does nothing if the - * constant pool already contains a similar item. - * - * @param packageName the internal name of a package. - * @return a new or already existing Symbol with the given value. - */ - Symbol addConstantPackage(final String packageName) { - return addConstantUtf8Reference(Symbol.CONSTANT_PACKAGE_TAG, packageName); - } - - /** - * Adds a CONSTANT_Class_info, CONSTANT_String_info, CONSTANT_MethodType_info, - * CONSTANT_Module_info or CONSTANT_Package_info to the constant pool of this symbol table. Does - * nothing if the constant pool already contains a similar item. - * - * @param tag one of {@link Symbol#CONSTANT_CLASS_TAG}, {@link Symbol#CONSTANT_STRING_TAG}, {@link - * Symbol#CONSTANT_METHOD_TYPE_TAG}, {@link Symbol#CONSTANT_MODULE_TAG} or {@link - * Symbol#CONSTANT_PACKAGE_TAG}. - * @param value an internal class name, an arbitrary string, a method descriptor, a module or a - * package name, depending on tag. - * @return a new or already existing Symbol with the given value. - */ - private Symbol addConstantUtf8Reference(final int tag, final String value) { - int hashCode = hash(tag, value); - Entry entry = get(hashCode); - while (entry != null) { - if (entry.tag == tag && entry.hashCode == hashCode && entry.value.equals(value)) { - return entry; - } - entry = entry.next; - } - constantPool.put12(tag, addConstantUtf8(value)); - return put(new Entry(constantPoolCount++, tag, value, hashCode)); - } - - /** - * Adds a new CONSTANT_Class_info, CONSTANT_String_info, CONSTANT_MethodType_info, - * CONSTANT_Module_info or CONSTANT_Package_info to the constant pool of this symbol table. - * - * @param index the constant pool index of the new Symbol. - * @param tag one of {@link Symbol#CONSTANT_CLASS_TAG}, {@link Symbol#CONSTANT_STRING_TAG}, {@link - * Symbol#CONSTANT_METHOD_TYPE_TAG}, {@link Symbol#CONSTANT_MODULE_TAG} or {@link - * Symbol#CONSTANT_PACKAGE_TAG}. - * @param value an internal class name, an arbitrary string, a method descriptor, a module or a - * package name, depending on tag. - */ - private void addConstantUtf8Reference(final int index, final int tag, final String value) { - add(new Entry(index, tag, value, hash(tag, value))); - } - - // ----------------------------------------------------------------------------------------------- - // Bootstrap method entries management. - // ----------------------------------------------------------------------------------------------- - - /** - * Adds a bootstrap method to the BootstrapMethods attribute of this symbol table. Does nothing if - * the BootstrapMethods already contains a similar bootstrap method. - * - * @param bootstrapMethodHandle a bootstrap method handle. - * @param bootstrapMethodArguments the bootstrap method arguments. - * @return a new or already existing Symbol with the given value. - */ - Symbol addBootstrapMethod( - final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) { - ByteVector bootstrapMethodsAttribute = bootstrapMethods; - if (bootstrapMethodsAttribute == null) { - bootstrapMethodsAttribute = bootstrapMethods = new ByteVector(); - } - - // The bootstrap method arguments can be Constant_Dynamic values, which reference other - // bootstrap methods. We must therefore add the bootstrap method arguments to the constant pool - // and BootstrapMethods attribute first, so that the BootstrapMethods attribute is not modified - // while adding the given bootstrap method to it, in the rest of this method. - for (Object bootstrapMethodArgument : bootstrapMethodArguments) { - addConstant(bootstrapMethodArgument); - } - - // Write the bootstrap method in the BootstrapMethods table. This is necessary to be able to - // compare it with existing ones, and will be reverted below if there is already a similar - // bootstrap method. - int bootstrapMethodOffset = bootstrapMethodsAttribute.length; - bootstrapMethodsAttribute.putShort( - addConstantMethodHandle( - bootstrapMethodHandle.getTag(), - bootstrapMethodHandle.getOwner(), - bootstrapMethodHandle.getName(), - bootstrapMethodHandle.getDesc(), - bootstrapMethodHandle.isInterface()) - .index); - int numBootstrapArguments = bootstrapMethodArguments.length; - bootstrapMethodsAttribute.putShort(numBootstrapArguments); - for (Object bootstrapMethodArgument : bootstrapMethodArguments) { - bootstrapMethodsAttribute.putShort(addConstant(bootstrapMethodArgument).index); - } - - // Compute the length and the hash code of the bootstrap method. - int bootstrapMethodlength = bootstrapMethodsAttribute.length - bootstrapMethodOffset; - int hashCode = bootstrapMethodHandle.hashCode(); - for (Object bootstrapMethodArgument : bootstrapMethodArguments) { - hashCode ^= bootstrapMethodArgument.hashCode(); - } - hashCode &= 0x7FFFFFFF; - - // Add the bootstrap method to the symbol table or revert the above changes. - return addBootstrapMethod(bootstrapMethodOffset, bootstrapMethodlength, hashCode); - } - - /** - * Adds a bootstrap method to the BootstrapMethods attribute of this symbol table. Does nothing if - * the BootstrapMethods already contains a similar bootstrap method (more precisely, reverts the - * content of {@link #bootstrapMethods} to remove the last, duplicate bootstrap method). - * - * @param offset the offset of the last bootstrap method in {@link #bootstrapMethods}, in bytes. - * @param length the length of this bootstrap method in {@link #bootstrapMethods}, in bytes. - * @param hashCode the hash code of this bootstrap method. - * @return a new or already existing Symbol with the given value. - */ - private Symbol addBootstrapMethod(final int offset, final int length, final int hashCode) { - final byte[] bootstrapMethodsData = bootstrapMethods.data; - Entry entry = get(hashCode); - while (entry != null) { - if (entry.tag == Symbol.BOOTSTRAP_METHOD_TAG && entry.hashCode == hashCode) { - int otherOffset = (int) entry.data; - boolean isSameBootstrapMethod = true; - for (int i = 0; i < length; ++i) { - if (bootstrapMethodsData[offset + i] != bootstrapMethodsData[otherOffset + i]) { - isSameBootstrapMethod = false; - break; - } - } - if (isSameBootstrapMethod) { - bootstrapMethods.length = offset; // Revert to old position. - return entry; - } - } - entry = entry.next; - } - return put(new Entry(bootstrapMethodCount++, Symbol.BOOTSTRAP_METHOD_TAG, offset, hashCode)); - } - - // ----------------------------------------------------------------------------------------------- - // Type table entries management. - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the type table element whose index is given. - * - * @param typeIndex a type table index. - * @return the type table element whose index is given. - */ - Symbol getType(final int typeIndex) { - return typeTable[typeIndex]; - } - - /** - * Adds a type in the type table of this symbol table. Does nothing if the type table already - * contains a similar type. - * - * @param value an internal class name. - * @return the index of a new or already existing type Symbol with the given value. - */ - int addType(final String value) { - int hashCode = hash(Symbol.TYPE_TAG, value); - Entry entry = get(hashCode); - while (entry != null) { - if (entry.tag == Symbol.TYPE_TAG && entry.hashCode == hashCode && entry.value.equals(value)) { - return entry.index; - } - entry = entry.next; - } - return addTypeInternal(new Entry(typeCount, Symbol.TYPE_TAG, value, hashCode)); - } - - /** - * Adds an {@link Frame#ITEM_UNINITIALIZED} type in the type table of this symbol table. Does - * nothing if the type table already contains a similar type. - * - * @param value an internal class name. - * @param bytecodeOffset the bytecode offset of the NEW instruction that created this {@link - * Frame#ITEM_UNINITIALIZED} type value. - * @return the index of a new or already existing type Symbol with the given value. - */ - int addUninitializedType(final String value, final int bytecodeOffset) { - int hashCode = hash(Symbol.UNINITIALIZED_TYPE_TAG, value, bytecodeOffset); - Entry entry = get(hashCode); - while (entry != null) { - if (entry.tag == Symbol.UNINITIALIZED_TYPE_TAG - && entry.hashCode == hashCode - && entry.data == bytecodeOffset - && entry.value.equals(value)) { - return entry.index; - } - entry = entry.next; - } - return addTypeInternal( - new Entry(typeCount, Symbol.UNINITIALIZED_TYPE_TAG, value, bytecodeOffset, hashCode)); - } - - /** - * Adds a merged type in the type table of this symbol table. Does nothing if the type table - * already contains a similar type. - * - * @param typeTableIndex1 a {@link Symbol#TYPE_TAG} type, specified by its index in the type - * table. - * @param typeTableIndex2 another {@link Symbol#TYPE_TAG} type, specified by its index in the type - * table. - * @return the index of a new or already existing {@link Symbol#TYPE_TAG} type Symbol, - * corresponding to the common super class of the given types. - */ - int addMergedType(final int typeTableIndex1, final int typeTableIndex2) { - long data = - typeTableIndex1 < typeTableIndex2 - ? typeTableIndex1 | (((long) typeTableIndex2) << 32) - : typeTableIndex2 | (((long) typeTableIndex1) << 32); - int hashCode = hash(Symbol.MERGED_TYPE_TAG, typeTableIndex1 + typeTableIndex2); - Entry entry = get(hashCode); - while (entry != null) { - if (entry.tag == Symbol.MERGED_TYPE_TAG && entry.hashCode == hashCode && entry.data == data) { - return entry.info; - } - entry = entry.next; - } - String type1 = typeTable[typeTableIndex1].value; - String type2 = typeTable[typeTableIndex2].value; - int commonSuperTypeIndex = addType(classWriter.getCommonSuperClass(type1, type2)); - put(new Entry(typeCount, Symbol.MERGED_TYPE_TAG, data, hashCode)).info = commonSuperTypeIndex; - return commonSuperTypeIndex; - } - - /** - * Adds the given type Symbol to {@link #typeTable}. - * - * @param entry a {@link Symbol#TYPE_TAG} or {@link Symbol#UNINITIALIZED_TYPE_TAG} type symbol. - * The index of this Symbol must be equal to the current value of {@link #typeCount}. - * @return the index in {@link #typeTable} where the given type was added, which is also equal to - * entry's index by hypothesis. - */ - private int addTypeInternal(final Entry entry) { - if (typeTable == null) { - typeTable = new Entry[16]; - } - if (typeCount == typeTable.length) { - Entry[] newTypeTable = new Entry[2 * typeTable.length]; - System.arraycopy(typeTable, 0, newTypeTable, 0, typeTable.length); - typeTable = newTypeTable; - } - typeTable[typeCount++] = entry; - return put(entry).index; - } - - // ----------------------------------------------------------------------------------------------- - // Static helper methods to compute hash codes. - // ----------------------------------------------------------------------------------------------- - - private static int hash(final int tag, final int value) { - return 0x7FFFFFFF & (tag + value); - } - - private static int hash(final int tag, final long value) { - return 0x7FFFFFFF & (tag + (int) value + (int) (value >>> 32)); - } - - private static int hash(final int tag, final String value) { - return 0x7FFFFFFF & (tag + value.hashCode()); - } - - private static int hash(final int tag, final String value1, final int value2) { - return 0x7FFFFFFF & (tag + value1.hashCode() + value2); - } - - private static int hash(final int tag, final String value1, final String value2) { - return 0x7FFFFFFF & (tag + value1.hashCode() * value2.hashCode()); - } - - private static int hash( - final int tag, final String value1, final String value2, final int value3) { - return 0x7FFFFFFF & (tag + value1.hashCode() * value2.hashCode() * (value3 + 1)); - } - - private static int hash( - final int tag, final String value1, final String value2, final String value3) { - return 0x7FFFFFFF & (tag + value1.hashCode() * value2.hashCode() * value3.hashCode()); - } - - private static int hash( - final int tag, - final String value1, - final String value2, - final String value3, - final int value4) { - return 0x7FFFFFFF & (tag + value1.hashCode() * value2.hashCode() * value3.hashCode() * value4); - } - - /** - * An entry of a SymbolTable. This concrete and private subclass of {@link Symbol} adds two fields - * which are only used inside SymbolTable, to implement hash sets of symbols (in order to avoid - * duplicate symbols). See {@link #entries}. - * - * @author Eric Bruneton - */ - private static class Entry extends Symbol { - - /** The hash code of this entry. */ - final int hashCode; - - /** - * Another entry (and so on recursively) having the same hash code (modulo the size of {@link - * #entries}) as this one. - */ - Entry next; - - Entry( - final int index, - final int tag, - final String owner, - final String name, - final String value, - final long data, - final int hashCode) { - super(index, tag, owner, name, value, data); - this.hashCode = hashCode; - } - - Entry(final int index, final int tag, final String value, final int hashCode) { - super(index, tag, /* owner = */ null, /* name = */ null, value, /* data = */ 0); - this.hashCode = hashCode; - } - - Entry(final int index, final int tag, final String value, final long data, final int hashCode) { - super(index, tag, /* owner = */ null, /* name = */ null, value, data); - this.hashCode = hashCode; - } - - Entry( - final int index, final int tag, final String name, final String value, final int hashCode) { - super(index, tag, /* owner = */ null, name, value, /* data = */ 0); - this.hashCode = hashCode; - } - - Entry(final int index, final int tag, final long data, final int hashCode) { - super(index, tag, /* owner = */ null, /* name = */ null, /* value = */ null, data); - this.hashCode = hashCode; - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/Type.java b/jodd-proxetta/src/main/java/jodd/asm7/Type.java deleted file mode 100644 index 525592e70..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/Type.java +++ /dev/null @@ -1,891 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; - -/** - * A Java field or method type. This class can be used to make it easier to manipulate type and - * method descriptors. - * - * @author Eric Bruneton - * @author Chris Nokleberg - */ -public final class Type { - - /** The sort of the {@code void} type. See {@link #getSort}. */ - public static final int VOID = 0; - - /** The sort of the {@code boolean} type. See {@link #getSort}. */ - public static final int BOOLEAN = 1; - - /** The sort of the {@code char} type. See {@link #getSort}. */ - public static final int CHAR = 2; - - /** The sort of the {@code byte} type. See {@link #getSort}. */ - public static final int BYTE = 3; - - /** The sort of the {@code short} type. See {@link #getSort}. */ - public static final int SHORT = 4; - - /** The sort of the {@code int} type. See {@link #getSort}. */ - public static final int INT = 5; - - /** The sort of the {@code float} type. See {@link #getSort}. */ - public static final int FLOAT = 6; - - /** The sort of the {@code long} type. See {@link #getSort}. */ - public static final int LONG = 7; - - /** The sort of the {@code double} type. See {@link #getSort}. */ - public static final int DOUBLE = 8; - - /** The sort of array reference types. See {@link #getSort}. */ - public static final int ARRAY = 9; - - /** The sort of object reference types. See {@link #getSort}. */ - public static final int OBJECT = 10; - - /** The sort of method types. See {@link #getSort}. */ - public static final int METHOD = 11; - - /** The (private) sort of object reference types represented with an internal name. */ - private static final int INTERNAL = 12; - - /** The descriptors of the primitive types. */ - private static final String PRIMITIVE_DESCRIPTORS = "VZCBSIFJD"; - - /** The {@code void} type. */ - public static final Type VOID_TYPE = new Type(VOID, PRIMITIVE_DESCRIPTORS, VOID, VOID + 1); - - /** The {@code boolean} type. */ - public static final Type BOOLEAN_TYPE = - new Type(BOOLEAN, PRIMITIVE_DESCRIPTORS, BOOLEAN, BOOLEAN + 1); - - /** The {@code char} type. */ - public static final Type CHAR_TYPE = new Type(CHAR, PRIMITIVE_DESCRIPTORS, CHAR, CHAR + 1); - - /** The {@code byte} type. */ - public static final Type BYTE_TYPE = new Type(BYTE, PRIMITIVE_DESCRIPTORS, BYTE, BYTE + 1); - - /** The {@code short} type. */ - public static final Type SHORT_TYPE = new Type(SHORT, PRIMITIVE_DESCRIPTORS, SHORT, SHORT + 1); - - /** The {@code int} type. */ - public static final Type INT_TYPE = new Type(INT, PRIMITIVE_DESCRIPTORS, INT, INT + 1); - - /** The {@code float} type. */ - public static final Type FLOAT_TYPE = new Type(FLOAT, PRIMITIVE_DESCRIPTORS, FLOAT, FLOAT + 1); - - /** The {@code long} type. */ - public static final Type LONG_TYPE = new Type(LONG, PRIMITIVE_DESCRIPTORS, LONG, LONG + 1); - - /** The {@code double} type. */ - public static final Type DOUBLE_TYPE = - new Type(DOUBLE, PRIMITIVE_DESCRIPTORS, DOUBLE, DOUBLE + 1); - - // ----------------------------------------------------------------------------------------------- - // Fields - // ----------------------------------------------------------------------------------------------- - - /** - * The sort of this type. Either {@link #VOID}, {@link #BOOLEAN}, {@link #CHAR}, {@link #BYTE}, - * {@link #SHORT}, {@link #INT}, {@link #FLOAT}, {@link #LONG}, {@link #DOUBLE}, {@link #ARRAY}, - * {@link #OBJECT}, {@link #METHOD} or {@link #INTERNAL}. - */ - private final int sort; - - /** - * A buffer containing the value of this field or method type. This value is an internal name for - * {@link #OBJECT} and {@link #INTERNAL} types, and a field or method descriptor in the other - * cases. - * - *

For {@link #OBJECT} types, this field also contains the descriptor: the characters in - * [{@link #valueBegin},{@link #valueEnd}) contain the internal name, and those in [{@link - * #valueBegin} - 1, {@link #valueEnd} + 1) contain the descriptor. - */ - private final String valueBuffer; - - /** - * The beginning index, inclusive, of the value of this Java field or method type in {@link - * #valueBuffer}. This value is an internal name for {@link #OBJECT} and {@link #INTERNAL} types, - * and a field or method descriptor in the other cases. - */ - private final int valueBegin; - - /** - * The end index, exclusive, of the value of this Java field or method type in {@link - * #valueBuffer}. This value is an internal name for {@link #OBJECT} and {@link #INTERNAL} types, - * and a field or method descriptor in the other cases. - */ - private final int valueEnd; - - /** - * Constructs a reference type. - * - * @param sort the sort of this type, see {@link #sort}. - * @param valueBuffer a buffer containing the value of this field or method type. - * @param valueBegin the beginning index, inclusive, of the value of this field or method type in - * valueBuffer. - * @param valueEnd the end index, exclusive, of the value of this field or method type in - * valueBuffer. - */ - private Type(final int sort, final String valueBuffer, final int valueBegin, final int valueEnd) { - this.sort = sort; - this.valueBuffer = valueBuffer; - this.valueBegin = valueBegin; - this.valueEnd = valueEnd; - } - - // ----------------------------------------------------------------------------------------------- - // Methods to get Type(s) from a descriptor, a reflected Method or Constructor, other types, etc. - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the {@link Type} corresponding to the given type descriptor. - * - * @param typeDescriptor a field or method type descriptor. - * @return the {@link Type} corresponding to the given type descriptor. - */ - public static Type getType(final String typeDescriptor) { - return getTypeInternal(typeDescriptor, 0, typeDescriptor.length()); - } - - /** - * Returns the {@link Type} corresponding to the given class. - * - * @param clazz a class. - * @return the {@link Type} corresponding to the given class. - */ - public static Type getType(final Class clazz) { - if (clazz.isPrimitive()) { - if (clazz == Integer.TYPE) { - return INT_TYPE; - } else if (clazz == Void.TYPE) { - return VOID_TYPE; - } else if (clazz == Boolean.TYPE) { - return BOOLEAN_TYPE; - } else if (clazz == Byte.TYPE) { - return BYTE_TYPE; - } else if (clazz == Character.TYPE) { - return CHAR_TYPE; - } else if (clazz == Short.TYPE) { - return SHORT_TYPE; - } else if (clazz == Double.TYPE) { - return DOUBLE_TYPE; - } else if (clazz == Float.TYPE) { - return FLOAT_TYPE; - } else if (clazz == Long.TYPE) { - return LONG_TYPE; - } else { - throw new AssertionError(); - } - } else { - return getType(getDescriptor(clazz)); - } - } - - /** - * Returns the method {@link Type} corresponding to the given constructor. - * - * @param constructor a {@link Constructor} object. - * @return the method {@link Type} corresponding to the given constructor. - */ - public static Type getType(final Constructor constructor) { - return getType(getConstructorDescriptor(constructor)); - } - - /** - * Returns the method {@link Type} corresponding to the given method. - * - * @param method a {@link Method} object. - * @return the method {@link Type} corresponding to the given method. - */ - public static Type getType(final Method method) { - return getType(getMethodDescriptor(method)); - } - - /** - * Returns the type of the elements of this array type. This method should only be used for an - * array type. - * - * @return Returns the type of the elements of this array type. - */ - public Type getElementType() { - final int numDimensions = getDimensions(); - return getTypeInternal(valueBuffer, valueBegin + numDimensions, valueEnd); - } - - /** - * Returns the {@link Type} corresponding to the given internal name. - * - * @param internalName an internal name. - * @return the {@link Type} corresponding to the given internal name. - */ - public static Type getObjectType(final String internalName) { - return new Type( - internalName.charAt(0) == '[' ? ARRAY : INTERNAL, internalName, 0, internalName.length()); - } - - /** - * Returns the {@link Type} corresponding to the given method descriptor. Equivalent to - * Type.getType(methodDescriptor). - * - * @param methodDescriptor a method descriptor. - * @return the {@link Type} corresponding to the given method descriptor. - */ - public static Type getMethodType(final String methodDescriptor) { - return new Type(METHOD, methodDescriptor, 0, methodDescriptor.length()); - } - - /** - * Returns the method {@link Type} corresponding to the given argument and return types. - * - * @param returnType the return type of the method. - * @param argumentTypes the argument types of the method. - * @return the method {@link Type} corresponding to the given argument and return types. - */ - public static Type getMethodType(final Type returnType, final Type... argumentTypes) { - return getType(getMethodDescriptor(returnType, argumentTypes)); - } - - /** - * Returns the argument types of methods of this type. This method should only be used for method - * types. - * - * @return the argument types of methods of this type. - */ - public Type[] getArgumentTypes() { - return getArgumentTypes(getDescriptor()); - } - - /** - * Returns the {@link Type} values corresponding to the argument types of the given method - * descriptor. - * - * @param methodDescriptor a method descriptor. - * @return the {@link Type} values corresponding to the argument types of the given method - * descriptor. - */ - public static Type[] getArgumentTypes(final String methodDescriptor) { - // First step: compute the number of argument types in methodDescriptor. - int numArgumentTypes = 0; - // Skip the first character, which is always a '('. - int currentOffset = 1; - // Parse the argument types, one at a each loop iteration. - while (methodDescriptor.charAt(currentOffset) != ')') { - while (methodDescriptor.charAt(currentOffset) == '[') { - currentOffset++; - } - if (methodDescriptor.charAt(currentOffset++) == 'L') { - // Skip the argument descriptor content. - currentOffset = methodDescriptor.indexOf(';', currentOffset) + 1; - } - ++numArgumentTypes; - } - - // Second step: create a Type instance for each argument type. - Type[] argumentTypes = new Type[numArgumentTypes]; - // Skip the first character, which is always a '('. - currentOffset = 1; - // Parse and create the argument types, one at each loop iteration. - int currentArgumentTypeIndex = 0; - while (methodDescriptor.charAt(currentOffset) != ')') { - final int currentArgumentTypeOffset = currentOffset; - while (methodDescriptor.charAt(currentOffset) == '[') { - currentOffset++; - } - if (methodDescriptor.charAt(currentOffset++) == 'L') { - // Skip the argument descriptor content. - currentOffset = methodDescriptor.indexOf(';', currentOffset) + 1; - } - argumentTypes[currentArgumentTypeIndex++] = - getTypeInternal(methodDescriptor, currentArgumentTypeOffset, currentOffset); - } - return argumentTypes; - } - - /** - * Returns the {@link Type} values corresponding to the argument types of the given method. - * - * @param method a method. - * @return the {@link Type} values corresponding to the argument types of the given method. - */ - public static Type[] getArgumentTypes(final Method method) { - Class[] classes = method.getParameterTypes(); - Type[] types = new Type[classes.length]; - for (int i = classes.length - 1; i >= 0; --i) { - types[i] = getType(classes[i]); - } - return types; - } - - /** - * Returns the return type of methods of this type. This method should only be used for method - * types. - * - * @return the return type of methods of this type. - */ - public Type getReturnType() { - return getReturnType(getDescriptor()); - } - - /** - * Returns the {@link Type} corresponding to the return type of the given method descriptor. - * - * @param methodDescriptor a method descriptor. - * @return the {@link Type} corresponding to the return type of the given method descriptor. - */ - public static Type getReturnType(final String methodDescriptor) { - return getTypeInternal( - methodDescriptor, getReturnTypeOffset(methodDescriptor), methodDescriptor.length()); - } - - /** - * Returns the {@link Type} corresponding to the return type of the given method. - * - * @param method a method. - * @return the {@link Type} corresponding to the return type of the given method. - */ - public static Type getReturnType(final Method method) { - return getType(method.getReturnType()); - } - - /** - * Returns the start index of the return type of the given method descriptor. - * - * @param methodDescriptor a method descriptor. - * @return the start index of the return type of the given method descriptor. - */ - static int getReturnTypeOffset(final String methodDescriptor) { - // Skip the first character, which is always a '('. - int currentOffset = 1; - // Skip the argument types, one at a each loop iteration. - while (methodDescriptor.charAt(currentOffset) != ')') { - while (methodDescriptor.charAt(currentOffset) == '[') { - currentOffset++; - } - if (methodDescriptor.charAt(currentOffset++) == 'L') { - // Skip the argument descriptor content. - currentOffset = methodDescriptor.indexOf(';', currentOffset) + 1; - } - } - return currentOffset + 1; - } - - /** - * Returns the {@link Type} corresponding to the given field or method descriptor. - * - * @param descriptorBuffer a buffer containing the field or method descriptor. - * @param descriptorBegin the beginning index, inclusive, of the field or method descriptor in - * descriptorBuffer. - * @param descriptorEnd the end index, exclusive, of the field or method descriptor in - * descriptorBuffer. - * @return the {@link Type} corresponding to the given type descriptor. - */ - private static Type getTypeInternal( - final String descriptorBuffer, final int descriptorBegin, final int descriptorEnd) { - switch (descriptorBuffer.charAt(descriptorBegin)) { - case 'V': - return VOID_TYPE; - case 'Z': - return BOOLEAN_TYPE; - case 'C': - return CHAR_TYPE; - case 'B': - return BYTE_TYPE; - case 'S': - return SHORT_TYPE; - case 'I': - return INT_TYPE; - case 'F': - return FLOAT_TYPE; - case 'J': - return LONG_TYPE; - case 'D': - return DOUBLE_TYPE; - case '[': - return new Type(ARRAY, descriptorBuffer, descriptorBegin, descriptorEnd); - case 'L': - return new Type(OBJECT, descriptorBuffer, descriptorBegin + 1, descriptorEnd - 1); - case '(': - return new Type(METHOD, descriptorBuffer, descriptorBegin, descriptorEnd); - default: - throw new IllegalArgumentException(); - } - } - - // ----------------------------------------------------------------------------------------------- - // Methods to get class names, internal names or descriptors. - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the binary name of the class corresponding to this type. This method must not be used - * on method types. - * - * @return the binary name of the class corresponding to this type. - */ - public String getClassName() { - switch (sort) { - case VOID: - return "void"; - case BOOLEAN: - return "boolean"; - case CHAR: - return "char"; - case BYTE: - return "byte"; - case SHORT: - return "short"; - case INT: - return "int"; - case FLOAT: - return "float"; - case LONG: - return "long"; - case DOUBLE: - return "double"; - case ARRAY: - StringBuilder stringBuilder = new StringBuilder(getElementType().getClassName()); - for (int i = getDimensions(); i > 0; --i) { - stringBuilder.append("[]"); - } - return stringBuilder.toString(); - case OBJECT: - case INTERNAL: - return valueBuffer.substring(valueBegin, valueEnd).replace('/', '.'); - default: - throw new AssertionError(); - } - } - - /** - * Returns the internal name of the class corresponding to this object or array type. The internal - * name of a class is its fully qualified name (as returned by Class.getName(), where '.' are - * replaced by '/'). This method should only be used for an object or array type. - * - * @return the internal name of the class corresponding to this object type. - */ - public String getInternalName() { - return valueBuffer.substring(valueBegin, valueEnd); - } - - /** - * Returns the internal name of the given class. The internal name of a class is its fully - * qualified name, as returned by Class.getName(), where '.' are replaced by '/'. - * - * @param clazz an object or array class. - * @return the internal name of the given class. - */ - public static String getInternalName(final Class clazz) { - return clazz.getName().replace('.', '/'); - } - - /** - * Returns the descriptor corresponding to this type. - * - * @return the descriptor corresponding to this type. - */ - public String getDescriptor() { - if (sort == OBJECT) { - return valueBuffer.substring(valueBegin - 1, valueEnd + 1); - } else if (sort == INTERNAL) { - return 'L' + valueBuffer.substring(valueBegin, valueEnd) + ';'; - } else { - return valueBuffer.substring(valueBegin, valueEnd); - } - } - - /** - * Returns the descriptor corresponding to the given class. - * - * @param clazz an object class, a primitive class or an array class. - * @return the descriptor corresponding to the given class. - */ - public static String getDescriptor(final Class clazz) { - StringBuilder stringBuilder = new StringBuilder(); - appendDescriptor(clazz, stringBuilder); - return stringBuilder.toString(); - } - - /** - * Returns the descriptor corresponding to the given constructor. - * - * @param constructor a {@link Constructor} object. - * @return the descriptor of the given constructor. - */ - public static String getConstructorDescriptor(final Constructor constructor) { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append('('); - Class[] parameters = constructor.getParameterTypes(); - for (Class parameter : parameters) { - appendDescriptor(parameter, stringBuilder); - } - return stringBuilder.append(")V").toString(); - } - - /** - * Returns the descriptor corresponding to the given argument and return types. - * - * @param returnType the return type of the method. - * @param argumentTypes the argument types of the method. - * @return the descriptor corresponding to the given argument and return types. - */ - public static String getMethodDescriptor(final Type returnType, final Type... argumentTypes) { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append('('); - for (Type argumentType : argumentTypes) { - argumentType.appendDescriptor(stringBuilder); - } - stringBuilder.append(')'); - returnType.appendDescriptor(stringBuilder); - return stringBuilder.toString(); - } - - /** - * Returns the descriptor corresponding to the given method. - * - * @param method a {@link Method} object. - * @return the descriptor of the given method. - */ - public static String getMethodDescriptor(final Method method) { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append('('); - Class[] parameters = method.getParameterTypes(); - for (Class parameter : parameters) { - appendDescriptor(parameter, stringBuilder); - } - stringBuilder.append(')'); - appendDescriptor(method.getReturnType(), stringBuilder); - return stringBuilder.toString(); - } - - /** - * Appends the descriptor corresponding to this type to the given string buffer. - * - * @param stringBuilder the string builder to which the descriptor must be appended. - */ - private void appendDescriptor(final StringBuilder stringBuilder) { - if (sort == OBJECT) { - stringBuilder.append(valueBuffer, valueBegin - 1, valueEnd + 1); - } else if (sort == INTERNAL) { - stringBuilder.append('L').append(valueBuffer, valueBegin, valueEnd).append(';'); - } else { - stringBuilder.append(valueBuffer, valueBegin, valueEnd); - } - } - - /** - * Appends the descriptor of the given class to the given string builder. - * - * @param clazz the class whose descriptor must be computed. - * @param stringBuilder the string builder to which the descriptor must be appended. - */ - private static void appendDescriptor(final Class clazz, final StringBuilder stringBuilder) { - Class currentClass = clazz; - while (currentClass.isArray()) { - stringBuilder.append('['); - currentClass = currentClass.getComponentType(); - } - if (currentClass.isPrimitive()) { - char descriptor; - if (currentClass == Integer.TYPE) { - descriptor = 'I'; - } else if (currentClass == Void.TYPE) { - descriptor = 'V'; - } else if (currentClass == Boolean.TYPE) { - descriptor = 'Z'; - } else if (currentClass == Byte.TYPE) { - descriptor = 'B'; - } else if (currentClass == Character.TYPE) { - descriptor = 'C'; - } else if (currentClass == Short.TYPE) { - descriptor = 'S'; - } else if (currentClass == Double.TYPE) { - descriptor = 'D'; - } else if (currentClass == Float.TYPE) { - descriptor = 'F'; - } else if (currentClass == Long.TYPE) { - descriptor = 'J'; - } else { - throw new AssertionError(); - } - stringBuilder.append(descriptor); - } else { - stringBuilder.append('L').append(getInternalName(currentClass)).append(';'); - } - } - - // ----------------------------------------------------------------------------------------------- - // Methods to get the sort, dimension, size, and opcodes corresponding to a Type or descriptor. - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the sort of this type. - * - * @return {@link #VOID}, {@link #BOOLEAN}, {@link #CHAR}, {@link #BYTE}, {@link #SHORT}, {@link - * #INT}, {@link #FLOAT}, {@link #LONG}, {@link #DOUBLE}, {@link #ARRAY}, {@link #OBJECT} or - * {@link #METHOD}. - */ - public int getSort() { - return sort == INTERNAL ? OBJECT : sort; - } - - /** - * Returns the number of dimensions of this array type. This method should only be used for an - * array type. - * - * @return the number of dimensions of this array type. - */ - public int getDimensions() { - int numDimensions = 1; - while (valueBuffer.charAt(valueBegin + numDimensions) == '[') { - numDimensions++; - } - return numDimensions; - } - - /** - * Returns the size of values of this type. This method must not be used for method types. - * - * @return the size of values of this type, i.e., 2 for {@code long} and {@code double}, 0 for - * {@code void} and 1 otherwise. - */ - public int getSize() { - switch (sort) { - case VOID: - return 0; - case BOOLEAN: - case CHAR: - case BYTE: - case SHORT: - case INT: - case FLOAT: - case ARRAY: - case OBJECT: - case INTERNAL: - return 1; - case LONG: - case DOUBLE: - return 2; - default: - throw new AssertionError(); - } - } - - /** - * Returns the size of the arguments and of the return value of methods of this type. This method - * should only be used for method types. - * - * @return the size of the arguments of the method (plus one for the implicit this argument), - * argumentsSize, and the size of its return value, returnSize, packed into a single int i = - * {@code (argumentsSize << 2) | returnSize} (argumentsSize is therefore equal to {@code - * i >> 2}, and returnSize to {@code i & 0x03}). - */ - public int getArgumentsAndReturnSizes() { - return getArgumentsAndReturnSizes(getDescriptor()); - } - - /** - * Computes the size of the arguments and of the return value of a method. - * - * @param methodDescriptor a method descriptor. - * @return the size of the arguments of the method (plus one for the implicit this argument), - * argumentsSize, and the size of its return value, returnSize, packed into a single int i = - * {@code (argumentsSize << 2) | returnSize} (argumentsSize is therefore equal to {@code - * i >> 2}, and returnSize to {@code i & 0x03}). - */ - public static int getArgumentsAndReturnSizes(final String methodDescriptor) { - int argumentsSize = 1; - // Skip the first character, which is always a '('. - int currentOffset = 1; - int currentChar = methodDescriptor.charAt(currentOffset); - // Parse the argument types and compute their size, one at a each loop iteration. - while (currentChar != ')') { - if (currentChar == 'J' || currentChar == 'D') { - currentOffset++; - argumentsSize += 2; - } else { - while (methodDescriptor.charAt(currentOffset) == '[') { - currentOffset++; - } - if (methodDescriptor.charAt(currentOffset++) == 'L') { - // Skip the argument descriptor content. - currentOffset = methodDescriptor.indexOf(';', currentOffset) + 1; - } - argumentsSize += 1; - } - currentChar = methodDescriptor.charAt(currentOffset); - } - currentChar = methodDescriptor.charAt(currentOffset + 1); - if (currentChar == 'V') { - return argumentsSize << 2; - } else { - int returnSize = (currentChar == 'J' || currentChar == 'D') ? 2 : 1; - return argumentsSize << 2 | returnSize; - } - } - - /** - * Returns a JVM instruction opcode adapted to this {@link Type}. This method must not be used for - * method types. - * - * @param opcode a JVM instruction opcode. This opcode must be one of ILOAD, ISTORE, IALOAD, - * IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, ISHL, ISHR, IUSHR, IAND, IOR, IXOR and - * IRETURN. - * @return an opcode that is similar to the given opcode, but adapted to this {@link Type}. For - * example, if this type is {@code float} and {@code opcode} is IRETURN, this method returns - * FRETURN. - */ - public int getOpcode(final int opcode) { - if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) { - switch (sort) { - case BOOLEAN: - case BYTE: - return opcode + (Opcodes.BALOAD - Opcodes.IALOAD); - case CHAR: - return opcode + (Opcodes.CALOAD - Opcodes.IALOAD); - case SHORT: - return opcode + (Opcodes.SALOAD - Opcodes.IALOAD); - case INT: - return opcode; - case FLOAT: - return opcode + (Opcodes.FALOAD - Opcodes.IALOAD); - case LONG: - return opcode + (Opcodes.LALOAD - Opcodes.IALOAD); - case DOUBLE: - return opcode + (Opcodes.DALOAD - Opcodes.IALOAD); - case ARRAY: - case OBJECT: - case INTERNAL: - return opcode + (Opcodes.AALOAD - Opcodes.IALOAD); - case METHOD: - case VOID: - throw new UnsupportedOperationException(); - default: - throw new AssertionError(); - } - } else { - switch (sort) { - case VOID: - if (opcode != Opcodes.IRETURN) { - throw new UnsupportedOperationException(); - } - return Opcodes.RETURN; - case BOOLEAN: - case BYTE: - case CHAR: - case SHORT: - case INT: - return opcode; - case FLOAT: - return opcode + (Opcodes.FRETURN - Opcodes.IRETURN); - case LONG: - return opcode + (Opcodes.LRETURN - Opcodes.IRETURN); - case DOUBLE: - return opcode + (Opcodes.DRETURN - Opcodes.IRETURN); - case ARRAY: - case OBJECT: - case INTERNAL: - if (opcode != Opcodes.ILOAD && opcode != Opcodes.ISTORE && opcode != Opcodes.IRETURN) { - throw new UnsupportedOperationException(); - } - return opcode + (Opcodes.ARETURN - Opcodes.IRETURN); - case METHOD: - throw new UnsupportedOperationException(); - default: - throw new AssertionError(); - } - } - } - - // ----------------------------------------------------------------------------------------------- - // Equals, hashCode and toString. - // ----------------------------------------------------------------------------------------------- - - /** - * Tests if the given object is equal to this type. - * - * @param object the object to be compared to this type. - * @return {@literal true} if the given object is equal to this type. - */ - @Override - public boolean equals(final Object object) { - if (this == object) { - return true; - } - if (!(object instanceof Type)) { - return false; - } - Type other = (Type) object; - if ((sort == INTERNAL ? OBJECT : sort) != (other.sort == INTERNAL ? OBJECT : other.sort)) { - return false; - } - int begin = valueBegin; - int end = valueEnd; - int otherBegin = other.valueBegin; - int otherEnd = other.valueEnd; - // Compare the values. - if (end - begin != otherEnd - otherBegin) { - return false; - } - for (int i = begin, j = otherBegin; i < end; i++, j++) { - if (valueBuffer.charAt(i) != other.valueBuffer.charAt(j)) { - return false; - } - } - return true; - } - - /** - * Returns a hash code value for this type. - * - * @return a hash code value for this type. - */ - @Override - public int hashCode() { - int hashCode = 13 * (sort == INTERNAL ? OBJECT : sort); - if (sort >= ARRAY) { - for (int i = valueBegin, end = valueEnd; i < end; i++) { - hashCode = 17 * (hashCode + valueBuffer.charAt(i)); - } - } - return hashCode; - } - - /** - * Returns a string representation of this type. - * - * @return the descriptor of this type. - */ - @Override - public String toString() { - return getDescriptor(); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/TypePath.java b/jodd-proxetta/src/main/java/jodd/asm7/TypePath.java deleted file mode 100644 index f22a5d09e..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/TypePath.java +++ /dev/null @@ -1,201 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. - -package jodd.asm7; - -/** - * The path to a type argument, wildcard bound, array element type, or static inner type within an - * enclosing type. - * - * @author Eric Bruneton - */ -public final class TypePath { - - /** A type path step that steps into the element type of an array type. See {@link #getStep}. */ - public static final int ARRAY_ELEMENT = 0; - - /** A type path step that steps into the nested type of a class type. See {@link #getStep}. */ - public static final int INNER_TYPE = 1; - - /** A type path step that steps into the bound of a wildcard type. See {@link #getStep}. */ - public static final int WILDCARD_BOUND = 2; - - /** A type path step that steps into a type argument of a generic type. See {@link #getStep}. */ - public static final int TYPE_ARGUMENT = 3; - - /** - * The byte array where the 'type_path' structure - as defined in the Java Virtual Machine - * Specification (JVMS) - corresponding to this TypePath is stored. The first byte of the - * structure in this array is given by {@link #typePathOffset}. - * - * @see JVMS - * 4.7.20.2 - */ - private final byte[] typePathContainer; - - /** The offset of the first byte of the type_path JVMS structure in {@link #typePathContainer}. */ - private final int typePathOffset; - - /** - * Constructs a new TypePath. - * - * @param typePathContainer a byte array containing a type_path JVMS structure. - * @param typePathOffset the offset of the first byte of the type_path structure in - * typePathContainer. - */ - TypePath(final byte[] typePathContainer, final int typePathOffset) { - this.typePathContainer = typePathContainer; - this.typePathOffset = typePathOffset; - } - - /** - * Returns the length of this path, i.e. its number of steps. - * - * @return the length of this path. - */ - public int getLength() { - // path_length is stored in the first byte of a type_path. - return typePathContainer[typePathOffset]; - } - - /** - * Returns the value of the given step of this path. - * - * @param index an index between 0 and {@link #getLength()}, exclusive. - * @return one of {@link #ARRAY_ELEMENT}, {@link #INNER_TYPE}, {@link #WILDCARD_BOUND}, or {@link - * #TYPE_ARGUMENT}. - */ - public int getStep(final int index) { - // Returns the type_path_kind of the path element of the given index. - return typePathContainer[typePathOffset + 2 * index + 1]; - } - - /** - * Returns the index of the type argument that the given step is stepping into. This method should - * only be used for steps whose value is {@link #TYPE_ARGUMENT}. - * - * @param index an index between 0 and {@link #getLength()}, exclusive. - * @return the index of the type argument that the given step is stepping into. - */ - public int getStepArgument(final int index) { - // Returns the type_argument_index of the path element of the given index. - return typePathContainer[typePathOffset + 2 * index + 2]; - } - - /** - * Converts a type path in string form, in the format used by {@link #toString()}, into a TypePath - * object. - * - * @param typePath a type path in string form, in the format used by {@link #toString()}. May be - * {@literal null} or empty. - * @return the corresponding TypePath object, or {@literal null} if the path is empty. - */ - public static TypePath fromString(final String typePath) { - if (typePath == null || typePath.length() == 0) { - return null; - } - int typePathLength = typePath.length(); - ByteVector output = new ByteVector(typePathLength); - output.putByte(0); - int typePathIndex = 0; - while (typePathIndex < typePathLength) { - char c = typePath.charAt(typePathIndex++); - if (c == '[') { - output.put11(ARRAY_ELEMENT, 0); - } else if (c == '.') { - output.put11(INNER_TYPE, 0); - } else if (c == '*') { - output.put11(WILDCARD_BOUND, 0); - } else if (c >= '0' && c <= '9') { - int typeArg = c - '0'; - while (typePathIndex < typePathLength) { - c = typePath.charAt(typePathIndex++); - if (c >= '0' && c <= '9') { - typeArg = typeArg * 10 + c - '0'; - } else if (c == ';') { - break; - } else { - throw new IllegalArgumentException(); - } - } - output.put11(TYPE_ARGUMENT, typeArg); - } else { - throw new IllegalArgumentException(); - } - } - output.data[0] = (byte) (output.length / 2); - return new TypePath(output.data, 0); - } - - /** - * Returns a string representation of this type path. {@link #ARRAY_ELEMENT} steps are represented - * with '[', {@link #INNER_TYPE} steps with '.', {@link #WILDCARD_BOUND} steps with '*' and {@link - * #TYPE_ARGUMENT} steps with their type argument index in decimal form followed by ';'. - */ - @Override - public String toString() { - int length = getLength(); - StringBuilder result = new StringBuilder(length * 2); - for (int i = 0; i < length; ++i) { - switch (getStep(i)) { - case ARRAY_ELEMENT: - result.append('['); - break; - case INNER_TYPE: - result.append('.'); - break; - case WILDCARD_BOUND: - result.append('*'); - break; - case TYPE_ARGUMENT: - result.append(getStepArgument(i)).append(';'); - break; - default: - throw new AssertionError(); - } - } - return result.toString(); - } - - /** - * Puts the type_path JVMS structure corresponding to the given TypePath into the given - * ByteVector. - * - * @param typePath a TypePath instance, or {@literal null} for empty paths. - * @param output where the type path must be put. - */ - static void put(final TypePath typePath, final ByteVector output) { - if (typePath == null) { - output.putByte(0); - } else { - int length = typePath.typePathContainer[typePath.typePathOffset] * 2 + 1; - output.putByteArray(typePath.typePathContainer, typePath.typePathOffset, length); - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/TypeReference.java b/jodd-proxetta/src/main/java/jodd/asm7/TypeReference.java deleted file mode 100644 index 26d3cc42c..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/TypeReference.java +++ /dev/null @@ -1,436 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. - -package jodd.asm7; - -/** - * A reference to a type appearing in a class, field or method declaration, or on an instruction. - * Such a reference designates the part of the class where the referenced type is appearing (e.g. an - * 'extends', 'implements' or 'throws' clause, a 'new' instruction, a 'catch' clause, a type cast, a - * local variable declaration, etc). - * - * @author Eric Bruneton - */ -public class TypeReference { - - /** - * The sort of type references that target a type parameter of a generic class. See {@link - * #getSort}. - */ - public static final int CLASS_TYPE_PARAMETER = 0x00; - - /** - * The sort of type references that target a type parameter of a generic method. See {@link - * #getSort}. - */ - public static final int METHOD_TYPE_PARAMETER = 0x01; - - /** - * The sort of type references that target the super class of a class or one of the interfaces it - * implements. See {@link #getSort}. - */ - public static final int CLASS_EXTENDS = 0x10; - - /** - * The sort of type references that target a bound of a type parameter of a generic class. See - * {@link #getSort}. - */ - public static final int CLASS_TYPE_PARAMETER_BOUND = 0x11; - - /** - * The sort of type references that target a bound of a type parameter of a generic method. See - * {@link #getSort}. - */ - public static final int METHOD_TYPE_PARAMETER_BOUND = 0x12; - - /** The sort of type references that target the type of a field. See {@link #getSort}. */ - public static final int FIELD = 0x13; - - /** The sort of type references that target the return type of a method. See {@link #getSort}. */ - public static final int METHOD_RETURN = 0x14; - - /** - * The sort of type references that target the receiver type of a method. See {@link #getSort}. - */ - public static final int METHOD_RECEIVER = 0x15; - - /** - * The sort of type references that target the type of a formal parameter of a method. See {@link - * #getSort}. - */ - public static final int METHOD_FORMAL_PARAMETER = 0x16; - - /** - * The sort of type references that target the type of an exception declared in the throws clause - * of a method. See {@link #getSort}. - */ - public static final int THROWS = 0x17; - - /** - * The sort of type references that target the type of a local variable in a method. See {@link - * #getSort}. - */ - public static final int LOCAL_VARIABLE = 0x40; - - /** - * The sort of type references that target the type of a resource variable in a method. See {@link - * #getSort}. - */ - public static final int RESOURCE_VARIABLE = 0x41; - - /** - * The sort of type references that target the type of the exception of a 'catch' clause in a - * method. See {@link #getSort}. - */ - public static final int EXCEPTION_PARAMETER = 0x42; - - /** - * The sort of type references that target the type declared in an 'instanceof' instruction. See - * {@link #getSort}. - */ - public static final int INSTANCEOF = 0x43; - - /** - * The sort of type references that target the type of the object created by a 'new' instruction. - * See {@link #getSort}. - */ - public static final int NEW = 0x44; - - /** - * The sort of type references that target the receiver type of a constructor reference. See - * {@link #getSort}. - */ - public static final int CONSTRUCTOR_REFERENCE = 0x45; - - /** - * The sort of type references that target the receiver type of a method reference. See {@link - * #getSort}. - */ - public static final int METHOD_REFERENCE = 0x46; - - /** - * The sort of type references that target the type declared in an explicit or implicit cast - * instruction. See {@link #getSort}. - */ - public static final int CAST = 0x47; - - /** - * The sort of type references that target a type parameter of a generic constructor in a - * constructor call. See {@link #getSort}. - */ - public static final int CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT = 0x48; - - /** - * The sort of type references that target a type parameter of a generic method in a method call. - * See {@link #getSort}. - */ - public static final int METHOD_INVOCATION_TYPE_ARGUMENT = 0x49; - - /** - * The sort of type references that target a type parameter of a generic constructor in a - * constructor reference. See {@link #getSort}. - */ - public static final int CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT = 0x4A; - - /** - * The sort of type references that target a type parameter of a generic method in a method - * reference. See {@link #getSort}. - */ - public static final int METHOD_REFERENCE_TYPE_ARGUMENT = 0x4B; - - /** - * The target_type and target_info structures - as defined in the Java Virtual Machine - * Specification (JVMS) - corresponding to this type reference. target_type uses one byte, and all - * the target_info union fields use up to 3 bytes (except localvar_target, handled with the - * specific method {@link MethodVisitor#visitLocalVariableAnnotation}). Thus, both structures can - * be stored in an int. - * - *

This int field stores target_type (called the TypeReference 'sort' in the public API of this - * class) in its most significant byte, followed by the target_info fields. Depending on - * target_type, 1, 2 or even 3 least significant bytes of this field are unused. target_info - * fields which reference bytecode offsets are set to 0 (these offsets are ignored in ClassReader, - * and recomputed in MethodWriter). - * - * @see JVMS - * 4.7.20 - * @see JVMS - * 4.7.20.1 - */ - private final int targetTypeAndInfo; - - /** - * Constructs a new TypeReference. - * - * @param typeRef the int encoded value of the type reference, as received in a visit method - * related to type annotations, such as {@link ClassVisitor#visitTypeAnnotation}. - */ - public TypeReference(final int typeRef) { - this.targetTypeAndInfo = typeRef; - } - - /** - * Returns a type reference of the given sort. - * - * @param sort one of {@link #FIELD}, {@link #METHOD_RETURN}, {@link #METHOD_RECEIVER}, {@link - * #LOCAL_VARIABLE}, {@link #RESOURCE_VARIABLE}, {@link #INSTANCEOF}, {@link #NEW}, {@link - * #CONSTRUCTOR_REFERENCE}, or {@link #METHOD_REFERENCE}. - * @return a type reference of the given sort. - */ - public static TypeReference newTypeReference(final int sort) { - return new TypeReference(sort << 24); - } - - /** - * Returns a reference to a type parameter of a generic class or method. - * - * @param sort one of {@link #CLASS_TYPE_PARAMETER} or {@link #METHOD_TYPE_PARAMETER}. - * @param paramIndex the type parameter index. - * @return a reference to the given generic class or method type parameter. - */ - public static TypeReference newTypeParameterReference(final int sort, final int paramIndex) { - return new TypeReference((sort << 24) | (paramIndex << 16)); - } - - /** - * Returns a reference to a type parameter bound of a generic class or method. - * - * @param sort one of {@link #CLASS_TYPE_PARAMETER} or {@link #METHOD_TYPE_PARAMETER}. - * @param paramIndex the type parameter index. - * @param boundIndex the type bound index within the above type parameters. - * @return a reference to the given generic class or method type parameter bound. - */ - public static TypeReference newTypeParameterBoundReference( - final int sort, final int paramIndex, final int boundIndex) { - return new TypeReference((sort << 24) | (paramIndex << 16) | (boundIndex << 8)); - } - - /** - * Returns a reference to the super class or to an interface of the 'implements' clause of a - * class. - * - * @param itfIndex the index of an interface in the 'implements' clause of a class, or -1 to - * reference the super class of the class. - * @return a reference to the given super type of a class. - */ - public static TypeReference newSuperTypeReference(final int itfIndex) { - return new TypeReference((CLASS_EXTENDS << 24) | ((itfIndex & 0xFFFF) << 8)); - } - - /** - * Returns a reference to the type of a formal parameter of a method. - * - * @param paramIndex the formal parameter index. - * @return a reference to the type of the given method formal parameter. - */ - public static TypeReference newFormalParameterReference(final int paramIndex) { - return new TypeReference((METHOD_FORMAL_PARAMETER << 24) | (paramIndex << 16)); - } - - /** - * Returns a reference to the type of an exception, in a 'throws' clause of a method. - * - * @param exceptionIndex the index of an exception in a 'throws' clause of a method. - * @return a reference to the type of the given exception. - */ - public static TypeReference newExceptionReference(final int exceptionIndex) { - return new TypeReference((THROWS << 24) | (exceptionIndex << 8)); - } - - /** - * Returns a reference to the type of the exception declared in a 'catch' clause of a method. - * - * @param tryCatchBlockIndex the index of a try catch block (using the order in which they are - * visited with visitTryCatchBlock). - * @return a reference to the type of the given exception. - */ - public static TypeReference newTryCatchReference(final int tryCatchBlockIndex) { - return new TypeReference((EXCEPTION_PARAMETER << 24) | (tryCatchBlockIndex << 8)); - } - - /** - * Returns a reference to the type of a type argument in a constructor or method call or - * reference. - * - * @param sort one of {@link #CAST}, {@link #CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT}, {@link - * #METHOD_INVOCATION_TYPE_ARGUMENT}, {@link #CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT}, or {@link - * #METHOD_REFERENCE_TYPE_ARGUMENT}. - * @param argIndex the type argument index. - * @return a reference to the type of the given type argument. - */ - public static TypeReference newTypeArgumentReference(final int sort, final int argIndex) { - return new TypeReference((sort << 24) | argIndex); - } - - /** - * Returns the sort of this type reference. - * - * @return one of {@link #CLASS_TYPE_PARAMETER}, {@link #METHOD_TYPE_PARAMETER}, {@link - * #CLASS_EXTENDS}, {@link #CLASS_TYPE_PARAMETER_BOUND}, {@link #METHOD_TYPE_PARAMETER_BOUND}, - * {@link #FIELD}, {@link #METHOD_RETURN}, {@link #METHOD_RECEIVER}, {@link - * #METHOD_FORMAL_PARAMETER}, {@link #THROWS}, {@link #LOCAL_VARIABLE}, {@link - * #RESOURCE_VARIABLE}, {@link #EXCEPTION_PARAMETER}, {@link #INSTANCEOF}, {@link #NEW}, - * {@link #CONSTRUCTOR_REFERENCE}, {@link #METHOD_REFERENCE}, {@link #CAST}, {@link - * #CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT}, {@link #METHOD_INVOCATION_TYPE_ARGUMENT}, {@link - * #CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT}, or {@link #METHOD_REFERENCE_TYPE_ARGUMENT}. - */ - public int getSort() { - return targetTypeAndInfo >>> 24; - } - - /** - * Returns the index of the type parameter referenced by this type reference. This method must - * only be used for type references whose sort is {@link #CLASS_TYPE_PARAMETER}, {@link - * #METHOD_TYPE_PARAMETER}, {@link #CLASS_TYPE_PARAMETER_BOUND} or {@link - * #METHOD_TYPE_PARAMETER_BOUND}. - * - * @return a type parameter index. - */ - public int getTypeParameterIndex() { - return (targetTypeAndInfo & 0x00FF0000) >> 16; - } - - /** - * Returns the index of the type parameter bound, within the type parameter {@link - * #getTypeParameterIndex}, referenced by this type reference. This method must only be used for - * type references whose sort is {@link #CLASS_TYPE_PARAMETER_BOUND} or {@link - * #METHOD_TYPE_PARAMETER_BOUND}. - * - * @return a type parameter bound index. - */ - public int getTypeParameterBoundIndex() { - return (targetTypeAndInfo & 0x0000FF00) >> 8; - } - - /** - * Returns the index of the "super type" of a class that is referenced by this type reference. - * This method must only be used for type references whose sort is {@link #CLASS_EXTENDS}. - * - * @return the index of an interface in the 'implements' clause of a class, or -1 if this type - * reference references the type of the super class. - */ - public int getSuperTypeIndex() { - return (short) ((targetTypeAndInfo & 0x00FFFF00) >> 8); - } - - /** - * Returns the index of the formal parameter whose type is referenced by this type reference. This - * method must only be used for type references whose sort is {@link #METHOD_FORMAL_PARAMETER}. - * - * @return a formal parameter index. - */ - public int getFormalParameterIndex() { - return (targetTypeAndInfo & 0x00FF0000) >> 16; - } - - /** - * Returns the index of the exception, in a 'throws' clause of a method, whose type is referenced - * by this type reference. This method must only be used for type references whose sort is {@link - * #THROWS}. - * - * @return the index of an exception in the 'throws' clause of a method. - */ - public int getExceptionIndex() { - return (targetTypeAndInfo & 0x00FFFF00) >> 8; - } - - /** - * Returns the index of the try catch block (using the order in which they are visited with - * visitTryCatchBlock), whose 'catch' type is referenced by this type reference. This method must - * only be used for type references whose sort is {@link #EXCEPTION_PARAMETER} . - * - * @return the index of an exception in the 'throws' clause of a method. - */ - public int getTryCatchBlockIndex() { - return (targetTypeAndInfo & 0x00FFFF00) >> 8; - } - - /** - * Returns the index of the type argument referenced by this type reference. This method must only - * be used for type references whose sort is {@link #CAST}, {@link - * #CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT}, {@link #METHOD_INVOCATION_TYPE_ARGUMENT}, {@link - * #CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT}, or {@link #METHOD_REFERENCE_TYPE_ARGUMENT}. - * - * @return a type parameter index. - */ - public int getTypeArgumentIndex() { - return targetTypeAndInfo & 0xFF; - } - - /** - * Returns the int encoded value of this type reference, suitable for use in visit methods related - * to type annotations, like visitTypeAnnotation. - * - * @return the int encoded value of this type reference. - */ - public int getValue() { - return targetTypeAndInfo; - } - - /** - * Puts the given target_type and target_info JVMS structures into the given ByteVector. - * - * @param targetTypeAndInfo a target_type and a target_info structures encoded as in {@link - * #targetTypeAndInfo}. LOCAL_VARIABLE and RESOURCE_VARIABLE target types are not supported. - * @param output where the type reference must be put. - */ - static void putTarget(final int targetTypeAndInfo, final ByteVector output) { - switch (targetTypeAndInfo >>> 24) { - case CLASS_TYPE_PARAMETER: - case METHOD_TYPE_PARAMETER: - case METHOD_FORMAL_PARAMETER: - output.putShort(targetTypeAndInfo >>> 16); - break; - case FIELD: - case METHOD_RETURN: - case METHOD_RECEIVER: - output.putByte(targetTypeAndInfo >>> 24); - break; - case CAST: - case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: - case METHOD_INVOCATION_TYPE_ARGUMENT: - case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: - case METHOD_REFERENCE_TYPE_ARGUMENT: - output.putInt(targetTypeAndInfo); - break; - case CLASS_EXTENDS: - case CLASS_TYPE_PARAMETER_BOUND: - case METHOD_TYPE_PARAMETER_BOUND: - case THROWS: - case EXCEPTION_PARAMETER: - case INSTANCEOF: - case NEW: - case CONSTRUCTOR_REFERENCE: - case METHOD_REFERENCE: - output.put12(targetTypeAndInfo >>> 24, (targetTypeAndInfo & 0xFFFF00) >> 8); - break; - default: - throw new IllegalArgumentException(); - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/signature/SignatureReader.java b/jodd-proxetta/src/main/java/jodd/asm7/signature/SignatureReader.java deleted file mode 100644 index 35c1b35bd..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/signature/SignatureReader.java +++ /dev/null @@ -1,252 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7.signature; - -/** - * A parser for signature literals, as defined in the Java Virtual Machine Specification (JVMS), to - * visit them with a SignatureVisitor. - * - * @see JVMS - * 4.7.9.1 - * @author Thomas Hallgren - * @author Eric Bruneton - */ -public class SignatureReader { - - /** The JVMS signature to be read. */ - private final String signatureValue; - - /** - * Constructs a {@link SignatureReader} for the given signature. - * - * @param signature A JavaTypeSignature, ClassSignature or MethodSignature. - */ - public SignatureReader(final String signature) { - this.signatureValue = signature; - } - - /** - * Makes the given visitor visit the signature of this {@link SignatureReader}. This signature is - * the one specified in the constructor (see {@link #SignatureReader}). This method is intended to - * be called on a {@link SignatureReader} that was created using a ClassSignature (such as - * the signature parameter of the {@link ClassVisitor#visit} - * method) or a MethodSignature (such as the signature parameter of the {@link - * ClassVisitor#visitMethod} method). - * - * @param signatureVistor the visitor that must visit this signature. - */ - public void accept(final SignatureVisitor signatureVistor) { - String signature = this.signatureValue; - int length = signature.length(); - int offset; // Current offset in the parsed signature (parsed from left to right). - char currentChar; // The signature character at 'offset', or just before. - - // If the signature starts with '<', it starts with TypeParameters, i.e. a formal type parameter - // identifier, followed by one or more pair ':',ReferenceTypeSignature (for its class bound and - // interface bounds). - if (signature.charAt(0) == '<') { - // Invariant: offset points to the second character of a formal type parameter name at the - // beginning of each iteration of the loop below. - offset = 2; - do { - // The formal type parameter name is everything between offset - 1 and the first ':'. - int classBoundStartOffset = signature.indexOf(':', offset); - signatureVistor.visitFormalTypeParameter( - signature.substring(offset - 1, classBoundStartOffset)); - - // If the character after the ':' class bound marker is not the start of a - // ReferenceTypeSignature, it means the class bound is empty (which is a valid case). - offset = classBoundStartOffset + 1; - currentChar = signature.charAt(offset); - if (currentChar == 'L' || currentChar == '[' || currentChar == 'T') { - offset = parseType(signature, offset, signatureVistor.visitClassBound()); - } - - // While the character after the class bound or after the last parsed interface bound - // is ':', we need to parse another interface bound. - while ((currentChar = signature.charAt(offset++)) == ':') { - offset = parseType(signature, offset, signatureVistor.visitInterfaceBound()); - } - - // At this point a TypeParameter has been fully parsed, and we need to parse the next one - // (note that currentChar is now the first character of the next TypeParameter, and that - // offset points to the second character), unless the character just after this - // TypeParameter signals the end of the TypeParameters. - } while (currentChar != '>'); - } else { - offset = 0; - } - - // If the (optional) TypeParameters is followed by '(' this means we are parsing a - // MethodSignature, which has JavaTypeSignature type inside parentheses, followed by a Result - // type and optional ThrowsSignature types. - if (signature.charAt(offset) == '(') { - offset++; - while (signature.charAt(offset) != ')') { - offset = parseType(signature, offset, signatureVistor.visitParameterType()); - } - // Use offset + 1 to skip ')'. - offset = parseType(signature, offset + 1, signatureVistor.visitReturnType()); - while (offset < length) { - // Use offset + 1 to skip the first character of a ThrowsSignature, i.e. '^'. - offset = parseType(signature, offset + 1, signatureVistor.visitExceptionType()); - } - } else { - // Otherwise we are parsing a ClassSignature (by hypothesis on the method input), which has - // one or more ClassTypeSignature for the super class and the implemented interfaces. - offset = parseType(signature, offset, signatureVistor.visitSuperclass()); - while (offset < length) { - offset = parseType(signature, offset, signatureVistor.visitInterface()); - } - } - } - - /** - * Makes the given visitor visit the signature of this {@link SignatureReader}. This signature is - * the one specified in the constructor (see {@link #SignatureReader}). This method is intended to - * be called on a {@link SignatureReader} that was created using a JavaTypeSignature, such - * as the signature parameter of the {@link - * ClassVisitor#visitField} or {@link - * MethodVisitor#visitLocalVariable} methods. - * - * @param signatureVisitor the visitor that must visit this signature. - */ - public void acceptType(final SignatureVisitor signatureVisitor) { - parseType(signatureValue, 0, signatureVisitor); - } - - /** - * Parses a JavaTypeSignature and makes the given visitor visit it. - * - * @param signature a string containing the signature that must be parsed. - * @param startOffset index of the first character of the signature to parsed. - * @param signatureVisitor the visitor that must visit this signature. - * @return the index of the first character after the parsed signature. - */ - private static int parseType( - final String signature, final int startOffset, final SignatureVisitor signatureVisitor) { - int offset = startOffset; // Current offset in the parsed signature. - char currentChar = signature.charAt(offset++); // The signature character at 'offset'. - - // Switch based on the first character of the JavaTypeSignature, which indicates its kind. - switch (currentChar) { - case 'Z': - case 'C': - case 'B': - case 'S': - case 'I': - case 'F': - case 'J': - case 'D': - case 'V': - // Case of a BaseType or a VoidDescriptor. - signatureVisitor.visitBaseType(currentChar); - return offset; - - case '[': - // Case of an ArrayTypeSignature, a '[' followed by a JavaTypeSignature. - return parseType(signature, offset, signatureVisitor.visitArrayType()); - - case 'T': - // Case of TypeVariableSignature, an identifier between 'T' and ';'. - int endOffset = signature.indexOf(';', offset); - signatureVisitor.visitTypeVariable(signature.substring(offset, endOffset)); - return endOffset + 1; - - case 'L': - // Case of a ClassTypeSignature, which ends with ';'. - // These signatures have a main class type followed by zero or more inner class types - // (separated by '.'). Each can have type arguments, inside '<' and '>'. - int start = offset; // The start offset of the currently parsed main or inner class name. - boolean visited = false; // Whether the currently parsed class name has been visited. - boolean inner = false; // Whether we are currently parsing an inner class type. - // Parses the signature, one character at a time. - while (true) { - currentChar = signature.charAt(offset++); - if (currentChar == '.' || currentChar == ';') { - // If a '.' or ';' is encountered, this means we have fully parsed the main class name - // or an inner class name. This name may already have been visited it is was followed by - // type arguments between '<' and '>'. If not, we need to visit it here. - if (!visited) { - String name = signature.substring(start, offset - 1); - if (inner) { - signatureVisitor.visitInnerClassType(name); - } else { - signatureVisitor.visitClassType(name); - } - } - // If we reached the end of the ClassTypeSignature return, otherwise start the parsing - // of a new class name, which is necessarily an inner class name. - if (currentChar == ';') { - signatureVisitor.visitEnd(); - break; - } - start = offset; - visited = false; - inner = true; - } else if (currentChar == '<') { - // If a '<' is encountered, this means we have fully parsed the main class name or an - // inner class name, and that we now need to parse TypeArguments. First, we need to - // visit the parsed class name. - String name = signature.substring(start, offset - 1); - if (inner) { - signatureVisitor.visitInnerClassType(name); - } else { - signatureVisitor.visitClassType(name); - } - visited = true; - // Now, parse the TypeArgument(s), one at a time. - while ((currentChar = signature.charAt(offset)) != '>') { - switch (currentChar) { - case '*': - // Unbounded TypeArgument. - ++offset; - signatureVisitor.visitTypeArgument(); - break; - case '+': - case '-': - // Extends or Super TypeArgument. Use offset + 1 to skip the '+' or '-'. - offset = - parseType( - signature, offset + 1, signatureVisitor.visitTypeArgument(currentChar)); - break; - default: - // Instanceof TypeArgument. The '=' is implicit. - offset = parseType(signature, offset, signatureVisitor.visitTypeArgument('=')); - break; - } - } - } - } - return offset; - - default: - throw new IllegalArgumentException(); - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/asm7/signature/SignatureVisitor.java b/jodd-proxetta/src/main/java/jodd/asm7/signature/SignatureVisitor.java deleted file mode 100644 index 3b9a7d39a..000000000 --- a/jodd-proxetta/src/main/java/jodd/asm7/signature/SignatureVisitor.java +++ /dev/null @@ -1,203 +0,0 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package jodd.asm7.signature; - -import jodd.asm7.Opcodes; - -/** - * A visitor to visit a generic signature. The methods of this interface must be called in one of - * the three following orders (the last one is the only valid order for a {@link SignatureVisitor} - * that is returned by a method of this interface): - * - *

    - *
  • ClassSignature = ( {@code visitFormalTypeParameter} {@code visitClassBound}? {@code - * visitInterfaceBound}* )* ({@code visitSuperclass} {@code visitInterface}* ) - *
  • MethodSignature = ( {@code visitFormalTypeParameter} {@code visitClassBound}? {@code - * visitInterfaceBound}* )* ({@code visitParameterType}* {@code visitReturnType} {@code - * visitExceptionType}* ) - *
  • TypeSignature = {@code visitBaseType} | {@code visitTypeVariable} | {@code - * visitArrayType} | ( {@code visitClassType} {@code visitTypeArgument}* ( {@code - * visitInnerClassType} {@code visitTypeArgument}* )* {@code visitEnd} ) ) - *
- * - * @author Thomas Hallgren - * @author Eric Bruneton - */ -public abstract class SignatureVisitor { - - /** Wildcard for an "extends" type argument. */ - public static final char EXTENDS = '+'; - - /** Wildcard for a "super" type argument. */ - public static final char SUPER = '-'; - - /** Wildcard for a normal type argument. */ - public static final char INSTANCEOF = '='; - - /** - * The ASM API version implemented by this visitor. The value of this field must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - */ - protected final int api; - - /** - * Constructs a new {@link SignatureVisitor}. - * - * @param api the ASM API version implemented by this visitor. Must be one of {@link - * Opcodes#ASM4}, {@link Opcodes#ASM5}, {@link Opcodes#ASM6} or {@link Opcodes#ASM7}. - */ - public SignatureVisitor(final int api) { - if (api != Opcodes.ASM7 && api != Opcodes.ASM6 && api != Opcodes.ASM5 && api != Opcodes.ASM4) { - throw new IllegalArgumentException("Unsupported api " + api); - } - this.api = api; - } - - /** - * Visits a formal type parameter. - * - * @param name the name of the formal parameter. - */ - public void visitFormalTypeParameter(final String name) {} - - /** - * Visits the class bound of the last visited formal type parameter. - * - * @return a non null visitor to visit the signature of the class bound. - */ - public SignatureVisitor visitClassBound() { - return this; - } - - /** - * Visits an interface bound of the last visited formal type parameter. - * - * @return a non null visitor to visit the signature of the interface bound. - */ - public SignatureVisitor visitInterfaceBound() { - return this; - } - - /** - * Visits the type of the super class. - * - * @return a non null visitor to visit the signature of the super class type. - */ - public SignatureVisitor visitSuperclass() { - return this; - } - - /** - * Visits the type of an interface implemented by the class. - * - * @return a non null visitor to visit the signature of the interface type. - */ - public SignatureVisitor visitInterface() { - return this; - } - - /** - * Visits the type of a method parameter. - * - * @return a non null visitor to visit the signature of the parameter type. - */ - public SignatureVisitor visitParameterType() { - return this; - } - - /** - * Visits the return type of the method. - * - * @return a non null visitor to visit the signature of the return type. - */ - public SignatureVisitor visitReturnType() { - return this; - } - - /** - * Visits the type of a method exception. - * - * @return a non null visitor to visit the signature of the exception type. - */ - public SignatureVisitor visitExceptionType() { - return this; - } - - /** - * Visits a signature corresponding to a primitive type. - * - * @param descriptor the descriptor of the primitive type, or 'V' for {@code void} . - */ - public void visitBaseType(final char descriptor) {} - - /** - * Visits a signature corresponding to a type variable. - * - * @param name the name of the type variable. - */ - public void visitTypeVariable(final String name) {} - - /** - * Visits a signature corresponding to an array type. - * - * @return a non null visitor to visit the signature of the array element type. - */ - public SignatureVisitor visitArrayType() { - return this; - } - - /** - * Starts the visit of a signature corresponding to a class or interface type. - * - * @param name the internal name of the class or interface. - */ - public void visitClassType(final String name) {} - - /** - * Visits an inner class. - * - * @param name the local name of the inner class in its enclosing class. - */ - public void visitInnerClassType(final String name) {} - - /** Visits an unbounded type argument of the last visited class or inner class type. */ - public void visitTypeArgument() {} - - /** - * Visits a type argument of the last visited class or inner class type. - * - * @param wildcard '+', '-' or '='. - * @return a non null visitor to visit the signature of the type argument. - */ - public SignatureVisitor visitTypeArgument(final char wildcard) { - return this; - } - - /** Ends the visit of a signature corresponding to a class or interface type. */ - public void visitEnd() {} -} diff --git a/jodd-proxetta/src/main/java/jodd/methref/InterfaceImplementation.java b/jodd-proxetta/src/main/java/jodd/methref/InterfaceImplementation.java deleted file mode 100644 index c06b49396..000000000 --- a/jodd-proxetta/src/main/java/jodd/methref/InterfaceImplementation.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.methref; - -import java.lang.reflect.Proxy; - -public class InterfaceImplementation { - private final Class target; - - private InterfaceImplementation(final Class target) { - this.target = target; - } - - public static InterfaceImplementation of(final Class target) { - return new InterfaceImplementation<>(target); - } - - @SuppressWarnings("unchecked") - public C createInstanceFor(final Methref m) { - return (C) Proxy.newProxyInstance( - target.getClassLoader(), - new Class[]{target}, - new InterfaceMethodInvocationHandler(m) - ); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/methref/InterfaceMethodInvocationHandler.java b/jodd-proxetta/src/main/java/jodd/methref/InterfaceMethodInvocationHandler.java deleted file mode 100644 index c0e0fc30e..000000000 --- a/jodd-proxetta/src/main/java/jodd/methref/InterfaceMethodInvocationHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package jodd.methref; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; - -@SuppressWarnings("rawtypes") -public class InterfaceMethodInvocationHandler implements InvocationHandler { - private final Methref methref; - - public InterfaceMethodInvocationHandler(final Methref methref) { - this.methref = methref; - } - - @Override - public Object invoke(final Object proxy, final Method method, final Object[] args) { - final String method_name = method.getName(); - methref.lastName(method_name); - if (method.getReturnType().isPrimitive()) { - final Class primitiveReturnType = method.getReturnType(); - if (primitiveReturnType.equals(boolean.class)) { - return false; - } - return 0; - } - return null; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/methref/Methref.java b/jodd-proxetta/src/main/java/jodd/methref/Methref.java deleted file mode 100644 index ead26bd08..000000000 --- a/jodd-proxetta/src/main/java/jodd/methref/Methref.java +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.methref; - -import jodd.proxetta.ProxettaUtil; -import jodd.util.ClassUtil; -import jodd.util.TypeCache; - -import java.lang.reflect.Field; -import java.util.function.Consumer; - -/** - * Super tool for getting method references (names) in compile-time. - */ -@SuppressWarnings({"UnusedDeclaration"}) -public class Methref { - - public static TypeCache cache = TypeCache.create().threadsafe(true).get(); - - private static final MethrefProxetta proxetta = new MethrefProxetta(); - - private final C instance; - /** - * Last called method name. Don't use this field directly. - */ - private String lastName; - - - /** - * Creates new proxified instance of target. - * Proxy classes are cached. If given target is also - * proxified, it's real target will be used. - */ - @SuppressWarnings({"unchecked"}) - public Methref(Class target) { - target = ProxettaUtil.resolveTargetClass(target); - - if (target.isInterface()) { - this.instance = InterfaceImplementation.of(target).createInstanceFor(this); - return; - } - - final Class proxyClass = cache.get(target, proxetta::defineProxy); - - final C proxy; - - try { - proxy = (C) ClassUtil.newInstance(proxyClass); - injectMethref(proxy); - } catch (final Exception ex) { - throw new MethrefException(ex); - } - - this.instance = proxy; - } - - // ---------------------------------------------------------------- use - - /** - * Static factory, for convenient use. - */ - public static Methref of(final Class target) { - return new Methref<>(target); - } - - /** - * Returns name of called method. - */ - public String name(final Consumer consumer) { - consumer.accept(proxy()); - return lastName(); - } - - - // ---------------------------------------------------------------- proxy method - - private boolean injectedMethref = false; - - /** - * Returns proxy instance that is ready to collect the method name of invoked methods. - */ - public C proxy() { - if (!injectedMethref) { - - injectedMethref = true; - } - return instance; - } - - /** - * Returns {@code true} if given object is proxified by this Methref. - */ - public boolean isMyProxy(final Object instance) { - final Methref usedMethref = readMethref(instance); - return this == usedMethref; - } - - /** - * Returns method name of last invoked method on a proxy. - */ - public static String lastName(final Object instance) { - final Methref m = readMethref(instance); - if (m == null) { - return null; - } - return m.lastName; - } - - /** - * Returns name of last method invoked on proxy. - */ - public String lastName() { - return lastName; - } - - public void lastName(final String name) { - this.lastName = name; - } - - - // ---------------------------------------------------------------- detect - - private void injectMethref(final C instance) { - try { - final Field f = instance.getClass().getDeclaredField("$__methref$0"); - f.setAccessible(true); - f.set(instance, this); - } catch (final Exception ex) { - if (ex instanceof MethrefException) { - throw ((MethrefException) ex); - } - throw new MethrefException("Methref field not found", ex); - } - } - - private static Methref readMethref(final Object instance) { - try { - final Field f = instance.getClass().getDeclaredField("$__methref$0"); - f.setAccessible(true); - return (Methref) f.get(instance); - } catch (final Exception ex) { - if (ex instanceof MethrefException) { - throw ((MethrefException) ex); - } - return null; - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/methref/MethrefAdvice.java b/jodd-proxetta/src/main/java/jodd/methref/MethrefAdvice.java deleted file mode 100644 index bfa6fc961..000000000 --- a/jodd-proxetta/src/main/java/jodd/methref/MethrefAdvice.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.methref; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -import static jodd.proxetta.ProxyTarget.returnType; -import static jodd.proxetta.ProxyTarget.targetMethodName; - -/** - * Methref advice applied on all methods. It puts method name in - * class variable that can be accessed later using reflection. - */ -public class MethrefAdvice implements ProxyAdvice { - - Methref methref; - - /** - * Reads method name and stores it in local variable. - * For methods that return String returns the method name, - * otherwise returns null. - */ - @Override - public Object execute() { - methref.lastName(targetMethodName()); - - final Class returnType = returnType(); - - if (returnType == String.class) { - return ProxyTarget.returnValue(targetMethodName()); - } - return ProxyTarget.returnValue(null); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/methref/MethrefException.java b/jodd-proxetta/src/main/java/jodd/methref/MethrefException.java deleted file mode 100644 index 3127233b3..000000000 --- a/jodd-proxetta/src/main/java/jodd/methref/MethrefException.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.methref; - -import jodd.proxetta.ProxettaException; - -/** - * Methref exception. - */ -public class MethrefException extends ProxettaException { - - public MethrefException(final Throwable throwable) { - super(throwable); - } - - public MethrefException(final String string) { - super(string); - } - - public MethrefException(final String string, final Throwable throwable) { - super(string, throwable); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/methref/MethrefProxetta.java b/jodd-proxetta/src/main/java/jodd/methref/MethrefProxetta.java deleted file mode 100644 index 3a7b9106d..000000000 --- a/jodd-proxetta/src/main/java/jodd/methref/MethrefProxetta.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.methref; - -import jodd.proxetta.Proxetta; -import jodd.proxetta.ProxyAspect; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.impl.ProxyProxettaFactory; -import jodd.proxetta.pointcuts.AllMethodsPointcut; - -/** - * Methref Proxetta builder and holder and facade. - */ -public class MethrefProxetta { - - protected final ProxyProxetta proxetta; - - public static final String METHREF_CLASSNAME_SUFFIX = "$Methref"; - - public MethrefProxetta() { - ProxyAspect aspects = new ProxyAspect(MethrefAdvice.class, new AllMethodsPointcut()); - - proxetta = Proxetta.proxyProxetta().withAspect(aspects); - - proxetta.setClassNameSuffix(METHREF_CLASSNAME_SUFFIX); - } - - /** - * Generates new class. - */ - public Class defineProxy(final Class target) { - ProxyProxettaFactory builder = proxetta.proxy(); - builder.setTarget(target); - return builder.define(); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/methref/package-info.java b/jodd-proxetta/src/main/java/jodd/methref/package-info.java deleted file mode 100644 index e0d5dd0dc..000000000 --- a/jodd-proxetta/src/main/java/jodd/methref/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Strong typed method name references. - */ -package jodd.methref; \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/paramo/MethodFinder.java b/jodd-proxetta/src/main/java/jodd/paramo/MethodFinder.java deleted file mode 100644 index e68c76462..000000000 --- a/jodd-proxetta/src/main/java/jodd/paramo/MethodFinder.java +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.paramo; - -import jodd.asm.EmptyClassVisitor; -import jodd.asm7.MethodVisitor; -import jodd.asm7.Type; - -import java.lang.reflect.Modifier; -import java.lang.reflect.Parameter; -import java.util.HashMap; -import java.util.Map; - -/** - * Lookups for specific method in order to start with - * {@link jodd.paramo.ParamExtractor parameter extraction}. - */ -final class MethodFinder extends EmptyClassVisitor { - - private static final Map primitives = new HashMap<>(8); - - private static final String TYPE_INT = "int"; - private static final String TYPE_BOOLEAN = "boolean"; - private static final String TYPE_BYTE = "byte"; - private static final String TYPE_CHAR = "char"; - private static final String TYPE_SHORT = "short"; - private static final String TYPE_FLOAT = "float"; - private static final String TYPE_LONG = "long"; - private static final String TYPE_DOUBLE = "double"; - private static final String ARRAY = "[]"; - - static { - primitives.put(TYPE_INT, "I"); - primitives.put(TYPE_BOOLEAN, "Z"); - primitives.put(TYPE_CHAR, "C"); - primitives.put(TYPE_BYTE, "B"); - primitives.put(TYPE_FLOAT, "F"); - primitives.put(TYPE_LONG, "J"); - primitives.put(TYPE_DOUBLE, "D"); - primitives.put(TYPE_SHORT, "S"); - } - - private final Class declaringClass; - private final String methodName; - private final Class[] parameterTypes; - private final Parameter[] parameters; - private ParamExtractor paramExtractor; - - MethodFinder( - final Class declaringClass, - final String methodName, - final Class[] parameterTypes, - final Parameter[] parameters) - { - this.declaringClass = declaringClass; - this.methodName = methodName; - this.parameterTypes = parameterTypes; - this.parameters = parameters; - this.paramExtractor = null; - } - - @Override - public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { - if (paramExtractor != null) { - return null; // method already found, skip all further methods - } - if (!name.equals(methodName)) { - return null; // different method - } - - final Type[] argumentTypes = Type.getArgumentTypes(desc); - int dwordsCount = 0; - for (final Type t : argumentTypes) { - if (t.getClassName().equals(TYPE_LONG) || t.getClassName().equals(TYPE_DOUBLE)) { - dwordsCount++; - } - } - - final int paramCount = argumentTypes.length; - if (paramCount != this.parameterTypes.length) { - return null; // different number of params - } - - for (int i = 0; i < argumentTypes.length; i++) { - if (!isEqualTypeName(argumentTypes[i], this.parameterTypes[i])) { - return null; // wrong param types - } - } - - this.paramExtractor = new ParamExtractor( - (Modifier.isStatic(access) ? 0 : 1), - argumentTypes.length + dwordsCount, - parameters); - return paramExtractor; - } - - /** - * Returns true if type name equals param type. - */ - boolean isEqualTypeName(final Type argumentType, final Class paramType) { - String s = argumentType.getClassName(); - if (s.endsWith(ARRAY)) { // arrays detected - final String prefix = s.substring(0, s.length() - 2); - final String bytecodeSymbol = primitives.get(prefix); - if (bytecodeSymbol != null) { - s = '[' + bytecodeSymbol; - } else { - s = "[L" + prefix + ';'; - } - } - return s.equals(paramType.getName()); - } - - - /** - * Returns method parameters once when method is parsed. - * If method has no parameters, an empty array is returned. - */ - MethodParameter[] getResolvedParameters() { - if (paramExtractor == null) { - return MethodParameter.EMPTY_ARRAY; - } - if (!paramExtractor.debugInfoPresent) { - throw new ParamoException("Parameter names not available for method: " - + declaringClass.getName() + '#' + methodName); - } - return paramExtractor.getMethodParameters(); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/paramo/MethodParameter.java b/jodd-proxetta/src/main/java/jodd/paramo/MethodParameter.java deleted file mode 100644 index 11d0388fc..000000000 --- a/jodd-proxetta/src/main/java/jodd/paramo/MethodParameter.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.paramo; - -import java.lang.reflect.Parameter; - -/** - * Resolved method parameter from bytecode. - * It consist of parameter name and parameter bytecode signature - * (including generics info). - */ -public class MethodParameter { - - public static final MethodParameter[] EMPTY_ARRAY = new MethodParameter[0]; - - private final String name; - private final String signature; - private final Parameter parameter; - - public MethodParameter(final String name, final String signature, final Parameter parameter) { - this.name = name; - this.signature = signature; - this.parameter = parameter; - } - - /** - * Returns method parameter name. - */ - public String getName() { - return name; - } - - /** - * Returns method parameter signature. - * Generics information is available, too. - */ - public String getSignature() { - return signature; - } - - /** - * Returns parameter. - */ - public Parameter getParameter() { - return parameter; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/paramo/ParamExtractor.java b/jodd-proxetta/src/main/java/jodd/paramo/ParamExtractor.java deleted file mode 100644 index 230a3de25..000000000 --- a/jodd-proxetta/src/main/java/jodd/paramo/ParamExtractor.java +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.paramo; - -import jodd.asm.EmptyMethodVisitor; -import jodd.asm7.Label; -import jodd.util.ArraysUtil; - -import java.lang.reflect.Parameter; - -/** - * Extracts param information from a method. - */ -final class ParamExtractor extends EmptyMethodVisitor { - - private final int paramCount; - private final int ignoreCount; - private final Parameter[] parameters; - private MethodParameter[] methodParameters; - private int currentParam; - boolean debugInfoPresent; - - ParamExtractor(final int ignoreCount, final int paramCount, final Parameter[] parameters) { - this.ignoreCount = ignoreCount; - this.paramCount = paramCount; - this.methodParameters = new MethodParameter[paramCount]; - this.currentParam = 0; - this.debugInfoPresent = paramCount == 0; - this.parameters = parameters;// for 0 params, no need for debug info - } - - @Override - public void visitLocalVariable(final String name, final String desc, String signature, final Label start, final Label end, final int index) { - if ((index >= ignoreCount) && (index < (ignoreCount + paramCount))) { - if (!name.equals("arg" + currentParam)) { - debugInfoPresent = true; - } - if (signature == null) { - signature = desc; - } - methodParameters[currentParam] = new MethodParameter( - name, signature, parameters[currentParam]); - currentParam++; - } - } - - @Override - public void visitEnd() { - if (methodParameters.length > currentParam) { - methodParameters = ArraysUtil.subarray(methodParameters, 0, currentParam); - } - } - - MethodParameter[] getMethodParameters() { - return methodParameters; - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/paramo/Paramo.java b/jodd-proxetta/src/main/java/jodd/paramo/Paramo.java deleted file mode 100644 index 7f16e17cf..000000000 --- a/jodd-proxetta/src/main/java/jodd/paramo/Paramo.java +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.paramo; - -import jodd.asm7.ClassReader; -import jodd.io.IOUtil; -import jodd.util.ClassLoaderUtil; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; - -/** - * Extracts method or constructor parameter names from bytecode debug information in runtime. - */ -public class Paramo { - - protected static final String CTOR_METHOD = ""; - - /** - * Resolves method parameters from a method or constructor. - * Returns an empty array when target does not contain any parameter. - * No caching is involved in this process, i.e. class bytecode - * is examined every time this method is called. - */ - public static MethodParameter[] resolveParameters(final AccessibleObject methodOrCtor) { - final Class[] paramTypes; - final Parameter[] parameters; - final Class declaringClass; - final String name; - - if (methodOrCtor instanceof Method) { - final Method method = (Method) methodOrCtor; - paramTypes = method.getParameterTypes(); - name = method.getName(); - declaringClass = method.getDeclaringClass(); - parameters = method.getParameters(); - } else { - final Constructor constructor = (Constructor) methodOrCtor; - paramTypes = constructor.getParameterTypes(); - declaringClass = constructor.getDeclaringClass(); - name = CTOR_METHOD; - parameters = constructor.getParameters(); - } - - if (paramTypes.length == 0) { - return MethodParameter.EMPTY_ARRAY; - } - - final InputStream stream; - try { - stream = ClassLoaderUtil.getClassAsStream(declaringClass); - } catch (final IOException ioex) { - throw new ParamoException("Failed to read class bytes: " + declaringClass.getName(), ioex); - } - - if (stream == null) { - throw new ParamoException("Class not found: " + declaringClass); - } - - try { - final ClassReader reader = new ClassReader(stream); - final MethodFinder visitor = new MethodFinder(declaringClass, name, paramTypes, parameters); - reader.accept(visitor, 0); - return visitor.getResolvedParameters(); - } - catch (final IOException ioex) { - throw new ParamoException(ioex); - } - finally { - IOUtil.close(stream); - } - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/paramo/ParamoException.java b/jodd-proxetta/src/main/java/jodd/paramo/ParamoException.java deleted file mode 100644 index 589e09714..000000000 --- a/jodd-proxetta/src/main/java/jodd/paramo/ParamoException.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.paramo; - -import jodd.exception.UncheckedException; - -/** - * Exception thrown on {@link Paramo} problems. - */ -public class ParamoException extends UncheckedException { - - public ParamoException(final Throwable t) { - super(t); - } - - public ParamoException(final String message) { - super(message); - } - - public ParamoException(final String message, final Throwable t) { - super(message, t); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/paramo/package-info.java b/jodd-proxetta/src/main/java/jodd/paramo/package-info.java deleted file mode 100644 index 81f9d7d13..000000000 --- a/jodd-proxetta/src/main/java/jodd/paramo/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Paramo is small tool for resolving method parameter names in runtime. - */ -package jodd.paramo; \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/pathref/Pathref.java b/jodd-proxetta/src/main/java/jodd/pathref/Pathref.java deleted file mode 100644 index feda37e5f..000000000 --- a/jodd-proxetta/src/main/java/jodd/pathref/Pathref.java +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.pathref; - -import jodd.proxetta.ProxettaUtil; -import jodd.util.ClassUtil; -import jodd.util.StringPool; -import jodd.util.StringUtil; -import jodd.util.TypeCache; - -import java.lang.reflect.Field; -import java.util.function.Consumer; - -/** - * Super tool for getting calling path reference in compile-time. - */ -@SuppressWarnings({"UnusedDeclaration"}) -public class Pathref { - - public static final int ALL = -1; - - public static TypeCache cache = TypeCache.create().threadsafe(true).get(); - - private static final PathrefProxetta proxetta = new PathrefProxetta(); - - private final C instance; - - /** - * Creates new proxified instance of target. - * Proxy instances are cached. If given target is also - * proxified, it's real target will be used. - */ - @SuppressWarnings({"unchecked"}) - public Pathref(final Class target) { - final C proxy = createProxyObject(target); - - this.instance = proxy; - - injectPathRef(this, instance); - - this.path = StringPool.EMPTY; - } - - Pathref(final Class target, final Pathref root) { - final C proxy = createProxyObject(target); - - this.instance = proxy; - - injectPathRef(root, instance); - - this.path = null; - } - - /** - * Creates proxy object. - */ - protected C createProxyObject(Class target) { - target = ProxettaUtil.resolveTargetClass(target); - - final Class proxyClass = cache.get(target, proxetta::defineProxy); - - final C proxy; - - try { - proxy = (C) ClassUtil.newInstance(proxyClass); - } catch (final Exception ex) { - throw new PathrefException(ex); - } - - return proxy; - } - - protected String path; - - // ---------------------------------------------------------------- use - - /** - * Appends method name to existing path. - */ - protected void append(final String methodName) { - if (path.length() != 0) { - path += StringPool.DOT; - } - if (methodName.startsWith(StringPool.LEFT_SQ_BRACKET)) { - path = StringUtil.substring(path, 0, -1); - } - path += methodName; - } - - /** - * Static factory, for convenient use. - */ - public static Pathref of(final Class target) { - return new Pathref<>(target); - } - - /** - * Returns proxy instance of target class, so methods can be called - * immediately after (fluent interface). - */ - C get() { - path = StringPool.EMPTY; - return instance; - } - - public String path(final Consumer consumer) { - path = StringPool.EMPTY; - consumer.accept(proxy()); - return path(); - } - - protected static void injectPathRef(final Pathref pathref, final Object target) { - try { - final Field f = target.getClass().getDeclaredField("$__pathref$0"); - f.setAccessible(true); - f.set(target, new PathrefContinue(pathref)); - } catch (final Exception ex) { - throw new PathrefException("Pathref field not found", ex); - } - } - - // ---------------------------------------------------------------- - - public C proxy() { - return instance; - } - - public String path() { - final String collectedPath = path; - this.path = StringPool.EMPTY; - return collectedPath; - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/pathref/PathrefAdvice.java b/jodd-proxetta/src/main/java/jodd/pathref/PathrefAdvice.java deleted file mode 100644 index db85d9da8..000000000 --- a/jodd-proxetta/src/main/java/jodd/pathref/PathrefAdvice.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.pathref; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -import static jodd.proxetta.ProxyTarget.returnType; -import static jodd.proxetta.ProxyTarget.targetMethodName; - -/** - * Pathref advice applied on all methods. - */ -public class PathrefAdvice implements ProxyAdvice { - - PathrefContinue pathref; - - /** - * Reads method name and appends it. Creates object for next call and - * returns that value. If next object is unsupported, it will return null; - */ - @Override - public Object execute() { - final String methodName = targetMethodName(); - - final Class returnType = returnType(); - - final Object next = pathref.continueWith(this, methodName, returnType); - - return ProxyTarget.returnValue(next); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/pathref/PathrefContinue.java b/jodd-proxetta/src/main/java/jodd/pathref/PathrefContinue.java deleted file mode 100644 index 710ef2c34..000000000 --- a/jodd-proxetta/src/main/java/jodd/pathref/PathrefContinue.java +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.pathref; - -import jodd.util.ClassUtil; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -public class PathrefContinue { - - private final Pathref pathref; - - public PathrefContinue(final Pathref pathref) { - this.pathref = pathref; - } - - /** - * Factory of next target. It handles special cases of maps, sets - * and lists. In case target can not be proxified (like for Java classes) - * it returns null. - */ - @SuppressWarnings("unchecked") - public T continueWith(final Object currentInstance, final String methodName, final Class target) { - final Class currentClass = currentInstance.getClass(); - - final Method method; - - try { - method = currentClass.getDeclaredMethod(methodName); - } - catch (final NoSuchMethodException e) { - throw new PathrefException("Not a getter: " + methodName, e); - } - - if (!ClassUtil.isBeanPropertyGetter(method)) { - throw new PathrefException("Not a getter: " + methodName); - } - - final String getterName = ClassUtil.getBeanPropertyGetterName(method); - - pathref.append(getterName); - - if (ClassUtil.isTypeOf(target, List.class)) { - final Class componentType = - ClassUtil.getComponentType(method.getGenericReturnType(), currentClass, 0); - - if (componentType == null) { - throw new PathrefException("Unknown component name for: " + methodName); - } - - return (T) new ArrayList() { - @Override - public Object get(final int index) { - if (index >= 0) { - pathref.append("[" + index + "]"); - } - return new Pathref<>(componentType, pathref).get(); - } - }; - } - - try { - return new Pathref<>(target, pathref).get(); - } - catch (final Exception ex) { - return null; - } - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/pathref/PathrefException.java b/jodd-proxetta/src/main/java/jodd/pathref/PathrefException.java deleted file mode 100644 index f8663a476..000000000 --- a/jodd-proxetta/src/main/java/jodd/pathref/PathrefException.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.pathref; - -import jodd.proxetta.ProxettaException; - -/** - * Pathref exception. - */ -public class PathrefException extends ProxettaException { - - public PathrefException(final String message) { - super(message); - } - - public PathrefException(final Throwable throwable) { - super(throwable); - } - - public PathrefException(final String string, final Throwable throwable) { - super(string, throwable); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/pathref/PathrefProxetta.java b/jodd-proxetta/src/main/java/jodd/pathref/PathrefProxetta.java deleted file mode 100644 index c4f8ad6be..000000000 --- a/jodd-proxetta/src/main/java/jodd/pathref/PathrefProxetta.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.pathref; - -import jodd.proxetta.Proxetta; -import jodd.proxetta.ProxyAspect; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.impl.ProxyProxettaFactory; -import jodd.proxetta.pointcuts.AllMethodsPointcut; - -/** - * Methref Proxetta builder and holder and facade. - */ -public class PathrefProxetta { - - protected final ProxyProxetta proxetta; - - public static final String PATHREF_CLASSNAME_SUFFIX = "$Pathref"; - - public PathrefProxetta() { - ProxyAspect aspects = new ProxyAspect(PathrefAdvice.class, new AllMethodsPointcut()); - - proxetta = Proxetta.proxyProxetta().withAspect(aspects); - - proxetta.setClassNameSuffix(PATHREF_CLASSNAME_SUFFIX); - } - - /** - * Generates new class. - */ - public Class defineProxy(final Class target) { - ProxyProxettaFactory builder = proxetta.proxy(); - builder.setTarget(target); - return builder.define(); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/pathref/package-info.java b/jodd-proxetta/src/main/java/jodd/pathref/package-info.java deleted file mode 100644 index 78e83fd19..000000000 --- a/jodd-proxetta/src/main/java/jodd/pathref/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Resolver for calling path. - */ -package jodd.pathref; \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/AnnotationInfo.java b/jodd-proxetta/src/main/java/jodd/proxetta/AnnotationInfo.java deleted file mode 100644 index 2bb765ce4..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/AnnotationInfo.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import java.util.Set; - -/** - * Annotation information. - */ -public interface AnnotationInfo { - - String getAnnotationClassname(); - - String getAnnotationSignature(); - - boolean isVisible(); - - /** - * Lookups for annotation element. May return: - *
    - *
  • String - for simple values,
  • - *
  • Object[] - for array values
  • - *
  • String[2] - pair of two strings, representing description and value
  • - *
  • AnnotationInfo - nested annotation.
  • - *
- */ - Object getElement(String name); - - /** - * Returns annotation element names. - */ - Set getElementNames(); - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/ClassInfo.java b/jodd-proxetta/src/main/java/jodd/proxetta/ClassInfo.java deleted file mode 100644 index 615875571..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/ClassInfo.java +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import java.lang.annotation.Annotation; - -/** - * Various target class information. - */ -public interface ClassInfo { - - /** - * Returns package name. - */ - String getPackage(); - - /** - * Returns simple class name. - */ - String getClassname(); - - /** - * Returns super class reference. - */ - String getSuperName(); - - /** - * Returns class reference. - */ - String getReference(); - - /** - * Returns array of super classes. - */ - public String[] getSuperClasses(); - - /** - * Returns annotation information or null if target class has no annotations. - */ - AnnotationInfo[] getAnnotations(); - -// /** -// * Returns a map of generic definitions. Keys are map names and values are -// * raw types (after erasure). -// */ -// Map getGenerics(); - - // ---------------------------------------------------------------- annotations - - /** - * Finds annotation in class info. Returns null if annotation doesn't exist. - */ - default AnnotationInfo getAnnotation(final Class an) { - AnnotationInfo[] anns = getAnnotations(); - if (anns == null) { - return null; - } - String anName = an.getName(); - for (AnnotationInfo ann : anns) { - if (ann.getAnnotationClassname().equals(anName)) { - return ann; - } - } - return null; - } - - /** - * Returns true if class is annotated with one of provided annotation. - */ - default boolean hasAnnotation(final Class... an) { - AnnotationInfo[] anns = getAnnotations(); - if (anns == null) { - return false; - } - for (Class annotationClass : an) { - String anName = annotationClass.getName(); - for (AnnotationInfo ann : anns) { - if (ann.getAnnotationClassname().equals(anName)) { - return true; - } - } - } - return false; - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/GenericsReader.java b/jodd-proxetta/src/main/java/jodd/proxetta/GenericsReader.java deleted file mode 100644 index 1cb4cb7c6..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/GenericsReader.java +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.asm.TraceSignatureVisitor; -import jodd.asm7.signature.SignatureReader; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * Collector of generics information from the signature. - */ -public class GenericsReader { - - final Map genericsMap; - - public GenericsReader() { - this.genericsMap = new LinkedHashMap<>(); - } - - /** - * Parses signature for generic information and returns a map where key is generic name - * and value is raw type. Returns an empty map if signature does not define any generics. - */ - public Map parseSignatureForGenerics(final String signature, final boolean isInterface) { - - if (signature == null) { - return Collections.emptyMap(); - } - - final int indexOfBracket = signature.indexOf("<"); - final String declaringClass; - if (indexOfBracket > 0) { - declaringClass = signature.substring(1, indexOfBracket) + ":"; - } - else { - declaringClass = null; - } - - final SignatureReader sr = new SignatureReader(signature); - final StringBuilder sb = new StringBuilder(); - - TraceSignatureVisitor v = new TraceSignatureVisitor(sb, isInterface) { - String genericName; - int classTypeCounter = 0; - - @Override - public void visitFormalTypeParameter(final String name) { - genericName = name; - super.visitFormalTypeParameter(name); - } - - @Override - public void visitClassType(final String name) { - classTypeCounter++; - - if (genericName != null) { - genericsMap.put(genericName, 'L' + name + ';'); - genericName = null; - } else { - if (declaringClass != null) { - genericsMap.put(declaringClass + (classTypeCounter - 1), 'L' + name + ';'); - } - } - super.visitClassType(name); - } - - }; - sr.accept(v); - - return genericsMap; - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/InvokeAspect.java b/jodd-proxetta/src/main/java/jodd/proxetta/InvokeAspect.java deleted file mode 100644 index 004642bfb..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/InvokeAspect.java +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -/** - * Invoke aspect defines method pointcuts that should be replaced and - * their advice replacements. - */ -@FunctionalInterface -public interface InvokeAspect { - - /** - * Determines if some method should be scanned for pointcuts. - * Returns true if method should be scanned. - */ - default boolean apply(final MethodInfo methodInfo) { - return true; - } - - - /** - * Defines method invocation pointcut and returns replacement advice. - * Returns null if method doesn't have to be replaced at all. - *

- * Special case is new instruction. Since new opcode - * appears in the bytecode before actual constructor invocation, - * description of InvokeInfo is unknown. Therefore, for each - * constructor that will be replaced, there must be an advice replacement method - * with the same description. - */ - InvokeReplacer pointcut(InvokeInfo invokeInfo); - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/InvokeInfo.java b/jodd-proxetta/src/main/java/jodd/proxetta/InvokeInfo.java deleted file mode 100644 index 7e4dade84..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/InvokeInfo.java +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.asm.AsmUtil; -import jodd.mutable.MutableInteger; - -import java.util.ArrayList; -import java.util.List; - -/** - * Information about invocation. - */ -public class InvokeInfo { - - private final String owner; - private final String className; - private final String classShortName; - private final String methodName; - private final String description; - private final String returnType; - private final String signature; - private final String[] arguments; - - public InvokeInfo(final String owner, final String methodName, final String description) { - this.owner = owner; - this.className = owner.replace('/', '.'); - this.methodName = methodName; - this.description = description; - - // short name - int ndx = className.lastIndexOf('.'); - classShortName = ndx == -1 ? className : className.substring(ndx + 1); - - // arguments - List args = new ArrayList<>(); - MutableInteger from = new MutableInteger(1); - if (description.length() != 0) { - while (description.charAt(from.value) != ')') { - String a = AsmUtil.typedescToSignature(description, from); - args.add(a); - } - } - - arguments = new String[args.size()]; - args.toArray(arguments); - - from.value++; - returnType = description.length() > 0 ? - AsmUtil.typedescToSignature(description, from) : - className; - - StringBuilder s = new StringBuilder(); - s.append(returnType).append(' ').append(methodName).append('('); - for (int i = 0; i < arguments.length; i++) { - if (i != 0) { - s.append(',').append(' '); - } - String argument = arguments[i]; - s.append(argument); - } - s.append(')'); - - signature = s.toString(); - } - - // ---------------------------------------------------------------- getters - - /** - * Returns bytecode-like class that is method owner. - */ - public String getOwner() { - return owner; - } - - /** - * Returns java-like class name. - */ - public String getClassName() { - return className; - } - - /** - * Returns class short name, without a package. - */ - public String getClassShortName() { - return classShortName; - } - - /** - * Returns method name. - */ - public String getMethodName() { - return methodName; - } - - /** - * Returns bytecode-like method description. - */ - public String getDescription() { - return description; - } - - /** - * Returns java-like return type. - */ - public String getReturnType() { - return returnType; - } - - /** - * Returns java-like method signature. - */ - public String getSignature() { - return signature; - } - - /** - * Return arguments count. - */ - public int getArgumentsCount() { - return arguments.length; - } - - /** - * Return java-like argument types. - */ - public String[] getArguments() { - return arguments; - } - - @Override - public String toString() { - return "InvokeInfo: " + signature; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/InvokeReplacer.java b/jodd-proxetta/src/main/java/jodd/proxetta/InvokeReplacer.java deleted file mode 100644 index 61b48763b..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/InvokeReplacer.java +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -/** - * Invocation advice represents a method that will replace some invocation pointcut. - */ -public class InvokeReplacer { - - public static final InvokeReplacer NONE = new InvokeReplacer(); - - protected final String owner; - protected final String methodName; - - public InvokeReplacer(final Class target, final String methodName) { - this(target.getCanonicalName(), methodName); - } - - public InvokeReplacer(final String classCanonicalName, final String methodName) { - this.owner = classCanonicalName.replace('.', '/'); - this.methodName = methodName; - } - - InvokeReplacer() { - this.owner = null; - this.methodName = null; - } - - public static InvokeReplacer with(final String classCanonicalName, final String methodName) { - return new InvokeReplacer(classCanonicalName, methodName); - } - - public static InvokeReplacer with(final Class target, final String methodName) { - return new InvokeReplacer(target, methodName); - } - - // ---------------------------------------------------------------- getters - - public String getOwner() { - return owner; - } - - public String getMethodName() { - return methodName; - } - - // ---------------------------------------------------------------- settings - - protected boolean passOwnerName; - protected boolean passMethodName; - protected boolean passMethodSignature; - protected boolean passThis; - protected boolean passTargetClass; - - public boolean isPassOwnerName() { - return passOwnerName; - } - - public void setPassOwnerName(final boolean passOwnerName) { - this.passOwnerName = passOwnerName; - } - - public InvokeReplacer passOwnerName(final boolean passOwnerName) { - this.passOwnerName = passOwnerName; - return this; - } - - public boolean isPassMethodName() { - return passMethodName; - } - - public void setPassMethodName(final boolean passMethodName) { - this.passMethodName = passMethodName; - } - - public InvokeReplacer passMethodName(final boolean passMethodName) { - this.passMethodName = passMethodName; - return this; - } - - public boolean isPassMethodSignature() { - return passMethodSignature; - } - - public void setPassMethodSignature(final boolean passMethodSignature) { - this.passMethodSignature = passMethodSignature; - } - - public InvokeReplacer passMethodSignature(final boolean passMethodSignature) { - this.passMethodSignature = passMethodSignature; - return this; - } - - public boolean isPassThis() { - return passThis; - } - - public void setPassThis(final boolean passThis) { - this.passThis = passThis; - } - - public InvokeReplacer passThis(final boolean passThis) { - this.passThis = passThis; - return this; - } - - public boolean isPassTargetClass() { - return passTargetClass; - } - - public void setPassTargetClass(final boolean passTargetClass) { - this.passTargetClass = passTargetClass; - } - - public InvokeReplacer passTargetClass(final boolean passTargetClass) { - this.passTargetClass = passTargetClass; - return this; - } - - /** - * Returns true if this InvokeReplaces is {@link #NONE}. - */ - public boolean isNone() { - return owner == null; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/MethodInfo.java b/jodd-proxetta/src/main/java/jodd/proxetta/MethodInfo.java deleted file mode 100644 index 20bfc839f..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/MethodInfo.java +++ /dev/null @@ -1,265 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.asm.AsmUtil; -import jodd.util.StringUtil; -import jodd.util.Wildcard; - -import java.lang.annotation.Annotation; - -/** - * Method info provides various information about a method. There are two types - * of information: - *

    - *
  • java-like, user-readable, that matches the java code, where, for example, - * packages in class names are separated with a dot; - *
  • - *
  • - * bytecode-related, where information is more suitable for bytecodes, - * where, for example, packages in class names are separated with a slash. - *
  • - *
- */ -public interface MethodInfo { - - /** - * Returns full java-like declaration of method's arguments and return type. - * For example: {@code (long, java.lang.Integer)int}. - * @see #getSignature() - */ - String getDeclaration(); - - /** - * Returns return {@link TypeInfo type information}. - */ - TypeInfo getReturnType(); - - /** - * Returns exceptions as a comma-seaprated string. - * @see #getExceptions() - */ - default String getExceptionsAsString() { - if (getExceptions() == null) { - return null; - } - - return StringUtil.join(getExceptions(),','); - } - - /** - * Returns array of exceptions or {@code null} if no exception is declared. - */ - String[] getExceptions(); - - /** - * Returns java-like method signature of {@link #getDescription description}. - * Does not contain any generic information. - */ - String getSignature(); - - /** - * Returns a "clean" signature, that is ready for the comparison. - * It does not have any generics information. - */ - String getCleanSignature(); - - /** - * Returns method name. - */ - String getMethodName(); - - /** - * Returns the number of methods arguments. - */ - int getArgumentsCount(); - - /** - * Returns bytecode offset of an argument in local variables. - */ - int getArgumentOffset(int index); - - /** - * Returns methods argument (1-indexed). - */ - TypeInfo getArgument(int index); - - /** - * Returns the size of all arguments on stack. - * It is not equal to argument count, because some types - * takes 2 places, like long. - */ - int getAllArgumentsSize(); - - /** - * Returns methods access flags. - */ - int getAccessFlags(); - - /** - * Returns bytecode-like class name, where packages are separated by a slash. - * For example: {@code org/jodd/Jodd} - */ - String getClassname(); - - /** - * Returns bytecode-like method description. - * @see #getSignature() - */ - String getDescription(); - - /** - * Returns annotation information, if there is any. - */ - AnnotationInfo[] getAnnotations(); - - /** - * Returns declared class name for inner methods or - * {@link #getClassname() classname} for top-level methods. - */ - String getDeclaredClassName(); - - /** - * Returns true if method is declared in top-level class. - */ - boolean isTopLevelMethod(); - - /** - * Returns target {@link jodd.proxetta.ClassInfo class informations}. - */ - ClassInfo getClassInfo(); - - // ---------------------------------------------------------------- utils - - /** - * Returns {@code true} if method is public. - */ - default boolean isPublicMethod() { - return (getAccessFlags() & AsmUtil.ACC_PUBLIC) != 0; - } - - /** - * Returns {@code true} if method is private. - */ - default boolean isPrivateMethod() { - return (getAccessFlags() & AsmUtil.ACC_PRIVATE) != 0; - } - - /** - * Returns true if method has no argument. - */ - default boolean hasNoArguments() { - return getArgumentsCount() == 0; - } - - /** - * Returns true if method has only one argument. - */ - default boolean hasOneArgument() { - return getArgumentsCount() == 1; - } - - /** - * Returns true if method is declared in Object class (root class). - */ - default boolean isRootMethod() { - return AsmUtil.SIGNATURE_JAVA_LANG_OBJECT.equals(getDeclaredClassName()); - } - - // ---------------------------------------------------------------- return - - - /** - * Returns true if method's return type is void. - */ - default boolean hasNoReturnValue() { - return getReturnType().getOpcode() == AsmUtil.TYPE_VOID; - } - - /** - * Returns true if method has a return type. - */ - default boolean hasReturnValue() { - return getReturnType().getOpcode() != AsmUtil.TYPE_VOID; - } - - // ---------------------------------------------------------------- wildcards - - /** - * Match method name to provided {@link jodd.util.Wildcard} pattern. - */ - default boolean matchMethodName(final String wildcard) { - return Wildcard.match(getMethodName(), wildcard); - } - - /** - * Match class name to provided {@link jodd.util.Wildcard} pattern. - */ - default boolean matchClassName(final String wildcard) { - return Wildcard.match(getClassname(), wildcard); - } - - // ---------------------------------------------------------------- annotations - - /** - * Returns true if method is annotated with one of provided annotation. - */ - default boolean hasAnnotation(final Class... an) { - AnnotationInfo[] anns = getAnnotations(); - if (anns == null) { - return false; - } - - for (Class annotationClass : an) { - String anName = annotationClass.getName(); - for (AnnotationInfo ann : anns) { - if (ann.getAnnotationClassname().equals(anName)) { - return true; - } - } - } - return false; - } - - /** - * Returns true if method is annotated with provided annotation. - */ - default AnnotationInfo getAnnotation(final Class an) { - AnnotationInfo[] anns = getAnnotations(); - if (anns == null) { - return null; - } - String anName = an.getName(); - for (AnnotationInfo ann : anns) { - if (ann.getAnnotationClassname().equals(anName)) { - return ann; - } - } - return null; - } - - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/Proxetta.java b/jodd-proxetta/src/main/java/jodd/proxetta/Proxetta.java deleted file mode 100644 index 1f58a039f..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/Proxetta.java +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.proxetta.impl.InvokeProxetta; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.impl.WrapperProxetta; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Proxetta creates dynamic proxy classes in the run-time. - *

- * To wrap a class with proxy Proxetta needs a target class (or its name or InputStream) - * and one or more {@link jodd.proxetta.ProxyAspect proxy aspects} that will be applied to target. - * Proxetta will examine target class and check if there are any methods to wrap, as defined by aspects pointcut. - * If there is at least one matched method, new proxy class will be created that extends target class. - *

- * If no matching method founded, Proxetta may or may not create an empty proxy class. - * This behaviour is defined by forced mode during creation. - *

- * There are several options that describes how proxy class will be named. By default, - * proxy class name is created from target class name by adding default suffix. Suffix - * can be changed, also, name can be variable, so each time class is created it will have a new name. - *

- * It is also possible to set proxy simple class name and/or package name. This is useful when - * proxyfing JDK classes or any other that can't be loaded by some classloader. Requested proxy name - * can be in the following forms: - *

    - *
  • .Foo (starting with a dot) - proxy package name is equal to target package, just proxy simple class name is set.
  • - *
  • foo. (ending with a dot) - proxy package is set, proxy simple name is create from target simple class name.
  • - *
  • foo.Foo - full proxy class name is specified.
  • - *
- * @see ProxettaFactory - */ -public abstract class Proxetta { - - /** - * Creates a new instance of {@link WrapperProxetta}. - */ - public static WrapperProxetta wrapperProxetta() { - return new WrapperProxetta(); - } - - /** - * Creates a new instance of {@link ProxyProxetta}. - */ - public static ProxyProxetta proxyProxetta() { - return new ProxyProxetta(); - } - - /** - * Creates a new instance of {@link InvokeProxetta}. - */ - public static InvokeProxetta invokeProxetta() { - return new InvokeProxetta(); - } - - - @SuppressWarnings("unchecked") - protected T _this() { - return (T) this; - } - - // ---------------------------------------------------------------- properties - - protected boolean forced; - protected ClassLoader classLoader; - protected boolean variableClassName; - protected String classNameSuffix; - protected File debugFolder; - protected final List proxyAspectList = new ArrayList<>(); - - // ---------------------------------------------------------------- aspects - - /** - * Adds an aspect. - */ - public T withAspect(final A proxyAspect) { - proxyAspectList.add(proxyAspect); - return _this(); - } - - public T withAspects(final A... aspects) { - Collections.addAll(proxyAspectList, aspects); - return _this(); - } - - public A[] getAspects(final A[] array) { - return proxyAspectList.toArray(array); - } - - /** - * Specifies 'forced' mode. If true, new proxy class will be created even if there are no - * matching pointcuts. If false, new proxy class will be created only if there is at least one - * matching pointcut - otherwise, original class will be returned. - */ - public T setForced(final boolean forced) { - this.forced = forced; - return _this(); - } - - public boolean isForced() { - return forced; - } - - - /** - * Specifies classloaders for loading created classes. - * If classloader not specified, default one will be used. - */ - public T setClassLoader(final ClassLoader classLoader) { - this.classLoader = classLoader; - return _this(); - } - - /** - * Returns specified classloader for loading created classes. - * If classloader is not specified, returns null. - */ - public ClassLoader getClassLoader() { - return classLoader; - } - - /** - * Sets variable proxy class name so every time when new proxy class is created - * its name will be different,so one classloader may load it without a problem. - * Otherwise, sets constant proxy class name so each time created proxy - * class will have the same name. Such class can be loaded only once by a classloader. - *

- * This prevents "java.lang.LinkageError: duplicate class definition" errors. - */ - public T setVariableClassName(final boolean variableClassName) { - this.variableClassName = variableClassName; - return _this(); - } - - public boolean isVariableClassName() { - return variableClassName; - } - - - /** - * Specifies custom classname suffix to be added to the class name of created proxy. - * Warning: when class name suffix is not used, full classname has to be - * specified that differs from target class name. - */ - public T setClassNameSuffix(final String suffix) { - this.classNameSuffix = suffix; - return _this(); - } - - public String getClassNameSuffix() { - return classNameSuffix; - } - - /** - * Specifies the debug folder where all created classes will be - * written to, for debugging purposes. - */ - public T setDebugFolder(final String debugFolder) { - this.debugFolder = new File(debugFolder); - return _this(); - } - - public T setDebugFolder(final File debugFolder) { - this.debugFolder = debugFolder; - return _this(); - } - - /** - * Returns debug folder or {@code null} if debug folder does not exist. - */ - public File getDebugFolder() { - return debugFolder; - } - - // ---------------------------------------------------------------- builder - - /** - * Creates {@link ProxettaFactory} with of this Proxetta. - */ - public abstract ProxettaFactory proxy(); - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/ProxettaException.java b/jodd-proxetta/src/main/java/jodd/proxetta/ProxettaException.java deleted file mode 100644 index 4df202691..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/ProxettaException.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.exception.UncheckedException; - -public class ProxettaException extends UncheckedException { - - public ProxettaException(final Throwable throwable) { - super(throwable); - } - - public ProxettaException() { - } - - public ProxettaException(final String string) { - super(string); - } - - public ProxettaException(final String string, final Throwable throwable) { - super(string, throwable); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/ProxettaFactory.java b/jodd-proxetta/src/main/java/jodd/proxetta/ProxettaFactory.java deleted file mode 100644 index 686558fd8..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/ProxettaFactory.java +++ /dev/null @@ -1,391 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.asm7.ClassReader; -import jodd.asm7.ClassWriter; -import jodd.io.FileUtil; -import jodd.io.IOUtil; -import jodd.proxetta.asm.TargetClassInfoReader; -import jodd.proxetta.asm.WorkData; -import jodd.util.ClassLoaderUtil; -import jodd.util.ClassUtil; -import jodd.util.DefineClass; -import jodd.util.StringUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -/** - * Proxetta builder. While {@link Proxetta} only holds aspects and - * configuration, ProxettaBuilder deals with the - * actually building proxies and wrappers over provided target. - */ -public abstract class ProxettaFactory { - - Logger log = LoggerFactory.getLogger(ProxettaFactory.class); - - protected final P proxetta; - - /** - * Creates new builder. - */ - protected ProxettaFactory(final P proxetta) { - this.proxetta = proxetta; - } - - @SuppressWarnings("unchecked") - protected T _this() { - return (T) this; - } - - // ---------------------------------------------------------------- IN - - /** - * Main target source. - */ - private InputStream targetInputStream; - - /** - * Target class, when available. - */ - private Class targetClass; - - /** - * Target class name, when available. - */ - private String targetClassName; - - /** - * Requested proxy class name (or class name template). - */ - protected String requestedProxyClassName; - - /** - * Sets requested proxy class name. - */ - public T setTargetProxyClassName(final String targetProxyClassName) { - this.requestedProxyClassName = targetProxyClassName; - return _this(); - } - - // ---------------------------------------------------------------- IN targets - - /** - * Defines class input stream as a target. - */ - protected T setTarget(final InputStream target) { - assertTargetIsNotDefined(); - - targetInputStream = target; - targetClass = null; - targetClassName = null; - - return _this(); - } - - /** - * Defines class name as a target. - * Class will not be loaded by classloader! - */ - protected T setTarget(final String targetName) { - assertTargetIsNotDefined(); - - try { - targetInputStream = ClassLoaderUtil.getClassAsStream(targetName); - if (targetInputStream == null) { - throw new ProxettaException("Target class not found: " + targetName); - } - targetClassName = targetName; - targetClass = null; - } - catch (final IOException ioex) { - IOUtil.close(targetInputStream); - throw new ProxettaException("Unable to get stream class name: " + targetName, ioex); - } - return _this(); - } - - /** - * Defines class as a target. - */ - public T setTarget(final Class target) { - assertTargetIsNotDefined(); - - try { - targetInputStream = ClassLoaderUtil.getClassAsStream(target); - if (targetInputStream == null) { - throw new ProxettaException("Target class not found: " + target.getName()); - } - targetClass = target; - targetClassName = target.getName(); - } - catch (final IOException ioex) { - IOUtil.close(targetInputStream); - throw new ProxettaException("Unable to stream class: " + target.getName(), ioex); - } - return _this(); - } - - /** - * Checks if target is not defined yet. - */ - private void assertTargetIsNotDefined() { - if (targetInputStream != null) { - throw new ProxettaException("Target already defined"); - } - - } - - // ---------------------------------------------------------------- IN naming - - /** - * Number appended to proxy class name, incremented on each use to make classnames unique - * in the system (e.g. classloader). - * - * @see Proxetta#setVariableClassName(boolean) - */ - protected static int suffixCounter; - - /** - * Returns new suffix or null if suffix is not in use. - */ - protected String resolveClassNameSuffix() { - final String classNameSuffix = proxetta.getClassNameSuffix(); - - if (classNameSuffix == null) { - return null; - } - - if (!proxetta.isVariableClassName()) { - return classNameSuffix; - } - - suffixCounter++; - return classNameSuffix + suffixCounter; - } - - // ---------------------------------------------------------------- PROCESS - - /** - * Creates custom class builder and process the target class with it. - */ - protected abstract WorkData process(ClassReader cr, TargetClassInfoReader targetClassInfoReader); - - // ---------------------------------------------------------------- ACCEPT - - protected ClassWriter destClassWriter; // destination class writer - protected boolean proxyApplied; - protected String proxyClassName; - - /** - * Reads the target and creates destination class. - */ - protected void process() { - if (targetInputStream == null) { - throw new ProxettaException("Target missing: " + targetClassName); - } - // create class reader - final ClassReader classReader; - try { - classReader = new ClassReader(targetInputStream); - } catch (final IOException ioex) { - throw new ProxettaException("Error reading class input stream", ioex); - } - - // reads information - final TargetClassInfoReader targetClassInfoReader = new TargetClassInfoReader(proxetta.getClassLoader()); - classReader.accept(targetClassInfoReader, 0); - - this.destClassWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); - - // create proxy - if (log.isDebugEnabled()) { - log.debug("processing: " + classReader.getClassName()); - } - final WorkData wd = process(classReader, targetClassInfoReader); - - // store important data - proxyApplied = wd.proxyApplied; - proxyClassName = wd.thisReference.replace('/', '.'); - } - - /** - * Returns byte array of created class. - */ - public byte[] create() { - process(); - - final byte[] result = toByteArray(); - - dumpClassInDebugFolder(result); - - if ((!proxetta.isForced()) && (!isProxyApplied())) { - if (log.isDebugEnabled()) { - log.debug("Proxy not applied: " + StringUtil.toSafeString(targetClassName)); - } - return null; - } - - if (log.isDebugEnabled()) { - log.debug("Proxy created " + StringUtil.toSafeString(targetClassName)); - } - - return result; - } - - /** - * Defines class. - */ - public Class define() { - process(); - - if ((!proxetta.isForced()) && (!isProxyApplied())) { - if (log.isDebugEnabled()) { - log.debug("Proxy not applied: " + StringUtil.toSafeString(targetClassName)); - } - - if (targetClass != null) { - return targetClass; - } - - if (targetClassName != null) { - try { - return ClassLoaderUtil.loadClass(targetClassName); - } catch (final ClassNotFoundException cnfex) { - throw new ProxettaException(cnfex); - } - } - } - - if (log.isDebugEnabled()) { - log.debug("Proxy created: " + StringUtil.toSafeString(targetClassName)); - } - - try { - ClassLoader classLoader = proxetta.getClassLoader(); - - if (classLoader == null) { - classLoader = ClassLoaderUtil.getDefaultClassLoader(); - - if ((classLoader == null) && (targetClass != null)) { - classLoader = targetClass.getClassLoader(); - } - } - - final byte[] bytes = toByteArray(); - - dumpClassInDebugFolder(bytes); - - return DefineClass.of(getProxyClassName(), bytes, classLoader); - } catch (final Exception ex) { - throw new ProxettaException("Class definition failed", ex); - } - } - - /** - * Creates new instance of created class. - * Assumes default no-arg constructor. - */ - public Object newInstance() { - final Class type = define(); - try { - return ClassUtil.newInstance(type); - } catch (final Exception ex) { - throw new ProxettaException("Invalid Proxetta class", ex); - } - } - - - // ---------------------------------------------------------------- debug - - /** - * Writes created class content to output folder for debugging purposes. - */ - protected void dumpClassInDebugFolder(final byte[] bytes) { - final File debugFolder = proxetta.getDebugFolder(); - if (debugFolder == null) { - return; - } - - if (!debugFolder.exists() || !debugFolder.isDirectory()) { - log.warn("Invalid debug folder: " + debugFolder); - } - - String fileName = proxyClassName; - if (fileName == null) { - fileName = "proxetta-" + System.currentTimeMillis(); - } - - fileName += ".class"; - - final File file = new File(debugFolder, fileName); - try { - FileUtil.writeBytes(file, bytes); - } catch (final IOException ioex) { - log.warn("Error writing class as " + file, ioex); - } - } - - // ---------------------------------------------------------------- OUT - - /** - * Checks if proxy is created and throws an exception if not. - */ - protected void assertProxyIsCreated() { - if (destClassWriter == null) { - throw new ProxettaException("Target not accepted yet!"); - } - } - - /** - * Returns raw bytecode. - */ - protected byte[] toByteArray() { - assertProxyIsCreated(); - return destClassWriter.toByteArray(); - } - - /** - * Returns true if at least one method was wrapped. - */ - public boolean isProxyApplied() { - assertProxyIsCreated(); - return proxyApplied; - } - - /** - * Returns proxy class name. - */ - public String getProxyClassName() { - assertProxyIsCreated(); - return proxyClassName; - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/ProxettaNames.java b/jodd-proxetta/src/main/java/jodd/proxetta/ProxettaNames.java deleted file mode 100644 index 173473d7b..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/ProxettaNames.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -/** - * Jodd PROXETTA default names, used all over the library.. - */ -public class ProxettaNames { - - /** - * {@link jodd.proxetta.ProxyAdvice#execute()} - */ - public static String executeMethodName = "execute"; - /** - * Proxy class name suffix. - */ - public static String proxyClassNameSuffix = "$$JoddProxy"; - /** - * Invoke proxy class name suffix. - */ - public static String invokeProxyClassNameSuffix = "$$JoddClone"; - /** - * Wrapper class name suffix. - */ - public static String wrapperClassNameSuffix = "$$JoddWrap"; - /** - * Prefix for advice method names. - */ - public static String methodPrefix = "$__"; - /** - * Divider for method names. - */ - public static String methodDivider = "$"; - /** - * Method name for advice 'clinit' methods. - */ - public static String clinitMethodName = "$clinit"; - /** - * Method name for advice default constructor ('init') methods. - */ - public static String initMethodName = "$init"; - /** - * Prefix for advice field names. - */ - public static String fieldPrefix = "$__"; - /** - * Divider for field names. - */ - public static String fieldDivider = "$"; - /** - * Wrapper target field name. - */ - public static String wrapperTargetFieldName = "_target"; - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/ProxettaUtil.java b/jodd-proxetta/src/main/java/jodd/proxetta/ProxettaUtil.java deleted file mode 100644 index a848a0fda..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/ProxettaUtil.java +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.proxetta.impl.WrapperProxettaFactory; - -import java.lang.reflect.Field; - -/** - * Proxetta utilities. - */ -public class ProxettaUtil { - - /** - * Returns target class if proxetta applied on given class. - * If not, returns given class as result. - */ - public static Class resolveTargetClass(final Class proxy) { - final String name = proxy.getName(); - - if (name.endsWith(ProxettaNames.proxyClassNameSuffix)) { - return proxy.getSuperclass(); - } - - if (name.endsWith(ProxettaNames.wrapperClassNameSuffix)) { - return getTargetWrapperType(proxy); - } - - return proxy; - } - - - /** - * Injects some target instance into {@link jodd.proxetta.impl.WrapperProxetta wrapper} proxy - * in given {@link WrapperProxettaFactory#setTargetFieldName(String) target field name}. - */ - public static void injectTargetIntoWrapper(final Object target, final Object wrapper, final String targetFieldName) { - try { - final Field field = wrapper.getClass().getField(targetFieldName); - field.setAccessible(true); - field.set(wrapper, target); - } catch (Exception ex) { - throw new ProxettaException(ex); - } - } - - /** - * Injects target instance into proxy using default target field name. - * @see #injectTargetIntoWrapper(Object, Object, String) - */ - public static void injectTargetIntoWrapper(final Object target, final Object wrapper) { - injectTargetIntoWrapper(target, wrapper, ProxettaNames.wrapperTargetFieldName); - } - - /** - * Returns wrapper target type. - */ - public static Class getTargetWrapperType(final Class wrapperClass) { - try { - final Field field = wrapperClass.getDeclaredField(ProxettaNames.wrapperTargetFieldName); - return field.getType(); - } catch (NoSuchFieldException nsfex) { - throw new ProxettaException(nsfex); - } - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/ProxyAdvice.java b/jodd-proxetta/src/main/java/jodd/proxetta/ProxyAdvice.java deleted file mode 100644 index 92a45cca1..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/ProxyAdvice.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -/** - * ProxyAdvice is the code portion of an aspect, i.e. the logic that replaces crosscutting concern. - */ -@FunctionalInterface -public interface ProxyAdvice { - - /** - * Intercepts wrapped method. - */ - Object execute() throws Exception; -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/ProxyAspect.java b/jodd-proxetta/src/main/java/jodd/proxetta/ProxyAspect.java deleted file mode 100644 index 57765f9d3..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/ProxyAspect.java +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -/** - * Proxy aspect contains advice and pointcut rules for applying advice. - */ -public class ProxyAspect { - - protected final Class advice; - protected final ProxyPointcut pointcut; - - public static ProxyAspect of(final Class advice, final ProxyPointcut pointcut) { - return new ProxyAspect(advice, pointcut); - } - - /** - * Creates aspect defined with provided advice and pointcut. - */ - public ProxyAspect(final Class advice, final ProxyPointcut pointcut) { - this.advice = advice; - this.pointcut = pointcut; - } - - /** - * Returns proxy advice class. - */ - public Class advice() { - return advice; - } - - /** - * Returns proxy pointcut. - */ - public ProxyPointcut pointcut() { - return pointcut; - } - - - @Override - public String toString() { - return "ProxyAspect{" + - "advice=" + advice.getName() + - ", pointcut=" + pointcut.getClass().getName() + - '}'; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/ProxyPointcut.java b/jodd-proxetta/src/main/java/jodd/proxetta/ProxyPointcut.java deleted file mode 100644 index d28cff591..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/ProxyPointcut.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -/** - * Pointcut is a set of points in the application where advice should be applied, i.e. - * which methods will be wrapped by proxy. - */ -@FunctionalInterface -public interface ProxyPointcut { - - /** - * Returns true if method should be wrapped with the proxy. - * Returns false if method should not be wrapped. - */ - boolean apply(MethodInfo methodInfo); - - /** - * Performs AND operation on this and the next proxy. - */ - default ProxyPointcut and(final ProxyPointcut otherProxyPointcut) { - return (t) -> apply(t) && otherProxyPointcut.apply(t); - } - - /** - * Performs OR operation on this and the next proxy. - */ - default ProxyPointcut or(final ProxyPointcut other) { - return (t) -> apply(t) || other.apply(t); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/ProxyTarget.java b/jodd-proxetta/src/main/java/jodd/proxetta/ProxyTarget.java deleted file mode 100644 index 18a5b5aaf..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/ProxyTarget.java +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -/** - * Marker class for {@link ProxyAdvice proxy} implementations. - */ -@SuppressWarnings({"UnusedDeclaration"}) -public final class ProxyTarget { - - // ---------------------------------------------------------------- invocation - - /** - * Inserts the invocation of target method and getting the invocation results. - * Small types are converted to wrappers. If method is void, - * null is used for return value. - */ - public static Object invoke() { - throw new ProxettaException(); - } - - // ---------------------------------------------------------------- arguments - - /** - * Inserts total number of method's arguments. - */ - public static int argumentsCount() { - throw new ProxettaException(); - } - - /** - * Inserts type of method argument specified by 1-based index. - * Works correctly with null argument values. - * @see #createArgumentsClassArray() - */ - public static Class argumentType(final int index) { - throw new ProxettaException(); - } - - /** - * Inserts value of method argument specified by 1-based index. - * @see #createArgumentsArray() - */ - public static Object argument(final int index) { - throw new ProxettaException(); - } - - /** - * Assigns new value for an argument specified by 1-based index. - */ - public static void setArgument(final Object value, final int index) { - throw new ProxettaException(); - } - - // ---------------------------------------------------------------- arguments array - - /** - * Creates array of arguments values. It is more safely then to get one argument at time, since - * the returned array has correct length. - * Equals to: new Object[] {arg1, arg2,...} - * @see #createArgumentsClassArray() - * @see #argument(int) - */ - public static Object[] createArgumentsArray() { - throw new ProxettaException(); - } - - /** - * Creates array of arguments types. Works correctly with null argument values. - * Equals to: new Class[] {Arg1Type.class, Arg2Type.class...} - * @see #createArgumentsArray() - * @see #argumentType(int) - */ - public static Class[] createArgumentsClassArray() { - throw new ProxettaException(); - } - - // ---------------------------------------------------------------- return value - - /** - * Inserts return type of target method. null is used for void. - */ - public static Class returnType() { - throw new ProxettaException(); - } - - /** - * Prepares return value. Must be used as last method call: - *

-	 *     ...
-	 *     return ProxyTarget.returnValue(xxx);
-	 * 
- * - * Used when returning values in general case, when return type may - * be either primitive or an object. Also, must be used when returning null - * for primitives. - */ - public static Object returnValue(final Object value) { - throw new ProxettaException(); - } - - // ---------------------------------------------------------------- target - - /** - * Inserts proxy (i.e. target) instance. - */ - public static Object target() { - throw new ProxettaException(); - } - - /** - * Inserts target class. - */ - public static Class targetClass() { - throw new ProxettaException(); - } - - /** - * Inserts target method name. Useful for reflection. - */ - public static String targetMethodName() { - throw new ProxettaException(); - } - - /** - * Inserts target method signature, java alike, including the method name. - * Useful for identifying the method, since it is unique for class. - * @see #targetMethodDescription() - */ - public static String targetMethodSignature() { - throw new ProxettaException(); - } - - /** - * Inserts target method description, bytecode alike, without method name. - * May be used for identifying the method. - * @see #targetMethodSignature() - */ - public static String targetMethodDescription() { - throw new ProxettaException(); - } - - /** - * Inserts targets method annotation value. Inserts null - * if annotation or element is missing. - */ - public static Object targetMethodAnnotation(final String annotationClassName, final String element) { - throw new ProxettaException(); - } - /** - * Inserts targets class annotation value. Inserts null - * if annotation or element is missing. - */ - public static Object targetClassAnnotation(final String annotationClassName, final String element) { - throw new ProxettaException(); - } - - // ---------------------------------------------------------------- info - - /** - * Inserts populated {@link jodd.proxetta.ProxyTargetInfo} instance. - */ - public static ProxyTargetInfo info() { - throw new ProxettaException(); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/ProxyTargetInfo.java b/jodd-proxetta/src/main/java/jodd/proxetta/ProxyTargetInfo.java deleted file mode 100644 index a76af76dc..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/ProxyTargetInfo.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -/** - * Holder for various {@link jodd.proxetta.ProxyTarget} information. - */ -public final class ProxyTargetInfo { - - public int argumentCount; - - public Class[] argumentsClasses; - - public Object[] arguments; - - public Class returnType; - - public String targetMethodName; - - public String targetMethodSignature; - - public String targetMethodDescription; - - public Class targetClass; - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/ProxyTargetReplacement.java b/jodd-proxetta/src/main/java/jodd/proxetta/ProxyTargetReplacement.java deleted file mode 100644 index d7097b806..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/ProxyTargetReplacement.java +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.asm.AsmUtil; -import jodd.asm7.MethodVisitor; -import jodd.asm7.Opcodes; -import jodd.asm7.Type; -import jodd.proxetta.asm.ProxettaAsmUtil; -import jodd.util.ClassLoaderUtil; - -import java.lang.reflect.Array; -import java.lang.reflect.Method; - -import static jodd.asm7.Opcodes.AASTORE; -import static jodd.asm7.Opcodes.ANEWARRAY; -import static jodd.asm7.Opcodes.DUP; -import static jodd.asm7.Opcodes.POP; -import static jodd.proxetta.asm.ProxettaAsmUtil.checkArgumentIndex; -import static jodd.proxetta.asm.ProxettaAsmUtil.loadMethodArgumentAsObject; -import static jodd.proxetta.asm.ProxettaAsmUtil.loadMethodArgumentClass; -import static jodd.proxetta.asm.ProxettaAsmUtil.pushInt; - -/** - * Replacements methods for {@link jodd.proxetta.ProxyTarget} methods. - */ -public class ProxyTargetReplacement { - - public static final String PROXY_TARGET_INFO = "jodd/proxetta/ProxyTargetInfo"; - - /** - * Visits replacement code for {@link ProxyTarget#argumentsCount()}. - */ - public static void argumentsCount(final MethodVisitor mv, final MethodInfo methodInfo) { - final int argsCount = methodInfo.getArgumentsCount(); - pushInt(mv, argsCount); - } - - /** - * Visits replacement code for {@link ProxyTarget#argumentType(int)}. - */ - public static void argumentType(final MethodVisitor mv, final MethodInfo methodInfo, final int argIndex) { - checkArgumentIndex(methodInfo, argIndex); - mv.visitInsn(POP); - loadMethodArgumentClass(mv, methodInfo, argIndex); - } - - /** - * Visits replacement code for {@link ProxyTarget#argument(int)}. - */ - public static void argument(final MethodVisitor mv, final MethodInfo methodInfo, final int argIndex) { - checkArgumentIndex(methodInfo, argIndex); - mv.visitInsn(POP); - loadMethodArgumentAsObject(mv, methodInfo, argIndex); - } - - /** - * Visits replacement code for {@link ProxyTarget#createArgumentsArray()}. - */ - public static void createArgumentsArray(final MethodVisitor mv, final MethodInfo methodInfo) { - final int argsCount = methodInfo.getArgumentsCount(); - pushInt(mv, argsCount); - mv.visitTypeInsn(ANEWARRAY, AsmUtil.SIGNATURE_JAVA_LANG_OBJECT); - for (int i = 0; i < argsCount; i++) { - mv.visitInsn(DUP); - pushInt(mv, i); - loadMethodArgumentAsObject(mv, methodInfo, i + 1); - mv.visitInsn(AASTORE); - } - } - - /** - * Visits replacement code for {@link ProxyTarget#createArgumentsClassArray()}. - */ - public static void createArgumentsClassArray(final MethodVisitor mv, final MethodInfo methodInfo) { - final int argsCount = methodInfo.getArgumentsCount(); - pushInt(mv, argsCount); - mv.visitTypeInsn(ANEWARRAY, AsmUtil.SIGNATURE_JAVA_LANG_CLASS); - for (int i = 0; i < argsCount; i++) { - mv.visitInsn(DUP); - pushInt(mv, i); - loadMethodArgumentClass(mv, methodInfo, i + 1); - mv.visitInsn(AASTORE); - } - } - - /** - * Visits replacement code for {@link ProxyTarget#returnType()}. - */ - public static void returnType(final MethodVisitor mv, final MethodInfo methodInfo) { - ProxettaAsmUtil.loadClass(mv, methodInfo.getReturnType().getOpcode(), methodInfo.getReturnType().getName()); - } - - /** - * Visits replacement code for {@link ProxyTarget#targetMethodName()}. - */ - public static void targetMethodName(final MethodVisitor mv, final MethodInfo methodInfo) { - mv.visitLdcInsn(methodInfo.getMethodName()); - } - - /** - * Visits replacement code for {@link ProxyTarget#targetMethodSignature()}. - */ - public static void targetMethodSignature(final MethodVisitor mv, final MethodInfo methodInfo) { - mv.visitLdcInsn(methodInfo.getSignature()); - } - - /** - * Visits replacement code for {@link ProxyTarget#targetMethodDescription()}. - */ - public static void targetMethodDescription(final MethodVisitor mv, final MethodInfo methodInfo) { - mv.visitLdcInsn(methodInfo.getDescription()); - } - - /** - * Visits replacement code for {@link ProxyTarget#targetClass()}. - */ - public static void targetClass(final MethodVisitor mv, final MethodInfo methodInfo) { - final ClassInfo classInfo = methodInfo.getClassInfo(); - mv.visitLdcInsn(Type.getType('L' + classInfo.getReference() + ';')); - } - - /** - * Visits replacement code for {@link ProxyTarget#info()}. - */ - public static void info(final MethodVisitor mv, final MethodInfo methodInfo, final int argsOff) { - mv.visitTypeInsn(Opcodes.NEW, PROXY_TARGET_INFO); - mv.visitInsn(DUP); - mv.visitMethodInsn(Opcodes.INVOKESPECIAL, PROXY_TARGET_INFO, "", "()V", false); - -// int argsOff = methodInfo.getAllArgumentsSize(); -// argsOff++; - - mv.visitVarInsn(Opcodes.ASTORE, argsOff); - - // argument count - mv.visitVarInsn(Opcodes.ALOAD, argsOff); - argumentsCount(mv, methodInfo); - mv.visitFieldInsn(Opcodes.PUTFIELD, PROXY_TARGET_INFO, "argumentCount", "I"); - - // arguments class - mv.visitVarInsn(Opcodes.ALOAD, argsOff); - createArgumentsClassArray(mv, methodInfo); - mv.visitFieldInsn(Opcodes.PUTFIELD, PROXY_TARGET_INFO, "argumentsClasses", "[Ljava/lang/Class;"); - - // arguments - mv.visitVarInsn(Opcodes.ALOAD, argsOff); - createArgumentsArray(mv, methodInfo); - mv.visitFieldInsn(Opcodes.PUTFIELD, PROXY_TARGET_INFO, "arguments", "[Ljava/lang/Object;"); - - // return type - mv.visitVarInsn(Opcodes.ALOAD, argsOff); - returnType(mv, methodInfo); - mv.visitFieldInsn(Opcodes.PUTFIELD, PROXY_TARGET_INFO, "returnType", AsmUtil.L_SIGNATURE_JAVA_LANG_CLASS); - - // target method name - mv.visitVarInsn(Opcodes.ALOAD, argsOff); - targetMethodName(mv, methodInfo); - mv.visitFieldInsn(Opcodes.PUTFIELD, PROXY_TARGET_INFO, "targetMethodName", AsmUtil.L_SIGNATURE_JAVA_LANG_STRING); - - // target method name - mv.visitVarInsn(Opcodes.ALOAD, argsOff); - targetMethodDescription(mv, methodInfo); - mv.visitFieldInsn(Opcodes.PUTFIELD, PROXY_TARGET_INFO, "targetMethodDescription", AsmUtil.L_SIGNATURE_JAVA_LANG_STRING); - - // target method name - mv.visitVarInsn(Opcodes.ALOAD, argsOff); - targetMethodSignature(mv, methodInfo); - mv.visitFieldInsn(Opcodes.PUTFIELD, PROXY_TARGET_INFO, "targetMethodSignature", AsmUtil.L_SIGNATURE_JAVA_LANG_STRING); - - // target class - mv.visitVarInsn(Opcodes.ALOAD, argsOff); - targetClass(mv, methodInfo); - mv.visitFieldInsn(Opcodes.PUTFIELD, PROXY_TARGET_INFO, "targetClass", AsmUtil.L_SIGNATURE_JAVA_LANG_CLASS); - - // the end - mv.visitVarInsn(Opcodes.ALOAD, argsOff); - } - - /** - * Visits replacement code for {@link ProxyTarget#targetMethodAnnotation(String, String)}. - */ - public static void targetMethodAnnotation(final MethodVisitor mv, final MethodInfo methodInfo, final String[] args) { - final AnnotationInfo[] anns = methodInfo.getAnnotations(); - - if (anns != null) { - targetAnnotation(mv, anns, args); - } - } - - /** - * Visits replacement code for {@link ProxyTarget#targetClassAnnotation(String, String)}. - */ - public static void targetClassAnnotation(final MethodVisitor mv, final ClassInfo classInfo, final String[] args) { - final AnnotationInfo[] anns = classInfo.getAnnotations(); - - if (anns != null) { - targetAnnotation(mv, anns, args); - } else { - mv.visitInsn(Opcodes.ACONST_NULL); - } - } - - private static void targetAnnotation(final MethodVisitor mv, final AnnotationInfo[] anns, final String[] args) { - for (final AnnotationInfo ann : anns) { - final String annotationSignature = ann.getAnnotationSignature(); - Method annotationMethod = null; - - if (annotationSignature.equals(args[0])) { - final String elementName = args[1]; - Object elementValue = ann.getElement(elementName); - - if (elementValue == null) { - // read default annotation - final String annotationClass = ann.getAnnotationClassname(); - - try { - final Class annotation = ClassLoaderUtil.loadClass(annotationClass); - - annotationMethod = annotation.getMethod(elementName); - - elementValue = annotationMethod.getDefaultValue(); - } - catch (final Exception ignore) { - elementValue = null; - } - - if (elementValue == null) { - mv.visitInsn(Opcodes.ACONST_NULL); - return; - } - } - - final Class elementValueClass = elementValue.getClass(); - - if (!elementValueClass.isArray()) { - // non-arrays - ProxettaAsmUtil.visitElementValue(mv, elementValue, true); - return; - } - else { - // arrays - Class componentType = elementValueClass.getComponentType(); - - final String annotationClass = ann.getAnnotationClassname(); - - try { - if (annotationMethod == null) { - final Class annotation = ClassLoaderUtil.loadClass(annotationClass); - - annotationMethod = annotation.getMethod(elementName); - } - - componentType = annotationMethod.getReturnType().getComponentType(); - } - catch (final Exception ignore) { - } - - final int size = Array.getLength(elementValue); - - ProxettaAsmUtil.pushInt(mv, size); - - ProxettaAsmUtil.newArray(mv, componentType); - - for (int i = 0; i < size; i++) { - mv.visitInsn(DUP); - - ProxettaAsmUtil.pushInt(mv, i); - - final Object value = Array.get(elementValue, i); - ProxettaAsmUtil.visitElementValue(mv, value, false); - - ProxettaAsmUtil.storeIntoArray(mv, componentType); - } - - return; - } - } - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/TypeInfo.java b/jodd-proxetta/src/main/java/jodd/proxetta/TypeInfo.java deleted file mode 100644 index 0f276874a..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/TypeInfo.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -/** - * Holds information about the types. Used for methods return type and arguments. - */ -public interface TypeInfo { - - /** - * Returns annotation info of type. SOme types (like for returning value) - * can't have annotation information. - */ - AnnotationInfo[] getAnnotations(); - - /** - * Returns bytecode opcode. - */ - char getOpcode(); - - /** - * Returns java-like, e.g. {@code "java.lang.Integer"}. - */ - String getType(); - - /** - * Returns bytecode-like type name, e.g. {@code "Ljava/lang/Integer;"}. - * Note that generics type names are not resolved. - * @see #getRawName() - */ - String getName(); - - /** - * Returns bytecode-like type name, e.g. {@code "Ljava/lang/Integer;"}. - * @see #getName() - */ - String getRawName(); -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/advice/DelegateAdvice.java b/jodd-proxetta/src/main/java/jodd/proxetta/advice/DelegateAdvice.java deleted file mode 100644 index 3396df0ff..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/advice/DelegateAdvice.java +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.advice; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -import java.lang.reflect.Method; - -/** - * Delegates calls to target using reflection. Offers - * separation between between points where class is loaded - * and class is used. - *

- * Allows usage of classes loaded by different class loader. - * For example, if you have an instance of class loaded by - * parent-last class loader, delegate allows - * to still call it using plain java. Under the hood, - * each method will actually invoke target method - * using reflection. - */ -public class DelegateAdvice implements ProxyAdvice { - - /** - * Target object. - */ - public Object _target; - - /** - * Looks up for method in target object and invokes it using reflection. - */ - public Object execute() throws Exception { - String methodName = ProxyTarget.targetMethodName(); - Class[] argTypes = ProxyTarget.createArgumentsClassArray(); - Object[] args = ProxyTarget.createArgumentsArray(); - - // lookup method on target object class (and not #targetClass!() - Class type = _target.getClass(); - Method method = type.getMethod(methodName, argTypes); - - // remember context classloader - ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - - Object result; - try { - // change class loader - Thread.currentThread().setContextClassLoader(type.getClassLoader()); - - // invoke - result = method.invoke(_target, args); - } - finally { - // return context classloader - Thread.currentThread().setContextClassLoader(contextClassLoader); - - } - - return ProxyTarget.returnValue(result); - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/advice/DelegateAdviceUtil.java b/jodd-proxetta/src/main/java/jodd/proxetta/advice/DelegateAdviceUtil.java deleted file mode 100644 index 31c080470..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/advice/DelegateAdviceUtil.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.advice; - -import jodd.proxetta.MethodInfo; -import jodd.proxetta.Proxetta; -import jodd.proxetta.ProxettaException; -import jodd.proxetta.ProxyAspect; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.util.ClassUtil; -import jodd.util.TypeCache; - -import java.lang.reflect.Field; - -/** - * Utilities for applying {@link DelegateAdvice} to target. - */ -public class DelegateAdviceUtil { - - public static TypeCache cache = TypeCache.create().threadsafe(true).get(); - - /** - * Proxy Proxetta, applied on all public methods of the target class. - */ - private static final ProxyProxetta PROXY_PROXETTA = - Proxetta - .proxyProxetta() - .withAspect(ProxyAspect.of(DelegateAdvice.class, MethodInfo::isPublicMethod)); - - /** - * Applies advice on given target class and returns proxy instance. - */ - public static T applyAdvice(final Class targetClass) { - final Class adviceClass = cache.get(targetClass, (t) -> PROXY_PROXETTA.proxy().setTarget(t).define()); - - // create new advice instance and injects target instance to it - - try { - final Object advice = ClassUtil.newInstance(adviceClass); - - final Field field = adviceClass.getField("$___target$0"); - - field.set(advice, targetClass); - - return (T) advice; - } catch (final Exception ex) { - throw new ProxettaException(ex); - } - } - - /** - * Injects target into proxy. - */ - public static void injectTargetIntoProxy(final Object proxy, final Object target) { - final Class proxyClass = proxy.getClass(); - - try { - final Field field = proxyClass.getField("$___target$0"); - - field.set(proxy, target); - } catch (final Exception ex) { - throw new ProxettaException(ex); - } - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/advice/package-info.java b/jodd-proxetta/src/main/java/jodd/proxetta/advice/package-info.java deleted file mode 100644 index f8f6f0650..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/advice/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Some proxetta advices. - */ -package jodd.proxetta.advice; \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/AnnotationReader.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/AnnotationReader.java deleted file mode 100644 index 520496965..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/AnnotationReader.java +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.asm.AsmUtil; -import jodd.asm.EmptyAnnotationVisitor; -import jodd.asm7.AnnotationVisitor; -import jodd.proxetta.AnnotationInfo; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - - -/** - * Reads annotation inner data. - */ -@SuppressWarnings({"AnonymousClassVariableHidesContainingMethodVariable"}) -public class AnnotationReader extends EmptyAnnotationVisitor implements AnnotationInfo { - - public static final AnnotationInfo[] NO_ANNOTATIONS = new AnnotationInfo[0]; - - protected final String desc; - protected final String className; - protected final boolean visible; - protected final Map elements; - - public AnnotationReader(final String desc, final boolean visible) { - this.desc = desc; - this.visible = visible; - this.elements = new HashMap<>(); - this.className = AsmUtil.typeref2Name(desc); - } - - // ---------------------------------------------------------------- info - - @Override - public String getAnnotationClassname() { - return className; - } - - @Override - public String getAnnotationSignature() { - return desc; - } - - @Override - public boolean isVisible() { - return visible; - } - - @Override - public Object getElement(final String name) { - return elements.get(name); - } - - @Override - public Set getElementNames() { - return elements.keySet(); - } - - // ---------------------------------------------------------------- visitor - - - @Override - public void visit(final String name, final Object value) { - elements.put(name, value); - } - - @Override - public void visitEnum(final String name, final String desc, final String value) { - elements.put(name, new String[]{desc, value}); - } - - @Override - public AnnotationVisitor visitAnnotation(final String name, final String desc) { - AnnotationReader nestedAnnotation = new AnnotationReader(desc, true); - elements.put(name, nestedAnnotation); - return nestedAnnotation; - } - - @Override - public AnnotationVisitor visitArray(final String name) { - final List array = new ArrayList<>(); - return new EmptyAnnotationVisitor() { - - @Override - public void visit(final String name, final Object value) { - array.add(value); - } - - @Override - public void visitEnd() { - Object[] data = array.toArray(new Object[0]); - elements.put(name, data); - } - }; - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/HistoryMethodAdapter.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/HistoryMethodAdapter.java deleted file mode 100644 index 3f8dc3f2c..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/HistoryMethodAdapter.java +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.asm.MethodAdapter; -import jodd.asm7.Label; -import jodd.asm7.MethodVisitor; -import jodd.proxetta.ProxettaException; - -import static jodd.asm7.Opcodes.BIPUSH; -import static jodd.asm7.Opcodes.ICONST_0; -import static jodd.asm7.Opcodes.ICONST_1; -import static jodd.asm7.Opcodes.ICONST_2; -import static jodd.asm7.Opcodes.ICONST_3; -import static jodd.asm7.Opcodes.ICONST_4; -import static jodd.asm7.Opcodes.ICONST_5; -import static jodd.asm7.Opcodes.SIPUSH; - -/** - * Method adapter that tracks history of previous instructions. - *
    - *
  • that remembers previous opcode of 'insn' and 'intInsn' instructions. - * Used to detect single (last) int argument value of a method call.
  • - *
  • Stores last two arguments as strings
  • - *
- */ -abstract class HistoryMethodAdapter extends MethodAdapter { - - protected HistoryMethodAdapter(final MethodVisitor methodVisitor) { - super(methodVisitor); - } - - // ---------------------------------------------------------------- history - - protected int opcode; - protected int operand; - protected boolean isPrevious; // true only if previous opcode is of the correct type - protected boolean traceNext; // true only to trace very next opcode - protected String[] strArgs = new String[2]; - - // ---------------------------------------------------------------- get index - - /** - * Returns argument index from the history. - * Must POP value from the stack after the execution. - */ - protected int getArgumentIndex() { - if (!isPrevious) { - throw new ProxettaException("Unexpected previous instruction type used for setting argument index"); - } - int argIndex; - switch (opcode) { - case ICONST_0: argIndex = 0; break; - case ICONST_1: argIndex = 1; break; - case ICONST_2: argIndex = 2; break; - case ICONST_3: argIndex = 3; break; - case ICONST_4: argIndex = 4; break; - case ICONST_5: argIndex = 5; break; - case BIPUSH: - case SIPUSH: - argIndex = operand; break; - default: - throw new ProxettaException("Unexpected previous instruction used for setting argument index"); - } - return argIndex; - } - - /** - * Returns last two string arguments. - */ - public String[] getLastTwoStringArguments() { - return strArgs; - } - - /** - * Adds last LDC arguments to {@link #getLastTwoStringArguments() string arguments}. - */ - private void keepStringArgument(final Object value) { - strArgs[0] = strArgs[1]; - strArgs[1] = value.toString(); - } - - // ---------------------------------------------------------------- visitors - - @Override - public void visitInsn(final int opcode) { - this.opcode = opcode; - isPrevious = true; - traceNext = false; - super.visitInsn(opcode); - } - - @Override - public void visitIntInsn(final int opcode, final int operand) { - this.opcode = opcode; - this.operand = operand; - isPrevious = true; - traceNext = false; - super.visitIntInsn(opcode, operand); - } - - @Override - public void visitVarInsn(final int opcode, final int var) { - isPrevious = false; - traceNext = false; - super.visitVarInsn(opcode, var); - } - - @Override - public void visitTypeInsn(final int opcode, final String type) { - isPrevious = false; - traceNext = false; - super.visitTypeInsn(opcode, type); - } - - @Override - public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { - isPrevious = false; - traceNext = false; - super.visitFieldInsn(opcode, owner, name, desc); - } - - @Override - public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc, final boolean isInterface) { - isPrevious = false; - traceNext = false; - super.visitMethodInsn(opcode, owner, name, desc, isInterface); - } - - @Override - public void visitJumpInsn(final int opcode, final Label label) { - isPrevious = false; - traceNext = false; - super.visitJumpInsn(opcode, label); - } - - @Override - public void visitLdcInsn(final Object cst) { - isPrevious = false; - traceNext = false; - - keepStringArgument(cst); - - super.visitLdcInsn(cst); - } - - @Override - public void visitIincInsn(final int var, final int increment) { - isPrevious = false; - traceNext = false; - super.visitIincInsn(var, increment); - } - - @Override - public void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label[] labels) { - isPrevious = false; - traceNext = false; - super.visitTableSwitchInsn(min, max, dflt, labels); - } - - @Override - public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) { - isPrevious = false; - traceNext = false; - super.visitLookupSwitchInsn(dflt, keys, labels); - } - - @Override - public void visitMultiANewArrayInsn(final String desc, final int dims) { - isPrevious = false; - traceNext = false; - super.visitMultiANewArrayInsn(desc, dims); - } - - @Override - public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { - //super.visitLocalVariable(name, desc, signature, start, end, index); - } - - @Override - public void visitLineNumber(final int line, final Label start) { - //super.visitLineNumber(line, start); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/InvokeClassBuilder.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/InvokeClassBuilder.java deleted file mode 100644 index ca30e5b78..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/InvokeClassBuilder.java +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.asm.ClassAdapter; -import jodd.asm7.ClassVisitor; -import jodd.asm7.MethodVisitor; -import jodd.proxetta.InvokeAspect; - -import java.util.ArrayList; -import java.util.List; - -/** - * Invocation replacer class adapter. - */ -public class InvokeClassBuilder extends ClassAdapter { - - protected final WorkData wd; - protected final InvokeAspect[] aspects; - protected final String suffix; - protected final String reqProxyClassName; - protected final TargetClassInfoReader targetClassInfo; - - public InvokeClassBuilder(final ClassVisitor dest, final InvokeAspect[] invokeAspects, final String suffix, final String reqProxyClassName, final TargetClassInfoReader targetClassInfoReader) { - super(dest); - this.aspects = invokeAspects; - this.suffix = suffix; - this.wd = new WorkData(dest); - this.targetClassInfo = targetClassInfoReader; - this.reqProxyClassName = reqProxyClassName; - } - - /** - * Returns working data. - */ - public WorkData getWorkData() { - return wd; - } - - // ---------------------------------------------------------------- header - - @Override - public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { - wd.init(name, superName, suffix, reqProxyClassName); - - // write destination class - final int v = ProxettaAsmUtil.resolveJavaVersion(version); - super.visit(v, access, wd.thisReference, signature, wd.superName, interfaces); - } - - @Override - public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { - final MethodSignatureVisitor msign = targetClassInfo.lookupMethodSignatureVisitor(access, name, desc, wd.superReference); - - if (msign == null) { - super.visitMethod(access, name, desc, signature, exceptions); - return null; - } - - // check aspects that apply to this method - List applicableAspects = new ArrayList<>(aspects.length); - for (InvokeAspect aspect : aspects) { - if (aspect.apply(msign)) { - applicableAspects.add(aspect); - } - } - - if (applicableAspects.isEmpty()) { - super.visitMethod(access, name, desc, signature, exceptions); - return null; - } - - InvokeAspect[] nextAspects = new InvokeAspect[applicableAspects.size()]; - nextAspects = applicableAspects.toArray(nextAspects); - - return new InvokeReplacerMethodAdapter( - super.visitMethod(access, name, desc, signature, exceptions), msign, wd, nextAspects); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/InvokeReplacerMethodAdapter.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/InvokeReplacerMethodAdapter.java deleted file mode 100644 index 83287c91e..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/InvokeReplacerMethodAdapter.java +++ /dev/null @@ -1,370 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.asm.AsmUtil; -import jodd.asm7.Label; -import jodd.asm7.MethodVisitor; -import jodd.asm7.Type; -import jodd.proxetta.InvokeAspect; -import jodd.proxetta.InvokeInfo; -import jodd.proxetta.InvokeReplacer; -import jodd.proxetta.MethodInfo; -import jodd.proxetta.ProxettaException; -import jodd.proxetta.ProxyTargetReplacement; -import jodd.util.StringPool; - -import static jodd.asm7.Opcodes.ALOAD; -import static jodd.asm7.Opcodes.ASTORE; -import static jodd.asm7.Opcodes.DUP; -import static jodd.asm7.Opcodes.INVOKEINTERFACE; -import static jodd.asm7.Opcodes.INVOKESPECIAL; -import static jodd.asm7.Opcodes.INVOKESTATIC; -import static jodd.asm7.Opcodes.INVOKEVIRTUAL; -import static jodd.asm7.Opcodes.NEW; -import static jodd.asm7.Opcodes.POP; -import static jodd.proxetta.asm.ProxettaAsmUtil.INIT; -import static jodd.proxetta.asm.ProxettaAsmUtil.isArgumentMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isArgumentTypeMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isInfoMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isTargetClassAnnotationMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isTargetMethodAnnotationMethod; - -/** - * Invocation replacer method adapter. - */ -public class InvokeReplacerMethodAdapter extends HistoryMethodAdapter { - - protected final WorkData wd; - protected final MethodInfo methodInfo; - protected final InvokeAspect[] aspects; - - public InvokeReplacerMethodAdapter(final MethodVisitor mv, final MethodInfo methodInfo, final WorkData wd, final InvokeAspect[] aspects) { - super(mv); - this.wd = wd; - this.aspects = aspects; - this.methodInfo = methodInfo; - } - - /** - * Detects super ctor invocation. - */ - protected boolean firstSuperCtorInitCalled; - - protected boolean proxyInfoRequested; - - /** - * New object creation matched. - */ - protected InvokeReplacer newInvokeReplacer; - - /** - * Invoked on INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC, INVOKEINTERFACE or INVOKEDYNAMIC. - */ - @Override - public void visitMethodInsn(final int opcode, String owner, String name, String desc, final boolean isInterface) { - - // replace NEW. - if ((newInvokeReplacer != null) && (opcode == INVOKESPECIAL)) { - String exOwner = owner; - owner = newInvokeReplacer.getOwner(); - name = newInvokeReplacer.getMethodName(); - desc = changeReturnType(desc, 'L' + exOwner + ';'); - super.visitMethodInsn(INVOKESTATIC, owner, name, desc, isInterface); - newInvokeReplacer = null; - return; - } - - - InvokeInfo invokeInfo = new InvokeInfo(owner, name, desc); - - // [*] - // creating FooClone.; inside the FOO constructor - // replace the very first invokespecial call (SUB.) - // to targets subclass with target (FOO.). - if (methodInfo.getMethodName().equals(INIT)) { - if ( - (!firstSuperCtorInitCalled) && - (opcode == INVOKESPECIAL) && - name.equals(INIT) && - owner.equals(wd.nextSupername) - ) { - firstSuperCtorInitCalled = true; - owner = wd.superReference; - super.visitMethodInsn(opcode, owner, name, desc, isInterface); - return; - } - } - - // detection of super calls - if ((opcode == INVOKESPECIAL) && (owner.equals(wd.nextSupername) && (!name.equals(INIT)))) { - throw new ProxettaException("Super call detected in class " + methodInfo.getClassname() + " method: " + methodInfo.getSignature() + - "\nProxetta can't handle super calls due to VM limitations."); - } - - - InvokeReplacer ir = null; - - // find first matching aspect - for (InvokeAspect aspect : aspects) { - ir = aspect.pointcut(invokeInfo); - if (ir != null) { - break; - } - } - - if (ir == null || ir.isNone()) { - - if (ProxettaAsmUtil.isCreateArgumentsArrayMethod(name, desc)) { - ProxyTargetReplacement.createArgumentsArray(mv, methodInfo); - wd.proxyApplied = true; - return; - } - - if (ProxettaAsmUtil.isCreateArgumentsClassArrayMethod(name, desc)) { - ProxyTargetReplacement.createArgumentsClassArray(mv, methodInfo); - wd.proxyApplied = true; - return; - } - - if (ProxettaAsmUtil.isArgumentsCountMethod(name, desc)) { - ProxyTargetReplacement.argumentsCount(mv, methodInfo); - wd.proxyApplied = true; - return; - } - - if (ProxettaAsmUtil.isTargetMethodNameMethod(name, desc)) { - ProxyTargetReplacement.targetMethodName(mv, methodInfo); - wd.proxyApplied = true; - return; - } - - if (ProxettaAsmUtil.isTargetMethodDescriptionMethod(name, desc)) { - ProxyTargetReplacement.targetMethodDescription(mv, methodInfo); - wd.proxyApplied = true; - return; - } - - if (ProxettaAsmUtil.isTargetMethodSignatureMethod(name, desc)) { - ProxyTargetReplacement.targetMethodSignature(mv, methodInfo); - wd.proxyApplied = true; - return; - } - - if (ProxettaAsmUtil.isReturnTypeMethod(name, desc)) { - ProxyTargetReplacement.returnType(mv, methodInfo); - wd.proxyApplied = true; - return; - } - - if (ProxettaAsmUtil.isTargetClassMethod(name, desc)) { - ProxyTargetReplacement.targetClass(mv, methodInfo); - wd.proxyApplied = true; - return; - } - - if (isArgumentTypeMethod(name, desc)) { - int argIndex = this.getArgumentIndex(); - ProxyTargetReplacement.argumentType(mv, methodInfo, argIndex); - wd.proxyApplied = true; - return; - } - - if (isArgumentMethod(name, desc)) { - int argIndex = this.getArgumentIndex(); - ProxyTargetReplacement.argument(mv, methodInfo, argIndex); - wd.proxyApplied = true; - return; - } - - if (isInfoMethod(name, desc)) { - proxyInfoRequested = true; - // we are NOT calling the replacement here, as we would expect. - // NO, we need to wait for the very next ASTORE method so we - // can read the index and use it for replacement method!!! - - //ProxyTargetReplacement.info(mv, methodInfo); - wd.proxyApplied = true; - return; - } - - if (isTargetMethodAnnotationMethod(name, desc)) { - String[] args = getLastTwoStringArguments(); - - // pop current two args - mv.visitInsn(POP); - mv.visitInsn(POP); - - ProxyTargetReplacement.targetMethodAnnotation(mv, methodInfo, args); - wd.proxyApplied = true; - return; - } - - if (isTargetClassAnnotationMethod(name, desc)) { - String[] args = getLastTwoStringArguments(); - - // pop current two args - mv.visitInsn(POP); - mv.visitInsn(POP); - - ProxyTargetReplacement.targetClassAnnotation(mv, methodInfo.getClassInfo(), args); - wd.proxyApplied = true; - return; - } - - - super.visitMethodInsn(opcode, owner, name, desc, isInterface); - return; - } - - wd.proxyApplied = true; - - String exOwner = owner; - owner = ir.getOwner(); - name = ir.getMethodName(); - - switch (opcode) { - case INVOKEINTERFACE: - desc = prependArgument(desc, AsmUtil.L_SIGNATURE_JAVA_LANG_OBJECT); - break; - case INVOKEVIRTUAL: - desc = prependArgument(desc, AsmUtil.L_SIGNATURE_JAVA_LANG_OBJECT); - break; - case INVOKESTATIC: - break; - default: - throw new ProxettaException("Unsupported opcode: " + opcode); - } - - // additional arguments - if (ir.isPassOwnerName()) { - desc = appendArgument(desc, AsmUtil.L_SIGNATURE_JAVA_LANG_STRING); - super.visitLdcInsn(exOwner); - } - if (ir.isPassMethodName()) { - desc = appendArgument(desc, AsmUtil.L_SIGNATURE_JAVA_LANG_STRING); - super.visitLdcInsn(methodInfo.getMethodName()); - } - if (ir.isPassMethodSignature()) { - desc = appendArgument(desc, AsmUtil.L_SIGNATURE_JAVA_LANG_STRING); - super.visitLdcInsn(methodInfo.getSignature()); - } - if (ir.isPassTargetClass()) { - desc = appendArgument(desc, AsmUtil.L_SIGNATURE_JAVA_LANG_CLASS); - super.mv.visitLdcInsn(Type.getType('L' + wd.superReference + ';')); - } - if (ir.isPassThis()) { - desc = appendArgument(desc, AsmUtil.L_SIGNATURE_JAVA_LANG_OBJECT); - super.mv.visitVarInsn(ALOAD, 0); - } - - super.visitMethodInsn(INVOKESTATIC, owner, name, desc, false); - } - - @Override - public void visitFieldInsn(final int opcode, String owner, final String name, final String desc) { - // [*] - // Fix all Foo. to FooClone. - if (owner.equals(wd.superReference)) { - owner = wd.thisReference; - } - super.visitFieldInsn(opcode, owner, name, desc); - } - - @Override - public void visitTypeInsn(final int opcode, final String type) { - if (opcode == NEW) { - InvokeInfo invokeInfo = new InvokeInfo(type, INIT, StringPool.EMPTY); - for (InvokeAspect aspect : aspects) { - InvokeReplacer ir = aspect.pointcut(invokeInfo); - if (ir != null && !ir.isNone()) { - newInvokeReplacer = ir; - - // new pointcut found, skip the new instruction and the following dup. - // and then go to the invokespecial - return; - } - } - } - super.visitTypeInsn(opcode, type); - } - - @Override - public void visitVarInsn(final int opcode, final int var) { - if (proxyInfoRequested) { - proxyInfoRequested = false; - if (opcode == ASTORE) { - ProxyTargetReplacement.info(mv, methodInfo, var); - } - } - super.visitVarInsn(opcode, var); - } - - @Override - public void visitInsn(final int opcode) { - if ((newInvokeReplacer != null) && (opcode == DUP)) { - return; // skip dup after new - } - super.visitInsn(opcode); - } - - @Override - public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { - } - - @Override - public void visitLineNumber(final int line, final Label start) { - } - - - // ---------------------------------------------------------------- util - - /** - * Appends argument to the existing description. - */ - protected static String appendArgument(final String desc, final String type) { - int ndx = desc.indexOf(')'); - return desc.substring(0, ndx) + type + desc.substring(ndx); - } - - /** - * Prepends argument to the existing description. - */ - protected static String prependArgument(final String desc, final String type) { - int ndx = desc.indexOf('('); - ndx++; - return desc.substring(0, ndx) + type + desc.substring(ndx); - } - - /** - * Changes return type. - */ - protected static String changeReturnType(final String desc, final String type) { - int ndx = desc.indexOf(')'); - return desc.substring(0, ndx + 1) + type; - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/MethodSignatureVisitor.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/MethodSignatureVisitor.java deleted file mode 100644 index 472e7e6c0..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/MethodSignatureVisitor.java +++ /dev/null @@ -1,468 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.asm.AsmUtil; -import jodd.asm.TraceSignatureVisitor; -import jodd.asm7.Opcodes; -import jodd.asm7.signature.SignatureVisitor; -import jodd.buffer.FastIntBuffer; -import jodd.proxetta.AnnotationInfo; -import jodd.proxetta.ClassInfo; -import jodd.proxetta.GenericsReader; -import jodd.proxetta.MethodInfo; -import jodd.proxetta.ProxettaException; -import jodd.proxetta.TypeInfo; -import jodd.util.StringPool; -import jodd.util.StringUtil; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import static jodd.proxetta.asm.AnnotationReader.NO_ANNOTATIONS; - -/** - * Resolves method signature and holds all information. Uses {@link jodd.asm.TraceSignatureVisitor} from ASM library. - *
- * MethodSignature = ( visitFormalTypeParameter visitClassBound? visitInterfaceBound* )* ( visitParameterType* visitReturnType visitExceptionType* )
- * 
- */ -public class MethodSignatureVisitor extends TraceSignatureVisitor implements MethodInfo { - - protected final String classname; - protected final String methodName; - protected final String[] exceptionsArray; - protected final boolean isStatic; - protected final boolean isFinal; - protected final ClassInfo targetClassInfo; - protected final FastIntBuffer argumentsOffset; - protected final List arguments; - protected final int access; - protected final String description; - - protected TypeInfo returnType; - protected String signature; - protected int argumentsCount; - protected int argumentsWords; - protected String asmMethodSignature; - protected AnnotationInfo[] annotations; - protected String declaredClassName; - protected final Map generics; - protected final Map declaredTypeGeneric; - - - // ---------------------------------------------------------------- ctors - - public MethodSignatureVisitor( - final String methodName, - final int access, - final String classname, - String description, - final String[] exceptions, - String signature, - final Map declaredTypeGenerics, - final ClassInfo targetClassInfo) { - - super(new StringBuilder(), (access & Opcodes.ACC_INTERFACE) != 0); - - if (signature != null && signature.startsWith("(") && !declaredTypeGenerics.isEmpty()) { - // special case when we can replace the signature - // as generic types are defined in declaration in superclass - // e.g.: Foo extends Bar - - String newSignature = signature; - - for (Map.Entry entry : declaredTypeGenerics.entrySet()) { - newSignature = StringUtil.replace(newSignature, "T" + entry.getKey() + ";", entry.getValue()); - } - - description = AsmUtil.removeGenericsFromSignature(newSignature); - signature = null; - } - -// this.isInterface = (access & Opcodes.ACC_INTERFACE) != 0; - this.isStatic = (access & Opcodes.ACC_STATIC) != 0; - this.isFinal = (access & Opcodes.ACC_FINAL) != 0; - this.methodName = methodName; - this.access = access; - this.classname = classname; - this.description = description; - this.targetClassInfo = targetClassInfo; - this.asmMethodSignature = signature; - this.generics = new GenericsReader().parseSignatureForGenerics(signature, isInterface); - this.exceptionsArray = exceptions; - this.declaredTypeGeneric = declaredTypeGenerics; - - this.arguments = new ArrayList<>(); - this.arguments.add(new TypeInfoImpl('L', null, null, null)); - - this.argumentsOffset = new FastIntBuffer(); - this.argumentsOffset.append(0); - - this.annotations = NO_ANNOTATIONS; - } - - // ---------------------------------------------------------------- method-info signature - - @Override - public String getSignature() { - if (signature == null) { - String decl = getDeclaration(); - - int ndx = decl.indexOf(')'); - ndx++; - String retType = decl.substring(ndx); - - StringBuilder methodDeclaration = new StringBuilder(50); - methodDeclaration.append(retType).append(' ').append(methodName).append(decl, 0, ndx); - - String exceptionsAsString = getExceptionsAsString(); - if (exceptionsAsString != null) { - methodDeclaration.append(" throws ").append(exceptionsAsString); - } - - signature = methodDeclaration.toString(); - } - return signature; - } - - @Override - public String getCleanSignature() { - return methodName + '#' + getDescription(); - } - - public String getAsmMethodSignature() { - return asmMethodSignature; - } - - @Override - public String getMethodName() { - return methodName; - } - - @Override - public int getArgumentsCount() { - return argumentsCount; - } - - @Override - public TypeInfoImpl getArgument(final int ndx) { - return arguments.get(ndx); - } - - @Override - public int getArgumentOffset(final int index) { - return argumentsOffset.get(index); - } - - @Override - public int getAllArgumentsSize() { - return argumentsWords; - } - - @Override - public TypeInfo getReturnType() { - return returnType; - } - - @Override - public int getAccessFlags() { - return access; - } - - @Override - public String getClassname() { - return classname; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public AnnotationInfo[] getAnnotations() { - return annotations; - } - - @Override - public String getDeclaredClassName() { - if (declaredClassName == null) { - return classname; - } - return declaredClassName; - } - - public void setDeclaredClassName(final String declaredClassName) { - this.declaredClassName = declaredClassName; - } - - @Override - public boolean isTopLevelMethod() { - return declaredClassName == null; - } - - @Override - public ClassInfo getClassInfo() { - return targetClassInfo; - } - - @Override - public String[] getExceptions() { - return exceptionsArray; - } - - // ---------------------------------------------------------------- type - - private boolean visitingArgument; - private boolean visitingReturnType; - private boolean visitingArray; - private int declarationTypeOffset; - - @Override - public SignatureVisitor visitParameterType() { - super.visitParameterType(); - - visitingArgument = true; - - return this; - } - - @Override - public SignatureVisitor visitReturnType() { - super.visitReturnType(); - - visitingReturnType = true; - - return this; - } - - @Override - public SignatureVisitor visitArrayType() { - visitingArray = true; - return super.visitArrayType(); - } - - @Override - public void visitBaseType(final char descriptor) { - if (isTopLevelType()) { - // mark type start - declarationTypeOffset = declaration.length(); - } - - super.visitBaseType(descriptor); - } - - @Override - public void visitClassType(final String name) { - if (isTopLevelType()) { - // mark type start - declarationTypeOffset = declaration.length(); - } - - super.visitClassType(name); - } - - @Override - protected void startType() { - super.startType(); - - if (isTopLevelType()) { - // mark type start - declarationTypeOffset = declaration.length(); - } - } - - @Override - protected void endType() { - super.endType(); - - String type = declaration.subSequence(declarationTypeOffset, declaration.length()).toString(); - - maybeUseType(type); - } - - private void maybeUseType(final String typeName) { - if (!isTopLevelType()) { - return; - } - - char type; - String bytecodeName; - - if (visitingArray) { - type = '['; - - int arrayCount = StringUtil.count(typeName, '['); - String arrayDepth = StringUtil.repeat('[', arrayCount); - - int ndx = typeName.indexOf('['); - bytecodeName = typeName.substring(0, ndx); - - char arrayType = AsmUtil.typeNameToOpcode(bytecodeName); - if (arrayType != 'L') { - bytecodeName = String.valueOf(arrayType); - } - else { - bytecodeName = resolveBytecodeName(bytecodeName); - } - - bytecodeName = arrayDepth + bytecodeName; - } - else { - type = AsmUtil.typeNameToOpcode(typeName); - - if (type != 'L') { - bytecodeName = String.valueOf(type); - } - else { - bytecodeName = resolveBytecodeName(typeName); - } - } - - final TypeInfoImpl typeInfo = new TypeInfoImpl( - type, - typeName, - bytecodeName, - resolveRawTypeName(bytecodeName)); - - if (visitingArgument) { - if (type == 'V') { - throw new ProxettaException("Method argument can't be void"); - } - - arguments.add(typeInfo); - - argumentsCount++; - argumentsOffset.append(argumentsWords + 1); - - if ((type == 'D') || (type == 'J')) { - argumentsWords += 2; - } else { - argumentsWords++; - } - } - else if (visitingReturnType) { - returnType = typeInfo; - } - - visitingReturnType = false; - visitingArgument = false; - visitingArray = false; - } - - /** - * Returns {@code true} if we are scanning the top-level type and not - * the inner ones, like generics. - */ - private boolean isTopLevelType() { - return argumentStack == 0; - } - - private String resolveBytecodeName(String typeName) { - int ndx = 0; - int genericsStartNdx = -1; - int bracketCount = 0; - - while (ndx < typeName.length()) { - final char c = typeName.charAt(ndx); - - if (c == '<') { - if (bracketCount == 0) { - genericsStartNdx = ndx; - } - bracketCount++; - ndx++; - continue; - } - - if (c == '>') { - bracketCount--; - if (bracketCount == 0) { - break; - } - } - - ndx++; - } - - if (genericsStartNdx != -1) { - typeName = typeName.substring(0, genericsStartNdx) + typeName.substring(ndx + 1); - } - - if (isGenericType(typeName)) { - return typeName; - } - - return 'L' + typeName.replace('.', '/') + ';'; - } - - /** - * Resolves raw type name using the generics information from the class - * or method information. - */ - private String resolveRawTypeName(String typeName) { - if (typeName == null) { - return null; - } - - boolean isArray = typeName.startsWith(StringPool.LEFT_SQ_BRACKET); - if (isArray) { - typeName = typeName.substring(1); - } - - String rawTypeName; - - if (generics.containsKey(typeName)) { - rawTypeName = generics.get(typeName); - } - else { - rawTypeName = declaredTypeGeneric.getOrDefault(typeName, typeName); - } - - if (isArray) { - rawTypeName = '[' + rawTypeName; - } - - return rawTypeName; - } - - private boolean isGenericType(final String typeName) { - if (generics.containsKey(typeName)) { - return true; - } - return declaredTypeGeneric.containsKey(typeName); - } - - // ---------------------------------------------------------------- toString - - @Override - public String toString() { - return getDeclaredClassName() + '#' + getMethodName() + getDescription(); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaAsmUtil.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaAsmUtil.java deleted file mode 100644 index 73080973f..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaAsmUtil.java +++ /dev/null @@ -1,970 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.asm.AsmUtil; -import jodd.asm7.Label; -import jodd.asm7.MethodVisitor; -import jodd.asm7.Type; -import jodd.proxetta.MethodInfo; -import jodd.proxetta.ProxettaException; -import jodd.proxetta.ProxettaNames; -import jodd.proxetta.TypeInfo; -import jodd.util.ClassUtil; -import jodd.util.StringBand; -import jodd.util.StringPool; -import jodd.util.SystemUtil; - -import java.lang.reflect.Method; - -import static jodd.asm7.Opcodes.AASTORE; -import static jodd.asm7.Opcodes.ACONST_NULL; -import static jodd.asm7.Opcodes.ALOAD; -import static jodd.asm7.Opcodes.ANEWARRAY; -import static jodd.asm7.Opcodes.ARETURN; -import static jodd.asm7.Opcodes.ASTORE; -import static jodd.asm7.Opcodes.BASTORE; -import static jodd.asm7.Opcodes.BIPUSH; -import static jodd.asm7.Opcodes.CASTORE; -import static jodd.asm7.Opcodes.CHECKCAST; -import static jodd.asm7.Opcodes.DASTORE; -import static jodd.asm7.Opcodes.DCONST_0; -import static jodd.asm7.Opcodes.DLOAD; -import static jodd.asm7.Opcodes.DRETURN; -import static jodd.asm7.Opcodes.DSTORE; -import static jodd.asm7.Opcodes.DUP; -import static jodd.asm7.Opcodes.FASTORE; -import static jodd.asm7.Opcodes.FCONST_0; -import static jodd.asm7.Opcodes.FLOAD; -import static jodd.asm7.Opcodes.FRETURN; -import static jodd.asm7.Opcodes.FSTORE; -import static jodd.asm7.Opcodes.GETSTATIC; -import static jodd.asm7.Opcodes.IASTORE; -import static jodd.asm7.Opcodes.ICONST_0; -import static jodd.asm7.Opcodes.IFNONNULL; -import static jodd.asm7.Opcodes.ILOAD; -import static jodd.asm7.Opcodes.IRETURN; -import static jodd.asm7.Opcodes.ISTORE; -import static jodd.asm7.Opcodes.LASTORE; -import static jodd.asm7.Opcodes.LCONST_0; -import static jodd.asm7.Opcodes.LLOAD; -import static jodd.asm7.Opcodes.LRETURN; -import static jodd.asm7.Opcodes.LSTORE; -import static jodd.asm7.Opcodes.NEWARRAY; -import static jodd.asm7.Opcodes.POP; -import static jodd.asm7.Opcodes.RETURN; -import static jodd.asm7.Opcodes.SASTORE; -import static jodd.asm7.Opcodes.SIPUSH; -import static jodd.asm7.Opcodes.T_BOOLEAN; -import static jodd.asm7.Opcodes.T_BYTE; -import static jodd.asm7.Opcodes.T_CHAR; -import static jodd.asm7.Opcodes.T_DOUBLE; -import static jodd.asm7.Opcodes.T_FLOAT; -import static jodd.asm7.Opcodes.T_INT; -import static jodd.asm7.Opcodes.T_LONG; -import static jodd.asm7.Opcodes.T_SHORT; -import static jodd.util.StringPool.COLON; - -/** - * Various ASM utilities used by {@link jodd.proxetta.Proxetta}. - * For more generic ASM tools, see {@link jodd.asm.AsmUtil}. - */ -public class ProxettaAsmUtil { - - public static final String INIT = ""; - public static final String CLINIT = ""; - public static final String DESC_VOID = "()V"; - - // ---------------------------------------------------------------- versions - - /** - * Resolves Java version from current version. - */ - public static int resolveJavaVersion(final int version) { - final int javaVersionNumber = SystemUtil.info().getJavaVersionNumber(); - final int platformVersion = javaVersionNumber - 8 + 52; - - return version > platformVersion ? version : platformVersion; - } - - // ---------------------------------------------------------------- misc - - /** - * Pushes int value in an optimal way. - */ - public static void pushInt(final MethodVisitor mv, final int value) { - if (value <= 5) { - mv.visitInsn(ICONST_0 + value); - } else if (value <= Byte.MAX_VALUE) { - mv.visitIntInsn(BIPUSH, value); - } else { - mv.visitIntInsn(SIPUSH, value); - } - } - - /** - * Changes method access to private and final. - */ - public static int makePrivateFinalAccess(final int access) { - return (access & 0xFFFFFFF0) | AsmUtil.ACC_PRIVATE | AsmUtil.ACC_FINAL; - } - - /** - * Validates argument index. - */ - public static void checkArgumentIndex(final MethodInfo methodInfo, final int argIndex) { - if ((argIndex < 1) || (argIndex > methodInfo.getArgumentsCount())) { - throw new ProxettaException("Invalid argument index: " + argIndex); - } - } - - /** - * Builds advice field name. - */ - public static String adviceFieldName(final String name, final int index) { - return ProxettaNames.fieldPrefix + name + ProxettaNames.fieldDivider + index; - } - - /** - * Builds advice method name. - */ - public static String adviceMethodName(final String name, final int index) { - return ProxettaNames.methodPrefix + name + ProxettaNames.methodDivider + index; - } - - // ---------------------------------------------------------------- load - - public static void loadMethodArgumentClass(final MethodVisitor mv, final MethodInfo methodInfo, final int index) { - final TypeInfo argument = methodInfo.getArgument(index); - loadClass(mv, argument.getOpcode(), argument.getRawName()); - } - - public static void loadClass(final MethodVisitor mv, final int type, final String typeName) { - switch (type) { - case 'V': - mv.visitFieldInsn(GETSTATIC, AsmUtil.SIGNATURE_JAVA_LANG_VOID, "TYPE", AsmUtil.L_SIGNATURE_JAVA_LANG_CLASS); - break; - case 'B': - mv.visitFieldInsn(GETSTATIC, AsmUtil.SIGNATURE_JAVA_LANG_BYTE, "TYPE", AsmUtil.L_SIGNATURE_JAVA_LANG_CLASS); - break; - case 'C': - mv.visitFieldInsn(GETSTATIC, AsmUtil.SIGNATURE_JAVA_LANG_CHARACTER, "TYPE", AsmUtil.L_SIGNATURE_JAVA_LANG_CLASS); - break; - case 'S': - mv.visitFieldInsn(GETSTATIC, AsmUtil.SIGNATURE_JAVA_LANG_SHORT, "TYPE", AsmUtil.L_SIGNATURE_JAVA_LANG_CLASS); - break; - case 'I': - mv.visitFieldInsn(GETSTATIC, AsmUtil.SIGNATURE_JAVA_LANG_INTEGER, "TYPE", AsmUtil.L_SIGNATURE_JAVA_LANG_CLASS); - break; - case 'Z': - mv.visitFieldInsn(GETSTATIC, AsmUtil.SIGNATURE_JAVA_LANG_BOOLEAN, "TYPE", AsmUtil.L_SIGNATURE_JAVA_LANG_CLASS); - break; - case 'J': - mv.visitFieldInsn(GETSTATIC, AsmUtil.SIGNATURE_JAVA_LANG_LONG, "TYPE", AsmUtil.L_SIGNATURE_JAVA_LANG_CLASS); - break; - case 'F': - mv.visitFieldInsn(GETSTATIC, AsmUtil.SIGNATURE_JAVA_LANG_FLOAT, "TYPE", AsmUtil.L_SIGNATURE_JAVA_LANG_CLASS); - break; - case 'D': - mv.visitFieldInsn(GETSTATIC, AsmUtil.SIGNATURE_JAVA_LANG_DOUBLE, "TYPE", AsmUtil.L_SIGNATURE_JAVA_LANG_CLASS); - break; - default: - mv.visitLdcInsn(Type.getType(typeName)); - break; - } - - } - - /** - * Loads all method arguments before INVOKESPECIAL call. - */ - public static void loadSpecialMethodArguments(final MethodVisitor mv, final MethodInfo methodInfo) { - mv.visitVarInsn(ALOAD, 0); - for (int i = 1; i <= methodInfo.getArgumentsCount(); i++) { - loadMethodArgument(mv, methodInfo, i); - } - } - - /** - * Loads all method arguments before INVOKESTATIC call. - */ - public static void loadStaticMethodArguments(final MethodVisitor mv, final MethodInfo methodInfo) { - for (int i = 0; i < methodInfo.getArgumentsCount(); i++) { - loadMethodArgument(mv, methodInfo, i); - } - } - - /** - * Loads all method arguments before INVOKEVIRTUAL call. - */ - public static void loadVirtualMethodArguments(final MethodVisitor mv, final MethodInfo methodInfo) { - for (int i = 1; i <= methodInfo.getArgumentsCount(); i++) { - loadMethodArgument(mv, methodInfo, i); - } - } - - /** - * Loads one argument. Index is 1-based. No conversion occurs. - */ - public static void loadMethodArgument(final MethodVisitor mv, final MethodInfo methodInfo, final int index) { - final int offset = methodInfo.getArgumentOffset(index); - final int type = methodInfo.getArgument(index).getOpcode(); - switch (type) { - case 'V': - break; - case 'B': - case 'C': - case 'S': - case 'I': - case 'Z': - mv.visitVarInsn(ILOAD, offset); - break; - case 'J': - mv.visitVarInsn(LLOAD, offset); - break; - case 'F': - mv.visitVarInsn(FLOAD, offset); - break; - case 'D': - mv.visitVarInsn(DLOAD, offset); - break; - default: - mv.visitVarInsn(ALOAD, offset); - } - } - - - public static void loadMethodArgumentAsObject(final MethodVisitor mv, final MethodInfo methodInfo, final int index) { - final int offset = methodInfo.getArgumentOffset(index); - final int type = methodInfo.getArgument(index).getOpcode(); - switch (type) { - case 'V': - break; - case 'B': - mv.visitVarInsn(ILOAD, offset); - AsmUtil.valueOfByte(mv); - break; - case 'C': - mv.visitVarInsn(ILOAD, offset); - AsmUtil.valueOfCharacter(mv); - break; - case 'S': - mv.visitVarInsn(ILOAD, offset); - AsmUtil.valueOfShort(mv); - break; - case 'I': - mv.visitVarInsn(ILOAD, offset); - AsmUtil.valueOfInteger(mv); - break; - case 'Z': - mv.visitVarInsn(ILOAD, offset); - AsmUtil.valueOfBoolean(mv); - break; - case 'J': - mv.visitVarInsn(LLOAD, offset); - AsmUtil.valueOfLong(mv); - break; - case 'F': - mv.visitVarInsn(FLOAD, offset); - AsmUtil.valueOfFloat(mv); - break; - case 'D': - mv.visitVarInsn(DLOAD, offset); - AsmUtil.valueOfDouble(mv); - break; - default: - mv.visitVarInsn(ALOAD, offset); - } - } - - // ---------------------------------------------------------------- store - - /** - * Stores one argument. Index is 1-based. No conversion occurs. - */ - public static void storeMethodArgument(final MethodVisitor mv, final MethodInfo methodInfo, final int index) { - final int offset = methodInfo.getArgumentOffset(index); - final int type = methodInfo.getArgument(index).getOpcode(); - switch (type) { - case 'V': - break; - case 'B': - case 'C': - case 'S': - case 'I': - case 'Z': - mv.visitVarInsn(ISTORE, offset); break; - case 'J': - mv.visitVarInsn(LSTORE, offset); break; - case 'F': - mv.visitVarInsn(FSTORE, offset); break; - case 'D': - mv.visitVarInsn(DSTORE, offset); break; - default: - mv.visitVarInsn(ASTORE, offset); - } - } - - /** - * Returns true if opcode is xSTORE. - */ - public static boolean isStoreOpcode(final int opcode) { - return (opcode == ISTORE) - || (opcode == LSTORE) - || (opcode == FSTORE) - || (opcode == DSTORE) - || (opcode == ASTORE); - } - - - public static void storeMethodArgumentFromObject(final MethodVisitor mv, final MethodInfo methodInfo, final int index) { - final int type = methodInfo.getArgument(index).getOpcode(); - final int offset = methodInfo.getArgumentOffset(index); - storeValue(mv, offset, type); - } - - public static void storeValue(final MethodVisitor mv, final int offset, final int type) { - switch (type) { - case 'V': - break; - case 'B': - AsmUtil.byteValue(mv); - mv.visitVarInsn(ISTORE, offset); - break; - case 'C': - AsmUtil.charValue(mv); - mv.visitVarInsn(ISTORE, offset); - break; - case 'S': - AsmUtil.shortValue(mv); - mv.visitVarInsn(ISTORE, offset); - break; - case 'I': - AsmUtil.intValue(mv); - mv.visitVarInsn(ISTORE, offset); - break; - case 'Z': - AsmUtil.booleanValue(mv); - mv.visitVarInsn(ISTORE, offset); - break; - case 'J': - AsmUtil.longValue(mv); - mv.visitVarInsn(LSTORE, offset); - break; - case 'F': - AsmUtil.floatValue(mv); - mv.visitVarInsn(FSTORE, offset); - break; - case 'D': - AsmUtil.doubleValue(mv); - mv.visitVarInsn(DSTORE, offset); - break; - default: - mv.visitVarInsn(ASTORE, offset); - } - } - - // ---------------------------------------------------------------- return - - /** - * Visits return opcodes. - */ - public static void visitReturn(final MethodVisitor mv, final MethodInfo methodInfo, final boolean isLast) { - switch (methodInfo.getReturnType().getOpcode()) { - case 'V': - if (isLast) { - mv.visitInsn(POP); - } - mv.visitInsn(RETURN); - break; - - case 'B': - if (isLast) { - mv.visitInsn(DUP); - final Label label = new Label(); - mv.visitJumpInsn(IFNONNULL, label); - mv.visitInsn(POP); - mv.visitInsn(ICONST_0); - mv.visitInsn(IRETURN); - mv.visitLabel(label); - - AsmUtil.byteValue(mv); - } - mv.visitInsn(IRETURN); - break; - - case 'C': - if (isLast) { - mv.visitInsn(DUP); - final Label label = new Label(); - mv.visitJumpInsn(IFNONNULL, label); - mv.visitInsn(POP); - mv.visitInsn(ICONST_0); - mv.visitInsn(IRETURN); - mv.visitLabel(label); - - AsmUtil.charValue(mv); - } - mv.visitInsn(IRETURN); - break; - - case 'S': - if (isLast) { - mv.visitInsn(DUP); - final Label label = new Label(); - mv.visitJumpInsn(IFNONNULL, label); - mv.visitInsn(POP); - mv.visitInsn(ICONST_0); - mv.visitInsn(IRETURN); - mv.visitLabel(label); - - AsmUtil.shortValue(mv); - } - mv.visitInsn(IRETURN); - break; - - case 'I': - if (isLast) { - mv.visitInsn(DUP); - final Label label = new Label(); - mv.visitJumpInsn(IFNONNULL, label); - mv.visitInsn(POP); - mv.visitInsn(ICONST_0); - mv.visitInsn(IRETURN); - mv.visitLabel(label); - - AsmUtil.intValue(mv); - } - mv.visitInsn(IRETURN); - break; - - case 'Z': - if (isLast) { - mv.visitInsn(DUP); - final Label label = new Label(); - mv.visitJumpInsn(IFNONNULL, label); - mv.visitInsn(POP); - mv.visitInsn(ICONST_0); - mv.visitInsn(IRETURN); - mv.visitLabel(label); - - AsmUtil.booleanValue(mv); - } - mv.visitInsn(IRETURN); - break; - - case 'J': - if (isLast) { - mv.visitInsn(DUP); - final Label label = new Label(); - mv.visitJumpInsn(IFNONNULL, label); - mv.visitInsn(POP); - mv.visitInsn(LCONST_0); - mv.visitInsn(LRETURN); - mv.visitLabel(label); - - AsmUtil.longValue(mv); - } - mv.visitInsn(LRETURN); - break; - - case 'F': - if (isLast) { - mv.visitInsn(DUP); - final Label label = new Label(); - mv.visitJumpInsn(IFNONNULL, label); - mv.visitInsn(POP); - mv.visitInsn(FCONST_0); - mv.visitInsn(FRETURN); - mv.visitLabel(label); - - AsmUtil.floatValue(mv); - } - mv.visitInsn(FRETURN); - break; - - case 'D': - if (isLast) { - mv.visitInsn(DUP); - final Label label = new Label(); - mv.visitJumpInsn(IFNONNULL, label); - mv.visitInsn(POP); - mv.visitInsn(DCONST_0); - mv.visitInsn(DRETURN); - mv.visitLabel(label); - - AsmUtil.doubleValue(mv); - } - mv.visitInsn(DRETURN); - break; - - default: - mv.visitInsn(ARETURN); - break; - } - } - - /** - * Prepares return value. - */ - public static void prepareReturnValue(final MethodVisitor mv, final MethodInfo methodInfo, int varOffset) { - varOffset += methodInfo.getAllArgumentsSize(); - switch (methodInfo.getReturnType().getOpcode()) { - case 'V': - mv.visitInsn(ACONST_NULL); - break; - case 'B': - AsmUtil.valueOfByte(mv); - break; - case 'C': - AsmUtil.valueOfCharacter(mv); - break; - case 'S': - AsmUtil.valueOfShort(mv); - break; - case 'I': - AsmUtil.valueOfInteger(mv); - break; - case 'Z': - AsmUtil.valueOfBoolean(mv); - break; - case 'J': - AsmUtil.valueOfLong(mv); - break; - case 'F': - AsmUtil.valueOfFloat(mv); - break; - case 'D': - AsmUtil.valueOfDouble(mv); - break; - - } - } - - public static void castToReturnType(final MethodVisitor mv, final MethodInfo methodInfo) { - final String returnType; - - final char returnOpcodeType = methodInfo.getReturnType().getOpcode(); - - switch (returnOpcodeType) { - case 'I': - returnType = AsmUtil.SIGNATURE_JAVA_LANG_INTEGER; - break; - case 'J': - returnType = AsmUtil.SIGNATURE_JAVA_LANG_LONG; - break; - case 'S': - returnType = AsmUtil.SIGNATURE_JAVA_LANG_SHORT; - break; - case 'B': - returnType = AsmUtil.SIGNATURE_JAVA_LANG_BYTE; - break; - case 'Z': - returnType = AsmUtil.SIGNATURE_JAVA_LANG_BOOLEAN; - break; - case 'F': - returnType = AsmUtil.SIGNATURE_JAVA_LANG_FLOAT; - break; - case 'D': - returnType = AsmUtil.SIGNATURE_JAVA_LANG_DOUBLE; - break; - case 'C': - returnType = AsmUtil.SIGNATURE_JAVA_LANG_CHARACTER; - break; - case '[': - returnType = methodInfo.getReturnType().getRawName(); - break; - default: - final String rtname = methodInfo.getReturnType().getRawName(); - returnType = rtname.length() == 0 ? - AsmUtil.typeToSignature(methodInfo.getReturnType().getType()) : - AsmUtil.typedesc2ClassName(rtname); - break; - } - - mv.visitTypeInsn(CHECKCAST, returnType); - } - - // ---------------------------------------------------------------- method signature - - - /** - * Creates unique key for method signatures map. - */ - public static String createMethodSignaturesKey(final int access, final String methodName, final String description, final String className) { - return new StringBand(7) - .append(access) - .append(COLON) - .append(description) - .append(StringPool.UNDERSCORE) - .append(className) - .append(StringPool.HASH) - .append(methodName) - .toString(); - } - - // ---------------------------------------------------------------- annotation work - - /** - * Visits non-array element value for annotation. Returns true - * if value is successfully processed. - */ - public static void visitElementValue(final MethodVisitor mv, final Object elementValue, final boolean boxPrimitives) { - if (elementValue instanceof String) { // string - mv.visitLdcInsn(elementValue); - return; - } - if (elementValue instanceof Type) { // class - mv.visitLdcInsn(elementValue); - return; - } - if (elementValue instanceof Class) { - mv.visitLdcInsn(Type.getType((Class) elementValue)); - return; - } - - // primitives - - if (elementValue instanceof Integer) { - mv.visitLdcInsn(elementValue); - if (boxPrimitives) { - AsmUtil.valueOfInteger(mv); - } - return; - } - if (elementValue instanceof Long) { - mv.visitLdcInsn(elementValue); - if (boxPrimitives) { - AsmUtil.valueOfLong(mv); - } - return; - } - if (elementValue instanceof Short) { - mv.visitLdcInsn(elementValue); - if (boxPrimitives) { - AsmUtil.valueOfShort(mv); - } - return; - } - if (elementValue instanceof Byte) { - mv.visitLdcInsn(elementValue); - if (boxPrimitives) { - AsmUtil.valueOfByte(mv); - } - return; - } - if (elementValue instanceof Float) { - mv.visitLdcInsn(elementValue); - if (boxPrimitives) { - AsmUtil.valueOfFloat(mv); - } - return; - } - if (elementValue instanceof Double) { - mv.visitLdcInsn(elementValue); - if (boxPrimitives) { - AsmUtil.valueOfDouble(mv); - } - return; - } - if (elementValue instanceof Character) { - mv.visitLdcInsn(elementValue); - if (boxPrimitives) { - AsmUtil.valueOfCharacter(mv); - } - return; - } - if (elementValue instanceof Boolean) { - mv.visitLdcInsn(elementValue); - if (boxPrimitives) { - AsmUtil.valueOfBoolean(mv); - } - return; - } - - // enum - - final Class elementValueClass = elementValue.getClass(); - final Class enumClass = ClassUtil.findEnum(elementValueClass); - - if (enumClass != null) { - try { - final String typeRef = AsmUtil.typeToTyperef(enumClass); - final String typeSignature = AsmUtil.typeToSignature(enumClass); - - // invoke - final Method nameMethod = elementValue.getClass().getMethod("name"); - final String name = (String) nameMethod.invoke(elementValue); - - mv.visitFieldInsn(GETSTATIC, typeSignature, name, typeRef); - - return; - } catch (final Exception ignore) { - } - } - - throw new ProxettaException("Unsupported annotation type: " + elementValue.getClass()); - } - - // ---------------------------------------------------------------- array - - /** - * Creates new array. - */ - public static void newArray(final MethodVisitor mv, final Class componentType) { - if (componentType == int.class) { - mv.visitIntInsn(NEWARRAY, T_INT); - return; - } - if (componentType == long.class) { - mv.visitIntInsn(NEWARRAY, T_LONG); - return; - } - if (componentType == float.class) { - mv.visitIntInsn(NEWARRAY, T_FLOAT); - return; - } - if (componentType == double.class) { - mv.visitIntInsn(NEWARRAY, T_DOUBLE); - return; - } - if (componentType == byte.class) { - mv.visitIntInsn(NEWARRAY, T_BYTE); - return; - } - if (componentType == short.class) { - mv.visitIntInsn(NEWARRAY, T_SHORT); - return; - } - if (componentType == boolean.class) { - mv.visitIntInsn(NEWARRAY, T_BOOLEAN); - return; - } - if (componentType == char.class) { - mv.visitIntInsn(NEWARRAY, T_CHAR); - return; - } - - mv.visitTypeInsn(ANEWARRAY, AsmUtil.typeToSignature(componentType)); - } - - /** - * Stores element on stack into an array. - */ - public static void storeIntoArray(final MethodVisitor mv, final Class componentType) { - if (componentType == int.class) { - mv.visitInsn(IASTORE); - return; - } - if (componentType == long.class) { - mv.visitInsn(LASTORE); - return; - } - if (componentType == float.class) { - mv.visitInsn(FASTORE); - return; - } - if (componentType == double.class) { - mv.visitInsn(DASTORE); - return; - } - if (componentType == byte.class) { - mv.visitInsn(BASTORE); - return; - } - if (componentType == short.class) { - mv.visitInsn(SASTORE); - return; - } - if (componentType == boolean.class) { - mv.visitInsn(BASTORE); - return; - } - if (componentType == char.class) { - mv.visitInsn(CASTORE); - return; - } - - mv.visitInsn(AASTORE); - } - - // ---------------------------------------------------------------- detect advice macros - - public static boolean isInvokeMethod(final String name, final String desc) { - if (name.equals("invoke")) { - if (desc.equals("()Ljava/lang/Object;")) { - return true; - } - } - return false; - } - - public static boolean isArgumentsCountMethod(final String name, final String desc) { - if (name.equals("argumentsCount")) { - if (desc.equals("()I")) { - return true; - } - } - return false; - } - - public static boolean isArgumentTypeMethod(final String name, final String desc) { - if (name.equals("argumentType")) { - if (desc.equals("(I)Ljava/lang/Class;")) { - return true; - } - } - return false; - } - - public static boolean isArgumentMethod(final String name, final String desc) { - if (name.equals("argument")) { - if (desc.equals("(I)Ljava/lang/Object;")) { - return true; - } - } - return false; - } - - public static boolean isSetArgumentMethod(final String name, final String desc) { - if (name.equals("setArgument")) { - if (desc.equals("(Ljava/lang/Object;I)V")) { - return true; - } - } - return false; - } - - public static boolean isCreateArgumentsArrayMethod(final String name, final String desc) { - if (name.equals("createArgumentsArray")) { - if (desc.equals("()[Ljava/lang/Object;")) { - return true; - } - } - return false; - } - - public static boolean isCreateArgumentsClassArrayMethod(final String name, final String desc) { - if (name.equals("createArgumentsClassArray")) { - if (desc.equals("()[Ljava/lang/Class;")) { - return true; - } - } - return false; - } - - public static boolean isReturnTypeMethod(final String name, final String desc) { - if (name.equals("returnType")) { - if (desc.equals("()Ljava/lang/Class;")) { - return true; - } - } - return false; - } - - public static boolean isTargetMethod(final String name, final String desc) { - if (name.equals("target")) { - if (desc.equals("()Ljava/lang/Object;")) { - return true; - } - } - return false; - } - - - public static boolean isTargetClassMethod(final String name, final String desc) { - if (name.equals("targetClass")) { - if (desc.equals("()Ljava/lang/Class;")) { - return true; - } - } - return false; - } - - public static boolean isTargetMethodNameMethod(final String name, final String desc) { - if (name.equals("targetMethodName")) { - if (desc.equals("()Ljava/lang/String;")) { - return true; - } - } - return false; - } - - public static boolean isTargetMethodSignatureMethod(final String name, final String desc) { - if (name.equals("targetMethodSignature")) { - if (desc.equals("()Ljava/lang/String;")) { - return true; - } - } - return false; - } - - public static boolean isTargetMethodDescriptionMethod(final String name, final String desc) { - if (name.equals("targetMethodDescription")) { - if (desc.equals("()Ljava/lang/String;")) { - return true; - } - } - return false; - } - - public static boolean isReturnValueMethod(final String name, final String desc) { - if (name.equals("returnValue")) { - if (desc.equals("(Ljava/lang/Object;)Ljava/lang/Object;")) { - return true; - } - } - return false; - } - - public static boolean isInfoMethod(final String name, final String desc) { - if (name.equals("info")) { - if (desc.equals("()Ljodd/proxetta/ProxyTargetInfo;")) { - return true; - } - } - return false; - } - - public static boolean isTargetMethodAnnotationMethod(final String name, final String desc) { - if (name.equals("targetMethodAnnotation")) { - if (desc.equals("(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;")) { - return true; - } - } - return false; - } - - public static boolean isTargetClassAnnotationMethod(final String name, final String desc) { - if (name.equals("targetClassAnnotation")) { - if (desc.equals("(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;")) { - return true; - } - } - return false; - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaClassBuilder.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaClassBuilder.java deleted file mode 100644 index 0ff83b33b..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaClassBuilder.java +++ /dev/null @@ -1,328 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.asm.AnnotationVisitorAdapter; -import jodd.asm.AsmUtil; -import jodd.asm.EmptyClassVisitor; -import jodd.asm7.AnnotationVisitor; -import jodd.asm7.Attribute; -import jodd.asm7.ClassReader; -import jodd.asm7.ClassVisitor; -import jodd.asm7.FieldVisitor; -import jodd.asm7.MethodVisitor; -import jodd.proxetta.ProxettaException; -import jodd.proxetta.ProxettaNames; -import jodd.proxetta.ProxyAspect; - -import java.util.ArrayList; -import java.util.List; - -import static jodd.asm7.Opcodes.ACC_ABSTRACT; -import static jodd.asm7.Opcodes.ALOAD; -import static jodd.asm7.Opcodes.INVOKESPECIAL; -import static jodd.asm7.Opcodes.INVOKESTATIC; -import static jodd.asm7.Opcodes.RETURN; -import static jodd.proxetta.asm.ProxettaAsmUtil.CLINIT; -import static jodd.proxetta.asm.ProxettaAsmUtil.DESC_VOID; -import static jodd.proxetta.asm.ProxettaAsmUtil.INIT; - -/** - * Proxetta class builder. - */ -public class ProxettaClassBuilder extends EmptyClassVisitor { - - protected final ProxyAspect[] aspects; - protected final String suffix; - protected final String reqProxyClassName; - protected final TargetClassInfoReader targetClassInfo; - - protected final WorkData wd; - - /** - * Constructs new Proxetta class builder. - * @param dest destination visitor - * @param aspects set of aspects to apply - * @param suffix proxy class name suffix, may be null - * @param reqProxyClassName requested proxy class name, may be nulls - * @param targetClassInfoReader target info reader, already invoked. - */ - public ProxettaClassBuilder(final ClassVisitor dest, final ProxyAspect[] aspects, final String suffix, final String reqProxyClassName, final TargetClassInfoReader targetClassInfoReader) { - this.wd = new WorkData(dest); - this.aspects = aspects; - this.suffix = suffix; - this.reqProxyClassName = reqProxyClassName; - this.targetClassInfo = targetClassInfoReader; - } - - /** - * Returns working data. - */ - public WorkData getWorkData() { - return wd; - } - - // ---------------------------------------------------------------- header - - - /** - * Creates destination subclass header from current target class. Destination name is created from targets by - * adding a suffix and, optionally, a number. Destination extends the target. - */ - @Override - public void visit(final int version, int access, final String name, final String signature, final String superName, final String[] interfaces) { - wd.init(name, superName, this.suffix, this.reqProxyClassName); - - // change access of destination - access &= ~AsmUtil.ACC_ABSTRACT; - - // write destination class - final int v = ProxettaAsmUtil.resolveJavaVersion(version); - wd.dest.visit(v, access, wd.thisReference, signature, wd.superName, null); - - wd.proxyAspects = new ProxyAspectData[aspects.length]; - for (int i = 0; i < aspects.length; i++) { - wd.proxyAspects[i] = new ProxyAspectData(wd, aspects[i], i); - } - } - - - // ---------------------------------------------------------------- methods and fields - - /** - * Creates proxified methods and constructors. - * Destination proxy will have all constructors as a target class, using {@link jodd.proxetta.asm.ProxettaCtorBuilder}. - * Static initializers are removed, since they will be execute in target anyway. - * For each method, {@link ProxettaMethodBuilder} determines if method matches pointcut. If so, method will be proxified. - */ - @Override - public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { - final MethodSignatureVisitor msign = targetClassInfo.lookupMethodSignatureVisitor(access, name, desc, wd.superReference); - if (msign == null) { - return null; - } - if (msign.isFinal && !wd.allowFinalMethods) { - return null; - } - - // destination constructors [A1] - if (name.equals(INIT)) { - MethodVisitor mv = wd.dest.visitMethod(access, name, desc, msign.getAsmMethodSignature(), null); - return new ProxettaCtorBuilder(mv, msign, wd); - } - // ignore destination static block - if (name.equals(CLINIT)) { - return null; - } - return applyProxy(msign); - } - - - /** - * Ignores fields. Fields are not copied to the destination. - */ - @Override - public FieldVisitor visitField(final int access, final String name, final String desc, final String signature, final Object value) { - return null; - } - - - // ---------------------------------------------------------------- annotation - - /** - * Copies all destination type annotations to the target. - */ - @Override - public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { - AnnotationVisitor destAnn = wd.dest.visitAnnotation(desc, visible); // [A3] - return new AnnotationVisitorAdapter(destAnn); - } - - // ---------------------------------------------------------------- end - - /** - * Finalizes creation of destination proxy class. - */ - @Override - public void visitEnd() { - makeStaticInitBlock(); - - makeProxyConstructor(); - - processSuperMethods(); - - wd.dest.visitEnd(); - } - - /** - * Creates static initialization block that simply calls all - * advice static init methods in correct order. - */ - protected void makeStaticInitBlock() { - if (wd.adviceClinits != null) { - MethodVisitor mv = wd.dest.visitMethod(AsmUtil.ACC_STATIC, CLINIT, DESC_VOID, null, null); - mv.visitCode(); - for (String name : wd.adviceClinits) { - mv.visitMethodInsn( - INVOKESTATIC, - wd.thisReference, - name, DESC_VOID, - false); - } - mv.visitInsn(RETURN); - mv.visitMaxs(0, 0); - mv.visitEnd(); - } - } - - /** - * Creates init method that simply calls all advice constructor methods in correct order. - * This created init method is called from each destination's constructor. - */ - protected void makeProxyConstructor() { - MethodVisitor mv = wd.dest.visitMethod(AsmUtil.ACC_PRIVATE | AsmUtil.ACC_FINAL, ProxettaNames.initMethodName, DESC_VOID, null, null); - mv.visitCode(); - if (wd.adviceInits != null) { - for (String name : wd.adviceInits) { - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn - (INVOKESPECIAL, - wd.thisReference, - name, DESC_VOID, - false); - } - } - mv.visitInsn(RETURN); - mv.visitMaxs(0, 0); - mv.visitEnd(); - } - - /** - * Checks for all public super methods that are not overridden. - */ - protected void processSuperMethods() { - - for (ClassReader cr : targetClassInfo.superClassReaders) { - cr.accept(new EmptyClassVisitor() { - - String declaredClassName; - - @Override - public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { - declaredClassName = name; - } - - @Override - public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { - if (name.equals(INIT) || name.equals(CLINIT)) { - return null; - } - MethodSignatureVisitor msign = targetClassInfo.lookupMethodSignatureVisitor(access, name, desc, declaredClassName); - if (msign == null) { - return null; - } - return applyProxy(msign); - } - }, 0); - } - } - - - // ---------------------------------------------------------------- not used - - /** - * Visits the source of the class (not used). - */ - @Override - public void visitSource(final String source, final String debug) { - // not used - } - - /** - * Visits the enclosing class of the class (not used). - */ - @Override - public void visitOuterClass(final String owner, final String name, final String desc) { - // not used - } - - /** - * Visits a non standard attribute of the class (not used). - */ - @Override - public void visitAttribute(final Attribute attr) { - // not used - } - - /** - * Visits information about an inner class (not used). - */ - @Override - public void visitInnerClass(final String name, final String outerName, final String innerName, final int access) { - // not used - } - - // ---------------------------------------------------------------- create proxy method builder if needed - - - /** - * Check if proxy should be applied on method and return proxy method builder if so. - * Otherwise, returns null. - */ - protected ProxettaMethodBuilder applyProxy(final MethodSignatureVisitor msign) { - List aspectList = matchMethodPointcuts(msign); - - if (aspectList == null) { - // no pointcuts on this method, return - return null; - } - - int access = msign.getAccessFlags(); - if ((access & ACC_ABSTRACT) != 0) { - throw new ProxettaException("Unable to process abstract method: " + msign); - } - - wd.proxyApplied = true; - return new ProxettaMethodBuilder(msign, wd, aspectList); - } - - /** - * Matches pointcuts on method. If no pointcut found, returns null. - */ - protected List matchMethodPointcuts(final MethodSignatureVisitor msign) { - List aspectList = null; - for (ProxyAspectData aspectData : wd.proxyAspects) { - if (aspectData.apply(msign)) { - if (aspectList == null) { - aspectList = new ArrayList<>(wd.proxyAspects.length); - } - aspectList.add(aspectData); - } - } - return aspectList; - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaCtorBuilder.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaCtorBuilder.java deleted file mode 100644 index 30aa618d8..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaCtorBuilder.java +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.asm.EmptyMethodVisitor; -import jodd.asm7.AnnotationVisitor; -import jodd.asm7.MethodVisitor; -import jodd.proxetta.ProxettaNames; - -import static jodd.asm7.Opcodes.ALOAD; -import static jodd.asm7.Opcodes.INVOKESPECIAL; -import static jodd.asm7.Opcodes.RETURN; -import static jodd.proxetta.asm.ProxettaAsmUtil.DESC_VOID; -import static jodd.proxetta.asm.ProxettaAsmUtil.loadSpecialMethodArguments; - -/** - * Destination ctor builder - */ -public class ProxettaCtorBuilder extends EmptyMethodVisitor { - - protected final MethodSignatureVisitor msign; - protected final MethodVisitor methodVisitor; - protected final WorkData wd; - - public ProxettaCtorBuilder(final MethodVisitor methodVisitor, final MethodSignatureVisitor msign, final WorkData wd) { - this.methodVisitor = methodVisitor; - this.msign = msign; - this.wd = wd; - } - - @Override - public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { - methodVisitor.visitAnnotation(desc, visible); - return null; - } - - @Override - public AnnotationVisitor visitParameterAnnotation(final int parameter, final String desc, final boolean visible) { - methodVisitor.visitParameterAnnotation(parameter, desc, visible); - return null; - } - - @Override - public AnnotationVisitor visitAnnotationDefault() { - methodVisitor.visitAnnotationDefault(); - return null; - } - - @Override - public void visitEnd() { - methodVisitor.visitCode(); - - // call super ctor - loadSpecialMethodArguments(methodVisitor, msign); - methodVisitor.visitMethodInsn( - INVOKESPECIAL, - wd.superReference, - msign.getMethodName(), - msign.getDescription(), - false); - - // invoke advice ctors - methodVisitor.visitVarInsn(ALOAD, 0); - - methodVisitor.visitMethodInsn( - INVOKESPECIAL, - wd.thisReference, - ProxettaNames.initMethodName, DESC_VOID, - false); - - methodVisitor.visitInsn(RETURN); - methodVisitor.visitMaxs(0, 0); - methodVisitor.visitEnd(); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaMethodBuilder.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaMethodBuilder.java deleted file mode 100644 index 2895fc266..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaMethodBuilder.java +++ /dev/null @@ -1,439 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.asm.AnnotationVisitorAdapter; -import jodd.asm.AsmUtil; -import jodd.asm.EmptyClassVisitor; -import jodd.asm.EmptyMethodVisitor; -import jodd.asm7.AnnotationVisitor; -import jodd.asm7.MethodVisitor; -import jodd.proxetta.ProxettaException; -import jodd.proxetta.ProxettaNames; -import jodd.proxetta.ProxyTarget; -import jodd.proxetta.ProxyTargetReplacement; - -import java.util.List; - -import static jodd.asm7.Opcodes.ACC_ABSTRACT; -import static jodd.asm7.Opcodes.ACC_NATIVE; -import static jodd.asm7.Opcodes.ALOAD; -import static jodd.asm7.Opcodes.ARETURN; -import static jodd.asm7.Opcodes.ASTORE; -import static jodd.asm7.Opcodes.GETFIELD; -import static jodd.asm7.Opcodes.INVOKEINTERFACE; -import static jodd.asm7.Opcodes.INVOKESPECIAL; -import static jodd.asm7.Opcodes.INVOKESTATIC; -import static jodd.asm7.Opcodes.INVOKEVIRTUAL; -import static jodd.asm7.Opcodes.POP; -import static jodd.asm7.Opcodes.POP2; -import static jodd.proxetta.asm.ProxettaAsmUtil.adviceFieldName; -import static jodd.proxetta.asm.ProxettaAsmUtil.adviceMethodName; -import static jodd.proxetta.asm.ProxettaAsmUtil.castToReturnType; -import static jodd.proxetta.asm.ProxettaAsmUtil.checkArgumentIndex; -import static jodd.proxetta.asm.ProxettaAsmUtil.isArgumentMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isArgumentTypeMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isArgumentsCountMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isCreateArgumentsArrayMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isCreateArgumentsClassArrayMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isInfoMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isInvokeMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isReturnTypeMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isReturnValueMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isSetArgumentMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isTargetClassAnnotationMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isTargetClassMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isTargetMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isTargetMethodAnnotationMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isTargetMethodDescriptionMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isTargetMethodNameMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.isTargetMethodSignatureMethod; -import static jodd.proxetta.asm.ProxettaAsmUtil.loadSpecialMethodArguments; -import static jodd.proxetta.asm.ProxettaAsmUtil.loadStaticMethodArguments; -import static jodd.proxetta.asm.ProxettaAsmUtil.loadVirtualMethodArguments; -import static jodd.proxetta.asm.ProxettaAsmUtil.prepareReturnValue; -import static jodd.proxetta.asm.ProxettaAsmUtil.storeMethodArgumentFromObject; -import static jodd.proxetta.asm.ProxettaAsmUtil.visitReturn; - -@SuppressWarnings({"AnonymousClassVariableHidesContainingMethodVariable"}) -public class ProxettaMethodBuilder extends EmptyMethodVisitor { - - public static final String TARGET_CLASS_NAME = ProxyTarget.class.getSimpleName(); // extract ProxyTarget name for recognition - - protected final MethodSignatureVisitor msign; - protected final WorkData wd; - protected final List aspectList; - - public ProxettaMethodBuilder(final MethodSignatureVisitor msign, final WorkData wd, final List aspectList) { - this.msign = msign; - this.wd = wd; - this.aspectList = aspectList; - createFirstChainDelegate_Start(); - } - - // ---------------------------------------------------------------- visits - - /** - * Copies target method annotations. - */ - @Override - public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { - AnnotationVisitor destAnn = methodVisitor.visitAnnotation(desc, visible); // [A4] - return new AnnotationVisitorAdapter(destAnn); - } - - @Override - public AnnotationVisitor visitAnnotationDefault() { - AnnotationVisitor destAnn = methodVisitor.visitAnnotationDefault(); - return new AnnotationVisitorAdapter(destAnn); - } - - @Override - public AnnotationVisitor visitParameterAnnotation(final int parameter, final String desc, final boolean visible) { - AnnotationVisitor destAnn = methodVisitor.visitParameterAnnotation(parameter, desc, visible); - return new AnnotationVisitorAdapter(destAnn); - } - - - /** - * Finally, builds proxy methods if applied to current method. - */ - @Override - public void visitEnd() { - createFirstChainDelegate_Continue(tmd); - for (int p = 0; p < tmd.proxyData.length; p++) { - tmd.selectCurrentProxy(p); - createProxyMethod(tmd); - } - } - - - // ---------------------------------------------------------------- creating - - protected TargetMethodData tmd; - protected MethodVisitor methodVisitor; - - /** - * Starts creation of first chain delegate. - */ - protected void createFirstChainDelegate_Start() { - // check invalid access flags - int access = msign.getAccessFlags(); - if (!wd.allowFinalMethods) { - if ((access & AsmUtil.ACC_FINAL) != 0) { // detect final - throw new ProxettaException( - "Unable to create proxy for final method: " + msign + ". Remove final modifier or change the pointcut definition."); - } - } - - // create proxy methods - tmd = new TargetMethodData(msign, aspectList); - - access &= ~ACC_NATIVE; - access &= ~ACC_ABSTRACT; - - methodVisitor = wd.dest.visitMethod( - access, tmd.msign.getMethodName(), tmd.msign.getDescription(), tmd.msign.getAsmMethodSignature(), null); - } - - /** - * Continues the creation of the very first method in calling chain that simply delegates invocation to the first proxy method. - * This method mirrors the target method. - */ - protected void createFirstChainDelegate_Continue(final TargetMethodData tmd) { - methodVisitor.visitCode(); - - if (tmd.msign.isStatic) { - loadStaticMethodArguments(methodVisitor, tmd.msign); - methodVisitor.visitMethodInsn( - INVOKESTATIC, - wd.thisReference, - tmd.firstMethodName(), - tmd.msign.getDescription(), - false); - } else { - loadSpecialMethodArguments(methodVisitor, tmd.msign); - methodVisitor.visitMethodInsn( - INVOKESPECIAL, - wd.thisReference, - tmd.firstMethodName(), - tmd.msign.getDescription(), - false); - } - - visitReturn(methodVisitor, tmd.msign, false); - - methodVisitor.visitMaxs(0, 0); - methodVisitor.visitEnd(); - } - - protected boolean proxyInfoRequested; - - /** - * Creates proxy methods over target method, For each matched proxy, new proxy method is created - * by taking advice bytecode and replaces usages of {@link jodd.proxetta.ProxyTarget}. - *

- * Invocation chain example: {@code name -> name$p0 -> name$p1 -> name$p4 -> super}. - */ - public void createProxyMethod(final TargetMethodData td) { - final ProxyAspectData aspectData = td.getProxyData(); - - int access = td.msign.getAccessFlags(); - - access &= ~ACC_NATIVE; - access &= ~ACC_ABSTRACT; - access = ProxettaAsmUtil.makePrivateFinalAccess(access); - - final MethodVisitor mv = wd.dest.visitMethod(access, td.methodName(), td.msign.getDescription(), null, null); - mv.visitCode(); - - //*** VISIT ADVICE - called for each aspect and each method - aspectData.getAdviceClassReader().accept(new EmptyClassVisitor() { - - @Override - public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { - - if (!name.equals(ProxettaNames.executeMethodName)) { - return null; - } - - return new HistoryMethodAdapter(mv) { - - @Override - public void visitFieldInsn(final int opcode, String owner, String name, final String desc) { - if (owner.equals(aspectData.adviceReference)) { - owner = wd.thisReference; // [F5] - name = adviceFieldName(name, aspectData.aspectIndex); - } - super.visitFieldInsn(opcode, owner, name, desc); - } - - - @Override - public void visitVarInsn(final int opcode, int var) { - var += (var == 0 ? 0 : td.msign.getAllArgumentsSize()); - - if (proxyInfoRequested) { - proxyInfoRequested = false; - if (opcode == ASTORE) { - ProxyTargetReplacement.info(mv, td.msign, var); - } - } - - super.visitVarInsn(opcode, var); // [F1] - } - - @Override - public void visitIincInsn(int var, final int increment) { - var += (var == 0 ? 0 : td.msign.getAllArgumentsSize()); - super.visitIincInsn(var, increment); // [F1] - } - - @Override - public void visitInsn(final int opcode) { - if (opcode == ARETURN) { - visitReturn(mv, td.msign, true); - return; - } - if (traceNext) { - if ((opcode == POP) || (opcode == POP2)) { // [F3] - invoke invoked without assignment - return; - } - } - super.visitInsn(opcode); - } - - @SuppressWarnings({"ParameterNameDiffersFromOverriddenParameter"}) - @Override - public void visitMethodInsn(final int opcode, String string, String mname, final String mdesc, final boolean isInterface) { - if ((opcode == INVOKEVIRTUAL) || (opcode == INVOKEINTERFACE) || (opcode == INVOKESPECIAL)) { - if (string.equals(aspectData.adviceReference)) { - string = wd.thisReference; - mname = adviceMethodName(mname, aspectData.aspectIndex); - } - } else - - if (opcode == INVOKESTATIC) { - if (string.equals(aspectData.adviceReference)) { - string = wd.thisReference; - mname = adviceMethodName(mname, aspectData.aspectIndex); - } else - - if (string.endsWith('/' + TARGET_CLASS_NAME)) { - - if (isInvokeMethod(mname, mdesc)) { // [R7] - if (td.isLastMethodInChain()) { // last proxy method just calls super target method - - if (!wd.isWrapper()) { - // PROXY - loadSpecialMethodArguments(mv, td.msign); - mv.visitMethodInsn(INVOKESPECIAL, wd.superReference, td.msign.getMethodName(), td.msign.getDescription(), isInterface); - } else { - // WRAPPER - mv.visitVarInsn(ALOAD, 0); - mv.visitFieldInsn(GETFIELD, wd.thisReference, wd.wrapperRef, wd.wrapperType); - loadVirtualMethodArguments(mv, td.msign); - if (wd.wrapInterface) { - mv.visitMethodInsn( - INVOKEINTERFACE, - wd.wrapperType.substring(1, wd.wrapperType.length() - 1), - td.msign.getMethodName(), - td.msign.getDescription(), - true); - } else { - mv.visitMethodInsn( - INVOKEVIRTUAL, - wd.wrapperType.substring(1, wd.wrapperType.length() - 1), - td.msign.getMethodName(), - td.msign.getDescription(), - isInterface); - } - } - - prepareReturnValue(mv, td.msign, aspectData.maxLocalVarOffset); // [F4] - traceNext = true; - } else { // calls next proxy method - loadSpecialMethodArguments(mv, td.msign); - mv.visitMethodInsn(INVOKESPECIAL, wd.thisReference, td.nextMethodName(), td.msign.getDescription(), isInterface); - visitReturn(mv, td.msign, false); - } - return; - } - - if (isArgumentsCountMethod(mname, mdesc)) { // [R2] - ProxyTargetReplacement.argumentsCount(mv, td.msign); - return; - } - - if (isArgumentTypeMethod(mname, mdesc)) { // [R3] - int argIndex = this.getArgumentIndex(); - ProxyTargetReplacement.argumentType(mv, td.msign, argIndex); - return; - } - - if (isArgumentMethod(mname, mdesc)) { // [R4] - int argIndex = this.getArgumentIndex(); - ProxyTargetReplacement.argument(mv, td.msign, argIndex); - return; - } - - if (isSetArgumentMethod(mname, mdesc)) { // [R5] - int argIndex = this.getArgumentIndex(); - checkArgumentIndex(td.msign, argIndex); - mv.visitInsn(POP); - storeMethodArgumentFromObject(mv, td.msign, argIndex); - return; - } - - if (isCreateArgumentsArrayMethod(mname, mdesc)) { // [R6] - ProxyTargetReplacement.createArgumentsArray(mv, td.msign); - return; - } - - if (isCreateArgumentsClassArrayMethod(mname, mdesc)) { // [R11] - ProxyTargetReplacement.createArgumentsClassArray(mv, td.msign); - return; - } - - if (isTargetMethod(mname, mdesc)) { // [R9.1] - mv.visitVarInsn(ALOAD, 0); - return; - } - - if (isTargetClassMethod(mname, mdesc)) { // [R9] - ProxyTargetReplacement.targetClass(mv, td.msign); - //ProxyTargetReplacement.targetClass(mv, wd.superReference); - return; - } - - if (isTargetMethodNameMethod(mname, mdesc)) { // [R10] - ProxyTargetReplacement.targetMethodName(mv, td.msign); - return; - } - - if (isTargetMethodSignatureMethod(mname, mdesc)) { - ProxyTargetReplacement.targetMethodSignature(mv, td.msign); - return; - } - - if (isTargetMethodDescriptionMethod(mname, mdesc)) { - ProxyTargetReplacement.targetMethodDescription(mv, td.msign); - return; - } - - if (isInfoMethod(mname, mdesc)) { - // we are NOT replacing info() here! First, we need to figure out - // what is the operand for the very next ASTORE instructions - // since we need to create an object and store it in this - // register - and reuse it, in replacement code. - - //ProxyTargetReplacement.info(mv, td.msign); - proxyInfoRequested = true; - return; - } - - if (isReturnTypeMethod(mname, mdesc)) { // [R11] - ProxyTargetReplacement.returnType(mv, td.msign); - return; - } - - if (isReturnValueMethod(mname, mdesc)) { - castToReturnType(mv, td.msign); - return; - } - - if (isTargetMethodAnnotationMethod(mname, mdesc)) { - String[] args = getLastTwoStringArguments(); - - // pop current two args - mv.visitInsn(POP); - mv.visitInsn(POP); - - ProxyTargetReplacement.targetMethodAnnotation(mv, td.msign, args); - return; - } - - if (isTargetClassAnnotationMethod(mname, mdesc)) { - String[] args = getLastTwoStringArguments(); - - // pop current two args - mv.visitInsn(POP); - mv.visitInsn(POP); - - ProxyTargetReplacement.targetClassAnnotation(mv, td.msign.getClassInfo(), args); - return; - } - } - } - super.visitMethodInsn(opcode, string, mname, mdesc, isInterface); - } - - }; - } - - }, 0); - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaWrapperClassBuilder.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaWrapperClassBuilder.java deleted file mode 100644 index cb753ea17..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxettaWrapperClassBuilder.java +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.asm.AsmUtil; -import jodd.asm7.ClassVisitor; -import jodd.asm7.FieldVisitor; -import jodd.asm7.MethodVisitor; -import jodd.asm7.Opcodes; -import jodd.proxetta.ProxyAspect; - -import java.lang.reflect.Modifier; -import java.util.List; - -import static jodd.asm7.Opcodes.ACC_ABSTRACT; -import static jodd.asm7.Opcodes.ACC_NATIVE; -import static jodd.asm7.Opcodes.ALOAD; -import static jodd.asm7.Opcodes.GETFIELD; -import static jodd.asm7.Opcodes.INVOKEINTERFACE; -import static jodd.asm7.Opcodes.INVOKEVIRTUAL; -import static jodd.proxetta.asm.ProxettaAsmUtil.CLINIT; -import static jodd.proxetta.asm.ProxettaAsmUtil.INIT; -import static jodd.proxetta.asm.ProxettaAsmUtil.loadVirtualMethodArguments; -import static jodd.proxetta.asm.ProxettaAsmUtil.visitReturn; - -public class ProxettaWrapperClassBuilder extends ProxettaClassBuilder { - - protected final Class targetClassOrInterface; - protected final Class targetInterface; - protected final String targetFieldName; - protected final boolean createTargetInDefaultCtor; - - public ProxettaWrapperClassBuilder( - final Class targetClassOrInterface, - final Class targetInterface, - final String targetFieldName, - final ClassVisitor dest, - final ProxyAspect[] aspects, - final String suffix, - final String reqProxyClassName, - final TargetClassInfoReader targetClassInfoReader, - final boolean createTargetInDefaultCtor - ) { - - super(dest, aspects, suffix, reqProxyClassName, targetClassInfoReader); - this.targetClassOrInterface = targetClassOrInterface; - this.targetInterface = targetInterface; - this.targetFieldName = targetFieldName; - this.createTargetInDefaultCtor = createTargetInDefaultCtor; - - wd.allowFinalMethods = true; - } - - /** - * {@inheritDoc} - */ - @Override - public void visit(final int version, int access, final String name, final String signature, final String superName, String[] interfaces) { - - wd.init(name, superName, this.suffix, this.reqProxyClassName); - - // no superclass - wd.superName = AsmUtil.SIGNATURE_JAVA_LANG_OBJECT; - - // change access of destination - access &= ~AsmUtil.ACC_ABSTRACT; - access &= ~AsmUtil.ACC_INTERFACE; - - // write destination class - if (targetClassOrInterface.isInterface()) { - // target is interface - wd.wrapInterface = true; - - interfaces = new String[] {targetClassOrInterface.getName().replace('.', '/')}; - } else { - // target is class - wd.wrapInterface = false; - - if (targetInterface != null) { - // interface provided - interfaces = new String[] {targetInterface.getName().replace('.', '/')}; - } else { - // no interface provided, use all - //interfaces = null; - } - } - final int v = ProxettaAsmUtil.resolveJavaVersion(version); - wd.dest.visit(v, access, wd.thisReference, signature, wd.superName, interfaces); - - wd.proxyAspects = new ProxyAspectData[aspects.length]; - for (int i = 0; i < aspects.length; i++) { - wd.proxyAspects[i] = new ProxyAspectData(wd, aspects[i], i); - } - - // create new field wrapper field and store it's reference into work-data - wd.wrapperRef = targetFieldName; - wd.wrapperType = 'L' + name + ';'; - - - if (createTargetInDefaultCtor) { - // create private, final field - final FieldVisitor fv = wd.dest.visitField(AsmUtil.ACC_PRIVATE | AsmUtil.ACC_FINAL, wd.wrapperRef, wd.wrapperType, null, null); - fv.visitEnd(); - - createEmptyCtorThatCreatesTarget(); - } - else { - // create public, non-final field - final FieldVisitor fv = wd.dest.visitField(AsmUtil.ACC_PUBLIC, wd.wrapperRef, wd.wrapperType, null, null); - fv.visitEnd(); - - createEmptyCtor(); - } - } - - /** - * Created empty default constructor. - */ - protected void createEmptyCtor() { - final MethodVisitor mv = wd.dest.visitMethod(AsmUtil.ACC_PUBLIC, INIT, "()V", null, null); - mv.visitCode(); - mv.visitVarInsn(Opcodes.ALOAD, 0); - mv.visitMethodInsn( - Opcodes.INVOKESPECIAL, - AsmUtil.SIGNATURE_JAVA_LANG_OBJECT, - INIT, "()V", - false); - mv.visitInsn(Opcodes.RETURN); - mv.visitMaxs(1, 1); - mv.visitEnd(); - } - - protected void createEmptyCtorThatCreatesTarget() { - final MethodVisitor mv = wd.dest.visitMethod(AsmUtil.ACC_PUBLIC, "", "()V", null, null); - mv.visitCode(); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn( - Opcodes.INVOKESPECIAL, - AsmUtil.SIGNATURE_JAVA_LANG_OBJECT, - INIT, "()V", - false); - mv.visitVarInsn(ALOAD, 0); - - mv.visitTypeInsn(Opcodes.NEW, wd.superReference); - mv.visitInsn(Opcodes.DUP); - mv.visitMethodInsn( - Opcodes.INVOKESPECIAL, - wd.superReference, - INIT, "()V", - false); - - mv.visitFieldInsn(Opcodes.PUTFIELD, - wd.thisReference, - wd.wrapperRef, - wd.wrapperType); - - mv.visitInsn(Opcodes.RETURN); - mv.visitMaxs(3, 1); - mv.visitEnd(); - } - - - /** - * {@inheritDoc} - */ - @Override - public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { - MethodSignatureVisitor msign = targetClassInfo.lookupMethodSignatureVisitor(access, name, desc, wd.superReference); - if (msign == null) { - return null; - } - - // ignore all destination constructors - if (name.equals(INIT)) { - return null; - } - // ignore all destination static block - if (name.equals(CLINIT)) { - return null; - } - - // skip all static methods - if (Modifier.isStatic(access)) { - return null; - } - - return applyProxy(msign); - } - - @Override - protected ProxettaMethodBuilder applyProxy(final MethodSignatureVisitor msign) { - List aspectList = matchMethodPointcuts(msign); - - if (aspectList == null) { - wd.proxyApplied = true; - createSimpleMethodWrapper(msign); - return null; - } - - wd.proxyApplied = true; - return new ProxettaMethodBuilder(msign, wd, aspectList); - - } - - /** - * Creates simple method wrapper without proxy. - */ - protected void createSimpleMethodWrapper(final MethodSignatureVisitor msign) { - - int access = msign.getAccessFlags(); - - access &= ~ACC_ABSTRACT; - access &= ~ACC_NATIVE; - - MethodVisitor mv = wd.dest.visitMethod( - access, msign.getMethodName(), msign.getDescription(), msign.getAsmMethodSignature(), msign.getExceptions()); - mv.visitCode(); - mv.visitVarInsn(ALOAD, 0); - mv.visitFieldInsn(GETFIELD, wd.thisReference, wd.wrapperRef, wd.wrapperType); - loadVirtualMethodArguments(mv, msign); - - if (wd.wrapInterface) { - mv.visitMethodInsn( - INVOKEINTERFACE, - wd.wrapperType.substring(1, wd.wrapperType.length() - 1), - msign.getMethodName(), - msign.getDescription(), - true); - } else { - mv.visitMethodInsn( - INVOKEVIRTUAL, - wd.wrapperType.substring(1, wd.wrapperType.length() - 1), - msign.getMethodName(), - msign.getDescription(), - false); - } - - ProxettaAsmUtil.prepareReturnValue(mv, msign, 0); - visitReturn(mv, msign, true); - mv.visitMaxs(0, 0); - mv.visitEnd(); - } - - @Override - public void visitEnd() { - makeStaticInitBlock(); - - processSuperMethods(); - - wd.dest.visitEnd(); - - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxyAspectData.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxyAspectData.java deleted file mode 100644 index 8ded1e78e..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/ProxyAspectData.java +++ /dev/null @@ -1,342 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.asm.AsmUtil; -import jodd.asm.EmptyClassVisitor; -import jodd.asm.EmptyMethodVisitor; -import jodd.asm.MethodAdapter; -import jodd.asm7.ClassReader; -import jodd.asm7.FieldVisitor; -import jodd.asm7.Label; -import jodd.asm7.MethodVisitor; -import jodd.io.IOUtil; -import jodd.proxetta.MethodInfo; -import jodd.proxetta.ProxettaException; -import jodd.proxetta.ProxettaNames; -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyAspect; -import jodd.proxetta.ProxyPointcut; -import jodd.util.ClassLoaderUtil; -import jodd.util.TypeCache; - -import java.io.IOException; -import java.io.InputStream; - -import static jodd.asm7.Opcodes.ALOAD; -import static jodd.asm7.Opcodes.INVOKEINTERFACE; -import static jodd.asm7.Opcodes.INVOKESPECIAL; -import static jodd.asm7.Opcodes.INVOKESTATIC; -import static jodd.asm7.Opcodes.INVOKEVIRTUAL; -import static jodd.proxetta.asm.ProxettaAsmUtil.CLINIT; -import static jodd.proxetta.asm.ProxettaAsmUtil.DESC_VOID; -import static jodd.proxetta.asm.ProxettaAsmUtil.INIT; -import static jodd.proxetta.asm.ProxettaAsmUtil.adviceFieldName; -import static jodd.proxetta.asm.ProxettaAsmUtil.adviceMethodName; -import static jodd.proxetta.asm.ProxettaAsmUtil.isStoreOpcode; - -/** - * Data of single aspect. - */ -@SuppressWarnings({"AnonymousClassVariableHidesContainingMethodVariable"}) -final class ProxyAspectData { - - final ClassReader adviceClassReader; - final ProxyAspect aspect; - final Class advice; - final ProxyPointcut pointcut; - - final int aspectIndex; - final WorkData wd; // destination class writer - - String adviceReference; // advice reference - boolean ready; // is advice ready for manipulation? - int maxLocalVarOffset; // first next local var offset - - ProxyAspectData(final WorkData wd, final ProxyAspect aspect, final int aspectIndex) { - this.aspect = aspect; - this.advice = aspect.advice(); - this.pointcut = aspect.pointcut(); - this.aspectIndex = aspectIndex; - this.wd = wd; - adviceClassReader = getCachedAdviceClassReader(advice); - readAdviceData(); - } - - /** - * Delegates to aspects pointcut. - */ - boolean apply(final MethodInfo msign) { - return pointcut.apply(msign); - } - - // ---------------------------------------------------------------- advice reader cache - - private static TypeCache adviceClassReaderCache; - - - /** - * Creates advice's class reader. - */ - private ClassReader createAdviceClassReader(final Class advice) { - InputStream inputStream = null; - try { - inputStream = ClassLoaderUtil.getClassAsStream(advice); - return new ClassReader(inputStream); - } catch (final IOException ioex) { - throw new ProxettaException(ioex); - } finally { - IOUtil.close(inputStream); - } - } - - /** - * Returns class reader for advice. - */ - private ClassReader getCachedAdviceClassReader(final Class advice) { - if (adviceClassReaderCache == null) { - adviceClassReaderCache = TypeCache.createDefault(); - } - return adviceClassReaderCache.get(advice, this::createAdviceClassReader); - } - - /** - * Returns class reader for advice. - */ - ClassReader getAdviceClassReader() { - return adviceClassReader; - } - - // ---------------------------------------------------------------- read - - /** - * Parse advice class to gather some advice data. Should be called before any advice use. - * Must be called only *once* per advice. - */ - private void readAdviceData() { - if (ready) { - return; - } - - adviceClassReader.accept(new EmptyClassVisitor() { - - /** - * Stores advice reference. - */ - @Override - public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { - adviceReference = name; - super.visit(version, access, name, signature, superName, interfaces); - } - - /** - * Prevents advice to have inner classes. - */ - @Override - public void visitInnerClass(final String name, final String outerName, final String innerName, final int access) { - if (outerName.equals(adviceReference)) { - throw new ProxettaException("Proxetta doesn't allow inner classes in/for advice: " + advice.getName()); - } - super.visitInnerClass(name, outerName, innerName, access); - } - - /** - * Clones advices fields to destination. - */ - @Override - public FieldVisitor visitField(final int access, final String name, final String desc, final String signature, final Object value) { - wd.dest.visitField(access, adviceFieldName(name, aspectIndex), desc, signature, value); // [A5] - return super.visitField(access, name, desc, signature, value); - } - - /** - * Copies advices methods to destination. - */ - @Override - public MethodVisitor visitMethod(int access, String name, final String desc, final String signature, final String[] exceptions) { - if (name.equals(CLINIT)) { // [A6] - if (!desc.equals(DESC_VOID)) { - throw new ProxettaException("Invalid static initialization block description for advice: " + advice.getName()); - } - name = ProxettaNames.clinitMethodName + ProxettaNames.methodDivider + aspectIndex; - access |= AsmUtil.ACC_PRIVATE | AsmUtil.ACC_FINAL; - wd.addAdviceClinitMethod(name); - return new MethodAdapter(wd.dest.visitMethod(access, name, desc, signature, exceptions)) { - - @Override - public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { - } - - @Override - public void visitLineNumber(final int line, final Label start) { - } - - @Override - public void visitMethodInsn(final int opcode, String owner, String name, final String desc, final boolean isInterface) { - if (opcode == INVOKESTATIC) { - if (owner.equals(adviceReference)) { - owner = wd.thisReference; - name = adviceMethodName(name, aspectIndex); - } - } - super.visitMethodInsn(opcode, owner, name, desc, isInterface); - } - - @Override - public void visitFieldInsn(final int opcode, String owner, String name, final String desc) { // [F6] - if (owner.equals(adviceReference)) { - owner = wd.thisReference; // [F5] - name = adviceFieldName(name, aspectIndex); - } - super.visitFieldInsn(opcode, owner, name, desc); - } - }; - } else - - if (name.equals(INIT)) { // [A7] - if (!desc.equals(DESC_VOID)) { - throw new ProxettaException("Advices can have only default constructors. Invalid advice: " + advice.getName()); - } - - name = ProxettaNames.initMethodName + ProxettaNames.methodDivider + aspectIndex; - access = ProxettaAsmUtil.makePrivateFinalAccess(access); - wd.addAdviceInitMethod(name); - return new MethodAdapter(wd.dest.visitMethod(access, name, desc, signature, exceptions)) { - @Override - public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { - } - - @Override - public void visitLineNumber(final int line, final Label start) { - } - - int state; // used to detect and to ignore the first super call() - - @Override - public void visitVarInsn(final int opcode, final int var) { // [F7] - if ((state == 0) && (opcode == ALOAD) && (var == 0)) { - state++; - return; - } - super.visitVarInsn(opcode, var); - } - - @Override - public void visitMethodInsn(final int opcode, String owner, String name, final String desc, final boolean isInterface) { - if ((state == 1) && (opcode == INVOKESPECIAL)) { - state++; - return; - } - if ((opcode == INVOKEVIRTUAL) || (opcode == INVOKEINTERFACE)) { - if (owner.equals(adviceReference)) { - owner = wd.thisReference; - name = adviceMethodName(name, aspectIndex); - } - } else - - if (opcode == INVOKESTATIC) { - if (owner.equals(adviceReference)) { - owner = wd.thisReference; - name = adviceMethodName(name, aspectIndex); - } - } - super.visitMethodInsn(opcode, owner, name, desc, isInterface); - } - - @Override - public void visitFieldInsn(final int opcode, String owner, String name, final String desc) { // [F7] - if (owner.equals(adviceReference)) { - owner = wd.thisReference; // [F5] - name = adviceFieldName(name, aspectIndex); - } - super.visitFieldInsn(opcode, owner, name, desc); - } - }; - - } else - - // other methods - if (!name.equals(ProxettaNames.executeMethodName)) { - name = adviceMethodName(name, aspectIndex); - return new MethodAdapter(wd.dest.visitMethod(access, name, desc, signature, exceptions)) { - - @Override - public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end, final int index) { - } - - @Override - public void visitLineNumber(final int line, final Label start) { - } - - @Override - public void visitMethodInsn(final int opcode, String owner, String name, final String desc, final boolean isInterface) { - if ((opcode == INVOKEVIRTUAL) || (opcode == INVOKEINTERFACE)) { - if (owner.equals(adviceReference)) { - owner = wd.thisReference; - name = adviceMethodName(name, aspectIndex); - } - } else - - if (opcode == INVOKESTATIC || opcode == INVOKESPECIAL) { - if (owner.equals(adviceReference)) { - owner = wd.thisReference; - name = adviceMethodName(name, aspectIndex); - } - } - super.visitMethodInsn(opcode, owner, name, desc, isInterface); - } - - @Override - public void visitFieldInsn(final int opcode, String owner, String name, final String desc) { // replace field references - if (owner.equals(adviceReference)) { - owner = wd.thisReference; - name = adviceFieldName(name, aspectIndex); - } - super.visitFieldInsn(opcode, owner, name, desc); - } - }; - } - - // Parse EXECUTE method, just to gather some info, real parsing will come later - //return new MethodAdapter(new EmptyMethodVisitor()) { // toask may we replace this with the following code? - return new EmptyMethodVisitor() { - @Override - public void visitVarInsn(final int opcode, final int var) { - if (isStoreOpcode(opcode)) { - if (var > maxLocalVarOffset) { - maxLocalVarOffset = var; // find max local var offset - } - } - super.visitVarInsn(opcode, var); - } - }; -// return super.visitMethod(access, name, desc, signature, exceptions); - } - }, 0); - maxLocalVarOffset += 2; // increment offset by 2 because var on last index may be a dword value - ready = true; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/TargetClassInfoReader.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/TargetClassInfoReader.java deleted file mode 100644 index 64ed3e472..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/TargetClassInfoReader.java +++ /dev/null @@ -1,425 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.asm.AsmUtil; -import jodd.asm.EmptyClassVisitor; -import jodd.asm.EmptyMethodVisitor; -import jodd.asm7.AnnotationVisitor; -import jodd.asm7.ClassReader; -import jodd.asm7.MethodVisitor; -import jodd.asm7.signature.SignatureReader; -import jodd.io.IOUtil; -import jodd.proxetta.AnnotationInfo; -import jodd.proxetta.ClassInfo; -import jodd.proxetta.GenericsReader; -import jodd.proxetta.ProxettaException; -import jodd.util.ClassLoaderUtil; -import jodd.util.StringPool; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static jodd.proxetta.asm.ProxettaAsmUtil.CLINIT; -import static jodd.proxetta.asm.ProxettaAsmUtil.INIT; - -/** - * Reads info from target class. - */ -@SuppressWarnings({"AnonymousClassVariableHidesContainingMethodVariable"}) -public class TargetClassInfoReader extends EmptyClassVisitor implements ClassInfo { - - //protected ClassInfo classInfo; - - protected final Map methodSignatures; - protected final List superClassReaders; // list of all super class readers - protected final Set allMethodSignatures; - protected final ClassLoader classLoader; - - public TargetClassInfoReader(final ClassLoader classLoader) { - this.methodSignatures = new HashMap<>(); - this.superClassReaders = new ArrayList<>(); - this.allMethodSignatures = new HashSet<>(); - this.classLoader = classLoader; - } - - - // ---------------------------------------------------------------- some getters - - /** - * Returns method signature for some method. If signature is not found, returns null. - * Founded signatures means that those method can be proxyfied. - */ - public MethodSignatureVisitor lookupMethodSignatureVisitor(final int access, final String name, final String desc, final String className) { - final String key = ProxettaAsmUtil.createMethodSignaturesKey(access, name, desc, className); - return methodSignatures.get(key); - } - - // ---------------------------------------------------------------- information - - protected String targetPackage; - protected String targetClassname; - protected String superName; - protected String thisReference; - protected String nextSupername; - protected String[] superClasses; - protected AnnotationInfo[] annotations; - protected List classAnnotations; - protected boolean isTargetInterface; - protected Set nextInterfaces; - protected Map generics; - - // ---------------------------------------------------------------- class interface - - @Override - public String getPackage() { - return targetPackage; - } - - @Override - public String getClassname() { - return targetClassname; - } - - @Override - public String getSuperName() { - return superName; - } - - @Override - public String getReference() { - return thisReference; - } - - @Override - public String[] getSuperClasses() { - return superClasses; - } - - @Override - public AnnotationInfo[] getAnnotations() { - return annotations; - } - -// @Override -// public Map getGenerics() { -// return generics; -// } - - // ---------------------------------------------------------------- visits - - - @Override - public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { - final int lastSlash = name.lastIndexOf('/'); - this.thisReference = name; - this.superName = superName; - this.nextSupername = superName; - this.targetPackage = lastSlash == -1 ? StringPool.EMPTY : name.substring(0, lastSlash).replace('/', '.'); - this.targetClassname = name.substring(lastSlash + 1); - - this.isTargetInterface = (access & AsmUtil.ACC_INTERFACE) != 0; - if (this.isTargetInterface) { - nextInterfaces = new HashSet<>(); - if (interfaces != null) { - Collections.addAll(nextInterfaces, interfaces); - } - } - generics = new GenericsReader().parseSignatureForGenerics(signature, isTargetInterface); - } - - - @Override - public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { - final AnnotationReader ar = new AnnotationReader(desc, visible); - if (classAnnotations == null) { - classAnnotations = new ArrayList<>(); - } - classAnnotations.add(ar); - return ar; - } - - /** - * Stores method signature for target method. - */ - @Override - public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { -// if ((access & AsmUtil.ACC_FINAL) != 0) { -// return null; // skip finals -// } - final MethodSignatureVisitor msign = createMethodSignature(access, name, desc, signature, exceptions, thisReference, this.generics); - final String key = ProxettaAsmUtil.createMethodSignaturesKey(access, name, desc, thisReference); - methodSignatures.put(key, msign); - allMethodSignatures.add(msign.getCleanSignature()); - return new MethodAnnotationReader(msign); - } - - /** - * Stores signatures for all super public methods not already overridden by target class. - * All this methods will be accepted for proxyfication. - */ - @Override - public void visitEnd() { - - // prepare class annotations - if (classAnnotations != null) { - annotations = classAnnotations.toArray(new AnnotationInfo[0]); - classAnnotations = null; - } - - final List superList = new ArrayList<>(); - - final Set allInterfaces = new HashSet<>(); - - if (nextInterfaces != null) { - allInterfaces.addAll(nextInterfaces); - } - - // check all public super methods that are not overridden in superclass - while (nextSupername != null) { - InputStream inputStream = null; - ClassReader cr; - - try { - inputStream = ClassLoaderUtil.getClassAsStream(nextSupername, classLoader); - cr = new ClassReader(inputStream); - } catch (final IOException ioex) { - throw new ProxettaException("Unable to inspect super class: " + nextSupername, ioex); - } finally { - IOUtil.close(inputStream); - } - - superList.add(nextSupername); - superClassReaders.add(cr); // remember the super class reader - cr.accept(new SuperClassVisitor(this), 0); - - if (cr.getInterfaces() != null) { - Collections.addAll(allInterfaces, cr.getInterfaces()); - } - } - superClasses = superList.toArray(new String[0]); - - // check all interface methods that are not overridden in super-interface - - final Set todoInterfaces = new HashSet<>(allInterfaces); - final Set newCollectedInterfaces = new HashSet<>(); - - while (true) { - - for (final String next : todoInterfaces) { - InputStream inputStream = null; - ClassReader cr; - try { - inputStream = ClassLoaderUtil.getClassAsStream(next, classLoader); - cr = new ClassReader(inputStream); - } - catch (final IOException ioex) { - throw new ProxettaException("Unable to inspect super interface: " + next, ioex); - } - finally { - IOUtil.close(inputStream); - } - superClassReaders.add(cr); // remember the super class reader - cr.accept(new SuperClassVisitor(this), 0); - - if (cr.getInterfaces() != null) { - for (final String newInterface : cr.getInterfaces()) { - if (!allInterfaces.contains(newInterface) && !todoInterfaces.contains(newInterface)) { - // new interface found - newCollectedInterfaces.add(newInterface); - } - } - } - } - - // perform collection - allInterfaces.addAll(todoInterfaces); - - if (newCollectedInterfaces.isEmpty()) { - // no new interface found - break; - } - todoInterfaces.clear(); - todoInterfaces.addAll(newCollectedInterfaces); - - newCollectedInterfaces.clear(); - } - } - - - /** - * Creates method signature from method name. - */ - protected MethodSignatureVisitor createMethodSignature( - final int access, - final String methodName, - final String description, - final String signature, - final String[] exceptions, - final String classname, - final Map declaredTypeGenerics) { - final MethodSignatureVisitor v = new MethodSignatureVisitor(methodName, access, classname, description, exceptions, signature, declaredTypeGenerics, this); - new SignatureReader(signature != null ? signature : description).accept(v); - return v; - } - - - // ---------------------------------------------------------------- util class - - /** - * Reads method annotations and stores to method info. - */ - static class MethodAnnotationReader extends EmptyMethodVisitor { - - final List methodAnns = new ArrayList<>(); - final List[] methodParamsAnns; - - final MethodSignatureVisitor msign; - - MethodAnnotationReader(final MethodSignatureVisitor msign) { - this.msign = msign; - this.methodParamsAnns = new ArrayList[msign.getAllArgumentsSize()]; - } - - @Override - public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { - final AnnotationReader ar = new AnnotationReader(desc, visible); - methodAnns.add(ar); - return ar; - } - - @Override - public AnnotationVisitor visitParameterAnnotation(final int parameter, final String desc, final boolean visible) { - final AnnotationReader ar = new AnnotationReader(desc, visible); - if (methodParamsAnns[parameter] == null) { - methodParamsAnns[parameter] = new ArrayList<>(); - } - - methodParamsAnns[parameter].add(ar); - - return ar; - } - - @Override - public void visitEnd() { - if (!methodAnns.isEmpty()) { - // method annotations - msign.annotations = methodAnns.toArray(new AnnotationInfo[0]); - } - - // arguments annotations - - for (int i = 0; i < methodParamsAnns.length; i++) { - final List methodParamsAnn = methodParamsAnns[i]; - - if (methodParamsAnn != null) { - msign.getArgument(i + 1).annotations = methodParamsAnn.toArray(new AnnotationInfo[0]); - } - } - } - } - - // ---------------------------------------------------------------- super class visitor - - private class SuperClassVisitor extends EmptyClassVisitor { - private final Map topGenerics; - - public SuperClassVisitor(final TargetClassInfoReader topClass) { - topGenerics = topClass.generics; - } - - String declaredClassName; - Map superGeneric; - - @Override - public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { - nextSupername = superName; - declaredClassName = name; - - // append inner interfaces - if (nextInterfaces != null) { - if (interfaces != null) { - Collections.addAll(nextInterfaces, interfaces); - } - } - - final boolean isInterface = (access & AsmUtil.ACC_INTERFACE) != 0; - this.superGeneric = new GenericsReader().parseSignatureForGenerics(signature, isInterface); - - // modify super generics with top generics. - - int index = 0; - for (final Map.Entry entry : superGeneric.entrySet()) { - final String newValue = this.topGenerics.get(declaredClassName + ":" + index); - if (newValue != null) { - entry.setValue(newValue); - } - index++; - } - - } - - @Override - public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { - if (name.equals(INIT) || name.equals(CLINIT)) { - return null; - } - - if ((access & AsmUtil.ACC_PUBLIC) == 0) { // skip non-public - return null; - } - if ((access & AsmUtil.ACC_FINAL) != 0) { // skip finals - return null; - } - - final MethodSignatureVisitor msign = createMethodSignature(access, name, desc, signature, exceptions, thisReference, this.superGeneric); - if (allMethodSignatures.contains(msign.getCleanSignature())) { // skip overridden method by some in above classes - return null; - } - - msign.setDeclaredClassName(declaredClassName); // indicates it is not a top level class - final String key = ProxettaAsmUtil.createMethodSignaturesKey(access, name, desc, declaredClassName); - methodSignatures.put(key, msign); - allMethodSignatures.add(msign.getCleanSignature()); - return new MethodAnnotationReader(msign); - } - } - - // ---------------------------------------------------------------- toString - - - @Override - public String toString() { - return "target: " + this.targetPackage + '.' + this.targetClassname; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/TargetMethodData.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/TargetMethodData.java deleted file mode 100644 index de0006332..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/TargetMethodData.java +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.proxetta.ProxettaNames; - -import java.util.List; - -/** - * Holds data for target method that should be wrapped. - */ -final class TargetMethodData { - - final MethodSignatureVisitor msign; - final String methodName; - final ProxyAspectData[] proxyData; // list of ***only*** applied proxies for the target - - TargetMethodData(final MethodSignatureVisitor msign, final List aspectList) { - this.msign = msign; - this.methodName = msign.getMethodName(); - this.proxyData = aspectList.toArray(new ProxyAspectData[0]); - } - - // ---------------------------------------------------------------- current - - int currentIndex; - - /** - * Selects current proxy. - */ - void selectCurrentProxy(final int currentIndex) { - this.currentIndex = currentIndex; - } - - ProxyAspectData getProxyData() { - return proxyData[currentIndex]; - } - - // ---------------------------------------------------------------- method names - - private String methodName(final int index) { - return methodName + ProxettaNames.methodDivider + proxyData[index].aspectIndex; - } - - /** - * Returns the first method name. - */ - String firstMethodName() { - return methodName(0); - } - - /** - * Returns current method name. - */ - String methodName() { - return methodName(currentIndex); - } - - /** - * Returns true for last method in chain. - */ - boolean isLastMethodInChain() { - return currentIndex == (proxyData.length - 1); - } - - /** - * Returns next method name. - */ - String nextMethodName() { - return methodName(currentIndex + 1); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/TypeInfoImpl.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/TypeInfoImpl.java deleted file mode 100644 index fa9d98cf8..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/TypeInfoImpl.java +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.proxetta.AnnotationInfo; -import jodd.proxetta.TypeInfo; - -import static jodd.proxetta.asm.AnnotationReader.NO_ANNOTATIONS; - -/** - * Implementation of {@link TypeInfo}. Method information is collected during - * different types of class scanning (signature, method), so not everything - * is available at one moment. - */ -public class TypeInfoImpl implements TypeInfo { - - private final char opcode; - private final String type; - private final String name; - private final String rawName; - - /** - * Argument annotations are not available on method signature scanning. - * Therefore, we need to inject them from the outside. - */ - protected AnnotationInfo[] annotations = NO_ANNOTATIONS; - - public TypeInfoImpl(final char opcode, final String type, final String name, final String rawName) { - this.opcode = opcode; - this.type = type; - this.name = name; - this.rawName = rawName; - } - - /** - * Returns annotation info of type. SOme types (like for returning value) - * can't have annotation information. - */ - @Override - public AnnotationInfo[] getAnnotations() { - return annotations; - } - - /** - * Returns bytecode opcode. - */ - @Override - public char getOpcode() { - return opcode; - } - - /** - * Returns java-like, e.g. {@code "java.lang.Integer"}. - */ - @Override - public String getType() { - return type; - } - - /** - * Returns bytecode-like type name, e.g. {@code "Ljava/lang/Integer;"}. - * Note that generics type names are not resolved. - * @see #getRawName() - */ - @Override - public String getName() { - return name; - } - - /** - * Returns bytecode-like type name, e.g. {@code "Ljava/lang/Integer;"}. - * @see #getName() - */ - @Override - public String getRawName() { - return rawName; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/WorkData.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/WorkData.java deleted file mode 100644 index e4053de88..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/WorkData.java +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.asm; - -import jodd.asm7.ClassVisitor; -import jodd.util.StringPool; - -import java.util.ArrayList; -import java.util.List; - -import static jodd.util.StringPool.DOT; - -/** - * Holds various information about the current process of making proxy. - */ -public final class WorkData { - - final ClassVisitor dest; - - WorkData(final ClassVisitor dest) { - this.dest = dest; - } - - // ---------------------------------------------------------------- data - - String targetPackage; - String targetClassname; - String nextSupername; - String superName; - String superReference; - ProxyAspectData[] proxyAspects; - String wrapperRef; - String wrapperType; - boolean wrapInterface; - boolean allowFinalMethods; - - public String thisReference; - public boolean proxyApplied; - - public boolean isWrapper() { - return wrapperRef != null; - } - - // ---------------------------------------------------------------- init - - /** - * Work data initialization. - */ - public void init(String name, final String superName, final String suffix, final String reqProxyClassName) { - int lastSlash = name.lastIndexOf('/'); - this.targetPackage = lastSlash == -1 ? StringPool.EMPTY : name.substring(0, lastSlash).replace('/', '.'); - this.targetClassname = name.substring(lastSlash + 1); - this.nextSupername = superName; - this.superName = name; - - // create proxy name - if (reqProxyClassName != null) { - if (reqProxyClassName.startsWith(DOT)) { - name = name.substring(0, lastSlash) + '/' + reqProxyClassName.substring(1); - } else if (reqProxyClassName.endsWith(DOT)) { - name = reqProxyClassName.replace('.', '/') + this.targetClassname; - } else { - name = reqProxyClassName.replace('.', '/'); - } - } - - // add optional suffix - if (suffix != null) { - name += suffix; - } - this.thisReference = name; - this.superReference = this.superName; - } - - - - // ---------------------------------------------------------------- advice clinits - - List adviceClinits; - - /** - * Saves used static initialization blocks (clinit) of advices. - */ - void addAdviceClinitMethod(final String name) { - if (adviceClinits == null) { - adviceClinits = new ArrayList<>(); - } - adviceClinits.add(name); - } - - // ---------------------------------------------------------------- advice inits - - List adviceInits; - - /** - * Saves used constructors of advices. - */ - void addAdviceInitMethod(final String name) { - if (adviceInits == null) { - adviceInits = new ArrayList<>(); - } - adviceInits.add(name); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/asm/package-info.java b/jodd-proxetta/src/main/java/jodd/proxetta/asm/package-info.java deleted file mode 100644 index 8cec1ded9..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/asm/package-info.java +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - *

- * This package assembles proxy classes. You will probably like to keep out from this code:) - *

- *

Replacements and modification rules

- *

- * During creation of proxy methods, several replacement and modification happens in order to produce valid proxy subclass. - * Here is the list of all such rules. - *

- *

Add all constructors [A1]

- *

- * Proxy subclass must contain all constructors as target subclass. New constructors simply - * delegates invocation to the super class. All constructor annotations are copied. - *

- *

Add the last method in chain [A2]

- *

- * Last method in proxy chain is the one that simply delegates the invocation to the target method in super class. - *

- *

Add all type annotations [A3]

- *

- * Proxy subclass must contain all type annotations as the target one. - *

- *

Copy all annotations to the first method in proxy method chain [A4]

- *

- * Proxy methods must contain all type annotations as the target one. - *

- *

Fix the offset of local variables [F1]

- *

- * Offset of all local variables has to be incremented by the size of target method argument list. - * Size of arguments list is the number of 32bit words used by arguments on stack, which means that - * all types has length of 1 word, except Long and Double that weight 2 words - * (or one dword). - *

- *
- *
- * iconst_1
- * istore_1
- * 
- *
- *
- *
- * iconst_1
- * istore_13
- * 
- *
- *

- * Here is the order of local variables:

- *
    - *
  • 0 - always 'this'
  • - *
  • arguments (if exist)
  • - *
  • locals (if exist)
  • - *
- *

- * Therefore, index 0 is left as it is and offset will not be added to it. - *

- *
- *

Replace ProxyTarget.argsCount [R2]

- *

- * Call to ProxyTarget.argsCount() has to be replaces with hardcoded arguments count. - * Method call is simply replaces with appropriate load instruction: iload_n where n is in [0. 5]; - * bipush n where n is in byte range; or sipush n when n is in integer range. - *

- *
- *

Replace ProxyTarget.getArgType [R3]

- *

- * Call to ProxyTarget.getArgType(int ) has to be replaces with hardcoded argument Class, where argument - * index is provided as an argument for ProxyTarget.getArgType(int ). - * Method call is replaced with getClass() call on specified argument. If argument is an primitive - * then method is replaced with reading the TYPE attribute of appropriate wrapper. - *

- *

- * One caveat: opcode for pushing argument offset to stack is not removed from the bytecode, - * due to performance issues of class creation. Instead, this value is poped from the stack before method call is replaced. - * It is assumed that this value is an integer. - *

- *
- *
- * iconst_1
- * invokestatic package/ProxyTarget.getArgClass
- * astore_1
- * iconst_2
- * invokestatic package/ProxyTarget.getArgClass
- * astore_2
- * 
- *
- *
- *
- * (iconst_1
- * pop)
- * aload_1
- * invokevirtual java/lang/Object.getClass
- * astore 13
- * (iconst_2
- * pop)
- * getstatic java/lang/Byte.TYPE
- * astore 14
- * 
- *
- *
- *

Replace ProxyTarget.getArg [R4]

- *

- * Call to ProxyTarget.getArg(int ) has to be replaces with hardcoded argument value, where - * index is provided as an argument for ProxyTarget.getArg(int ). - * If argument is a primitive, its wrapper object will be created. - *

- *
- *
- * iconst_1
- * invokestatic package/ProxyTarget.getArg
- * astore_1
- * bipush 6
- * invokestatic package/ProxyTarget.getArg
- * astore_3
- * 
- *
- *
- *
- * aload_1
- * astore_13
- * lload 6
- * invokestatic java/lang/Long.<init>
- * astore 14
- * 
- *
- *
- *

Replace ProxyTarget.setArg [R5]

- *

- * Call to ProxyTarget.setArg(Object, int ) has to be replaces with hardcoded setting of the argument value, - * where index is provided as an argument for ProxyTarget.setArg(Object, int ). - * If argument is a primitive, its wrapper object must be provided. - *

- *

Replace ProxyTarget.createArgsArray [R6]

- *

- * Call to ProxyTarget.createArgsArray() has to be replaces with hardcoded creation of an object array, - * where elements are target method arguments. Primitive arguments are wrapped. - *

- *

Replace ProxyTarget.invoke [R7]

- *

- * Call to ProxyTarget.invokeAndGetResult() has to be replaced with call to super target method. Since target methods - * may have one or more arguments, it is required to push all arguments to the stack prior to call of super target method. - * Note that aload_0 is always the first instruction (load this), no matter how many arguments there are. - *

- *
- *
- * invokestatic package/ProxyTarget.invoke
- * 
- *
- *
- *
- * aload_0
- * aload_1
- * iload_2
- * ...
- * invokespecial package/Target.method
- * 
- *
- *

- * Situation here is a bit more complicated since return value must be provided, so the following fixes has to be - * applied, too. - *

- *

Fix POP for ProxyTarget.invoke [F3]

- *

- * When ProxyTarget.invoke() is invoked without assignment, POP/POP2 instruction - * is added afterwards, to remove the value from the stack. For targets that do not return void, this opcode - * has to be fixed, i.e. removed. (Fact is that targets that return void, do not have POP:). - *

- *

Fix return value and Fix ASTORE for ProxyTarget.invoke [F4]

- *

- * When ProxyTarget.invoke() is invoked with assignment, xSTORE instruction - * is added afterwards, to assign return value to a local variable. Therefore, it has to be loaded again on stack - * before return. - *

- *

Creates all return values, performs casting for small types.

- *

Replace ProxyTarget.getTargetClass [R9]

- *

- * Returns the target class. - *

- *

Replace ProxyTarget.getTargetMethodName [R10]

- *

- * Returns target method name. - *

- *

Replace ProxyTarget.getReturnType [R11]

- *

- * Returns return type of the target method or null if metod returns void. - *

- *

Fix field access [F5]

- *

- * Access to advice's fields has to be replaced with access to local fields. In relation with [A5]. - *

- *

Copy advice's fields to proxy [A5]

- *

- * All fields from advice has to be copied to proxy, with proxy index added to the name, to prevent duplicate names. - *

- *

Copy and fix advice static constructor [A6/F6]

- *

- * Static block of an advice should be copied to the proxy, with fixed field access (see F5). - *

- *

Copy and fix advices default constructors [A7/F7]

- *

- * Advice's constructor will be copied to regular methods, except first two instructions (calling super constructor) will be - * ignored. Field access will be fixed (see F5). - *

- */ -package jodd.proxetta.asm; \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/impl/InvokeProxetta.java b/jodd-proxetta/src/main/java/jodd/proxetta/impl/InvokeProxetta.java deleted file mode 100644 index 72c55156e..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/impl/InvokeProxetta.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.impl; - -import jodd.proxetta.InvokeAspect; -import jodd.proxetta.Proxetta; -import jodd.proxetta.ProxettaNames; - -/** - * Proxetta that does method (i.e. invocation) replacements. - */ -public class InvokeProxetta extends Proxetta { - - public InvokeProxetta() { - classNameSuffix = ProxettaNames.invokeProxyClassNameSuffix; - } - - @Override - public InvokeProxettaFactory proxy() { - return new InvokeProxettaFactory(this); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/impl/InvokeProxettaFactory.java b/jodd-proxetta/src/main/java/jodd/proxetta/impl/InvokeProxettaFactory.java deleted file mode 100644 index ffae0839f..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/impl/InvokeProxettaFactory.java +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.impl; - -import jodd.asm7.ClassReader; -import jodd.proxetta.InvokeAspect; -import jodd.proxetta.ProxettaFactory; -import jodd.proxetta.asm.InvokeClassBuilder; -import jodd.proxetta.asm.TargetClassInfoReader; -import jodd.proxetta.asm.WorkData; - -import java.io.InputStream; - -/** - * Invocation replacer class processor. - */ -public class InvokeProxettaFactory extends ProxettaFactory { - - public InvokeProxettaFactory(final InvokeProxetta invokeProxetta) { - super(invokeProxetta); - } - - @Override - public InvokeProxettaFactory setTarget(final InputStream target) { - return super.setTarget(target); - } - - @Override - public InvokeProxettaFactory setTarget(final String targetName) { - return super.setTarget(targetName); - } - - @Override - public InvokeProxettaFactory setTarget(final Class target) { - return super.setTarget(target); - } - - /** - * {@inheritDoc} - */ - @Override - protected WorkData process(final ClassReader cr, final TargetClassInfoReader targetClassInfoReader) { - - InvokeClassBuilder icb = new InvokeClassBuilder( - destClassWriter, - proxetta.getAspects(new InvokeAspect[0]), - resolveClassNameSuffix(), - requestedProxyClassName, - targetClassInfoReader); - - cr.accept(icb, 0); - - return icb.getWorkData(); - } - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/impl/ProxyProxetta.java b/jodd-proxetta/src/main/java/jodd/proxetta/impl/ProxyProxetta.java deleted file mode 100644 index 66103ae93..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/impl/ProxyProxetta.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.impl; - -import jodd.proxetta.ProxettaNames; -import jodd.proxetta.Proxetta; -import jodd.proxetta.ProxyAspect; - -/** - * Proxetta that creates proxies. - */ -public class ProxyProxetta extends Proxetta { - - public ProxyProxetta() { - classNameSuffix = ProxettaNames.proxyClassNameSuffix; - } - - @Override - public ProxyProxettaFactory proxy() { - return new ProxyProxettaFactory(this); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/impl/ProxyProxettaFactory.java b/jodd-proxetta/src/main/java/jodd/proxetta/impl/ProxyProxettaFactory.java deleted file mode 100644 index 5f7dbb69c..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/impl/ProxyProxettaFactory.java +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.impl; - -import jodd.asm7.ClassReader; -import jodd.proxetta.ProxettaFactory; -import jodd.proxetta.ProxyAspect; -import jodd.proxetta.asm.ProxettaClassBuilder; -import jodd.proxetta.asm.TargetClassInfoReader; -import jodd.proxetta.asm.WorkData; - -import java.io.InputStream; - -/** - * Creates the proxy subclass using ASM library. - */ -public class ProxyProxettaFactory extends ProxettaFactory { - - public ProxyProxettaFactory(final ProxyProxetta proxyProxetta) { - super(proxyProxetta); - } - - @Override - public ProxyProxettaFactory setTarget(final InputStream target) { - return super.setTarget(target); - } - - @Override - public ProxyProxettaFactory setTarget(final String targetName) { - return super.setTarget(targetName); - } - - @Override - public ProxyProxettaFactory setTarget(final Class target) { - return super.setTarget(target); - } - - /** - * {@inheritDoc} - */ - @Override - protected WorkData process(final ClassReader cr, final TargetClassInfoReader targetClassInfoReader) { - - ProxettaClassBuilder pcb = new ProxettaClassBuilder( - destClassWriter, - proxetta.getAspects(new ProxyAspect[0]), - resolveClassNameSuffix(), - requestedProxyClassName, - targetClassInfoReader); - - cr.accept(pcb, 0); - - return pcb.getWorkData(); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/impl/WrapperProxetta.java b/jodd-proxetta/src/main/java/jodd/proxetta/impl/WrapperProxetta.java deleted file mode 100644 index ebda392c8..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/impl/WrapperProxetta.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.impl; - -import jodd.proxetta.Proxetta; -import jodd.proxetta.ProxettaNames; -import jodd.proxetta.ProxyAspect; - -/** - * Proxetta that creates wrappers. - */ -public class WrapperProxetta extends Proxetta { - - protected boolean createTargetInDefaultCtor; - - public WrapperProxetta() { - classNameSuffix = ProxettaNames.wrapperClassNameSuffix; - } - - @Override - public WrapperProxettaFactory proxy() { - return new WrapperProxettaFactory(this); - } - - /** - * Defines if target should be created in ctor, so no additional injection is required. - */ - public WrapperProxetta setCreateTargetInDefaultCtor(final boolean createTargetInstanceInDefaultCtor) { - this.createTargetInDefaultCtor = createTargetInstanceInDefaultCtor; - return _this(); - } - - -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/impl/WrapperProxettaFactory.java b/jodd-proxetta/src/main/java/jodd/proxetta/impl/WrapperProxettaFactory.java deleted file mode 100644 index d4e61017b..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/impl/WrapperProxettaFactory.java +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.impl; - -import jodd.asm7.ClassReader; -import jodd.proxetta.ProxettaException; -import jodd.proxetta.ProxettaFactory; -import jodd.proxetta.ProxettaNames; -import jodd.proxetta.ProxettaUtil; -import jodd.proxetta.ProxyAspect; -import jodd.proxetta.asm.ProxettaWrapperClassBuilder; -import jodd.proxetta.asm.TargetClassInfoReader; -import jodd.proxetta.asm.WorkData; - -/** - * Creates wrapper using ASM library. - */ -public class WrapperProxettaFactory extends ProxettaFactory { - - private final boolean createTargetInDefaultCtor; - - public WrapperProxettaFactory(final WrapperProxetta wrapperProxetta) { - super(wrapperProxetta); - this.createTargetInDefaultCtor = wrapperProxetta.createTargetInDefaultCtor; - } - - protected Class targetClassOrInterface; - protected Class targetInterface; - protected String targetFieldName = ProxettaNames.wrapperTargetFieldName; - - /** - * Defines class or interface to wrap. - * For setting the interface of the resulting class, - * use {@link #setTargetInterface(Class)}. - */ - @Override - public WrapperProxettaFactory setTarget(final Class target) { - super.setTarget(target); - this.targetClassOrInterface = target; - return this; - } - - /** - * Defines the interface of the resulting class. - */ - public WrapperProxettaFactory setTargetInterface(final Class targetInterface) { - if (!targetInterface.isInterface()) { - throw new ProxettaException("Not an interface: " + targetInterface.getName()); - } - this.targetInterface = targetInterface; - return this; - } - - /** - * Defines custom target field name. - */ - public WrapperProxettaFactory setTargetFieldName(final String targetFieldName) { - this.targetFieldName = targetFieldName; - return this; - } - - /** - * {@inheritDoc} - */ - @Override - protected WorkData process(final ClassReader cr, final TargetClassInfoReader targetClassInfoReader) { - final ProxettaWrapperClassBuilder pcb = - new ProxettaWrapperClassBuilder( - targetClassOrInterface, - targetInterface, - targetFieldName, - destClassWriter, - proxetta.getAspects(new ProxyAspect[0]), - resolveClassNameSuffix(), - requestedProxyClassName, - targetClassInfoReader, - createTargetInDefaultCtor - ); - - cr.accept(pcb, 0); - - return pcb.getWorkData(); - } - - /** - * Injects target into wrapper. - */ - public void injectTargetIntoWrapper(final Object target, final Object wrapper) { - ProxettaUtil.injectTargetIntoWrapper(target, wrapper, targetFieldName); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/impl/package-info.java b/jodd-proxetta/src/main/java/jodd/proxetta/impl/package-info.java deleted file mode 100644 index 07fde721b..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/impl/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * {@link jodd.proxetta.Proxetta} and {@link jodd.proxetta.ProxettaFactory} implementations. - */ -package jodd.proxetta.impl; \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/package-info.java b/jodd-proxetta/src/main/java/jodd/proxetta/package-info.java deleted file mode 100644 index 030876ff9..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/package-info.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Proxetta creates the fastest proxy subclasses in an easy, java-friendly way. - *

- * Proxy is defined by an aspect: advice and pointcut. Proxetta proxy implementation is all about - * wrapping target methods at defined pointcuts with advice's methods. Advice's methods intercepts - * target method invocation. - *

- * Proxetta advices are plain java code that use special 'macro'-alike static methods from ProxyTarget class. - * These static method invocations will be replaced with appropriate target invocation, once when proxy - * subclass is created. This unique feature makes generated code not to use reflections, and therefore, very fast. - */ -package jodd.proxetta; \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllGettersPointcut.java b/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllGettersPointcut.java deleted file mode 100644 index 3dad932ff..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllGettersPointcut.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.pointcuts; - -import jodd.proxetta.MethodInfo; -import jodd.proxetta.ProxyPointcut; - -/** - * Pointcut on all public non final getters methods. - */ -public class AllGettersPointcut implements ProxyPointcut { - - private static final AllGettersPointcut INSTANCE = new AllGettersPointcut(); - - public static AllGettersPointcut get() { - return INSTANCE; - } - - @Override - public boolean apply(final MethodInfo methodInfo) { - return - methodInfo.isPublicMethod() - && methodInfo.hasReturnValue() - && (methodInfo.matchMethodName("get*") || (methodInfo.matchMethodName("is*"))) - && methodInfo.hasNoArguments() - ; - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllMethodsPointcut.java b/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllMethodsPointcut.java deleted file mode 100644 index 6a2c86481..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllMethodsPointcut.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.pointcuts; - -import jodd.proxetta.MethodInfo; -import jodd.proxetta.ProxyPointcut; - -/** - * Pointcut on all public methods. - */ -public class AllMethodsPointcut implements ProxyPointcut { - - private static final AllMethodsPointcut INSTANCE = new AllMethodsPointcut(); - - public static AllMethodsPointcut get() { - return INSTANCE; - } - - @Override - public boolean apply(final MethodInfo methodInfo) { - return methodInfo.isPublicMethod(); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllRealMethodsPointcut.java b/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllRealMethodsPointcut.java deleted file mode 100644 index 8a6803d94..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllRealMethodsPointcut.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.pointcuts; - -import jodd.proxetta.MethodInfo; -import jodd.proxetta.ProxyPointcut; - -/** - * Pointcut on all public methods that are not getters or setters - */ -public class AllRealMethodsPointcut implements ProxyPointcut { - - private static final AllRealMethodsPointcut INSTANCE = new AllRealMethodsPointcut(); - - public static AllRealMethodsPointcut get() { - return INSTANCE; - } - - @Override - public boolean apply(final MethodInfo methodInfo) { - - if (methodInfo.hasReturnValue() - && (methodInfo.matchMethodName("get*") || (methodInfo.matchMethodName("is*"))) - && methodInfo.hasNoArguments()) { - // getter - return false; - } - - if (methodInfo.matchMethodName("set*") - && methodInfo.hasOneArgument()) { - // setter - return false; - } - - return methodInfo.isPublicMethod(); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllSettersPointcut.java b/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllSettersPointcut.java deleted file mode 100644 index 23245dfa2..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllSettersPointcut.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.pointcuts; - -import jodd.proxetta.MethodInfo; -import jodd.proxetta.ProxyPointcut; - -/** - * Pointcut on all public non final setters methods. - */ -public class AllSettersPointcut implements ProxyPointcut { - - private static final AllSettersPointcut INSTANCE = new AllSettersPointcut(); - - public static AllSettersPointcut get() { - return INSTANCE; - } - - - @Override - public boolean apply(final MethodInfo methodInfo) { - return - methodInfo.isPublicMethod() - && methodInfo.matchMethodName("set*") - && methodInfo.hasOneArgument() - ; - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllTopMethodsPointcut.java b/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllTopMethodsPointcut.java deleted file mode 100644 index 8a1db034a..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/AllTopMethodsPointcut.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.pointcuts; - -import jodd.proxetta.MethodInfo; -import jodd.proxetta.ProxyPointcut; - -/** - * Filter for top-level public methods - */ -public class AllTopMethodsPointcut implements ProxyPointcut { - - private static final AllTopMethodsPointcut INSTANCE = new AllTopMethodsPointcut(); - - public static AllTopMethodsPointcut get() { - return INSTANCE; - } - - @Override - public boolean apply(final MethodInfo methodInfo) { - return - methodInfo.isTopLevelMethod() && - methodInfo.isPublicMethod(); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/MethodWithAnnotationPointcut.java b/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/MethodWithAnnotationPointcut.java deleted file mode 100644 index 85f31e51b..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/MethodWithAnnotationPointcut.java +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.pointcuts; - -import jodd.proxetta.MethodInfo; -import jodd.proxetta.ProxyPointcut; - -import java.lang.annotation.Annotation; - -/** - * Pointcut on a method with one of given annotations. - */ -public class MethodWithAnnotationPointcut implements ProxyPointcut { - - public static MethodWithAnnotationPointcut of(final Class... annotationClasses) { - return new MethodWithAnnotationPointcut(annotationClasses); - } - - protected final Class[] annotationClasses; - - /** - * Defines set of annotations we are looking for. - */ - public MethodWithAnnotationPointcut(final Class... annotationClasses) { - this.annotationClasses = annotationClasses; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean apply(final MethodInfo methodInfo) { - return methodInfo.hasAnnotation(annotationClasses); - } -} diff --git a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/package-info.java b/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/package-info.java deleted file mode 100644 index b976bbcad..000000000 --- a/jodd-proxetta/src/main/java/jodd/proxetta/pointcuts/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -/** - * Various common proxy pointcuts. - */ -package jodd.proxetta.pointcuts; \ No newline at end of file diff --git a/jodd-proxetta/src/main/resources/META-INF/LICENSE b/jodd-proxetta/src/main/resources/META-INF/LICENSE deleted file mode 100644 index a040a3b95..000000000 --- a/jodd-proxetta/src/main/resources/META-INF/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2003-present, Jodd Team (https://jodd.org) -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, -this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright -notice, this list of conditions and the following disclaimer in the -documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. diff --git a/jodd-proxetta/src/main/resources/META-INF/NOTICE b/jodd-proxetta/src/main/resources/META-INF/NOTICE deleted file mode 100644 index 93dd75a07..000000000 --- a/jodd-proxetta/src/main/resources/META-INF/NOTICE +++ /dev/null @@ -1,4 +0,0 @@ - -This product includes software developed by -INRIA, France Telecom. (https://asm.ow2.io) -ASM is released under the 3-Clause BSD License. diff --git a/jodd-proxetta/src/test/java/GenericsInDefaultTest.java b/jodd-proxetta/src/test/java/GenericsInDefaultTest.java deleted file mode 100644 index 8b1a41514..000000000 --- a/jodd-proxetta/src/test/java/GenericsInDefaultTest.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -import jodd.proxetta.Proxetta; -import jodd.proxetta.ProxyAspect; -import jodd.proxetta.advice.DelegateAdvice; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.impl.ProxyProxettaFactory; -import jodd.proxetta.impl.WrapperProxetta; -import jodd.proxetta.impl.WrapperProxettaFactory; -import jodd.proxetta.pointcuts.AllMethodsPointcut; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.fail; - -class GenericsInDefaultTest { - - public static class Bar { - } - - public static interface IFoo { - String getId(); - Bar getFoo(); - } - - public static class Foo implements IFoo { - private String id; - @Override - public String getId() { - return id; - } - // remove the generic and it works - @Override - public Bar getFoo() { - return null; - } - } - - @Test - void testClassesWithGenericsAsReturnValueWrapperDefault() { - try { - ProxyAspect aspect = new ProxyAspect(DelegateAdvice.class, new AllMethodsPointcut()); - WrapperProxetta proxetta = Proxetta.wrapperProxetta().withAspects(aspect); - WrapperProxettaFactory builder = proxetta.proxy().setTarget(Foo.class).setTargetInterface(IFoo.class); - builder.newInstance(); - } - catch (Exception ex) { - ex.printStackTrace(); - fail(ex.toString()); - } - } - - @Test - void testClassesWithGenericsAsReturnValueProxyDefault() { - try { - ProxyAspect aspect = ProxyAspect.of(DelegateAdvice.class, new AllMethodsPointcut()); - ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspects(aspect); - ProxyProxettaFactory builder = proxetta.proxy().setTarget(Foo.class); - builder.newInstance(); - } - catch (Exception ex) { - ex.printStackTrace(); - fail(ex.toString()); - } - } -} diff --git a/jodd-proxetta/src/test/java/jodd/aop/AopProxyTest.java b/jodd-proxetta/src/test/java/jodd/aop/AopProxyTest.java deleted file mode 100644 index 04b6d1cb9..000000000 --- a/jodd-proxetta/src/test/java/jodd/aop/AopProxyTest.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.aop; - -import jodd.aop.fixture.Helloable; -import jodd.aop.fixture.LoggingAspect; -import jodd.aop.fixture.Simple; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class AopProxyTest { - - @Test - void testAspect() { - Helloable proxy = AopProxy.proxyOf(new LoggingAspect(new Simple())); - - proxy.hello(3); - - assertEquals("before jodd.aop.fixture.Simple#hello", LoggingAspect.log); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/aop/fixture/Helloable.java b/jodd-proxetta/src/test/java/jodd/aop/fixture/Helloable.java deleted file mode 100644 index fb3df8320..000000000 --- a/jodd-proxetta/src/test/java/jodd/aop/fixture/Helloable.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.aop.fixture; - -public interface Helloable { - - public String hello(int a); -} diff --git a/jodd-proxetta/src/test/java/jodd/aop/fixture/LoggingAspect.java b/jodd-proxetta/src/test/java/jodd/aop/fixture/LoggingAspect.java deleted file mode 100644 index 9372a7915..000000000 --- a/jodd-proxetta/src/test/java/jodd/aop/fixture/LoggingAspect.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.aop.fixture; - -import jodd.aop.Aspect; - -import java.lang.reflect.Method; - -public class LoggingAspect extends Aspect { - - public static String log = ""; - - public LoggingAspect(Object target) { - super(target); - } - - @Override - public boolean before(Object target, Method method, Object[] args) { - log += "before "; - return true; - } - - @Override - public boolean after(Object target, Method method, Object[] args) { - log += target.getClass().getName() + '#' + method.getName(); - return true; - } - - @Override - public boolean afterException(Object target, Method method, Object[] args, Throwable throwable) { - return true; - } -} diff --git a/jodd-proxetta/src/test/java/jodd/aop/fixture/Simple.java b/jodd-proxetta/src/test/java/jodd/aop/fixture/Simple.java deleted file mode 100644 index 281a48ee9..000000000 --- a/jodd-proxetta/src/test/java/jodd/aop/fixture/Simple.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.aop.fixture; - -public class Simple implements Helloable { - - @Override - public String hello(int a) { - return "Hello World " + a; - } -} diff --git a/jodd-proxetta/src/test/java/jodd/asm/AsmUtilTest.java b/jodd-proxetta/src/test/java/jodd/asm/AsmUtilTest.java deleted file mode 100644 index 8385c5fca..000000000 --- a/jodd-proxetta/src/test/java/jodd/asm/AsmUtilTest.java +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.asm; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class AsmUtilTest { - - @Test - void testTyperef2Name() { - assertEquals("java.lang.String", AsmUtil.typeref2Name("Ljava/lang/String;")); - } - - @ParameterizedTest - @MethodSource(value = "testdata_testTypeToTyperef") - void testTypeToTyperef(final String expected, final Class input) { - assertEquals(expected, AsmUtil.typeToTyperef(input)); - } - - private static List testdata_testTypeToTyperef() { - final List params = new ArrayList<>(); - - // primitives - params.add(Arguments.of("I", int.class)); - params.add(Arguments.of("J", long.class)); - params.add(Arguments.of("Z", boolean.class)); - params.add(Arguments.of("D", double.class)); - params.add(Arguments.of("F", float.class)); - params.add(Arguments.of("S", short.class)); - params.add(Arguments.of("V", void.class)); - params.add(Arguments.of("B", byte.class)); - params.add(Arguments.of("C", char.class)); - // non primitives - params.add(Arguments.of("Ljava/lang/String;", String.class)); - params.add(Arguments.of("Ljodd/asm/AsmUtil;", AsmUtil.class)); - // Array - params.add(Arguments.of("[I", int[].class)); - params.add(Arguments.of("[Ljava.lang.String;", String[].class)); - params.add(Arguments.of("[Ljodd.asm.AsmUtil;", AsmUtil[].class)); - - - return params; - } - - @ParameterizedTest - @MethodSource(value = "testdata_testTypeToSignature_Class") - void testTypeToSignature_Class(final String expected, final Class input) { - assertEquals(expected, AsmUtil.typeToSignature(input)); - } - - private static List testdata_testTypeToSignature_Class() { - final List params = new ArrayList<>(); - - // primitives - params.add(Arguments.of("int", int.class)); - params.add(Arguments.of("long", long.class)); - params.add(Arguments.of("boolean", boolean.class)); - params.add(Arguments.of("double", double.class)); - params.add(Arguments.of("float", float.class)); - params.add(Arguments.of("short", short.class)); - params.add(Arguments.of("void", void.class)); - params.add(Arguments.of("byte", byte.class)); - params.add(Arguments.of("char", char.class)); - // non primitives - params.add(Arguments.of("java/lang/String", String.class)); - params.add(Arguments.of("jodd/asm/AsmUtil", AsmUtil.class)); - - - return params; - } - - @ParameterizedTest - @MethodSource(value = "testdata_testTypeToSignature_String") - void testTypeToSignature_String(final String expected, final String input) { - assertEquals(expected, AsmUtil.typeToSignature(input)); - } - - private static List testdata_testTypeToSignature_String() { - final List params = new ArrayList<>(); - - params.add(Arguments.of("java/lang/String", String.class.getName())); - params.add(Arguments.of("Jodd/makes/fun", "Jodd.makes.fun")); - - return params; - } -} diff --git a/jodd-proxetta/src/test/java/jodd/methref/DummyAdvice.java b/jodd-proxetta/src/test/java/jodd/methref/DummyAdvice.java deleted file mode 100644 index 725802cf9..000000000 --- a/jodd-proxetta/src/test/java/jodd/methref/DummyAdvice.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.methref; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -public class DummyAdvice implements ProxyAdvice { - - public Object execute() throws Exception { - return ProxyTarget.invoke(); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/methref/InterfaceMethodInvocationHandlerTest.java b/jodd-proxetta/src/test/java/jodd/methref/InterfaceMethodInvocationHandlerTest.java deleted file mode 100644 index 860734ed7..000000000 --- a/jodd-proxetta/src/test/java/jodd/methref/InterfaceMethodInvocationHandlerTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package jodd.methref; - -import jodd.util.ClassUtil; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Method; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class InterfaceMethodInvocationHandlerTest { - interface Foo { - boolean b(); - int i(); - double d(); - char c(); - float f(); - } - - @Test - void testPrimitives() { - final Methref methref = new Methref(this.getClass()); - final InterfaceMethodInvocationHandler imih = new InterfaceMethodInvocationHandler(methref); - - Method m = ClassUtil.findMethod(Foo.class, "b"); - assertEquals(false, imih.invoke(null, m, null)); - - m = ClassUtil.findMethod(Foo.class, "i"); - assertEquals(0, imih.invoke(null, m, null)); - - m = ClassUtil.findMethod(Foo.class, "d"); - assertEquals(0, imih.invoke(null, m, null)); - - m = ClassUtil.findMethod(Foo.class, "c"); - assertEquals(0, imih.invoke(null, m, null)); - - m = ClassUtil.findMethod(Foo.class, "f"); - assertEquals(0, imih.invoke(null, m, null)); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/methref/InterfaceTest.java b/jodd-proxetta/src/test/java/jodd/methref/InterfaceTest.java deleted file mode 100644 index ed6700458..000000000 --- a/jodd-proxetta/src/test/java/jodd/methref/InterfaceTest.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.methref; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class InterfaceTest { - - public static interface Hi { - public String hello(); - public int hi(long a); - public Hi hihi(Hi a); - } - - @Test - void testSimpleInterface() { - assertEquals("hello", Methref.of(Hi.class).name(Hi::hello)); - assertEquals("hi", Methref.of(Hi.class).name(h -> h.hi(0))); - assertEquals("hihi", Methref.of(Hi.class).name(h -> h.hihi(null))); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/methref/MethrefDetectionTest.java b/jodd-proxetta/src/test/java/jodd/methref/MethrefDetectionTest.java deleted file mode 100644 index 1f4ba3cd0..000000000 --- a/jodd-proxetta/src/test/java/jodd/methref/MethrefDetectionTest.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.methref; - -import jodd.proxetta.fixtures.data.Str; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class MethrefDetectionTest { - - @Test - void testMyProxy() { - final Methref m1 = Methref.of(Str.class); - final Methref m2 = Methref.of(Str.class); - - assertTrue(m1.isMyProxy(m1.proxy())); - assertFalse(m1.isMyProxy(m2.proxy())); - - assertTrue(m2.isMyProxy(m2.proxy())); - assertFalse(m2.isMyProxy(m1.proxy())); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/methref/MethrefJava8Test.java b/jodd-proxetta/src/test/java/jodd/methref/MethrefJava8Test.java deleted file mode 100644 index 8acf5b9c6..000000000 --- a/jodd-proxetta/src/test/java/jodd/methref/MethrefJava8Test.java +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.methref; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class MethrefJava8Test { - - public static interface Foo { - - public void hello(int i); - -// default String hey() { -// return "HEY"; -// } - } - - public static class Chuck implements Foo { - - @Override - public void hello(final int i) { - System.out.println(i); - } - - public void nerd() { - System.out.println("nerd"); - } - } - - public static class Sara extends Chuck { - @Override - public void hello(final int i) { - super.hello(i); - } - } - - @Test - void testMethrefOnInterfaceWithDefaultMethod() { - final Methref methref = Methref.of(Sara.class); - - String name = methref.name(sara -> sara.hello(123)); - assertEquals("hello", name); - - name = methref.name(Chuck::nerd); - assertEquals("nerd", name); - -// methref.to().hey(); -// assertEquals("hey", methref.ref()); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/methref/MethrefTest.java b/jodd-proxetta/src/test/java/jodd/methref/MethrefTest.java deleted file mode 100644 index 1cbc2ad42..000000000 --- a/jodd-proxetta/src/test/java/jodd/methref/MethrefTest.java +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.methref; - -import jodd.proxetta.Proxetta; -import jodd.proxetta.ProxyAspect; -import jodd.proxetta.fixtures.data.Str; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.pointcuts.AllTopMethodsPointcut; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -class MethrefTest { - - @Test - void testString() { - assertEquals("foo", Methref.of(Str.class).name(Str::foo)); - assertEquals("foo2", Methref.of(Str.class).name(s -> s.foo2(null, null))); - - final Str str = Methref.of(Str.class).proxy(); - str.foo(); - assertEquals("foo", Methref.lastName(str)); - str.foo2(null, null); - assertEquals("foo2", Methref.lastName(str)); - } - - @Test - void testNonString() { - final Methref mref = Methref.of(Str.class); - assertEquals("redirect:boo", "redirect:" + mref.name(Str::boo)); - mref.proxy().boo(); - assertEquals("redirect:boo", "redirect:" + Methref.lastName(mref.proxy())); - } - - @Test - void testPrimitives() { - final Methref mref = Methref.of(Str.class); - assertEquals("izoo", mref.name(Str::izoo)); - assertEquals("fzoo", mref.name(Str::fzoo)); - assertEquals("dzoo", mref.name(Str::dzoo)); - assertEquals("lzoo", mref.name(Str::lzoo)); - assertEquals("bzoo", mref.name(Str::bzoo)); - assertEquals("szoo", mref.name(Str::szoo)); - assertEquals("czoo", mref.name(Str::czoo)); - assertEquals("yzoo", mref.name(Str::yzoo)); - - mref.proxy().izoo(); - assertEquals("izoo", mref.lastName()); - mref.proxy().fzoo(); - assertEquals("fzoo", mref.lastName()); - mref.proxy().dzoo(); - assertEquals("dzoo", mref.lastName()); - mref.proxy().lzoo(); - assertEquals("lzoo", mref.lastName()); - mref.proxy().bzoo(); - assertEquals("bzoo", mref.lastName()); - mref.proxy().szoo(); - assertEquals("szoo", mref.lastName()); - mref.proxy().czoo(); - assertEquals("czoo", mref.lastName()); - mref.proxy().yzoo(); - assertEquals("yzoo", mref.lastName()); - } - - @Test - void testVoidOrTwoSteps() { - final Methref m = Methref.of(Str.class); - assertEquals("voo", m.name(Str::voo)); - - m.proxy().voo(); - assertEquals("voo", m.lastName()); - } - - @Test - void testMethRefOnProxifiedClass() { - Methref m = Methref.of(Oink.class); - String name = m.name(Oink::woink); - assertEquals("woink", name); - - final ProxyAspect a1 = new ProxyAspect(DummyAdvice.class, new AllTopMethodsPointcut()); - final ProxyProxetta pp = Proxetta.proxyProxetta().withAspect(a1); - final Oink oink = (Oink) pp.proxy().setTarget(Oink.class).newInstance(); - - assertNotEquals(oink.getClass(), Oink.class); - - m = Methref.of(oink.getClass()); - name = m.name(Oink::woink); - assertEquals("woink", name); - } - - @Test - void testParallelAccess() { - final Methref methref1 = Methref.of(Str.class); - - final String m1 = methref1.name(Str::boo); - - final Methref methref2 = Methref.of(Str.class); - - final String m2 = methref2.name(Str::foo); - - assertEquals("boo", m1); - assertEquals("foo", m2); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/methref/Oink.java b/jodd-proxetta/src/test/java/jodd/methref/Oink.java deleted file mode 100644 index 46c1b557b..000000000 --- a/jodd-proxetta/src/test/java/jodd/methref/Oink.java +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.methref; - -public class Oink { - - public void woink() { - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/paramo/ParamoTest.java b/jodd-proxetta/src/test/java/jodd/paramo/ParamoTest.java deleted file mode 100644 index 6b5fbd991..000000000 --- a/jodd-proxetta/src/test/java/jodd/paramo/ParamoTest.java +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.paramo; - -import jodd.asm.TraceSignatureVisitor; -import jodd.asm7.signature.SignatureReader; -import jodd.paramo.fixtures.Foo; -import jodd.paramo.fixtures.Generic; -import jodd.paramo.fixtures.NonGeneric; -import jodd.util.ClassUtil; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.Iterator; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -class ParamoTest { - - private String[] resolveParameterNames(final MethodParameter[] methodParameters) { - final String[] result = new String[methodParameters.length]; - for ( - int i = 0, methodParametersLength = methodParameters.length; - i < methodParametersLength; i++) { - final MethodParameter methodParameter = methodParameters[i]; - - result[i] = methodParameter.getName(); - } - return result; - } - - @Test - void testConstructor() throws NoSuchMethodException { - final Constructor c = Foo.class.getConstructor(String.class); - final MethodParameter[] mps = Paramo.resolveParameters(c); - final String[] s = resolveParameterNames(mps); - assertEquals(1, s.length); - assertEquals("something", s[0]); - assertEquals(String.class, mps[0].getParameter().getType()); - } - - @Test - void testOneParam() throws NoSuchMethodException { - final Method m = Foo.class.getMethod("one", String.class); - final MethodParameter[] mps = Paramo.resolveParameters(m); - final String[] s = resolveParameterNames(mps); - assertEquals(1, s.length); - assertEquals("foo", s[0]); - assertEquals(String.class, mps[0].getParameter().getType()); - } - - @Test - void testTwoParams() throws NoSuchMethodException { - final Method m = Foo.class.getMethod("two", String.class, String.class); - final MethodParameter[] mps = Paramo.resolveParameters(m); - final String[] s = resolveParameterNames(mps); - assertEquals(2, s.length); - assertEquals("username", s[0]); - assertEquals("password", s[1]); - - assertEquals(String.class, mps[0].getParameter().getType()); - assertEquals(String.class, mps[1].getParameter().getType()); - } - - @Test - void testNoParams() throws NoSuchMethodException { - final Method m = Foo.class.getMethod("hello"); - final MethodParameter[] mps = Paramo.resolveParameters(m); - assertNotNull(mps); - assertEquals(0, mps.length); - } - - @Test - void testArray() throws NoSuchMethodException { - final Method m = Foo.class.getMethod("array", String.class, Integer[].class, float[].class); - final MethodParameter[] mps = Paramo.resolveParameters(m); - final String[] s = resolveParameterNames(mps); - assertEquals(3, s.length); - assertEquals("foo", s[0]); - assertEquals("ints", s[1]); - assertEquals("floats", s[2]); - - assertEquals(String.class, mps[0].getParameter().getType()); - assertEquals(Integer[].class, mps[1].getParameter().getType()); - assertEquals(float[].class, mps[2].getParameter().getType()); - } - - @Test - void testPrimitives() { - final Method m = ClassUtil.findDeclaredMethod(Foo.class, "primitives"); - final MethodParameter[] mps = Paramo.resolveParameters(m); - final String[] s = resolveParameterNames(mps); - assertEquals(8, s.length); - assertEquals("i", s[0]); - assertEquals("l", s[1]); - assertEquals("f", s[2]); - assertEquals("d", s[3]); - assertEquals("s", s[4]); - assertEquals("b", s[5]); - assertEquals("c", s[6]); - assertEquals("y", s[7]); - - assertEquals(int.class, mps[0].getParameter().getType()); - assertEquals(long.class, mps[1].getParameter().getType()); - assertEquals(float.class, mps[2].getParameter().getType()); - assertEquals(double.class, mps[3].getParameter().getType()); - assertEquals(short.class, mps[4].getParameter().getType()); - assertEquals(boolean.class, mps[5].getParameter().getType()); - assertEquals(char.class, mps[6].getParameter().getType()); - assertEquals(byte.class, mps[7].getParameter().getType()); - } - - @Test - void testPrimitivesArrays1() { - final Method m = ClassUtil.findDeclaredMethod(Foo.class, "primarr1"); - final MethodParameter[] mps = Paramo.resolveParameters(m); - final String[] s = resolveParameterNames(mps); - assertEquals(2, s.length); - assertEquals("one", s[0]); - assertEquals("two", s[1]); - } - - @Test - void testPrimitivesArrays2() { - final Method m = ClassUtil.findDeclaredMethod(Foo.class, "primarr2"); - final MethodParameter[] mps = Paramo.resolveParameters(m); - final String[] s = resolveParameterNames(mps); - assertEquals(6, s.length); - assertEquals("i", s[0]); - assertEquals("l", s[1]); - assertEquals("f", s[2]); - assertEquals("d", s[3]); - assertEquals("b", s[4]); - assertEquals("c", s[5]); - } - - @Test - void testPrimitivesArrays3() { - final Method m = ClassUtil.findDeclaredMethod(Foo.class, "primarrShortByte"); - final MethodParameter[] mps = Paramo.resolveParameters(m); - final String[] s = resolveParameterNames(mps); - assertEquals(3, s.length); - assertEquals("s", s[0]); - assertEquals("y", s[1]); - assertEquals("somethingElse", s[2]); - } - - @Test - void testNonGeneric() { - final Method m = ClassUtil.findDeclaredMethod(NonGeneric.class, "one"); - final MethodParameter[] mps = Paramo.resolveParameters(m); - assertEquals(2, mps.length); - assertEquals("foo", mps[0].getName()); - assertEquals("Ljava/util/Map;", mps[0].getSignature()); - assertEquals("aLong", mps[1].getName()); - assertEquals("Ljava/lang/Long;", mps[1].getSignature()); - } - - @Test - void testGeneric() { - Method m = ClassUtil.findDeclaredMethod(Generic.class, "one"); - MethodParameter[] mps = Paramo.resolveParameters(m); - assertEquals(2, mps.length); - assertEquals("foo", mps[0].getName()); - assertEquals("Ljava/util/Map;", mps[0].getSignature()); - assertEquals("aLong", mps[1].getName()); - assertEquals("Ljava/lang/Long;", mps[1].getSignature()); - - m = ClassUtil.findDeclaredMethod(Generic.class, "two"); - mps = Paramo.resolveParameters(m); - assertEquals(1, mps.length); - assertEquals("zzz", mps[0].getName()); - assertEquals("Ljava/util/Map;>;", mps[0].getSignature()); - } - - @Test - void testGenericsWildcards() { - final Method m = ClassUtil.findDeclaredMethod(Generic.class, "three"); - final MethodParameter[] mps = Paramo.resolveParameters(m); - assertEquals(3, mps.length); - - assertEquals("comparable", mps[0].getName()); - assertEquals("Ljava/lang/Comparable<*>;", mps[0].getSignature()); - assertEquals(Comparable.class, mps[0].getParameter().getType()); - assertEquals("(java.lang.Comparable)", resolveSignature(mps[0].getSignature())); - - - assertEquals("iterator", mps[1].getName()); - assertEquals("Ljava/util/Iterator<+Ljava/lang/CharSequence;>;", mps[1].getSignature()); - assertEquals(Iterator.class, mps[1].getParameter().getType()); - assertEquals("(java.util.Iterator)", resolveSignature(mps[1].getSignature())); - - - assertEquals("list", mps[2].getName()); - assertEquals("Ljava/util/List<-Ljava/lang/Integer;>;", mps[2].getSignature()); - assertEquals("(java.util.List)", resolveSignature(mps[2].getSignature())); - } - - - private String resolveSignature(final String signature) { - final SignatureReader signatureReader = new SignatureReader("(" + signature + ")V"); - final StringBuilder sb = new StringBuilder(); - signatureReader.accept(new TraceSignatureVisitor(sb, true)); - return sb.toString(); - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/paramo/fixtures/Bar.java b/jodd-proxetta/src/test/java/jodd/paramo/fixtures/Bar.java deleted file mode 100644 index 03a2b7dfc..000000000 --- a/jodd-proxetta/src/test/java/jodd/paramo/fixtures/Bar.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.paramo.fixtures; - -public class Bar { - -} diff --git a/jodd-proxetta/src/test/java/jodd/paramo/fixtures/Foo.java b/jodd-proxetta/src/test/java/jodd/paramo/fixtures/Foo.java deleted file mode 100644 index 98c58d000..000000000 --- a/jodd-proxetta/src/test/java/jodd/paramo/fixtures/Foo.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.paramo.fixtures; - -public class Foo { - - public Foo(String something) {} - public void hello() {} - public void one(String foo) {} - public void two(String username, String password) {} - public void array(String foo, Integer[] ints, float[] floats) {} - public void primitives(int i, long l, float f, double d, short s, boolean b, char c, byte y) {} - public void primarr1(int one, int[] two) {} - public void primarr2(int[] i, long[] l, float[] f, double[] d, boolean[] b, char[] c) {} - public void primarrShortByte(short[] s, byte[] y, int somethingElse) {} - -} diff --git a/jodd-proxetta/src/test/java/jodd/paramo/fixtures/Generic.java b/jodd-proxetta/src/test/java/jodd/paramo/fixtures/Generic.java deleted file mode 100644 index 2f0413c38..000000000 --- a/jodd-proxetta/src/test/java/jodd/paramo/fixtures/Generic.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.paramo.fixtures; - -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public class Generic { - - public void one(Map foo, Long aLong) { - } - - public void two(Map> zzz) { - } - - public void three(Comparable comparable, Iterator iterator, List list) { - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/paramo/fixtures/NonGeneric.java b/jodd-proxetta/src/test/java/jodd/paramo/fixtures/NonGeneric.java deleted file mode 100644 index 3060b3989..000000000 --- a/jodd-proxetta/src/test/java/jodd/paramo/fixtures/NonGeneric.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.paramo.fixtures; - -import java.util.Map; - -public class NonGeneric { - - public void one(Map foo, Long aLong) { - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/pathref/PathRefTest.java b/jodd-proxetta/src/test/java/jodd/pathref/PathRefTest.java deleted file mode 100644 index 3ecc96307..000000000 --- a/jodd-proxetta/src/test/java/jodd/pathref/PathRefTest.java +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.pathref; - -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static jodd.pathref.Pathref.ALL; -import static org.junit.jupiter.api.Assertions.assertEquals; - -class PathRefTest { - - public static class User { - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public Address getAddress() { - return address; - } - - public void setAddress(final Address address) { - this.address = address; - } - - public List getFriends() { - return friends; - } - - public void setFriends(final List friends) { - this.friends = friends; - } - - public User getBestFriend() { - return bestFriend; - } - - public void setBestFriend(final User bestFriend) { - this.bestFriend = bestFriend; - } - - protected String name; - protected Address address; - protected List friends; - protected User bestFriend; - } - - public static class Address { - public String getStreet() { - return street; - } - - public void setStreet(final String street) { - this.street = street; - } - - protected String street; - } - - @Test - void testPathCollection() { - final Pathref p = Pathref.of(User.class); - - assertEquals("address", p.path(User::getAddress)); - assertEquals("address.street", p.path((u) -> u.getAddress().getStreet())); - assertEquals("friends[0].address.street", p.path((u) -> u.getFriends().get(0).getAddress().getStreet())); - assertEquals("bestFriend.bestFriend.bestFriend.friends[123].address.street", - p.path((u) -> u.getBestFriend().getBestFriend().getBestFriend().getFriends().get(123).getAddress().getStreet())); - } - - @Test - void testPathAll() { - final Pathref p = Pathref.of(User.class); - - assertEquals("address", p.path((u) -> u.getAddress())); - assertEquals("address.street", p.path((u) -> u.getAddress().getStreet())); - assertEquals("friends.address.street", p.path((u) -> u.getFriends().get(ALL).getAddress().getStreet())); - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/AbstractsTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/AbstractsTest.java deleted file mode 100644 index dad7a9727..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/AbstractsTest.java +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.proxetta.fixtures.data.Abstra; -import jodd.proxetta.fixtures.data.Abstra2; -import jodd.proxetta.fixtures.data.Foo; -import jodd.proxetta.fixtures.data.FooProxyAdvice; -import jodd.proxetta.fixtures.data.Inter; -import jodd.proxetta.fixtures.data.InvalidAdvice; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.fail; - -class AbstractsTest { - - @Test - void testAbstract1() { - ProxyAspect proxyAspect = new ProxyAspect(FooProxyAdvice.class, methodInfo -> true); - - Abstra aaa = (Abstra) Proxetta.proxyProxetta().withAspect(proxyAspect).proxy().setTarget(Abstra.class).newInstance(); - assertNotNull(aaa); - aaa.foo(); - } - - @Test - void testAbstract2() { - ProxyAspect proxyAspect = new ProxyAspect(FooProxyAdvice.class, methodInfo -> true); - - try { - Proxetta.proxyProxetta().withAspect(proxyAspect).proxy().setTarget(Abstra2.class).newInstance(); - fail("error"); - } catch (ProxettaException ignore) { - } - } - - @Test - void testInterface() { - ProxyAspect proxyAspect = new ProxyAspect(FooProxyAdvice.class, methodInfo -> true); - - try { - Proxetta.proxyProxetta().withAspects(proxyAspect).proxy().setTarget(Inter.class).newInstance(); - fail("error"); - } catch (ProxettaException ignore) { - } - } - - @Test - void testAdviceWithInnerClass() { - ProxyAspect proxyAspect = new ProxyAspect(InvalidAdvice.class, methodInfo -> true); - - try { - Proxetta.proxyProxetta().withAspect(proxyAspect).proxy().setTarget(Foo.class).newInstance(); - fail("error"); - } catch (ProxettaException ignore) { - System.out.println(ignore); - } - - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/AdviceWithMethodTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/AdviceWithMethodTest.java deleted file mode 100644 index 93a89383c..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/AdviceWithMethodTest.java +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.proxetta.fixtures.data.CollectorAdvice; -import jodd.proxetta.fixtures.data.Foo; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.pointcuts.AllTopMethodsPointcut; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Field; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -class AdviceWithMethodTest { - - @Test - void testCollector() throws NoSuchFieldException, IllegalAccessException { - ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspects( - new ProxyAspect(CollectorAdvice.class, new AllTopMethodsPointcut()) - ); - -// proxetta.setDebugFolder("d:\\"); - - Foo foo = (Foo) proxetta.proxy().setTarget(Foo.class).newInstance(); - - Field field = foo.getClass().getDeclaredField("$__methods$0"); - - field.setAccessible(true); - - List list = (List) field.get(foo); - - assertNotNull(list); - - assertEquals(0, list.size()); - - foo.m1(); - assertEquals(1, list.size()); - assertEquals("m1", list.get(0)); - - foo.m1(); - assertEquals(2, list.size()); - assertEquals("m1", list.get(0)); - assertEquals("m1", list.get(1)); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/AnnTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/AnnTest.java deleted file mode 100644 index 826cf405c..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/AnnTest.java +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.proxetta.fixtures.data.Hero; -import jodd.proxetta.fixtures.data.HeroProxyAdvice; -import jodd.proxetta.fixtures.data.HeroProxyAdvice2; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.impl.WrapperProxetta; -import jodd.proxetta.impl.WrapperProxettaFactory; -import jodd.proxetta.pointcuts.AllRealMethodsPointcut; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class AnnTest { - - @Test - void testMethodAnnotationsProxy() { - ProxyProxetta proxetta = Proxetta - .proxyProxetta() - .withAspect( - ProxyAspect.of(HeroProxyAdvice.class, - ((ProxyPointcut) MethodInfo::isTopLevelMethod).and(AllRealMethodsPointcut.get()) - )) - //.setDebugFolder(FileUtil.file("~")) - ; - - ProxettaFactory proxettaFactory = proxetta.proxy(); - proxettaFactory.setTarget(Hero.class); - proxetta.setVariableClassName(true); - Hero hero = (Hero) proxettaFactory.newInstance(); - - assertEquals("BatmanHero37W88.3CatWoman99speeeeedXRAYnull", hero.name()); - } - - @Test - void testClassAnnotationsProxy() { - ProxyProxetta proxetta = Proxetta - .proxyProxetta() - .withAspect( - new ProxyAspect(HeroProxyAdvice2.class, - ((ProxyPointcut) MethodInfo::isTopLevelMethod).and(AllRealMethodsPointcut.get()) - )) - //.setDebugFolder("/Users/igor/") - ; - - ProxettaFactory proxettaFactory = proxetta.proxy(); - proxettaFactory.setTarget(Hero.class); - proxetta.setVariableClassName(true); - Hero hero = (Hero) proxettaFactory.newInstance(); - - assertEquals("SilverHero89W99.222None1000speeeeedXRAYnull", hero.name()); - } - - @Test - void testMethodAnnotationsWrapper() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { - WrapperProxetta proxetta = Proxetta - .wrapperProxetta() - .withAspect( - new ProxyAspect(HeroProxyAdvice.class, - ((ProxyPointcut) MethodInfo::isTopLevelMethod).and(AllRealMethodsPointcut.get()) - )) - //.setDebugFolder("/Users/igor/") - ; - - WrapperProxettaFactory proxettaBuilder = proxetta.proxy(); - proxettaBuilder.setTarget(Hero.class); - proxetta.setVariableClassName(true); - Object hero = proxettaBuilder.newInstance(); - - Method nameMethod = hero.getClass().getMethod("name"); - assertEquals("BatmanHero37W88.3CatWoman99speeeeedXRAYnull", nameMethod.invoke(hero)); - } - - @Test - void testClassAnnotationsWrapper() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { - WrapperProxetta proxetta = Proxetta - .wrapperProxetta() - .withAspects( - new ProxyAspect(HeroProxyAdvice2.class, - ((ProxyPointcut) MethodInfo::isTopLevelMethod).and(AllRealMethodsPointcut.get()) - )) - //.setDebugFolder("/Users/igor/") - ; - - WrapperProxettaFactory proxettaBuilder = proxetta.proxy(); - proxettaBuilder.setTarget(Hero.class); - proxetta.setVariableClassName(true); - Object hero = proxettaBuilder.newInstance(); - - Method nameMethod = hero.getClass().getMethod("name"); - assertEquals("SilverHero89W99.222None1000speeeeedXRAYnull", nameMethod.invoke(hero)); - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/BigClassTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/BigClassTest.java deleted file mode 100644 index 3f40a125c..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/BigClassTest.java +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.asm7.Type; -import jodd.introspector.ClassDescriptor; -import jodd.introspector.ClassIntrospector; -import jodd.mutable.MutableBoolean; -import jodd.proxetta.fixtures.data.Action; -import jodd.proxetta.fixtures.data.BigFatJoe; -import jodd.proxetta.fixtures.data.InterceptedBy; -import jodd.proxetta.fixtures.data.MadvocAction; -import jodd.proxetta.fixtures.data.PetiteBean; -import jodd.proxetta.fixtures.data.PetiteInject; -import jodd.proxetta.fixtures.data.StatCounter; -import jodd.proxetta.fixtures.data.StatCounterAdvice; -import jodd.proxetta.fixtures.data.Transaction; -import jodd.util.DefineClass; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class BigClassTest { - - @Test - void testAllFeatures() throws IOException, IllegalAccessException, InstantiationException { - StatCounter.counter = 0; - final MutableBoolean firstTime = new MutableBoolean(true); - - final ProxyAspect aspect = new ProxyAspect(StatCounterAdvice.class, mi -> { - if (firstTime.value) { - firstTime.value = false; - final ClassInfo ci = mi.getClassInfo(); - assertEquals("BigFatJoe", ci.getClassname()); - assertEquals(BigFatJoe.class.getPackage().getName(), ci.getPackage()); - assertEquals("jodd/proxetta/fixtures/data/BigFatJoe", ci.getReference()); - assertEquals("jodd/proxetta/fixtures/data/SmallSkinnyZoe", ci.getSuperName()); - final AnnotationInfo[] anns = ci.getAnnotations(); - assertNotNull(anns); - assertEquals(3, anns.length); - AnnotationInfo ai = anns[0]; - assertSame(ai, ci.getAnnotation(MadvocAction.class)); - assertEquals(MadvocAction.class.getName(), ai.getAnnotationClassname()); - assertEquals("L" + MadvocAction.class.getName().replace('.', '/') + ";", ai.getAnnotationSignature()); - assertEquals("madvocAction", ai.getElement("value")); - ai = anns[1]; - assertSame(ai, ci.getAnnotation(PetiteBean.class)); - assertEquals(PetiteBean.class.getName(), ai.getAnnotationClassname()); - assertEquals("L" + PetiteBean.class.getName().replace('.', '/') + ";", ai.getAnnotationSignature()); - ai = anns[2]; - assertSame(ai, ci.getAnnotation(InterceptedBy.class)); - assertEquals(InterceptedBy.class.getName(), ai.getAnnotationClassname()); - assertEquals("L" + InterceptedBy.class.getName().replace('.', '/') + ";", ai.getAnnotationSignature()); - assertTrue(ai.getElement("value") instanceof Object[]); - assertFalse(ai.getElement("value") instanceof String[]); - final Object c1 = ((Object[]) ai.getElement("value"))[0]; - assertEquals("Ljodd/proxetta/fixtures/data/Str;", ((Type) c1).getDescriptor()); - } - if (mi.getMethodName().equals("publicMethod")) { - final AnnotationInfo[] anns = mi.getAnnotations(); - assertNotNull(anns); - assertEquals(3, anns.length); - - AnnotationInfo ai = anns[0]; - assertSame(ai, mi.getAnnotation(Action.class)); - assertEquals(Action.class.getName(), ai.getAnnotationClassname()); - assertEquals("value", ai.getElement("value")); - assertEquals("alias", ai.getElement("alias")); - - ai = anns[1]; - assertSame(ai, mi.getAnnotation(PetiteInject.class)); - assertEquals(PetiteInject.class.getName(), ai.getAnnotationClassname()); - assertEquals(0, ai.getElementNames().size()); - - ai = anns[2]; - assertSame(ai, mi.getAnnotation(Transaction.class)); - assertEquals(Transaction.class.getName(), ai.getAnnotationClassname()); - assertEquals(2, ai.getElementNames().size()); - final String s = (String) ai.getElement("propagation"); - assertEquals("PROPAGATION_REQUIRES_NEW", s); - } - if (mi.getMethodName().equals("superPublicMethod")) { - final AnnotationInfo[] anns = mi.getAnnotations(); - assertNotNull(anns); - assertEquals(3, anns.length); - - AnnotationInfo ai = anns[0]; - assertSame(ai, mi.getAnnotation(Action.class)); - assertEquals(Action.class.getName(), ai.getAnnotationClassname()); - assertEquals(0, ai.getElementNames().size()); - - ai = anns[1]; - assertSame(ai, mi.getAnnotation(PetiteInject.class)); - assertEquals(PetiteInject.class.getName(), ai.getAnnotationClassname()); - assertEquals(0, ai.getElementNames().size()); - - ai = anns[2]; - assertSame(ai, mi.getAnnotation(Transaction.class)); - assertEquals(Transaction.class.getName(), ai.getAnnotationClassname()); - assertEquals(0, ai.getElementNames().size()); - } - //System.out.println(!isRootMethod(mi) + " " + mi.getDeclaredClassName() + '#' + mi.getMethodName()); - return !mi.isRootMethod(); - }); - - final byte[] classBytes = Proxetta.proxyProxetta().withAspect(aspect).proxy().setTarget(BigFatJoe.class).create(); -// URL resource = BigFatJoe.class.getResource("/" + BigFatJoe.class.getName().replace(".", "/") + ".class"); -// jodd.io.FileUtil.copy(FileUtil.toFile(resource), new java.io.File(SystemUtil.getUserHome(), "jo.class")); -// jodd.io.FileUtil.writeBytes(new java.io.File(SystemUtil.getUserHome(), "joe.class"), classBytes); - final Class clazz = DefineClass.of(null, classBytes, null); - final BigFatJoe bigFatJoe = (BigFatJoe) clazz.newInstance(); - - assertEquals(BigFatJoe.class.getName() + ProxettaNames.proxyClassNameSuffix, bigFatJoe.getClass().getName()); - assertEquals(BigFatJoe.class, ProxettaUtil.resolveTargetClass(bigFatJoe.getClass())); - - // test invocation - - assertEquals(3, StatCounter.counter); // 2 x static + 1 x instance - bigFatJoe.publicMethod(); - assertEquals(4, StatCounter.counter); - bigFatJoe.callInnerMethods(); - assertEquals(7, StatCounter.counter); // private method is not overridden - - bigFatJoe.superPublicMethod(); - assertEquals(8, StatCounter.counter); - bigFatJoe.callInnerMethods2(); - assertEquals(9, StatCounter.counter); // only public super methods are overridden - - // test class annotation - final MadvocAction ma = (MadvocAction) clazz.getAnnotation(MadvocAction.class); - assertEquals("madvocAction", ma.value()); - - final InterceptedBy ib = (InterceptedBy) clazz.getAnnotation(InterceptedBy.class); - assertNotNull(ib.value()); - assertEquals(2, ib.value().length); - - - // test method annotation - final ClassDescriptor cd = ClassIntrospector.get().lookup(clazz); - final Method m = cd.getMethodDescriptor("publicMethod", false).getMethod(); - assertNotNull(m); - final Annotation[] aa = m.getAnnotations(); - assertEquals(3, aa.length); - final Action a = (Action) aa[0]; - assertEquals("alias", a.alias()); - assertEquals("extension", a.extension()); - assertEquals("method", a.method()); - assertEquals("value", a.value()); - - final PetiteInject pi = (PetiteInject) aa[1]; - assertEquals("", pi.value()); - - final Transaction tx = (Transaction) aa[2]; - assertTrue(tx.readOnly()); - assertEquals(1000, tx.timeout()); - assertEquals("PROPAGATION_REQUIRES_NEW", tx.propagation()); - - bigFatJoe.runInnerClass(); - assertEquals(11, StatCounter.counter); // proxy + call - - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/GenericArrayTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/GenericArrayTest.java deleted file mode 100644 index 0eecb7c16..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/GenericArrayTest.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.proxetta.advice.DelegateAdvice; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.impl.ProxyProxettaFactory; -import jodd.proxetta.pointcuts.AllMethodsPointcut; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.fail; - -class GenericArrayTest { - - public static class Foo { - public Stuff[] getArray() { - return (Stuff[]) new Object[0]; - } - - public Thingy[] getArrayStatic() { - return (Thingy[]) new Object[0]; - } - } - - @Test - void testClassesWithGenericArraysAsReturnValueProxy() { - try { - ProxyAspect aspect = new ProxyAspect(DelegateAdvice.class, new AllMethodsPointcut()); - ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspect(aspect); - ProxyProxettaFactory builder = proxetta.proxy().setTarget(Foo.class); - builder.newInstance(); - } catch (Exception e) { - e.printStackTrace(); - fail(e.toString()); - } - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/GenericsTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/GenericsTest.java deleted file mode 100644 index d4bb4bb64..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/GenericsTest.java +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.introspector.ClassIntrospector; -import jodd.proxetta.advice.DelegateAdvice; -import jodd.proxetta.fixtures.data.Action; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.impl.ProxyProxettaFactory; -import jodd.proxetta.impl.WrapperProxetta; -import jodd.proxetta.impl.WrapperProxettaFactory; -import jodd.proxetta.pointcuts.AllMethodsPointcut; -import org.junit.jupiter.api.Test; - -import static jodd.proxetta.ProxyTarget.createArgumentsClassArray; -import static org.junit.jupiter.api.Assertions.fail; - -class GenericsTest { - public static class Bar { - } - - public static interface IFoo { - String getId(); - Bar getFoo(); - } - - public static class Foo implements IFoo { - private String id; - @Override - public String getId() { - return id; - } - // remove the generic and it works - @Override - public Bar getFoo() { - return null; - } - } - - @Test - void testClassesWithGenericsAsReturnValueWrapper() { - try { - ProxyAspect aspect = new ProxyAspect(DelegateAdvice.class, new AllMethodsPointcut()); - WrapperProxetta proxetta = Proxetta.wrapperProxetta().withAspects(aspect); - WrapperProxettaFactory builder = proxetta.proxy().setTarget(Foo.class).setTargetInterface(IFoo.class); - builder.newInstance(); - } - catch (Exception ex) { - fail(ex.toString()); - } - } - - @Test - void testClassesWithGenericsAsReturnValueProxy() { - try { - ProxyAspect aspect = new ProxyAspect(DelegateAdvice.class, new AllMethodsPointcut()); - ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspects(aspect); - ProxyProxettaFactory builder = proxetta.proxy().setTarget(Foo.class); - builder.newInstance(); - } - catch (Exception ex) { - ex.printStackTrace(); - fail(ex.toString()); - } - } - - // ---------------------------------------------------------------- daos - - - public static class JoyDao { - public T foo(Id[] val) { - return null; - } - } - public static class RoomDao extends JoyDao{ - } - public static class IncompleteDao extends JoyDao {} - public static class FinalDao extends IncompleteDao {} - - @Test - void testClassesWithGenericsAsReturnValueProxy_array1() { - RoomDao dao; - try { - ProxyAspect aspect = new ProxyAspect(LogAdvice.class, new AllMethodsPointcut()); - ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspects(aspect); - ProxyProxettaFactory builder = proxetta.proxy().setTarget(RoomDao.class); - dao = (RoomDao) builder.newInstance(); - - ClassIntrospector.get().lookup(dao.getClass()).getAllMethodDescriptors(); - dao.foo(null); - } - catch (Exception ex) { - ex.printStackTrace(); - fail(ex.toString()); - } - } - - @Test - void testClassesWithGenericsAsReturnValueProxy_array2() { - FinalDao dao; - try { - ProxyAspect aspect = new ProxyAspect(LogAdvice.class, new AllMethodsPointcut()); - ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspects(aspect); - ProxyProxettaFactory builder = proxetta.proxy().setTarget(FinalDao.class); - dao = (FinalDao) builder.newInstance(); - - ClassIntrospector.get().lookup(dao.getClass()).getAllMethodDescriptors(); - dao.foo(null); - } - catch (Exception ex) { - ex.printStackTrace(); - fail(ex.toString()); - } - } - - - // ---------------------------------------------------------------- misc - - public static class Boo { - @Action - public void save(T t) { - } - } - - public static class MyBoo extends Boo { - } - - public static class LogAdvice implements ProxyAdvice { - - @Override - public Object execute() { - System.out.println(ProxyTarget.targetMethodName()); - - Class[] methodArgsTypes = createArgumentsClassArray(); - - System.out.println(methodArgsTypes); - - return ProxyTarget.invoke(); - } - } - - @Test - void testExtendingGenerics() { - ProxyAspect aspect = new ProxyAspect(LogAdvice.class, new AllMethodsPointcut()); - ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspects(aspect); - ProxyProxettaFactory builder = proxetta.proxy().setTarget(MyBoo.class); - Boo boo = (Boo) builder.newInstance(); - boo.save(new Foo()); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/InvReplTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/InvReplTest.java deleted file mode 100644 index a72fb30e9..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/InvReplTest.java +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.io.FastByteArrayOutputStream; -import jodd.proxetta.fixtures.inv.Inter; -import jodd.proxetta.fixtures.inv.MySystem; -import jodd.proxetta.fixtures.inv.One; -import jodd.proxetta.fixtures.inv.OneWithSuper; -import jodd.proxetta.fixtures.inv.Replacer; -import jodd.proxetta.fixtures.inv.TimeClass; -import jodd.proxetta.fixtures.inv.Two; -import jodd.proxetta.fixtures.inv.Wimp; -import jodd.proxetta.impl.InvokeProxetta; -import jodd.util.DefineClass; -import org.junit.jupiter.api.Test; - -import java.io.PrintStream; -import java.io.Serializable; -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -class InvReplTest { - - @Test - void testReplacement() throws IllegalAccessException, InstantiationException, NoSuchMethodException { - - final InvokeProxetta proxetta = initProxetta(); - - final String className = One.class.getCanonicalName(); - final byte[] klazz = proxetta.proxy().setTarget(One.class).create(); - //FileUtil.writeBytes("/Users/igor/OneClone.class", klazz); - - final FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream(); -// PrintStream out = System.out; - System.setOut(new PrintStream(fbaos)); - - final One one = (One) DefineClass.of((new StringBuilder()).append(className).append(ProxettaNames.invokeProxyClassNameSuffix).toString(), klazz, null).newInstance(); - assertEquals("one ctor!one ctor!", fbaos.toString()); // clone ctor calls super ctor, - fbaos.reset(); - - one.example1(); - assertEquals("REPLACED VIRTUAL! jodd.proxetta.fixtures.inv.Two * one!173>overriden sub", fbaos.toString()); - fbaos.reset(); - - one.example2(); - assertEquals( - "REPLACED STATIC! one * jodd/proxetta/fixtures/inv/Two * " + - "example2 * void example2() * jodd.proxetta.fixtures.inv.One * " + - "jodd.proxetta.fixtures.inv.One" + ProxettaNames.invokeProxyClassNameSuffix + "!15013static: 4", fbaos.toString()); - fbaos.reset(); - - one.example3(); - assertEquals("state = REPLACED ctor!", fbaos.toString()); - fbaos.reset(); - - assertEquals("jodd.proxetta.fixtures.inv.One" + ProxettaNames.invokeProxyClassNameSuffix, one.getClass().getName()); - assertTrue(one instanceof Serializable); - - Annotation[] anns = one.getClass().getAnnotations(); - assertEquals(3, anns.length); - - final Method ms = one.getClass().getMethod("example1"); - anns = ms.getAnnotations(); - assertEquals(1, anns.length); - - } - - @Test - void testSuper() { - final InvokeProxetta proxetta = initProxetta(); - try { - proxetta.proxy().setTarget(OneWithSuper.class).define(); - fail("error"); - } catch (final ProxettaException ignore) { - - } - } - - @Test - void testInterface() { - final InvokeProxetta proxetta = initProxetta(); - try { - proxetta.proxy().setTarget(Inter.class).newInstance(); - fail("error"); - } catch (final ProxettaException ignore) { - } - } - - @Test - void testCurrentTimeMillis() { - final TimeClass timeClass = (TimeClass) Proxetta.invokeProxetta().withAspects(new InvokeAspect() { - @Override - public boolean apply(final MethodInfo methodInfo) { - return methodInfo.isTopLevelMethod(); - } - - @Override - public InvokeReplacer pointcut(final InvokeInfo invokeInfo) { - if ( - invokeInfo.getClassName().equals("java.lang.System") && - invokeInfo.getMethodName().equals("currentTimeMillis") - ) { - return InvokeReplacer.with(MySystem.class, "currentTimeMillis"); - } - return null; - } - }).proxy().setTarget(TimeClass.class).newInstance(); - - final long time = timeClass.time(); - - assertEquals(10823, time); - } - - @Test - void testWimp() { - final Wimp wimp = (Wimp) Proxetta.invokeProxetta().withAspect(new InvokeAspect() { - @Override - public boolean apply(final MethodInfo methodInfo) { - return methodInfo.isTopLevelMethod(); - } - - @Override - public InvokeReplacer pointcut(final InvokeInfo invokeInfo) { - return InvokeReplacer.NONE; - } - }).proxy().setTarget(Wimp.class).newInstance(); - - final int i = wimp.foo(); - assertEquals(0, i); - - String txt = wimp.aaa(3, null, null); - assertEquals("int3WelcomeToJodd", txt); - - txt = wimp.ccc(3, "XXX", 1, null); - assertEquals(">4:String:4long:4XXX:ccc:Wimp", txt); - } - - - protected InvokeProxetta initProxetta() { - return Proxetta.invokeProxetta().withAspects( - invokeInfo -> { - if (invokeInfo.getMethodName().equals("invvirtual")) { - return InvokeReplacer.with(Replacer.class, "rInvVirtual") - .passOwnerName(false); - } else { - return null; - } - }, - invokeInfo -> { - if (invokeInfo.getMethodName().equals("invstatic")) { - return InvokeReplacer.with(Replacer.class, "rInvStatic") - .passOwnerName(true) - .passMethodName(true) - .passMethodSignature(true) - .passThis(true) - .passTargetClass(true); - } else { - return null; - } - }, - invokeInfo -> { - if (invokeInfo.getMethodName().equals("invinterface")) { - return InvokeReplacer.with(Replacer.class, "rInvInterface"); - } else { - return null; - } - } - , - invokeInfo -> { - if (invokeInfo.getMethodName().equals("") && invokeInfo.getClassName().equals(Two.class.getCanonicalName())) { - return InvokeReplacer.with(Replacer.class, "rInvNew"); - } else { - return null; - } - } - ); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/KotlinTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/KotlinTest.java deleted file mode 100644 index d0af2804d..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/KotlinTest.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.proxetta.fixtures.data.Transaction; -import jodd.proxetta.petite.fixtures.LogProxyAdvice; -import jodd.proxetta.pointcuts.MethodWithAnnotationPointcut; -import org.junit.jupiter.api.Test; -import service.Test568OpenService; -import service.Test568Service; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -class KotlinTest { - - @Test - void testWrapperProxetta_unopen() throws InvocationTargetException, IllegalAccessException { - ProxyAspect proxyAspect = ProxyAspect.of(LogProxyAdvice.class, MethodWithAnnotationPointcut.of(Transaction.class)); - - final Object service = - Proxetta.wrapperProxetta() - .withAspect(proxyAspect) - .setCreateTargetInDefaultCtor(true) - .proxy() - .setTarget(Test568Service.class) - .newInstance(); - - // no need to inject since setCreateTargetInstanceInDefaultCtor is set -// ProxettaUtil.injectTargetIntoWrapper(new Test568Service(), service); - - Method method = jodd.util.ClassUtil.findMethod(service.getClass(), "findMember"); - - String result = (String) method.invoke(service, Long.valueOf(1)); - - assertEquals("1", result); - } - - @Test - void testProxyProxetta_open() { - ProxyAspect proxyAspect = ProxyAspect.of(LogProxyAdvice.class, MethodWithAnnotationPointcut.of(Transaction.class)); - Test568OpenService service = - (Test568OpenService) Proxetta.proxyProxetta() - .withAspect(proxyAspect) - .proxy() - .setTarget(Test568OpenService.class) - .newInstance(); - - String result = service.findMember(2L); - - assertEquals("2", result); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/MethodInfoTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/MethodInfoTest.java deleted file mode 100644 index 8c8ba95df..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/MethodInfoTest.java +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.mutable.Value; -import jodd.proxetta.fixtures.data.Foo; -import jodd.proxetta.fixtures.data.FooAnn; -import jodd.proxetta.fixtures.data.FooProxyAdvice; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.impl.ProxyProxettaFactory; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class MethodInfoTest { - - @Test - void testMethodInfo() { - - final Value value = Value.of(null); - - ProxyAspect proxyAspect = new ProxyAspect( - FooProxyAdvice.class, - methodInfo -> { - if (methodInfo.getMethodName().equals("p1")) { - value.set(methodInfo); - return true; - } - return false; - } - ); - - ProxyProxetta proxyProxetta = Proxetta.proxyProxetta().withAspect(proxyAspect); - proxyProxetta.setClassNameSuffix("$$$Proxetta888"); - ProxyProxettaFactory pb = proxyProxetta.proxy(); - pb.setTarget(Foo.class); - Foo foo = (Foo) pb.newInstance(); - - assertNotNull(foo); - - MethodInfo mi = value.get(); - - assertEquals("p1", mi.getMethodName()); - assertEquals(Foo.class.getName().replace('.', '/'), mi.getClassname()); - assertEquals("(java.lang.String)java.lang.String", mi.getDeclaration()); - assertEquals("(Ljava/lang/String;)Ljava/lang/String;", mi.getDescription()); - assertEquals("java.lang.String", mi.getReturnType().getType()); - assertEquals("Ljava/lang/String;", mi.getReturnType().getName()); - - assertEquals("java.lang.String p1(java.lang.String)", mi.getSignature()); - - assertEquals(1, mi.getArgumentsCount()); - assertEquals("Ljava/lang/String;", mi.getArgument(1).getName()); - - assertTrue(mi.isTopLevelMethod()); - - AnnotationInfo[] anns = mi.getArgument(1).getAnnotations(); - - assertNotNull(anns); - assertEquals(1, anns.length); - assertEquals(FooAnn.class.getName(), anns[0].getAnnotationClassname()); - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/MethodSignatureVisitorTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/MethodSignatureVisitorTest.java deleted file mode 100644 index d4df9ede5..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/MethodSignatureVisitorTest.java +++ /dev/null @@ -1,453 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.asm7.ClassReader; -import jodd.proxetta.asm.MethodSignatureVisitor; -import jodd.proxetta.fixtures.TargetClassInfoReaderFixture; -import jodd.proxetta.fixtures.data.FooAnn; -import jodd.util.ClassLoaderUtil; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static jodd.asm.AsmUtil.SIGNATURE_JAVA_LANG_DOUBLE; -import static jodd.asm.AsmUtil.SIGNATURE_JAVA_LANG_INTEGER; -import static jodd.asm.AsmUtil.SIGNATURE_JAVA_LANG_LONG; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -class MethodSignatureVisitorTest { - - private static final String CLASS_NAME = MethodSignatureVisitorTest.class.getName(); - private static final String CLASS_SIGNATURE = CLASS_NAME.replace('.', '/'); - private static final String L_CLASS_SIGNATURE = "L" + CLASS_SIGNATURE; - - // ---------------------------------------------------------------- 1 - - public static class M1 { - public void macka() {} - } - - @Test - void testMethodSignature1() throws IOException { - final MethodInfo mi = getMethodSignatureForSingleMethod(M1.class); - - assertEquals(0, mi.getArgumentsCount()); - - assertEquals(CLASS_SIGNATURE + "$M1", mi.getClassname()); - assertEquals("macka#()V", mi.getCleanSignature()); - assertEquals("()void", mi.getDeclaration()); - assertEquals(CLASS_SIGNATURE + "$M1", mi.getDeclaredClassName()); - assertEquals("()V", mi.getDescription()); - assertNull(mi.getExceptions()); - assertEquals("macka", mi.getMethodName()); - - assertEquals('V', mi.getReturnType().getOpcode()); - assertEquals("void", mi.getReturnType().getType()); - assertEquals("V", mi.getReturnType().getName()); - assertEquals("V", mi.getReturnType().getRawName()); - } - - - // ---------------------------------------------------------------- 2 - - public static class M2 { - public int macka(final long in1, final double in2) {return 0;} - } - - @Test - void testMethodSignature2() throws IOException { - final MethodInfo mi = getMethodSignatureForSingleMethod(M2.class); - - assertEquals(2, mi.getArgumentsCount()); - - assertEquals("long", mi.getArgument(1).getType()); - assertEquals("J", mi.getArgument(1).getName()); - assertEquals("J", mi.getArgument(1).getRawName()); - assertEquals('J', mi.getArgument(1).getOpcode()); - - assertEquals("double", mi.getArgument(2).getType()); - assertEquals("D", mi.getArgument(2).getName()); - assertEquals("D", mi.getArgument(2).getRawName()); - assertEquals('D', mi.getArgument(2).getOpcode()); - - assertEquals(CLASS_SIGNATURE + "$M2", mi.getClassname()); - assertEquals("macka#(JD)I", mi.getCleanSignature()); - assertEquals("(long, double)int", mi.getDeclaration()); - assertEquals(CLASS_SIGNATURE + "$M2", mi.getDeclaredClassName()); - assertEquals("(JD)I", mi.getDescription()); - assertNull(mi.getExceptions()); - assertEquals("macka", mi.getMethodName()); - - assertEquals('I', mi.getReturnType().getOpcode()); - assertEquals("int", mi.getReturnType().getType()); - assertEquals("I", mi.getReturnType().getName()); - assertEquals("I", mi.getReturnType().getRawName()); - } - - // ---------------------------------------------------------------- 3 - - public static class M3 { - public Integer macka(final Long in1, final Double in2) {return 0;} - } - - @Test - void testMethodSignature3() throws IOException { - final MethodInfo msv = getMethodSignatureForSingleMethod(M3.class); - - assertEquals(2, msv.getArgumentsCount()); - - assertEquals("java.lang.Long", msv.getArgument(1).getType()); - assertEquals("L" + SIGNATURE_JAVA_LANG_LONG + ";", msv.getArgument(1).getName()); - assertEquals("L" + SIGNATURE_JAVA_LANG_LONG + ";", msv.getArgument(1).getRawName()); - assertEquals('L', msv.getArgument(1).getOpcode()); - - assertEquals("java.lang.Double", msv.getArgument(2).getType()); - assertEquals("L" + SIGNATURE_JAVA_LANG_DOUBLE + ";", msv.getArgument(2).getName()); - assertEquals("L" + SIGNATURE_JAVA_LANG_DOUBLE + ";", msv.getArgument(2).getRawName()); - assertEquals('L', msv.getArgument(2).getOpcode()); - - assertEquals(CLASS_SIGNATURE + "$M3", msv.getClassname()); - assertEquals("macka#(L" + SIGNATURE_JAVA_LANG_LONG + ";L" + SIGNATURE_JAVA_LANG_DOUBLE + ";)L" + SIGNATURE_JAVA_LANG_INTEGER + ";", msv.getCleanSignature()); - assertEquals("(java.lang.Long, java.lang.Double)java.lang.Integer", msv.getDeclaration()); - assertEquals(CLASS_SIGNATURE + "$M3", msv.getDeclaredClassName()); - assertEquals("(Ljava/lang/Long;Ljava/lang/Double;)Ljava/lang/Integer;", msv.getDescription()); - assertNull(msv.getExceptions()); - assertEquals("macka", msv.getMethodName()); - - assertEquals('L', msv.getReturnType().getOpcode()); - assertEquals("java.lang.Integer", msv.getReturnType().getType()); - assertEquals("Ljava/lang/Integer;", msv.getReturnType().getName()); - assertEquals("Ljava/lang/Integer;", msv.getReturnType().getRawName()); - } - - // ---------------------------------------------------------------- 4 - - public static class M4 { - public M4[] macka(final Long[] in1, final double[] in2) {return null;} - } - - @Test - void testMethodSignature4() throws IOException { - final MethodInfo msv = getMethodSignatureForSingleMethod(M4.class); - - assertEquals(2, msv.getArgumentsCount()); - - assertEquals("java.lang.Long[]", msv.getArgument(1).getType()); - assertEquals("[L" + SIGNATURE_JAVA_LANG_LONG + ";", msv.getArgument(1).getName()); - assertEquals("[L" + SIGNATURE_JAVA_LANG_LONG + ";", msv.getArgument(1).getRawName()); - assertEquals('[', msv.getArgument(1).getOpcode()); - - assertEquals("double[]", msv.getArgument(2).getType()); - assertEquals("[D", msv.getArgument(2).getName()); - assertEquals("[D", msv.getArgument(2).getRawName()); - assertEquals('[', msv.getArgument(2).getOpcode()); - - assertEquals(CLASS_SIGNATURE + "$M4", msv.getClassname()); - assertEquals("macka#([L" + SIGNATURE_JAVA_LANG_LONG + ";[D)[" + L_CLASS_SIGNATURE + "$M4;", msv.getCleanSignature()); - assertEquals("(java.lang.Long[], double[])jodd.proxetta.MethodSignatureVisitorTest$M4[]", msv.getDeclaration()); - assertEquals(CLASS_SIGNATURE + "$M4", msv.getDeclaredClassName()); - assertEquals("([Ljava/lang/Long;[D)[Ljodd/proxetta/MethodSignatureVisitorTest$M4;", msv.getDescription()); - assertNull(msv.getExceptions()); - assertEquals("macka", msv.getMethodName()); - - assertEquals('[', msv.getReturnType().getOpcode()); - assertEquals("jodd.proxetta.MethodSignatureVisitorTest$M4[]", msv.getReturnType().getType()); - assertEquals("[Ljodd/proxetta/MethodSignatureVisitorTest$M4;", msv.getReturnType().getName()); - assertEquals("[Ljodd/proxetta/MethodSignatureVisitorTest$M4;", msv.getReturnType().getRawName()); - } - - // ---------------------------------------------------------------- 5 - - public static class M5 { - public List macka(final Set in1, final T[] in2) {return null;} - } - - @Test - void testMethodSignature5() throws IOException { - final MethodInfo msv = getMethodSignatureForSingleMethod(M5.class); - - assertEquals(2, msv.getArgumentsCount()); - assertEquals("java.util.Set", msv.getArgument(1).getType()); - assertEquals("Ljava/util/Set;", msv.getArgument(1).getName()); - assertEquals("Ljava/util/Set;", msv.getArgument(1).getRawName()); - assertEquals('L', msv.getArgument(1).getOpcode()); - - assertEquals("T[]", msv.getArgument(2).getType()); - assertEquals("[T", msv.getArgument(2).getName()); - assertEquals("[Ljava/lang/Object;", msv.getArgument(2).getRawName()); - assertEquals('[', msv.getArgument(2).getOpcode()); - - assertEquals(CLASS_SIGNATURE + "$M5", msv.getClassname()); - assertEquals("macka#(Ljava/util/Set;[Ljava/lang/Object;)Ljava/util/List;", msv.getCleanSignature()); - assertEquals("(java.util.Set, T[])java.util.List", msv.getDeclaration()); - assertEquals(CLASS_SIGNATURE + "$M5", msv.getDeclaredClassName()); - assertEquals("(Ljava/util/Set;[Ljava/lang/Object;)Ljava/util/List;", msv.getDescription()); - assertNull(msv.getExceptions()); - assertEquals("macka", msv.getMethodName()); - - assertEquals('L', msv.getReturnType().getOpcode()); - assertEquals("java.util.List", msv.getReturnType().getType()); - assertEquals("Ljava/util/List;", msv.getReturnType().getName()); - assertEquals("Ljava/util/List;", msv.getReturnType().getRawName()); - } - - // ---------------------------------------------------------------- 6 - - public static class M6 { - public Gen[] macka(final Set in1, final Tuta[] in2) {return null;} - } - - @Test - void testMethodSignature6() throws IOException { - final MethodInfo msv = getMethodSignatureForSingleMethod(M6.class); - - assertEquals(2, msv.getArgumentsCount()); - - assertEquals("java.util.Set", msv.getArgument(1).getType()); - assertEquals("Ljava/util/Set;", msv.getArgument(1).getName()); - assertEquals("Ljava/util/Set;", msv.getArgument(1).getRawName()); - assertEquals('L', msv.getArgument(1).getOpcode()); - - assertEquals("Tuta[]", msv.getArgument(2).getType()); - assertEquals("[Tuta", msv.getArgument(2).getName()); - assertEquals("[Ljava/lang/Object;", msv.getArgument(2).getRawName()); - assertEquals('[', msv.getArgument(2).getOpcode()); - - assertEquals(CLASS_SIGNATURE + "$M6", msv.getClassname()); - assertEquals("macka#(Ljava/util/Set;[Ljava/lang/Object;)[Ljava/lang/Object;", msv.getCleanSignature()); - assertEquals("(java.util.Set, Tuta[])Gen[]", msv.getDeclaration()); - assertEquals(CLASS_SIGNATURE + "$M6", msv.getDeclaredClassName()); - assertEquals("(Ljava/util/Set;[Ljava/lang/Object;)[Ljava/lang/Object;", msv.getDescription()); - assertNull(msv.getExceptions()); - assertEquals("macka", msv.getMethodName()); - - assertEquals('[', msv.getReturnType().getOpcode()); - assertEquals("Gen[]", msv.getReturnType().getType()); - assertEquals("[Gen", msv.getReturnType().getName()); - assertEquals("[Ljava/lang/Object;", msv.getReturnType().getRawName()); - } - - // ---------------------------------------------------------------- 7 - - public static class M7 { - public T[] macka(final Set in1, final T[] in2) {return null;} - } - - @Test - void testMethodSignature7() throws IOException { - final MethodInfo msv = getMethodSignatureForSingleMethod(M7.class); - - assertEquals(2, msv.getArgumentsCount()); - - assertEquals("java.util.Set", msv.getArgument(1).getType()); - assertEquals("Ljava/util/Set;", msv.getArgument(1).getName()); - assertEquals("Ljava/util/Set;", msv.getArgument(1).getRawName()); - assertEquals('L', msv.getArgument(1).getOpcode()); - - assertEquals("T[]", msv.getArgument(2).getType()); - assertEquals("[T", msv.getArgument(2).getName()); - assertEquals("[Ljava/lang/Object;", msv.getArgument(2).getRawName()); - assertEquals('[', msv.getArgument(2).getOpcode()); - - assertEquals(CLASS_SIGNATURE + "$M7", msv.getClassname()); - assertEquals("macka#(Ljava/util/Set;[Ljava/lang/Object;)[Ljava/lang/Object;", msv.getCleanSignature()); - assertEquals("(java.util.Set, T[])T[]", msv.getDeclaration()); - assertEquals(CLASS_SIGNATURE + "$M7", msv.getDeclaredClassName()); - assertEquals("(Ljava/util/Set;[Ljava/lang/Object;)[Ljava/lang/Object;", msv.getDescription()); - assertNull(msv.getExceptions()); - assertEquals("macka", msv.getMethodName()); - - assertEquals('[', msv.getReturnType().getOpcode()); - assertEquals("T[]", msv.getReturnType().getType()); - assertEquals("[T", msv.getReturnType().getName()); - assertEquals("[Ljava/lang/Object;", msv.getReturnType().getRawName()); - } - - // ---------------------------------------------------------------- 8 - - public static class M8 { - public void macka() throws IOException, NullPointerException {} - } - - @Test - void testMethodSignature8() throws IOException { - final MethodInfo msv = getMethodSignatureForSingleMethod(M8.class); - - assertEquals(0, msv.getArgumentsCount()); - - assertEquals(CLASS_SIGNATURE + "$M8", msv.getClassname()); - assertEquals("macka#()V", msv.getCleanSignature()); - assertEquals("()void", msv.getDeclaration()); - assertEquals(CLASS_SIGNATURE + "$M8", msv.getDeclaredClassName()); - assertEquals("()V", msv.getDescription()); - assertEquals("java/io/IOException,java/lang/NullPointerException", msv.getExceptionsAsString()); - assertEquals("macka", msv.getMethodName()); - } - - // ---------------------------------------------------------------- 9 - - public static class M9 { - public static void main(final String[] args) { - } - } - - @Test - void testMethodSignature9() throws IOException { - final MethodInfo msv = getMethodSignatureForSingleMethod(M9.class); - - assertEquals(1, msv.getArgumentsCount()); - - assertEquals("java.lang.String[]", msv.getArgument(1).getType()); - assertEquals("[Ljava/lang/String;", msv.getArgument(1).getName()); - assertEquals("[Ljava/lang/String;", msv.getArgument(1).getRawName()); - assertEquals('[', msv.getArgument(1).getOpcode()); - - - assertEquals(CLASS_SIGNATURE + "$M9", msv.getClassname()); - assertEquals("main#([Ljava/lang/String;)V", msv.getCleanSignature()); - assertEquals("(java.lang.String[])void", msv.getDeclaration()); - assertEquals(CLASS_SIGNATURE + "$M9", msv.getDeclaredClassName()); - assertEquals("([Ljava/lang/String;)V", msv.getDescription()); - assertEquals("main", msv.getMethodName()); - } - - // ---------------------------------------------------------------- 10 - - public static class M10 { - @FooAnn - public void macka(final int a, @FooAnn final long b) {} - } - - @Test - void testMethodSignature10() throws IOException { - final MethodInfo msv = getMethodSignatureForSingleMethod(M10.class); - - assertEquals(2, msv.getArgumentsCount()); - - assertEquals(0, msv.getArgument(1).getAnnotations().length); - assertEquals(1, msv.getArgument(2).getAnnotations().length); - assertEquals("jodd.proxetta.fixtures.data.FooAnn", msv.getArgument(2).getAnnotations()[0].getAnnotationClassname()); - - assertEquals("macka", msv.getMethodName()); - assertEquals(1, msv.getAnnotations().length); - assertEquals("jodd.proxetta.fixtures.data.FooAnn", msv.getAnnotations()[0].getAnnotationClassname()); - } - - // ---------------------------------------------------------------- 11 - - public static class M11 { - public List> macka(final Set>> in1) {return null;} - } - - @Test - void testMethodSignature11() throws IOException { - final MethodInfo msv = getMethodSignatureForSingleMethod(M11.class); - - assertEquals(1, msv.getArgumentsCount()); - assertEquals("java.util.Set>>", msv.getArgument(1).getType()); - assertEquals("Ljava/util/Set;", msv.getArgument(1).getName()); - assertEquals("Ljava/util/Set;", msv.getArgument(1).getRawName()); - assertEquals('L', msv.getArgument(1).getOpcode()); - - assertEquals(CLASS_SIGNATURE + "$M11", msv.getClassname()); - assertEquals("macka#(Ljava/util/Set;)Ljava/util/List;", msv.getCleanSignature()); - assertEquals("(java.util.Set>>)java.util.List>", msv.getDeclaration()); - assertEquals(CLASS_SIGNATURE + "$M11", msv.getDeclaredClassName()); - assertEquals("(Ljava/util/Set;)Ljava/util/List;", msv.getDescription()); - assertNull(msv.getExceptions()); - assertEquals("macka", msv.getMethodName()); - - assertEquals('L', msv.getReturnType().getOpcode()); - assertEquals("java.util.List>", msv.getReturnType().getType()); - assertEquals("Ljava/util/List;", msv.getReturnType().getName()); - assertEquals("Ljava/util/List;", msv.getReturnType().getRawName()); - } - - // ---------------------------------------------------------------- 12 - - public static class Tupel { - A a; B b; - } - - public static class M12 { - public Map, Long>, Byte> macka(final Tupel, Integer> in1) {return null;} - } - - @Test - void testMethodSignature12() throws IOException { - final MethodInfo msv = getMethodSignatureForSingleMethod(M12.class); - - assertEquals(1, msv.getArgumentsCount()); - assertEquals(CLASS_NAME + "$Tupel, java.lang.Integer>", msv.getArgument(1).getType()); - assertEquals(L_CLASS_SIGNATURE + "$Tupel;", msv.getArgument(1).getName()); - assertEquals(L_CLASS_SIGNATURE + "$Tupel;", msv.getArgument(1).getRawName()); - assertEquals('L', msv.getArgument(1).getOpcode()); - - assertEquals(CLASS_SIGNATURE + "$M12", msv.getClassname()); - assertEquals("macka#(" + L_CLASS_SIGNATURE + "$Tupel;)Ljava/util/Map;", msv.getCleanSignature()); - assertEquals("(" + CLASS_NAME + "$Tupel, java.lang.Integer>)java.util.Map, java.lang.Long>, java.lang.Byte>", msv.getDeclaration()); - assertEquals(CLASS_SIGNATURE + "$M12", msv.getDeclaredClassName()); - assertEquals("(" + L_CLASS_SIGNATURE + "$Tupel;)Ljava/util/Map;", msv.getDescription()); - assertNull(msv.getExceptions()); - assertEquals("macka", msv.getMethodName()); - - assertEquals('L', msv.getReturnType().getOpcode()); - assertEquals("java.util.Map, java.lang.Long>, java.lang.Byte>", msv.getReturnType().getType()); - assertEquals("Ljava/util/Map;", msv.getReturnType().getName()); - assertEquals("Ljava/util/Map;", msv.getReturnType().getRawName()); - } - - // ---------------------------------------------------------------- util - - private MethodInfo getMethodSignatureForSingleMethod(final Class klass) throws IOException { - final InputStream in = ClassLoaderUtil.getClassAsStream(klass.getName()); - final ClassReader classReader = new ClassReader(in); - final TargetClassInfoReaderFixture targetClassInfoReader = new TargetClassInfoReaderFixture(this.getClass().getClassLoader()); - classReader.accept(targetClassInfoReader, 0); - in.close(); - - final Map methodSignatures = targetClassInfoReader.getMethodSignatures(); - - return methodSignatures.values() - .stream() - .filter(msv -> { - if (msv.getMethodName().equals("")) { - return false; - } - if (msv.getDeclaredClassName().startsWith(CLASS_SIGNATURE)) { - return true; - } - return false; - }) - .findFirst().get(); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/ProxyInfoTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/ProxyInfoTest.java deleted file mode 100644 index 84466462e..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/ProxyInfoTest.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.proxetta.fixtures.data.DateDao; -import jodd.proxetta.fixtures.data.PerformanceMeasureProxyAdvice; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.pointcuts.AllTopMethodsPointcut; -import org.junit.jupiter.api.Test; - -import java.time.LocalDateTime; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - -class ProxyInfoTest { - - @Test - void testProxyInfo_createNotRightAfterTheMethod() { - ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspects(aspects()); - //proxetta.setDebugFolder(SystemUtil.userHome()); - - DateDao dateDateProxy = (DateDao) proxetta.proxy().setTarget(DateDao.class).newInstance(); - - LocalDateTime localDateTime = dateDateProxy.currentTime(); - - assertNotNull(localDateTime); - } - - private ProxyAspect[] aspects() { - ProxyAspect aspect_performance = new ProxyAspect( - PerformanceMeasureProxyAdvice.class, new AllTopMethodsPointcut()); - - return new ProxyAspect[] {aspect_performance}; - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/ReturnTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/ReturnTest.java deleted file mode 100644 index 0632c87be..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/ReturnTest.java +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.proxetta.fixtures.data.ReflectionReplacementAdvice; -import jodd.proxetta.fixtures.data.Retro; -import jodd.proxetta.fixtures.data.ReturnNullAdvice; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.impl.ProxyProxettaFactory; -import jodd.proxetta.pointcuts.AllMethodsPointcut; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Field; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - - -class ReturnTest { - - @Test - void testWrapperWithProxyReturns() throws Exception { - ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspects( - new ProxyAspect(ReflectionReplacementAdvice.class, new AllMethodsPointcut())); - - ProxyProxettaFactory builder = proxetta.proxy().setTarget(Retro.class).setTargetProxyClassName(".Retro2"); - -// proxetta.setDebugFolder("d:\\"); - - Class proxyClass = builder.define(); - - Object proxy = proxyClass.newInstance(); - - Field field = proxyClass.getField("$__target$0"); - - Retro retro = new Retro(); - - retro.flag = true; - - field.set(proxy, retro); - - retro = (Retro) proxy; - - assertNotNull(retro); - - assertEquals("retro", retro.method1()); - assertEquals(2, retro.method2()); - assertEquals(3, retro.method3()); - assertEquals(4, retro.method4()); - assertEquals(5, retro.method5()); - assertEquals(true, retro.method6()); - assertEquals(7.7, retro.method7(), 0.005); - assertEquals(8.8, retro.method8(), 0.005); - assertEquals(9, retro.method9().length); - assertEquals('r', retro.method11()); - - retro.method10(); - } - - @Test - void testNullReturns() throws Exception { - ProxyProxetta proxetta = Proxetta.proxyProxetta().withAspects( - new ProxyAspect(ReturnNullAdvice.class, new AllMethodsPointcut())); - - ProxyProxettaFactory builder = proxetta.proxy().setTarget(Retro.class).setTargetProxyClassName(".Retro3"); - -// proxetta.setDebugFolder("d:\\"); - - Class proxyClass = builder.define(); - - Object proxy = proxyClass.newInstance(); - - Retro retro = (Retro) proxy; - - assertNotNull(retro); - - assertNull(retro.method1()); - assertEquals(0, retro.method2()); - assertEquals(0, retro.method3()); - assertEquals(0, retro.method4()); - assertEquals(0, retro.method5()); - assertEquals(false, retro.method6()); - assertEquals(0, retro.method7(), 0.005); - assertEquals(0, retro.method8(), 0.005); - assertNull(retro.method9()); - assertEquals(0, retro.method11()); - - retro.method10(); - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/SubclassTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/SubclassTest.java deleted file mode 100644 index b80c55ddb..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/SubclassTest.java +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.proxetta.fixtures.data.Foo; -import jodd.proxetta.fixtures.data.FooProxyAdvice; -import jodd.proxetta.fixtures.data.StatCounter; -import jodd.proxetta.fixtures.data.StatCounterAdvice; -import jodd.proxetta.fixtures.data.Two; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.impl.ProxyProxettaFactory; -import jodd.proxetta.pointcuts.AllMethodsPointcut; -import jodd.util.StringUtil; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -class SubclassTest { - - @Test - void test1() { - - ProxyAspect a1 = new ProxyAspect(FooProxyAdvice.class, methodInfo -> true); - -/* - byte[] b = Proxetta.withAspects(a1).createProxy(Foo.class); - try { - FileUtil.writeBytes("d:\\Foo.class", b); - } catch (IOException e) { - e.printStackTrace(); - } -*/ - ProxyProxetta proxyProxetta = Proxetta.proxyProxetta().withAspect(a1); - proxyProxetta.setClassNameSuffix("$$$Proxetta"); - ProxyProxettaFactory pb = proxyProxetta.proxy(); - pb.setTarget(Foo.class); - Foo foo = (Foo) pb.newInstance(); - - Class fooProxyClass = foo.getClass(); - assertNotNull(fooProxyClass); - - Method[] methods = fooProxyClass.getMethods(); - assertEquals(12, methods.length); - try { - fooProxyClass.getMethod("m1"); - } catch (NoSuchMethodException nsmex) { - fail(nsmex.toString()); - } - - - methods = fooProxyClass.getDeclaredMethods(); - assertEquals(15, methods.length); - try { - fooProxyClass.getDeclaredMethod("m2"); - } catch (NoSuchMethodException nsmex) { - fail(nsmex.toString()); - } - - } - - @Test - void testProxyClassNames() { - ProxyProxetta proxyProxetta = Proxetta.proxyProxetta().withAspect(ProxyAspect.of(FooProxyAdvice.class, new AllMethodsPointcut())); - proxyProxetta.setVariableClassName(true); - - ProxyProxettaFactory builder = proxyProxetta.proxy(); - builder.setTarget(Foo.class); - Foo foo = (Foo) builder.newInstance(); - - assertNotNull(foo); - assertEquals(Foo.class.getName() + ProxettaNames.proxyClassNameSuffix, StringUtil.substring(foo.getClass().getName(), 0, -1)); - - builder = proxyProxetta.proxy(); - builder.setTarget(Foo.class); - foo = (Foo) builder.newInstance(); - - assertNotNull(foo); - assertEquals(Foo.class.getName() + ProxettaNames.proxyClassNameSuffix, StringUtil.substring(foo.getClass().getName(), 0, -1)); - - proxyProxetta.setClassNameSuffix("$$Ppp"); - builder = proxyProxetta.proxy(); - builder.setTarget(Foo.class); - foo = (Foo) builder.newInstance(); - - assertNotNull(foo); - assertEquals(Foo.class.getName() + "$$Ppp", StringUtil.substring(foo.getClass().getName(), 0, -1)); - - proxyProxetta.setClassNameSuffix(ProxettaNames.proxyClassNameSuffix); - proxyProxetta.setVariableClassName(false); - builder = proxyProxetta.proxy().setTarget(Foo.class).setTargetProxyClassName(".Too"); - - foo = (Foo) builder.newInstance(); - - assertNotNull(foo); - assertEquals(Foo.class.getPackage().getName() + ".Too" + ProxettaNames.proxyClassNameSuffix, foo.getClass().getName()); - - builder = proxyProxetta.proxy(); - builder.setTarget(Foo.class); - builder.setTargetProxyClassName("foo."); - foo = (Foo) builder.newInstance(); - - assertNotNull(foo); - assertEquals("foo.Foo" + ProxettaNames.proxyClassNameSuffix, foo.getClass().getName()); - - proxyProxetta.setClassNameSuffix(null); - builder = proxyProxetta.proxy(); - builder.setTargetProxyClassName("foo.Fff"); - builder.setTarget(Foo.class); - foo = (Foo) builder.newInstance(); - - assertNotNull(foo); - assertEquals("foo.Fff", foo.getClass().getName()); - - } - - @Test - void testInnerOverride() { - ProxyProxetta proxyProxetta = Proxetta.proxyProxetta().withAspect(new ProxyAspect(FooProxyAdvice.class, new AllMethodsPointcut())); - ProxyProxettaFactory builder = proxyProxetta.proxy(); - builder.setTarget(Two.class); - builder.setTargetProxyClassName("foo."); - - Two two = (Two) builder.newInstance(); - - assertNotNull(two); - assertEquals("foo.Two" + ProxettaNames.proxyClassNameSuffix, two.getClass().getName()); - } - - @SuppressWarnings({"CachedNumberConstructorCall", "UnnecessaryBoxing"}) - @Test - void testJdk() { - ProxyProxetta proxyProxetta = Proxetta.proxyProxetta().withAspect(new ProxyAspect(StatCounterAdvice.class, new AllMethodsPointcut())); - proxyProxetta.setVariableClassName(false); - - ProxyProxettaFactory builder = proxyProxetta.proxy(); - builder.setTarget(Object.class); - try { - builder.define(); - fail("Default class loader should not load java.*"); - } catch (RuntimeException rex) { - // ignore - } - - builder = proxyProxetta.proxy(); - builder.setTarget(Object.class); - builder.setTargetProxyClassName("foo."); - Object object = builder.newInstance(); - - assertNotNull(object); - assertEquals("foo.Object" + ProxettaNames.proxyClassNameSuffix, object.getClass().getName()); - - //System.out.println("----------list"); - - StatCounter.counter = 0; - - builder = proxyProxetta.proxy().setTarget(ArrayList.class).setTargetProxyClassName("foo."); - List list = (List) builder.newInstance(); - assertNotNull(list); - assertEquals("foo.ArrayList" + ProxettaNames.proxyClassNameSuffix, list.getClass().getName()); - - assertEquals(1, StatCounter.counter); - list.add(new Integer(1)); - assertTrue(StatCounter.counter == 3 || StatCounter.counter == 2); - - System.out.println("----------set"); - - builder = proxyProxetta.proxy().setTarget(HashSet.class).setTargetProxyClassName("foo."); - Set set = (Set) builder.newInstance(); - - assertNotNull(set); - assertEquals("foo.HashSet" + ProxettaNames.proxyClassNameSuffix, set.getClass().getName()); - - assertTrue(StatCounter.counter == 4 || StatCounter.counter == 3); - set.add(new Integer(1)); - assertTrue(StatCounter.counter == 5 || StatCounter.counter == 4); - - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/WrapperTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/WrapperTest.java deleted file mode 100644 index 89b4d831b..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/WrapperTest.java +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta; - -import jodd.proxetta.fixtures.data.Calc; -import jodd.proxetta.fixtures.data.CalcImpl; -import jodd.proxetta.fixtures.data.CalcSuper; -import jodd.proxetta.fixtures.data.CalcSuperImpl; -import jodd.proxetta.fixtures.data.StatCounter; -import jodd.proxetta.fixtures.data.StatCounterAdvice; -import jodd.proxetta.impl.WrapperProxetta; -import jodd.proxetta.impl.WrapperProxettaFactory; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Method; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -class WrapperTest { - - @BeforeEach - void setUp() throws Exception { - StatCounter.counter = 0; - } - - @Test - void testClassWrapper() throws Exception { - Calc calc = new CalcImpl(); - - WrapperProxetta proxetta = Proxetta.wrapperProxetta().withAspects(new ProxyAspect(StatCounterAdvice.class, methodInfo -> !methodInfo.isRootMethod() && methodInfo.isPublicMethod())); - -// proxetta.setDebugFolder("d:\\"); - - // wrapper over CLASS - // resulting object has ALL interfaces - // resulting object wraps ALL target class methods - WrapperProxettaFactory builder = proxetta.proxy().setTarget(calc.getClass()); - - Class calc2Class = builder.define(); - - Object object = calc2Class.newInstance(); - - assertTrue(object instanceof Calc); - assertEquals(CalcImpl.class, ProxettaUtil.resolveTargetClass(object.getClass())); - assertEquals(1, calc2Class.getInterfaces().length); - - builder.injectTargetIntoWrapper(calc, object); - - assertEquals(1, StatCounter.counter); // counter in static block !!! - - Method method = calc2Class.getMethod("hello"); - assertNotNull(method); - method.invoke(object); - - assertEquals(2, StatCounter.counter); - - method = calc2Class.getMethod("calculate", int.class, int.class); - assertNotNull(method); - Integer result = (Integer) method.invoke(object, 3, 7); - assertEquals(10, result.intValue()); - - assertEquals(3, StatCounter.counter); - - assertNotNull(calc2Class.getMethod("customMethod")); - } - - @Test - void testClassWrapperCastToInterface() throws Exception { - Calc calc = new CalcImpl(); - - WrapperProxetta proxetta = Proxetta.wrapperProxetta().withAspect(new ProxyAspect(StatCounterAdvice.class, methodInfo -> !methodInfo.isRootMethod() && methodInfo.isPublicMethod())); - - //proxetta.setDebugFolder("/Users/igor"); - - // wrapper over CLASS casted to interface, - // resulting object has ONE interface - // ALL target methods are wrapped - WrapperProxettaFactory builder = proxetta.proxy().setTarget(calc.getClass()).setTargetInterface(Calc.class).setTargetProxyClassName(".CalcImpl2"); - - Class calc2Class = builder.define(); - - Calc calc2 = calc2Class.newInstance(); - - builder.injectTargetIntoWrapper(calc, calc2); - - assertEquals(1, StatCounter.counter); // counter in static block !!! - - calc2.hello(); - - assertEquals(2, StatCounter.counter); - - assertEquals(10, calc2.calculate(3, 7)); - - assertEquals(3, StatCounter.counter); - - assertNotNull(calc2Class.getMethod("customMethod")); - } - - @Test - void testInterfaceWrapper() throws Exception { - Calc calc = new CalcImpl(); - - WrapperProxetta proxetta = Proxetta.wrapperProxetta().withAspect(new ProxyAspect(StatCounterAdvice.class, methodInfo -> methodInfo.isTopLevelMethod() && methodInfo.isPublicMethod())); - - //proxetta.setDebugFolder("/Users/igor"); - - // wrapper over INTERFACE - // resulting object has ONE interface - // only interface methods are wrapped - WrapperProxettaFactory builder = proxetta.proxy().setTarget(Calc.class).setTargetProxyClassName(".CalcImpl3"); - - Class calc2Class = builder.define(); - - Calc calc2 = calc2Class.newInstance(); - - builder.injectTargetIntoWrapper(calc, calc2); - - assertEquals(1, StatCounter.counter); // counter in static block !!! - - calc2.hello(); - - assertEquals(2, StatCounter.counter); - - assertEquals(10, calc2.calculate(3, 7)); - - assertEquals(3, StatCounter.counter); - - try { - calc2Class.getMethod("customMethod"); - fail("error"); - } catch (Exception ex) { - } - } - - - @Test - void testPartialMethodsWrapped() throws Exception { - - Calc calc = new CalcSuperImpl(); - - WrapperProxetta proxetta = Proxetta.wrapperProxetta().withAspect(new ProxyAspect(StatCounterAdvice.class, methodInfo -> methodInfo.isPublicMethod() && - (methodInfo.getMethodName().equals("hello") || methodInfo.getMethodName().equals("ola")))); - -// proxetta.setDebugFolder("d:\\"); - - WrapperProxettaFactory builder = proxetta.proxy().setTarget(CalcSuper.class); - - Class calc2Class = builder.define(); - - CalcSuper calc2 = calc2Class.newInstance(); - - builder.injectTargetIntoWrapper(calc, calc2); - - assertEquals(1, StatCounter.counter); // counter in static block !!! - - calc2.hello(); - - assertEquals(2, StatCounter.counter); - - assertEquals(10, calc2.calculate(3, 7)); - - assertEquals(2, StatCounter.counter); // counter not called in calculate! - - calc2.ola(); - - assertEquals(3, StatCounter.counter); - - calc2.superhi(); - calc2.maybe(4, 5); - calc2.calculate(4, 5); - - assertEquals(3, StatCounter.counter); - } - - @Test - void testNoPointcutMatched() throws Exception { - - Calc calc = new CalcSuperImpl(); - - WrapperProxetta proxetta = Proxetta.wrapperProxetta().withAspect(new ProxyAspect(StatCounterAdvice.class, methodInfo -> false)); - -// proxetta.setDebugFolder("d:\\"); - - WrapperProxettaFactory builder = proxetta.proxy().setTarget(CalcSuper.class).setTargetProxyClassName(".CalcSuper22"); - - Class calc2Class = builder.define(); - - CalcSuper calc2 = calc2Class.newInstance(); - - builder.injectTargetIntoWrapper(calc, calc2); - - assertEquals(1, StatCounter.counter); // counter in static block !!! - - calc2.hello(); - - assertEquals(1, StatCounter.counter); - - assertEquals(10, calc2.calculate(3, 7)); - - assertEquals(1, StatCounter.counter); // counter not called in calculate! - - calc2.ola(); - - assertEquals(1, StatCounter.counter); - - calc2.superhi(); - calc2.maybe(4, 5); - calc2.calculate(4, 5); - - assertEquals(1, StatCounter.counter); - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/advice/DelegateAdviceTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/advice/DelegateAdviceTest.java deleted file mode 100644 index 3254f5109..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/advice/DelegateAdviceTest.java +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.advice; - -import jodd.proxetta.fixtures.data.Calc; -import jodd.proxetta.fixtures.data.CalcImpl; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.fail; - -class DelegateAdviceTest { - - @Test - void testCalcImplDelegate() { - CalcImpl calc = new CalcImpl(); - - Calc newCalc = DelegateAdviceUtil.applyAdvice(CalcImpl.class); - DelegateAdviceUtil.injectTargetIntoProxy(newCalc, calc); - - assertNotEquals(newCalc.getClass(), calc.getClass()); - - assertEquals(calc.calculate(2, 8), newCalc.calculate(2, 8)); - assertEquals(calc.calculate(2L, 8L), newCalc.calculate(2L, 8L)); - assertEquals(calc.calculate(2.5d, 8.5d), newCalc.calculate(2.5d, 8.5d), 0.1); - assertEquals(calc.calculate(2.5f, 8.5f), newCalc.calculate(2.5f, 8.5f), 0.1); - assertEquals(calc.calculate((byte)2, (byte)8), newCalc.calculate((byte)2, (byte)8)); - assertEquals(calc.calculate((short)2, (short)8), newCalc.calculate((short)2, (short)8)); - - try { - newCalc.hello(); - } catch (Exception ex) { - ex.printStackTrace(); - fail(ex.toString()); - } - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/TargetClassInfoReaderFixture.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/TargetClassInfoReaderFixture.java deleted file mode 100644 index 6cdcba888..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/TargetClassInfoReaderFixture.java +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures; - -import jodd.proxetta.asm.MethodSignatureVisitor; -import jodd.proxetta.asm.TargetClassInfoReader; - -import java.util.Map; - -public class TargetClassInfoReaderFixture extends TargetClassInfoReader { - public TargetClassInfoReaderFixture(ClassLoader classLoader) { - super(classLoader); - } - - public Map getMethodSignatures() { - return methodSignatures; - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Abstra.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Abstra.java deleted file mode 100644 index 400e58c4f..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Abstra.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public abstract class Abstra { - - public void foo() { - - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Abstra2.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Abstra2.java deleted file mode 100644 index 67634035f..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Abstra2.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public abstract class Abstra2 { - - public abstract void aaa(); -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Action.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Action.java deleted file mode 100644 index f22019376..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Action.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import jodd.util.StringPool; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -public @interface Action { - - String NONE = StringPool.HASH; - - String value() default ""; - - String extension() default ""; - - String alias() default ""; - - String method() default ""; - -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/BigFatJoe.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/BigFatJoe.java deleted file mode 100644 index 4a987bb6a..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/BigFatJoe.java +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import java.util.Map; - -@MadvocAction(value = "madvocAction") -@PetiteBean(value = "petiteBean") -@InterceptedBy({Str.class, Two.class}) -public class BigFatJoe extends SmallSkinnyZoe { - - @PetiteInject - public BigFatJoe() { - System.out.println("BigFatJoe.BigFatJoe"); - } - - static { - System.out.println("BigFatJoe.static intializer"); - } - - static { - StatCounter.counter++; - } - - { - StatCounter.counter++; - } - - @Override - @Action(method = "method", extension = "extension", alias = "alias", value = "value") - @PetiteInject - @Transaction(readOnly = true, propagation = "PROPAGATION_REQUIRES_NEW") - public void publicMethod() { - System.out.println("BigFatJoe.publicMethod"); - super.publicMethod(); - } - - @SuppressWarnings({"UnusedDeclaration"}) - public Map fullDescription(int i1, String s2, Map m3, Class[] arr4) throws RuntimeException { - return null; - } - - public void callInnerMethods() { - System.out.println("BigFatJoe.callInner"); - protectedMethod(); - packageMethod(); - privateMethod(); - } - - public void callInnerMethods2() { - System.out.println("BigFatJoe.callInnerMethods2"); - superProtectedMethod(); - superPackageMethod(); - } - - protected void protectedMethod() { - System.out.println("BigFatJoe.protectedMethod"); - } - - void packageMethod() { - System.out.println("BigFatJoe.packageMethod"); - } - - private void privateMethod() { - System.out.println("BigFatJoe.privateMethod"); - } - - - public void runInnerClass() { - final int counter = StatCounter.counter; - new Runnable() { - public void run() { - StatCounter.counter = counter + 1; - } - }.run(); - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Calc.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Calc.java deleted file mode 100644 index 50b42e59b..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Calc.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public interface Calc { - - void hello(); - - int calculate(int a, int b); - - double calculate(double a, double b); - - long calculate(long a, long b); - - float calculate(float a, float b); - - short calculate(short a, short b); - - byte calculate(byte a, byte b); -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcCrazy.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcCrazy.java deleted file mode 100644 index 1e61db082..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcCrazy.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public interface CalcCrazy { - - void ola(); - - int maybe(int a, int b); -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcImpl.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcImpl.java deleted file mode 100644 index 4416c5305..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcImpl.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public class CalcImpl extends CalcImplBase implements Calc { - - public int calculate(int a, int b) { - return a + b; - } - - public double calculate(double a, double b) { - return a + b; - } - - public long calculate(long a, long b) { - return a + b; - } - - public float calculate(float a, float b) { - return a + b; - } - - public short calculate(short a, short b) { - return (short) (a + b); - } - - public byte calculate(byte a, byte b) { - return (byte) (a + b); - } - - public void customMethod() { - System.out.println("custom"); - } - - public static void main(String[] args) { - System.out.println(args); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcImplBase.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcImplBase.java deleted file mode 100644 index 79dc629e4..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcImplBase.java +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public class CalcImplBase { - - public void hello() { - System.out.println("calculator"); - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcSuper.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcSuper.java deleted file mode 100644 index f0cce88df..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcSuper.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public interface CalcSuper extends Calc, CalcCrazy { - - void superhi(); -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcSuperImpl.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcSuperImpl.java deleted file mode 100644 index 63c72e8fa..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CalcSuperImpl.java +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public class CalcSuperImpl implements CalcSuper { - - public void superhi() { - System.out.println("superhi"); - } - - public void hello() { - System.out.println("hello"); - } - - public int calculate(int a, int b) { - return a + b; - } - - public double calculate(double a, double b) { - return a + b; - } - - public long calculate(long a, long b) { - return a + b; - } - - public float calculate(float a, float b) { - return a + b; - } - - public short calculate(short a, short b) { - return (short) (a + b); - } - - public byte calculate(byte a, byte b) { - return (byte) (a + b); - } - - public void ola() { - System.out.println("ola!"); - } - - public int maybe(int a, int b) { - return a + b - (a - b); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CollectorAdvice.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CollectorAdvice.java deleted file mode 100644 index 74f70549e..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/CollectorAdvice.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -import java.util.ArrayList; -import java.util.List; - -public class CollectorAdvice implements ProxyAdvice { - - protected List methods = new ArrayList<>(); - - public Object execute() throws Exception { - addMethod(ProxyTarget.targetMethodName()); - return ProxyTarget.invoke(); - } - - private void addMethod(String methodName) { - methods.add(methodName); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/DateDao.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/DateDao.java deleted file mode 100644 index 15f08ab4d..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/DateDao.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import jodd.util.MathUtil; -import jodd.util.ThreadUtil; - -import java.time.LocalDateTime; - -public class DateDao { - - public LocalDateTime currentTime() { - ThreadUtil.sleep(MathUtil.randomLong(1, 2)); - return LocalDateTime.now(); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/DateDao2.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/DateDao2.java deleted file mode 100644 index 0b70e6af2..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/DateDao2.java +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import jodd.proxetta.ProxyTargetInfo; -import jodd.util.MathUtil; -import jodd.util.ThreadUtil; - -import java.time.LocalDateTime; - -public class DateDao2 { - - public LocalDateTime currentTime0() { - ThreadUtil.sleep(MathUtil.randomLong(1, 2)); - return LocalDateTime.now(); - } - - - public Object currentTime() { - final long start = System.currentTimeMillis(); - - ProxyTargetInfo proxyTargetInfo = new ProxyTargetInfo(); - proxyTargetInfo.argumentCount = 0; - proxyTargetInfo.argumentsClasses = new Class[0]; - proxyTargetInfo.arguments = new Object[0]; - proxyTargetInfo.returnType = LocalDateTime.class; - proxyTargetInfo.targetMethodName = "currentTime"; - proxyTargetInfo.targetMethodDescription = "()Ljava/time/LocalDateTime;"; - - long end = start; - - try { - return currentTime0(); - } - catch (Exception e) { - throw e; - } - finally { - end = System.currentTimeMillis(); - System.out.println((end-start)); - } - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Foo.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Foo.java deleted file mode 100644 index ee0adb66b..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Foo.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public class Foo { - - public void m1() { - System.out.println("Foo.m1"); - } - - protected void m2() { - System.out.println("Foo.m2"); - } - - protected String a1; - - public String a2; - - public String p1(@FooAnn String in) { - return in; - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/FooAnn.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/FooAnn.java deleted file mode 100644 index e32aa0963..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/FooAnn.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public @interface FooAnn { -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/FooProxyAdvice.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/FooProxyAdvice.java deleted file mode 100644 index 5ce331128..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/FooProxyAdvice.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -public class FooProxyAdvice implements ProxyAdvice { - - static int count; - - public static int getCount() { - return count++; - } - - public Object execute() { - return ProxyTarget.invoke(); - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Hero.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Hero.java deleted file mode 100644 index 5de78c716..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Hero.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -@HeroName( - value = "Silver", - secret = 89, - opacity = 99.222, - helpers = {"None", "None"}, - enemies = {2,1000}) -public class Hero { - - public enum POWER { - STRENGTH, - XRAY, - SPEED { - @Override - public String toString() { - return "speeeeed"; - } - } - } - - @HeroName( - value = "Batman", - secret = 37, - opacity = 88.3, - helpers = {"CatWoman", "Robin"}, - enemies = {1,99}) - public String name() { - return null; - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/HeroName.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/HeroName.java deleted file mode 100644 index e6550b88d..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/HeroName.java +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public @interface HeroName { - - String value(); - - Class power() default Hero.class; - - int secret(); - - char middle() default 'W'; - - double opacity(); - - String[] helpers(); - - int[] enemies(); - - Hero.POWER power2() default Hero.POWER.SPEED; - - Hero.POWER[] subpowers() default {Hero.POWER.XRAY}; -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/HeroProxyAdvice.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/HeroProxyAdvice.java deleted file mode 100644 index 91272ab8e..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/HeroProxyAdvice.java +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -import static jodd.proxetta.ProxyTarget.targetMethodAnnotation; - -public class HeroProxyAdvice implements ProxyAdvice { - - @Override - public Object execute() throws Exception { - String name = ""; - - String heroName = (String) targetMethodAnnotation(HeroName.class.getName(), "value"); - - name += heroName; - - Class heroClass = (Class) targetMethodAnnotation(HeroName.class.getName(), "power"); - - name += heroClass.getSimpleName(); - - Integer secret = (Integer) targetMethodAnnotation(HeroName.class.getName(), "secret"); - - name += secret; - - Character middle = (Character) targetMethodAnnotation(HeroName.class.getName(), "middle"); - - name += middle; - - Double opacity = (Double) targetMethodAnnotation(HeroName.class.getName(), "opacity"); - - name += opacity; - - String[] helpers = (String[]) targetMethodAnnotation(HeroName.class.getName(), "helpers"); - - name += helpers[0]; - - int[] enemies = (int[]) targetMethodAnnotation(HeroName.class.getName(), "enemies"); - - name += enemies[1]; - - Hero.POWER power = (Hero.POWER) targetMethodAnnotation(HeroName.class.getName(), "power2"); - - name += power; - - Hero.POWER[] subpowers = (Hero.POWER[]) targetMethodAnnotation(HeroName.class.getName(), "subpowers"); - - name += subpowers[0]; - - String missing = (String) targetMethodAnnotation(HeroName.class.getName(), "xxxxx"); - - name += missing; - - return ProxyTarget.returnValue(name); - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/HeroProxyAdvice2.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/HeroProxyAdvice2.java deleted file mode 100644 index 06414fd25..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/HeroProxyAdvice2.java +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -import static jodd.proxetta.ProxyTarget.targetClassAnnotation; - -public class HeroProxyAdvice2 implements ProxyAdvice { - - @Override - public Object execute() throws Exception { - String name = ""; - - String heroName = (String) targetClassAnnotation(HeroName.class.getName(), "value"); - - name += heroName; - - Class heroClass = (Class) targetClassAnnotation(HeroName.class.getName(), "power"); - - name += heroClass.getSimpleName(); - - Integer secret = (Integer) targetClassAnnotation(HeroName.class.getName(), "secret"); - - name += secret; - - Character middle = (Character) targetClassAnnotation(HeroName.class.getName(), "middle"); - - name += middle; - - Double opacity = (Double) targetClassAnnotation(HeroName.class.getName(), "opacity"); - - name += opacity; - - String[] helpers = (String[]) targetClassAnnotation(HeroName.class.getName(), "helpers"); - - name += helpers[0]; - - int[] enemies = (int[]) targetClassAnnotation(HeroName.class.getName(), "enemies"); - - name += enemies[1]; - - Hero.POWER power = (Hero.POWER) targetClassAnnotation(HeroName.class.getName(), "power2"); - - name += power; - - Hero.POWER[] subpowers = (Hero.POWER[]) targetClassAnnotation(HeroName.class.getName(), "subpowers"); - - name += subpowers[0]; - - String missing = (String) targetClassAnnotation(HeroName.class.getName(), "xxxxx"); - - name += missing; - - return ProxyTarget.returnValue(name); - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Inter.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Inter.java deleted file mode 100644 index 073d076d9..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Inter.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public interface Inter { -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/InterceptedBy.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/InterceptedBy.java deleted file mode 100644 index 330cb9d09..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/InterceptedBy.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) -public @interface InterceptedBy { - - Class[] value(); -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/InvalidAdvice.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/InvalidAdvice.java deleted file mode 100644 index 2f001c22a..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/InvalidAdvice.java +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -public class InvalidAdvice implements ProxyAdvice { - - public static class Aaa { - } - - public Object execute() throws Exception { - return ProxyTarget.invoke(); - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/MadvocAction.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/MadvocAction.java deleted file mode 100644 index 488adbb33..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/MadvocAction.java +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.PACKAGE}) -public @interface MadvocAction { - - String value() default ""; - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/One.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/One.java deleted file mode 100644 index 34cbb0181..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/One.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public class One { - - // 1:()V_jodd/proxetta/data/Two#foo - public void foo() { - } - - // 1:()Ljava/lang/String;_jodd/proxetta/data/Two#toString - @Override - public String toString() { - return "s"; - } - - public void tata() { - } - - - // 257:()I_jodd/proxetta/data/Two#hashCode - // 1:(Ljava/lang/Object;)Z_jodd/proxetta/data/Two#equals -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/PerformanceMeasureProxyAdvice.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/PerformanceMeasureProxyAdvice.java deleted file mode 100644 index 5023d659c..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/PerformanceMeasureProxyAdvice.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; -import jodd.proxetta.ProxyTargetInfo; - -public class PerformanceMeasureProxyAdvice implements ProxyAdvice { - - public Object execute() throws Exception { - final long start = System.currentTimeMillis(); - ProxyTargetInfo proxyTargetInfo = ProxyTarget.info(); - - System.out.println(proxyTargetInfo.argumentCount); - - long end = start; - - try { - return ProxyTarget.invoke(); - } - catch (Exception e) { - throw e; - } - finally { - end = System.currentTimeMillis(); - ProxyTargetInfo proxyTargetInfo2 = ProxyTarget.info(); - System.out.println((end-start)); - } - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/PetiteBean.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/PetiteBean.java deleted file mode 100644 index 1bf51b710..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/PetiteBean.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -public @interface PetiteBean { - - String value() default ""; - - Class scope() default Object.class; - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/PetiteInject.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/PetiteInject.java deleted file mode 100644 index ee28abfc3..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/PetiteInject.java +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR}) -public @interface PetiteInject { - - String value() default ""; - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/ReflectionReplacementAdvice.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/ReflectionReplacementAdvice.java deleted file mode 100644 index 470585619..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/ReflectionReplacementAdvice.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -import java.lang.reflect.Method; - -public class ReflectionReplacementAdvice implements ProxyAdvice { - - public Object target; - - public Object execute() throws Exception { - String methodName = ProxyTarget.targetMethodName(); - - Class[] methodArgumentTypes = ProxyTarget.createArgumentsClassArray(); - - Object[] methodArguments = ProxyTarget.createArgumentsArray(); - - Method targetMethod = target.getClass().getMethod(methodName, methodArgumentTypes); - - Object result = targetMethod.invoke(target, methodArguments); - - return ProxyTarget.returnValue(result); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Retro.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Retro.java deleted file mode 100644 index 15cba7c00..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Retro.java +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public class Retro { - - public boolean flag; - - public String method1() { - return flag ? "retro" : "RETRO"; - } - - public int method2() { - return flag ? 2 : -2; - } - - public long method3() { - return flag ? 3 : -3; - } - - public short method4() { - return (short) (flag ? 4 : -4); - } - - public byte method5() { - return (byte) (flag ? 5 : -5); - } - - public boolean method6() { - return flag; - } - - public float method7() { - return (float) (flag ? 7.7 : -7.7); - } - - public double method8() { - return (flag ? 8.8 : -8.8); - } - - public int[] method9() { - return (flag ? new int[9] : new int[1]); - } - - public void method10() { - } - - public char method11() { - return flag ? 'r' : 'R'; - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/ReturnNullAdvice.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/ReturnNullAdvice.java deleted file mode 100644 index 38365ebc4..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/ReturnNullAdvice.java +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -public class ReturnNullAdvice implements ProxyAdvice { - - public Object execute() throws Exception { - Object returnValue = null; - - if (returnValue != null) { - returnValue = "1"; - } - return ProxyTarget.returnValue(returnValue); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/SmallSkinnyZoe.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/SmallSkinnyZoe.java deleted file mode 100644 index a6b9e8da4..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/SmallSkinnyZoe.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public class SmallSkinnyZoe { - - public void publicMethod() { - System.out.println("SmallSkinnyZoe.publicMethod"); - } - - @Action - @PetiteInject - @Transaction - public void superPublicMethod() { - System.out.println("SmallSkinnyZoe.superPublicMethod"); - } - - protected void superProtectedMethod() { - System.out.println("SmallSkinnyZoe.superProtectedMethod"); - } - - void superPackageMethod() { - System.out.println("SmallSkinnyZoe.superPackageMethod"); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/StatCounter.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/StatCounter.java deleted file mode 100644 index 89482ae91..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/StatCounter.java +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public class StatCounter { - - public static int counter; - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/StatCounterAdvice.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/StatCounterAdvice.java deleted file mode 100644 index 6b464ec07..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/StatCounterAdvice.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import jodd.proxetta.ProxyTarget; -import jodd.proxetta.ProxyAdvice; - -public class StatCounterAdvice implements ProxyAdvice { - - static { - StatCounter.counter++; - } - - public Object execute() { - StatCounter.counter++; - System.out.println(">>" + ProxyTarget.targetMethodName()); - return ProxyTarget.invoke(); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Str.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Str.java deleted file mode 100644 index 2b2059155..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Str.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import java.util.List; - -public class Str { - - public String foo() { - System.out.println("Str.foo"); - return "123"; - } - public String foo2(List in1, Thread in2) { - System.out.println("Str.foo2"); - return "123"; - } - - public Integer boo() { - System.out.println("Str.boo"); - return Integer.valueOf(123); - } - - public int izoo() { - System.out.println("Str.izoo"); - return 345; - } - public float fzoo() { - System.out.println("Str.fzoo"); - return 345; - } - public double dzoo() { - System.out.println("Str.dzoo"); - return 345; - } - public long lzoo() { - System.out.println("Str.lzoo"); - return 345; - } - public boolean bzoo() { - System.out.println("Str.bzoo"); - return true; - } - public short szoo() { - System.out.println("Str.bzoo"); - return 1; - } - public char czoo() { - System.out.println("Str.czoo"); - return 'a'; - } - public byte yzoo() { - System.out.println("Str.yzoo"); - return 1; - } - - public void voo() { - System.out.println("Str.voo"); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Transaction.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Transaction.java deleted file mode 100644 index 90e6a5835..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Transaction.java +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.annotation.ElementType; - -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -public @interface Transaction { - - String propagation() default "PROPAGATION_SUPPORTS"; - - boolean readOnly() default true; - - int timeout() default 1000; - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Two.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Two.java deleted file mode 100644 index 15298de36..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/data/Two.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.data; - -public class Two extends One { - - // 1:()V_jodd/proxetta/data/Two# - - @Override - public void tata() { - - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Inter.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Inter.java deleted file mode 100644 index 17af60589..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Inter.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.inv; - -public interface Inter { - - void example1(); -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/MySystem.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/MySystem.java deleted file mode 100644 index c187c3f2d..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/MySystem.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.inv; - -public class MySystem { - - public static long currentTimeMillis() { - return 10823; - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/One.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/One.java deleted file mode 100644 index 64269760c..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/One.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.inv; - -import jodd.proxetta.fixtures.data.Action; -import jodd.proxetta.fixtures.data.InterceptedBy; -import jodd.proxetta.fixtures.data.MadvocAction; -import jodd.proxetta.fixtures.data.PetiteBean; - -import java.io.Serializable; - -@MadvocAction(value = "madvocAction") -@PetiteBean(value = "petiteBean") -@InterceptedBy({One.class, Two.class}) -public class One extends SubOne implements Serializable { - - public One() { - a = 12; - Object o = new Object(); - SubOne s = new SubOne(); - System.out.print("one ctor!"); - } - - @Action - public void example1() { - Two two = new Two(); - int i = two.invvirtual("one"); - System.out.print(i); - callSub(); - } - - public void example2() { - int i = Two.invstatic("one"); - System.out.print(i + ++a); - System.out.print(a); - System.out.print("static: " + s); - } - - public void example3() { - Two two = new Two("ctor!"); - two.printState(); - } - - public void example4() { - Three three = new ThreeImpl(); - three.invinterface("four!"); - } - - public void sub() { - System.out.print(">overriden sub"); - } - - private static int s = 4; - private int a; - -} - diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/OneWithSuper.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/OneWithSuper.java deleted file mode 100644 index 5d7941154..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/OneWithSuper.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.inv; - -public class OneWithSuper extends One { - - @Override - public void example1() { - Two two = new Two(); - int i = two.invvirtual("one"); - System.out.print(i); - super.example1(); - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Replacer.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Replacer.java deleted file mode 100644 index 455f2ac33..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Replacer.java +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.inv; - -public class Replacer { - - public static int rInvVirtual(Object target, String what) { - System.out.print("REPLACED VIRTUAL! " + target.getClass().getName() + " * " + what + '!'); - return 173; - } - - public static int rInvStatic(String what, String owner, String methodName, String methodSignature, Class targetClass, Object clone) { - System.out.print("REPLACED STATIC! " + what + " * " + owner + " * " + methodName + " * " + methodSignature + " * " + targetClass.getName() + " * " + clone.getClass().getName() + '!'); - return 137; - } - - public static void rInvInterface(Object implementation, String what) { - System.out.print("REPLACED INTERFACE! " + implementation + " * " + what + '!'); - } - - public static Two rInvNew() { - return new Two(); - } - - public static Two rInvNew(String state) { - return new Two("REPLACED " + state); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/SubOne.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/SubOne.java deleted file mode 100644 index 4c022682a..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/SubOne.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.inv; - -public class SubOne { - - public void sub() { - System.out.print("####from sub"); - } - - public void callSub() { - sub(); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Three.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Three.java deleted file mode 100644 index 49e1b0e5f..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Three.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.inv; - -public interface Three { - - void invinterface(String s); -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/ThreeImpl.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/ThreeImpl.java deleted file mode 100644 index 4826c006a..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/ThreeImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.inv; - -public class ThreeImpl implements Three { - - public void invinterface(String what) { - System.out.println((new StringBuilder()).append("*** ").append(what).toString()); - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/TimeClass.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/TimeClass.java deleted file mode 100644 index 9aa18d161..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/TimeClass.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.inv; - -public class TimeClass { - - public long time() { - return System.currentTimeMillis(); - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Two.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Two.java deleted file mode 100644 index 552c33a32..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Two.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.inv; - -public class Two { - - public Two() { - } - - public Two(String state) { - this.state = state; - } - - public int invvirtual(String what) { - System.out.print("invoke virtual " + what); - return -17; - } - - public static int invstatic(String what) { - System.out.print("invoke static! " + what); - return -13; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public void printState() { - System.out.print("state = " + state); - } - - private String state; -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Wimp.java b/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Wimp.java deleted file mode 100644 index ffb020495..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/fixtures/inv/Wimp.java +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package jodd.proxetta.fixtures.inv; - -import jodd.paramo.MethodParameter; -import jodd.paramo.Paramo; -import jodd.proxetta.ProxyTarget; -import jodd.proxetta.ProxyTargetInfo; - -import java.lang.reflect.Method; - -public class Wimp { - - public int foo() { - Object[] arguments = ProxyTarget.createArgumentsArray(); - return arguments.length; - } - - public String aaa(int Welcome, String To, Object Jodd) { - String methodName = ProxyTarget.targetMethodName(); - Class[] argTypes = ProxyTarget.createArgumentsClassArray(); - Class targetClass = ProxyTarget.targetClass(); - - Method m = null; - try { - m = targetClass.getDeclaredMethod(methodName, argTypes); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } - - MethodParameter[] methodParameters = Paramo.resolveParameters(m); - - Class c = ProxyTarget.argumentType(1); - Object val = ProxyTarget.argument(1); - - return c.getName() + val.toString() + - methodParameters[0].getName() + methodParameters[1].getName() + methodParameters[2].getName(); - } - - public String ccc(int Welcome, String to, long Jodd, Object Framework) { - ProxyTargetInfo pti = ProxyTarget.info(); - - return doit(pti); - } - - protected String doit(ProxyTargetInfo pti) { - return ">" + pti.argumentCount +':' + pti.returnType.getSimpleName() + - ':' + pti.argumentsClasses.length + pti.argumentsClasses[2].getSimpleName() + - ':' + pti.arguments.length + pti.arguments[1] + - ':' + pti.targetMethodName + - ':' + pti.targetClass.getSimpleName(); - } - -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/petite/WireBeansWithProxettaTest.java b/jodd-proxetta/src/test/java/jodd/proxetta/petite/WireBeansWithProxettaTest.java deleted file mode 100644 index 3e2643890..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/petite/WireBeansWithProxettaTest.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.proxetta.petite; - -import jodd.petite.PetiteConfig; -import jodd.petite.PetiteContainer; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.petite.fixtures.Bean1; -import jodd.proxetta.petite.fixtures.Bean2; -import jodd.proxetta.petite.fixtures.ExternalBean; -import jodd.proxetta.petite.fixtures.PetiteHelper; -import jodd.proxetta.petite.fixtures.PetiteProxettaContainer; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -class WireBeansWithProxettaTest { - - private PetiteContainer petiteContainer; - - @BeforeEach - void setupPetiteContainer() { - PetiteConfig petiteConfig = PetiteHelper.createPetiteConfig(); - - ProxyProxetta proxyProxetta = PetiteHelper.createProxyProxetta(); - petiteContainer = new PetiteProxettaContainer(proxyProxetta, petiteConfig); - - //AutomagicPetiteConfigurator petiteConfigurator = new AutomagicPetiteConfigurator(); - //petiteConfigurator.configure(petiteContainer); - - petiteContainer.registerPetiteBean(Bean1.class); - petiteContainer.registerPetiteBean(Bean2.class); - } - - public void teardownPetiteContainer() { - petiteContainer.shutdown(); - } - - @Test - void testWireExternalBeanAndCheckInjectedBean2Reference(){ - ExternalBean externalBean = new ExternalBean(); - - // --> inject - petiteContainer.wire(externalBean); - // <-- injection done - - Object value = externalBean.execute(); - - assertNotNull(value); - - assertTrue(value instanceof Bean2); - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/Bean1.java b/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/Bean1.java deleted file mode 100644 index 19ad68faa..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/Bean1.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.proxetta.petite.fixtures; - -import jodd.petite.meta.PetiteBean; -import jodd.petite.meta.PetiteInject; - -@PetiteBean ("___Bean1___") -public class Bean1 implements IBean1 { - - @PetiteInject ("++++Bean2++++") - protected Bean2 aBean; - - @Override - @Logged - public Object doInBean_1() { - return aBean.doInBean_2(); - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/Bean2.java b/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/Bean2.java deleted file mode 100644 index 222e97c35..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/Bean2.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.proxetta.petite.fixtures; - -import jodd.petite.meta.PetiteBean; - -@PetiteBean ("++++Bean2++++") -public class Bean2 implements IBean2 { - - @Override - public Object doInBean_2() { - return this; - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/ExternalBean.java b/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/ExternalBean.java deleted file mode 100644 index 1ea79eeec..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/ExternalBean.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.proxetta.petite.fixtures; - -import jodd.petite.meta.PetiteInject; - -public class ExternalBean { - - @PetiteInject ("___Bean1___") - private IBean1 aBean; - - public Object execute() { - return aBean.doInBean_1(); - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/IBean1.java b/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/IBean1.java deleted file mode 100644 index 01acd9da2..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/IBean1.java +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.proxetta.petite.fixtures; - -/** - * @author Sascha Fischer - */ -public interface IBean1 { - Object doInBean_1(); -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/IBean2.java b/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/IBean2.java deleted file mode 100644 index 7ea376211..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/IBean2.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.proxetta.petite.fixtures; - -/** - * @author Sascha Fischer - */ -public interface IBean2 { - @Logged - Object doInBean_2(); -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/LogProxyAdvice.java b/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/LogProxyAdvice.java deleted file mode 100644 index 39cffe669..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/LogProxyAdvice.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.proxetta.petite.fixtures; - -import jodd.proxetta.ProxyAdvice; -import jodd.proxetta.ProxyTarget; - -public class LogProxyAdvice implements ProxyAdvice { - - @Override - public Object execute() throws Exception { - System.out.println("execute now : " + ProxyTarget.targetClass().getCanonicalName()); - return ProxyTarget.invoke(); - } -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/Logged.java b/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/Logged.java deleted file mode 100644 index 84c76e1d2..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/Logged.java +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.proxetta.petite.fixtures; - -import static java.lang.annotation.ElementType.*; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Annotation für Methoden, die geloggt werden sollen. Dies kann sein fürs Tracing oder für Performance-Logging oder .... - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target(value = {TYPE, ANNOTATION_TYPE, CONSTRUCTOR, FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, PACKAGE}) -public @interface Logged { - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/PetiteHelper.java b/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/PetiteHelper.java deleted file mode 100644 index c15a1c7a3..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/PetiteHelper.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.proxetta.petite.fixtures; - -import jodd.petite.PetiteConfig; -import jodd.proxetta.Proxetta; -import jodd.proxetta.ProxyAspect; -import jodd.proxetta.ProxyPointcut; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.pointcuts.MethodWithAnnotationPointcut; - -public class PetiteHelper { - - public static PetiteConfig createPetiteConfig() { - - PetiteConfig petiteConfig = new PetiteConfig(); - petiteConfig.setDetectDuplicatedBeanNames(true); - - petiteConfig.setWireScopedProxy(true); - petiteConfig.setDetectMixedScopes(true); - - return petiteConfig; - } - - public static ProxyProxetta createProxyProxetta() { - - ProxyPointcut pointcut_logged = new MethodWithAnnotationPointcut(Logged.class); - ProxyAspect aspect_logged = new ProxyAspect(LogProxyAdvice.class, pointcut_logged); - - //proxetta.setDebugFolder(SystemUtil.userHome() + "\\inka\\proxetta"); - - return Proxetta.proxyProxetta().withAspects(aspect_logged); - } - -} diff --git a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/PetiteProxettaContainer.java b/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/PetiteProxettaContainer.java deleted file mode 100644 index 3785f3402..000000000 --- a/jodd-proxetta/src/test/java/jodd/proxetta/petite/fixtures/PetiteProxettaContainer.java +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -package jodd.proxetta.petite.fixtures; - -import jodd.petite.BeanDefinition; -import jodd.petite.PetiteConfig; -import jodd.petite.PetiteContainer; -import jodd.petite.WiringMode; -import jodd.petite.scope.Scope; -import jodd.proxetta.impl.ProxyProxetta; -import jodd.proxetta.impl.ProxyProxettaFactory; - -import java.util.function.Consumer; - -public class PetiteProxettaContainer extends PetiteContainer { - - private final ProxyProxetta proxetta; - - public PetiteProxettaContainer(ProxyProxetta proxetta, PetiteConfig petiteConfig) { - super(petiteConfig); - this.proxetta = proxetta; - } - -// @Override -// public BeanDefinition registerPetiteBean( -// Class type, -// String name, -// Class scopeType, -// WiringMode wiringMode, -// boolean define) { -// -// if (name == null) { -// name = PetiteUtil.resolveBeanName(type, false); -// } -// -// ProxyProxettaBuilder builder = proxetta.builder(); -// builder.setTarget(type); -// type = builder.define(); -// -// return super.registerPetiteBean(type, name, scopeType, wiringMode, false); -// } - - /** - * Applies proxetta on bean class before bean registration. - */ - @Override - protected BeanDefinition createBeanDefinitionForRegistration(String name, Class type, Scope scope, WiringMode wiringMode, Consumer consumer) { - if (proxetta != null) { - ProxyProxettaFactory builder = proxetta.proxy(); - - builder.setTarget(type); - - type = builder.define(); - } - - return super.createBeanDefinitionForRegistration(name, type, scope, wiringMode, consumer); - } - - @Override - public T getBean(Class type) { - return super.getBean(type); - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/kotlin/service/Test568OpenService.kt b/jodd-proxetta/src/test/kotlin/service/Test568OpenService.kt deleted file mode 100644 index 5a845df3a..000000000 --- a/jodd-proxetta/src/test/kotlin/service/Test568OpenService.kt +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package service - -import jodd.proxetta.fixtures.data.PetiteBean -import jodd.proxetta.fixtures.data.Transaction - -@PetiteBean -open class Test568OpenService { - - @Transaction - open fun findMember(id: Long?): String { - return id.toString() - } -} \ No newline at end of file diff --git a/jodd-proxetta/src/test/kotlin/service/Test568Service.kt b/jodd-proxetta/src/test/kotlin/service/Test568Service.kt deleted file mode 100644 index 1cf2280db..000000000 --- a/jodd-proxetta/src/test/kotlin/service/Test568Service.kt +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2003-present, Jodd Team (http://jodd.org) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. - -package service - -import jodd.proxetta.fixtures.data.PetiteBean -import jodd.proxetta.fixtures.data.Transaction - -@PetiteBean -class Test568Service { - - @Transaction - fun findMember(id: Long?): String { - return id.toString() - } -} \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index 253aa480b..16da3ff9e 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,11 +1,7 @@ include 'jodd-core' -include 'jodd-db' include 'jodd-decora' include 'jodd-htmlstapler' include 'jodd-joy' -include 'jodd-jtx' include 'jodd-madvoc' -include 'jodd-petite' -include 'jodd-proxetta' include 'jodd-servlet' include 'jodd-vtor'