From 8e5195a7dcba983fc13d7b03faa447595a8a4900 Mon Sep 17 00:00:00 2001 From: Pawel Nowak Date: Wed, 5 Aug 2020 21:51:29 +0200 Subject: [PATCH 1/4] upgrade spring and mongo driver --- pom.xml | 8 +- .../java/com/github/mongobeej/Mongobee.java | 813 ++++++++++-------- .../com/github/mongobeej/MongobeeTest.java | 7 +- .../mongobeej/resources/EnvironmentMock.java | 137 +-- 4 files changed, 524 insertions(+), 441 deletions(-) diff --git a/pom.xml b/pom.xml index bbdce62..4e010fc 100644 --- a/pom.xml +++ b/pom.xml @@ -45,7 +45,7 @@ - 5.0.6.RELEASE + 5.2.8.RELEASE UTF-8 UTF-8 @@ -54,7 +54,7 @@ org.mongodb mongo-java-driver - 3.8.0 + 3.9.1 org.springframework @@ -79,7 +79,7 @@ org.springframework.data spring-data-mongodb - 2.0.7.RELEASE + 3.0.2.RELEASE @@ -104,7 +104,7 @@ de.bwaldvogel mongo-java-server - 1.14.0 + 1.34.0 test diff --git a/src/main/java/com/github/mongobeej/Mongobee.java b/src/main/java/com/github/mongobeej/Mongobee.java index f0b3d35..f8dfab5 100644 --- a/src/main/java/com/github/mongobeej/Mongobee.java +++ b/src/main/java/com/github/mongobeej/Mongobee.java @@ -7,9 +7,8 @@ import com.github.mongobeej.exception.MongobeeConnectionException; import com.github.mongobeej.exception.MongobeeException; import com.github.mongobeej.utils.ChangeService; -import com.mongodb.DB; -import com.mongodb.MongoClient; -import com.mongodb.MongoClientURI; +import com.mongodb.*; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; import org.jongo.Jongo; import org.slf4j.Logger; @@ -24,6 +23,7 @@ import static com.mongodb.ServerAddress.defaultHost; import static com.mongodb.ServerAddress.defaultPort; +import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.springframework.util.StringUtils.hasText; /** @@ -33,392 +33,469 @@ * @since 26/07/2014 */ public class Mongobee implements InitializingBean { - private static final Logger logger = LoggerFactory.getLogger(Mongobee.class); - - private static final String DEFAULT_CHANGELOG_COLLECTION_NAME = "dbchangelog"; - private static final String DEFAULT_LOCK_COLLECTION_NAME = "mongobeelock"; - private static final boolean DEFAULT_WAIT_FOR_LOCK = false; - private static final long DEFAULT_CHANGE_LOG_LOCK_WAIT_TIME = 5L; - private static final long DEFAULT_CHANGE_LOG_LOCK_POLL_RATE = 10L; - private static final boolean DEFAULT_THROW_EXCEPTION_IF_CANNOT_OBTAIN_LOCK = false; - - private ChangeEntryDao dao; - - private boolean enabled = true; - private String changeLogsScanPackage; - private MongoClientURI mongoClientURI; - private MongoClient mongoClient; - private String dbName; - private Environment springEnvironment; - - private MongoTemplate mongoTemplate; - private Jongo jongo; - - - /** - *

Simple constructor with default configuration of host (localhost) and port (27017). Although - * the database name need to be provided using {@link Mongobee#setDbName(String)} setter.

- *

It is recommended to use constructors with MongoURI

- */ - public Mongobee() { - this(new MongoClientURI("mongodb://" + defaultHost() + ":" + defaultPort() + "/")); - } - - /** - *

Constructor takes db.mongodb.MongoClientURI object as a parameter. - *

For more details about MongoClientURI please see com.mongodb.MongoClientURI docs - *

- * - * @param mongoClientURI uri to your db - * @see MongoClientURI - */ - public Mongobee(MongoClientURI mongoClientURI) { - this.mongoClientURI = mongoClientURI; - this.setDbName(mongoClientURI.getDatabase()); - this.dao = new ChangeEntryDao(DEFAULT_CHANGELOG_COLLECTION_NAME, DEFAULT_LOCK_COLLECTION_NAME, DEFAULT_WAIT_FOR_LOCK, - DEFAULT_CHANGE_LOG_LOCK_WAIT_TIME, DEFAULT_CHANGE_LOG_LOCK_POLL_RATE, DEFAULT_THROW_EXCEPTION_IF_CANNOT_OBTAIN_LOCK); - } - - /** - *

Constructor takes db.mongodb.MongoClient object as a parameter. - *

For more details about MongoClient please see com.mongodb.MongoClient docs - *

- * - * @param mongoClient database connection client - * @see MongoClient - */ - public Mongobee(MongoClient mongoClient) { - this.mongoClient = mongoClient; - this.dao = new ChangeEntryDao(DEFAULT_CHANGELOG_COLLECTION_NAME, DEFAULT_LOCK_COLLECTION_NAME, DEFAULT_WAIT_FOR_LOCK, - DEFAULT_CHANGE_LOG_LOCK_WAIT_TIME, DEFAULT_CHANGE_LOG_LOCK_POLL_RATE, DEFAULT_THROW_EXCEPTION_IF_CANNOT_OBTAIN_LOCK); - } - - /** - *

Mongobee runner. Correct MongoDB URI should be provided.

- *

The format of the URI is: - *

-   *   mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database[.collection]][?options]]
-   * 
- *
    - *
  • {@code mongodb://} Required prefix
  • - *
  • {@code username:password@} are optional. If given, the driver will attempt to login to a database after - * connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, - * in which case the ":" after the username is left off as well.
  • - *
  • {@code host1} Required. It identifies a server address to connect to. More than one host can be provided.
  • - *
  • {@code :portX} is optional and defaults to :27017 if not provided.
  • - *
  • {@code /database} the name of the database to login to and thus is only relevant if the - * {@code username:password@} syntax is used. If not specified the "admin" database will be used by default. - * Mongobee will operate on the database provided here or on the database overriden by setter setDbName(String). - *
  • - *
  • {@code ?options} are connection options. For list of options please see com.mongodb.MongoClientURI docs
  • - *
- *

For details, please see com.mongodb.MongoClientURI - * - * @param mongoURI with correct format - * @see com.mongodb.MongoClientURI - */ - - public Mongobee(String mongoURI) { - this(new MongoClientURI(mongoURI)); - } - - /** - * For Spring users: executing mongobeej after bean is created in the Spring context - * - * @throws Exception exception - */ - @Override - public void afterPropertiesSet() throws Exception { - execute(); - } - - /** - * Executing migration - * - * @throws MongobeeException exception - */ - public void execute() throws MongobeeException { - if (!isEnabled()) { - logger.info("Mongobee is disabled. Exiting."); - return; + private static final Logger logger = LoggerFactory.getLogger(Mongobee.class); + + private static final String DEFAULT_CHANGELOG_COLLECTION_NAME = "dbchangelog"; + private static final String DEFAULT_LOCK_COLLECTION_NAME = "mongobeelock"; + private static final boolean DEFAULT_WAIT_FOR_LOCK = false; + private static final long DEFAULT_CHANGE_LOG_LOCK_WAIT_TIME = 5L; + private static final long DEFAULT_CHANGE_LOG_LOCK_POLL_RATE = 10L; + private static final boolean DEFAULT_THROW_EXCEPTION_IF_CANNOT_OBTAIN_LOCK = false; + + private ChangeEntryDao dao; + + private boolean enabled = true; + private String changeLogsScanPackage; + private MongoClientURI mongoClientURI; + private MongoClient legacyMongoClient; + private com.mongodb.client.MongoClient mongoClient; + private String dbName; + private Environment springEnvironment; + + private MongoTemplate mongoTemplate; + private Jongo jongo; + + + /** + *

Simple constructor with default configuration of host (localhost) and port (27017). Although + * the database name need to be provided using {@link Mongobee#setDbName(String)} setter.

+ *

It is recommended to use constructors with MongoURI

+ */ + public Mongobee() { + this(new MongoClientURI("mongodb://" + defaultHost() + ":" + defaultPort() + "/")); } - validateConfig(); + /** + *

Constructor takes db.mongodb.MongoClientURI object as a parameter. + *

For more details about MongoClientURI please see com.mongodb.MongoClientURI docs + *

+ * + * @param mongoClientURI uri to your db + * @see MongoClientURI + */ + public Mongobee(MongoClientURI mongoClientURI) { + this.mongoClientURI = mongoClientURI; + this.setDbName(mongoClientURI.getDatabase()); + this.dao = new ChangeEntryDao(DEFAULT_CHANGELOG_COLLECTION_NAME, DEFAULT_LOCK_COLLECTION_NAME, DEFAULT_WAIT_FOR_LOCK, + DEFAULT_CHANGE_LOG_LOCK_WAIT_TIME, DEFAULT_CHANGE_LOG_LOCK_POLL_RATE, DEFAULT_THROW_EXCEPTION_IF_CANNOT_OBTAIN_LOCK); + } - if (this.mongoClient != null) { - dao.connectMongoDb(this.mongoClient, dbName); - } else { - dao.connectMongoDb(this.mongoClientURI, dbName); + /** + *

Constructor takes db.mongodb.MongoClient object as a parameter. + *

For more details about MongoClient please see com.mongodb.MongoClient docs + *

+ * + * @param legacyMongoClient database connection client + * @see MongoClient + */ + public Mongobee(MongoClient legacyMongoClient) { + this.legacyMongoClient = legacyMongoClient; + this.dao = new ChangeEntryDao(DEFAULT_CHANGELOG_COLLECTION_NAME, DEFAULT_LOCK_COLLECTION_NAME, DEFAULT_WAIT_FOR_LOCK, + DEFAULT_CHANGE_LOG_LOCK_WAIT_TIME, DEFAULT_CHANGE_LOG_LOCK_POLL_RATE, DEFAULT_THROW_EXCEPTION_IF_CANNOT_OBTAIN_LOCK); } - if (!dao.acquireProcessLock()) { - logger.info("Mongobee did not acquire process lock. Exiting."); - return; + /** + *

Mongobee runner. Correct MongoDB URI should be provided.

+ *

The format of the URI is: + *

+     *   mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database[.collection]][?options]]
+     * 
+ *
    + *
  • {@code mongodb://} Required prefix
  • + *
  • {@code username:password@} are optional. If given, the driver will attempt to login to a database after + * connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, + * in which case the ":" after the username is left off as well.
  • + *
  • {@code host1} Required. It identifies a server address to connect to. More than one host can be provided.
  • + *
  • {@code :portX} is optional and defaults to :27017 if not provided.
  • + *
  • {@code /database} the name of the database to login to and thus is only relevant if the + * {@code username:password@} syntax is used. If not specified the "admin" database will be used by default. + * Mongobee will operate on the database provided here or on the database overridden by setter setDbName(String). + *
  • + *
  • {@code ?options} are connection options. For list of options please see com.mongodb.MongoClientURI docs
  • + *
+ *

For details, please see com.mongodb.MongoClientURI + * + * @param mongoURI with correct format + * @see com.mongodb.MongoClientURI + */ + public Mongobee(String mongoURI) { + this(new MongoClientURI(mongoURI)); } - logger.info("Mongobee acquired process lock, starting the data migration sequence.."); + /** + *

Constructor takes db.mongodb.client.MongoClient object as a parameter. + *

For more details about MongoClient please see com.mongodb.client.MongoClient docs + *

+ * + * @param mongoClient database connection client + * @see MongoClient + */ + public Mongobee(com.mongodb.client.MongoClient mongoClient) { + this.mongoClient = mongoClient; + this.dao = new ChangeEntryDao(DEFAULT_CHANGELOG_COLLECTION_NAME, DEFAULT_LOCK_COLLECTION_NAME, DEFAULT_WAIT_FOR_LOCK, + DEFAULT_CHANGE_LOG_LOCK_WAIT_TIME, DEFAULT_CHANGE_LOG_LOCK_POLL_RATE, DEFAULT_THROW_EXCEPTION_IF_CANNOT_OBTAIN_LOCK); + } - try { - executeMigration(); - } finally { - logger.info("Mongobee is releasing process lock."); - dao.releaseProcessLock(); + /** + * For Spring users: executing mongobeej after bean is created in the Spring context + * + * @throws Exception exception + */ + @Override + public void afterPropertiesSet() throws Exception { + execute(); } - logger.info("Mongobee has finished his job."); - } + /** + * Executing migration + * + * @throws MongobeeException exception + */ + public void execute() throws MongobeeException { + if (!isEnabled()) { + logger.info("Mongobee is disabled. Exiting."); + return; + } - private void executeMigration() throws MongobeeConnectionException, MongobeeException { + validateConfig(); - ChangeService service = new ChangeService(changeLogsScanPackage, springEnvironment); + if (this.legacyMongoClient != null) { + dao.connectMongoDb(this.legacyMongoClient, dbName); + } else { + dao.connectMongoDb(this.mongoClientURI, dbName); + } - for (Class changelogClass : service.fetchChangeLogs()) { + if (!dao.acquireProcessLock()) { + logger.info("Mongobee did not acquire process lock. Exiting."); + return; + } - Object changelogInstance = null; - try { - changelogInstance = changelogClass.getConstructor().newInstance(); - List changesetMethods = service.fetchChangeSets(changelogInstance.getClass()); + logger.info("Mongobee acquired process lock, starting the data migration sequence.."); - for (Method changesetMethod : changesetMethods) { - ChangeEntry changeEntry = service.createChangeEntry(changesetMethod); + try { + executeMigration(); + } finally { + logger.info("Mongobee is releasing process lock."); + dao.releaseProcessLock(); + } - try { - if (dao.isNewChange(changeEntry)) { - executeChangeSetMethod(changesetMethod, changelogInstance, dao.getDb(), dao.getMongoDatabase()); - dao.save(changeEntry); - logger.info(changeEntry + " applied"); - } else if (service.isRunAlwaysChangeSet(changesetMethod)) { - executeChangeSetMethod(changesetMethod, changelogInstance, dao.getDb(), dao.getMongoDatabase()); - logger.info(changeEntry + " reapplied"); - } else { - logger.info(changeEntry + " passed over"); + logger.info("Mongobee has finished his job."); + } + + private void executeMigration() throws MongobeeConnectionException, MongobeeException { + + ChangeService service = new ChangeService(changeLogsScanPackage, springEnvironment); + + for (Class changelogClass : service.fetchChangeLogs()) { + + Object changelogInstance = null; + try { + changelogInstance = changelogClass.getConstructor().newInstance(); + List changesetMethods = service.fetchChangeSets(changelogInstance.getClass()); + + for (Method changesetMethod : changesetMethods) { + ChangeEntry changeEntry = service.createChangeEntry(changesetMethod); + + try { + if (dao.isNewChange(changeEntry)) { + executeChangeSetMethod(changesetMethod, changelogInstance, dao.getDb(), dao.getMongoDatabase()); + dao.save(changeEntry); + logger.info(changeEntry + " applied"); + } else if (service.isRunAlwaysChangeSet(changesetMethod)) { + executeChangeSetMethod(changesetMethod, changelogInstance, dao.getDb(), dao.getMongoDatabase()); + logger.info(changeEntry + " reapplied"); + } else { + logger.info(changeEntry + " passed over"); + } + } catch (MongobeeChangeSetException e) { + logger.error(e.getMessage()); + } + } + } catch (NoSuchMethodException | IllegalAccessException | InstantiationException exception) { + throw new MongobeeException(exception.getMessage(), exception); + } catch (InvocationTargetException exception) { + Throwable targetException = exception.getTargetException(); + throw new MongobeeException(targetException.getMessage(), exception); } - } catch (MongobeeChangeSetException e) { - logger.error(e.getMessage()); - } } - } catch (NoSuchMethodException | IllegalAccessException | InstantiationException exception) { - throw new MongobeeException(exception.getMessage(), exception); - } catch (InvocationTargetException exception) { - Throwable targetException = exception.getTargetException(); - throw new MongobeeException(targetException.getMessage(), exception); - } } - } - - private Object executeChangeSetMethod(Method changeSetMethod, Object changeLogInstance, DB db, MongoDatabase mongoDatabase) - throws IllegalAccessException, InvocationTargetException, MongobeeChangeSetException { - if (changeSetMethod.getParameterTypes().length == 1 - && changeSetMethod.getParameterTypes()[0].equals(DB.class)) { - logger.debug("method with DB argument"); - - return changeSetMethod.invoke(changeLogInstance, db); - } else if (changeSetMethod.getParameterTypes().length == 1 - && changeSetMethod.getParameterTypes()[0].equals(Jongo.class)) { - logger.debug("method with Jongo argument"); - - return changeSetMethod.invoke(changeLogInstance, jongo != null ? jongo : new Jongo(db)); - } else if (changeSetMethod.getParameterTypes().length == 1 - && changeSetMethod.getParameterTypes()[0].equals(MongoTemplate.class)) { - logger.debug("method with MongoTemplate argument"); - - return changeSetMethod.invoke(changeLogInstance, mongoTemplate != null ? mongoTemplate : new MongoTemplate((MongoClient) db.getMongo(), dbName)); - } else if (changeSetMethod.getParameterTypes().length == 2 - && changeSetMethod.getParameterTypes()[0].equals(MongoTemplate.class) - && changeSetMethod.getParameterTypes()[1].equals(Environment.class)) { - logger.debug("method with MongoTemplate and environment arguments"); - - return changeSetMethod.invoke(changeLogInstance, mongoTemplate != null ? mongoTemplate : new MongoTemplate((MongoClient) db.getMongo(), dbName), springEnvironment); - } else if (changeSetMethod.getParameterTypes().length == 1 - && changeSetMethod.getParameterTypes()[0].equals(MongoDatabase.class)) { - logger.debug("method with DB argument"); - - return changeSetMethod.invoke(changeLogInstance, mongoDatabase); - } else if (changeSetMethod.getParameterTypes().length == 0) { - logger.debug("method with no params"); - - return changeSetMethod.invoke(changeLogInstance); - } else { - throw new MongobeeChangeSetException("ChangeSet method " + changeSetMethod.getName() + - " has wrong arguments list. Please see docs for more info!"); + + private Object executeChangeSetMethod( + Method changeSetMethod, + Object changeLogInstance, + DB db, + MongoDatabase mongoDatabase + ) throws IllegalAccessException, InvocationTargetException, MongobeeChangeSetException { + if (changeSetMethod.getParameterTypes().length == 1 + && changeSetMethod.getParameterTypes()[0].equals(DB.class)) { + logger.debug("method with DB argument"); + + return changeSetMethod.invoke(changeLogInstance, db); + } else if (changeSetMethod.getParameterTypes().length == 1 + && changeSetMethod.getParameterTypes()[0].equals(Jongo.class)) { + logger.debug("method with Jongo argument"); + + return changeSetMethod.invoke(changeLogInstance, jongo != null ? jongo : new Jongo(db)); + } else if (changeSetMethod.getParameterTypes().length == 1 + && changeSetMethod.getParameterTypes()[0].equals(MongoTemplate.class)) { + logger.debug("method with MongoTemplate argument"); + + return changeSetMethod.invoke(changeLogInstance, mongoTemplate != null ? mongoTemplate : createMongoTemplate()); + } else if (changeSetMethod.getParameterTypes().length == 2 + && changeSetMethod.getParameterTypes()[0].equals(MongoTemplate.class) + && changeSetMethod.getParameterTypes()[1].equals(Environment.class)) { + logger.debug("method with MongoTemplate and environment arguments"); + + return changeSetMethod.invoke(changeLogInstance, mongoTemplate != null ? mongoTemplate : createMongoTemplate(), springEnvironment); + } else if (changeSetMethod.getParameterTypes().length == 1 + && changeSetMethod.getParameterTypes()[0].equals(MongoDatabase.class)) { + logger.debug("method with DB argument"); + + return changeSetMethod.invoke(changeLogInstance, mongoDatabase); + } else if (changeSetMethod.getParameterTypes().length == 0) { + logger.debug("method with no params"); + + return changeSetMethod.invoke(changeLogInstance); + } else { + throw new MongobeeChangeSetException("ChangeSet method " + changeSetMethod.getName() + + " has wrong arguments list. Please see docs for more info!"); + } } - } - private void validateConfig() throws MongobeeConfigurationException { - if (!hasText(dbName)) { - throw new MongobeeConfigurationException("DB name is not set. It should be defined in MongoDB URI or via setter"); + private MongoTemplate createMongoTemplate() { + com.mongodb.client.MongoClient mongoClient; + if (this.mongoClient != null) { + mongoClient = this.mongoClient; + } else if (legacyMongoClient!= null) { + mongoClient = fromLegacyClient(); + } else { + mongoClient = MongoClients.create(mongoClientURI.toString()); + } + return new MongoTemplate(mongoClient, dbName); } - if (!hasText(changeLogsScanPackage)) { - throw new MongobeeConfigurationException("Scan package for changelogs is not set: use appropriate setter"); + + private com.mongodb.client.MongoClient fromLegacyClient() { + MongoClientOptions mongoClientOptions = legacyMongoClient.getMongoClientOptions(); + MongoClientSettings.Builder mongoClientSettingsBuilder = MongoClientSettings.builder() + .readPreference(legacyMongoClient.getReadPreference()) + .writeConcern(legacyMongoClient.getWriteConcern()) + .retryWrites(mongoClientOptions.getRetryWrites()) + .readConcern(legacyMongoClient.getReadConcern()) + .codecRegistry(mongoClientOptions.getCodecRegistry()) + .compressorList(mongoClientOptions.getCompressorList()) + .applicationName(mongoClientOptions.getApplicationName()) + .commandListenerList(mongoClientOptions.getCommandListeners()) + .codecRegistry(mongoClientOptions.getCodecRegistry()) + .applyToClusterSettings(clusterSettings -> { + clusterSettings.hosts(legacyMongoClient.getAllAddress()); + clusterSettings.localThreshold(mongoClientOptions.getLocalThreshold(), MILLISECONDS); + clusterSettings.serverSelectionTimeout(mongoClientOptions.getServerSelectionTimeout(), MILLISECONDS); + clusterSettings.serverSelector(mongoClientOptions.getServerSelector()); + clusterSettings.requiredReplicaSetName(mongoClientOptions.getRequiredReplicaSetName()); + mongoClientOptions.getClusterListeners().forEach(clusterSettings::addClusterListener); + }) + .applyToConnectionPoolSettings(connectionPoolSettings -> { + mongoClientOptions.getConnectionPoolListeners().forEach(connectionPoolSettings::addConnectionPoolListener); + connectionPoolSettings.maxConnectionIdleTime(mongoClientOptions.getMaxConnectionIdleTime(), MILLISECONDS); + connectionPoolSettings.maxConnectionLifeTime(mongoClientOptions.getMaxConnectionLifeTime(), MILLISECONDS); + connectionPoolSettings.maxWaitTime(mongoClientOptions.getMaxWaitTime(), MILLISECONDS); + }) + .applyToSocketSettings(socketSettings -> { + socketSettings.connectTimeout(mongoClientOptions.getConnectTimeout(), MILLISECONDS); + socketSettings.readTimeout(mongoClientOptions.getSocketTimeout(), MILLISECONDS); + }) + .applyToServerSettings(serverSettings -> { + mongoClientOptions.getServerListeners().forEach(serverSettings::addServerListener); + serverSettings.minHeartbeatFrequency(mongoClientOptions.getMinHeartbeatFrequency(), MILLISECONDS); + serverSettings.heartbeatFrequency(mongoClientOptions.getHeartbeatFrequency(), MILLISECONDS); + + }) + .applyToSslSettings(sslSettings -> { + sslSettings.enabled(mongoClientOptions.isSslEnabled()); + sslSettings.invalidHostNameAllowed(mongoClientOptions.isSslInvalidHostNameAllowed()); + sslSettings.context(mongoClientOptions.getSslContext()); + }); + if (legacyMongoClient.getCredential() != null) { + mongoClientSettingsBuilder.credential(legacyMongoClient.getCredential()); + } + return MongoClients.create(mongoClientSettingsBuilder.build()); + } + + private void validateConfig() throws MongobeeConfigurationException { + if (!hasText(dbName)) { + throw new MongobeeConfigurationException("DB name is not set. It should be defined in MongoDB URI or via setter"); + } + if (!hasText(changeLogsScanPackage)) { + throw new MongobeeConfigurationException("Scan package for changelogs is not set: use appropriate setter"); + } + } + + /** + * @return true if an execution is in progress, in any process. + * @throws MongobeeConnectionException exception + */ + public boolean isExecutionInProgress() throws MongobeeConnectionException { + return dao.isProccessLockHeld(); + } + + /** + * Used DB name should be set here or via MongoDB URI (in a constructor) + * + * @param dbName database name + * @return Mongobee object for fluent interface + */ + public Mongobee setDbName(String dbName) { + this.dbName = dbName; + return this; + } + + /** + * Sets uri to MongoDB + * + * @param mongoClientURI object with defined mongo uri + * @return Mongobee object for fluent interface + */ + public Mongobee setMongoClientURI(MongoClientURI mongoClientURI) { + this.mongoClientURI = mongoClientURI; + return this; + } + + /** + * Package name where @ChangeLog-annotated classes are kept. + * + * @param changeLogsScanPackage package where your changelogs are + * @return Mongobee object for fluent interface + */ + public Mongobee setChangeLogsScanPackage(String changeLogsScanPackage) { + this.changeLogsScanPackage = changeLogsScanPackage; + return this; + } + + /** + * @return true if Mongobee runner is enabled and able to run, otherwise false + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Feature which enables/disables Mongobee runner execution + * + * @param enabled MOngobee will run only if this option is set to true + * @return Mongobee object for fluent interface + */ + public Mongobee setEnabled(boolean enabled) { + this.enabled = enabled; + return this; + } + + /** + * Feature which enables/disables waiting for lock if it's already obtained + * + * @param waitForLock Mongobee will be waiting for lock if it's already obtained if this option is set to true + * @return Mongobee object for fluent interface + */ + public Mongobee setWaitForLock(boolean waitForLock) { + this.dao.setWaitForLock(waitForLock); + return this; + } + + /** + * Waiting time for acquiring lock if waitForLock is true + * + * @param changeLogLockWaitTime Waiting time in minutes for acquiring lock + * @return Mongobee object for fluent interface + */ + public Mongobee setChangeLogLockWaitTime(long changeLogLockWaitTime) { + this.dao.setChangeLogLockWaitTime(changeLogLockWaitTime); + return this; + } + + /** + * Poll rate for acquiring lock if waitForLock is true + * + * @param changeLogLockPollRate Poll rate in seconds for acquiring lock + * @return Mongobee object for fluent interface + */ + public Mongobee setChangeLogLockPollRate(long changeLogLockPollRate) { + this.dao.setChangeLogLockPollRate(changeLogLockPollRate); + return this; + } + + /** + * Feature which enables/disables throwing MongobeeLockException if Mongobee can not obtain lock + * + * @param throwExceptionIfCannotObtainLock Mongobee will throw MongobeeLockException if lock can not be obtained + * @return Mongobee object for fluent interface + */ + public Mongobee setThrowExceptionIfCannotObtainLock(boolean throwExceptionIfCannotObtainLock) { + this.dao.setThrowExceptionIfCannotObtainLock(throwExceptionIfCannotObtainLock); + return this; + } + + /** + * Set Environment object for Spring Profiles (@Profile) integration + * + * @param environment org.springframework.core.env.Environment object to inject + * @return Mongobee object for fluent interface + */ + public Mongobee setSpringEnvironment(Environment environment) { + this.springEnvironment = environment; + return this; + } + + /** + * Sets pre-configured {@link MongoTemplate} instance to use by the Mongobee + * + * @param mongoTemplate instance of the {@link MongoTemplate} + * @return Mongobee object for fluent interface + */ + public Mongobee setMongoTemplate(MongoTemplate mongoTemplate) { + this.mongoTemplate = mongoTemplate; + return this; + } + + /** + * Sets pre-configured {@link MongoTemplate} instance to use by the Mongobee + * + * @param jongo {@link Jongo} instance + * @return Mongobee object for fluent interface + */ + public Mongobee setJongo(Jongo jongo) { + this.jongo = jongo; + return this; + } + + /** + * Overwrites a default mongobeej changelog collection hardcoded in DEFAULT_CHANGELOG_COLLECTION_NAME. + *

+ * CAUTION! Use this method carefully - when changing the name on a existing system, + * your changelogs will be executed again on your MongoDB instance + * + * @param changelogCollectionName a new changelog collection name + * @return Mongobee object for fluent interface + */ + public Mongobee setChangelogCollectionName(String changelogCollectionName) { + this.dao.setChangelogCollectionName(changelogCollectionName); + return this; + } + + /** + * Overwrites a default mongobeej lock collection hardcoded in DEFAULT_LOCK_COLLECTION_NAME + * + * @param lockCollectionName a new lock collection name + * @return Mongobee object for fluent interface + */ + public Mongobee setLockCollectionName(String lockCollectionName) { + this.dao.setLockCollectionName(lockCollectionName); + return this; + } + + /** + * Closes the Mongo instance used by Mongobee. + * This will close either the connection Mongobee was initiated with or that which was internally created. + */ + public void close() { + dao.close(); } - } - - /** - * @return true if an execution is in progress, in any process. - * @throws MongobeeConnectionException exception - */ - public boolean isExecutionInProgress() throws MongobeeConnectionException { - return dao.isProccessLockHeld(); - } - - /** - * Used DB name should be set here or via MongoDB URI (in a constructor) - * - * @param dbName database name - * @return Mongobee object for fluent interface - */ - public Mongobee setDbName(String dbName) { - this.dbName = dbName; - return this; - } - - /** - * Sets uri to MongoDB - * - * @param mongoClientURI object with defined mongo uri - * @return Mongobee object for fluent interface - */ - public Mongobee setMongoClientURI(MongoClientURI mongoClientURI) { - this.mongoClientURI = mongoClientURI; - return this; - } - - /** - * Package name where @ChangeLog-annotated classes are kept. - * - * @param changeLogsScanPackage package where your changelogs are - * @return Mongobee object for fluent interface - */ - public Mongobee setChangeLogsScanPackage(String changeLogsScanPackage) { - this.changeLogsScanPackage = changeLogsScanPackage; - return this; - } - - /** - * @return true if Mongobee runner is enabled and able to run, otherwise false - */ - public boolean isEnabled() { - return enabled; - } - - /** - * Feature which enables/disables Mongobee runner execution - * - * @param enabled MOngobee will run only if this option is set to true - * @return Mongobee object for fluent interface - */ - public Mongobee setEnabled(boolean enabled) { - this.enabled = enabled; - return this; - } - - /** - * Feature which enables/disables waiting for lock if it's already obtained - * - * @param waitForLock Mongobee will be waiting for lock if it's already obtained if this option is set to true - * @return Mongobee object for fluent interface - */ - public Mongobee setWaitForLock(boolean waitForLock) { - this.dao.setWaitForLock(waitForLock); - return this; - } - - /** - * Waiting time for acquiring lock if waitForLock is true - * - * @param changeLogLockWaitTime Waiting time in minutes for acquiring lock - * @return Mongobee object for fluent interface - */ - public Mongobee setChangeLogLockWaitTime(long changeLogLockWaitTime) { - this.dao.setChangeLogLockWaitTime(changeLogLockWaitTime); - return this; - } - - /** - * Poll rate for acquiring lock if waitForLock is true - * - * @param changeLogLockPollRate Poll rate in seconds for acquiring lock - * @return Mongobee object for fluent interface - */ - public Mongobee setChangeLogLockPollRate(long changeLogLockPollRate) { - this.dao.setChangeLogLockPollRate(changeLogLockPollRate); - return this; - } - - /** - * Feature which enables/disables throwing MongobeeLockException if Mongobee can not obtain lock - * - * @param throwExceptionIfCannotObtainLock Mongobee will throw MongobeeLockException if lock can not be obtained - * @return Mongobee object for fluent interface - */ - public Mongobee setThrowExceptionIfCannotObtainLock(boolean throwExceptionIfCannotObtainLock) { - this.dao.setThrowExceptionIfCannotObtainLock(throwExceptionIfCannotObtainLock); - return this; - } - - /** - * Set Environment object for Spring Profiles (@Profile) integration - * - * @param environment org.springframework.core.env.Environment object to inject - * @return Mongobee object for fluent interface - */ - public Mongobee setSpringEnvironment(Environment environment) { - this.springEnvironment = environment; - return this; - } - - /** - * Sets pre-configured {@link MongoTemplate} instance to use by the Mongobee - * - * @param mongoTemplate instance of the {@link MongoTemplate} - * @return Mongobee object for fluent interface - */ - public Mongobee setMongoTemplate(MongoTemplate mongoTemplate) { - this.mongoTemplate = mongoTemplate; - return this; - } - - /** - * Sets pre-configured {@link MongoTemplate} instance to use by the Mongobee - * - * @param jongo {@link Jongo} instance - * @return Mongobee object for fluent interface - */ - public Mongobee setJongo(Jongo jongo) { - this.jongo = jongo; - return this; - } - - /** - * Overwrites a default mongobeej changelog collection hardcoded in DEFAULT_CHANGELOG_COLLECTION_NAME. - * - * CAUTION! Use this method carefully - when changing the name on a existing system, - * your changelogs will be executed again on your MongoDB instance - * - * @param changelogCollectionName a new changelog collection name - * @return Mongobee object for fluent interface - */ - public Mongobee setChangelogCollectionName(String changelogCollectionName) { - this.dao.setChangelogCollectionName(changelogCollectionName); - return this; - } - - /** - * Overwrites a default mongobeej lock collection hardcoded in DEFAULT_LOCK_COLLECTION_NAME - * - * @param lockCollectionName a new lock collection name - * @return Mongobee object for fluent interface - */ - public Mongobee setLockCollectionName(String lockCollectionName) { - this.dao.setLockCollectionName(lockCollectionName); - return this; - } - - /** - * Closes the Mongo instance used by Mongobee. - * This will close either the connection Mongobee was initiated with or that which was internally created. - */ - public void close() { - dao.close(); - } } diff --git a/src/test/java/com/github/mongobeej/MongobeeTest.java b/src/test/java/com/github/mongobeej/MongobeeTest.java index 89ffc00..3c08a5c 100644 --- a/src/test/java/com/github/mongobeej/MongobeeTest.java +++ b/src/test/java/com/github/mongobeej/MongobeeTest.java @@ -21,7 +21,6 @@ import org.mockito.runners.MockitoJUnitRunner; import org.springframework.data.mongodb.core.MongoTemplate; -import java.net.UnknownHostException; import java.util.Collections; import static com.github.mongobeej.utils.MongoEnvironmentCreator.DB_NAME; @@ -36,8 +35,9 @@ @RunWith(MockitoJUnitRunner.class) public class MongobeeTest { private static final String CHANGELOG_COLLECTION_NAME = "dbchangelog"; + MongoEnvironment mongoEnvironment = createMongoEnvironment(); @InjectMocks - private Mongobee mongobee = new Mongobee(); + private Mongobee mongobee = new Mongobee(mongoEnvironment.getMongoClient()); @Mock private ChangeEntryDao changeEntryDao; @Mock @@ -47,8 +47,7 @@ public class MongobeeTest { private MongoDatabase mongoDatabase; @Before - public void init() throws MongobeeException, UnknownHostException { - MongoEnvironment mongoEnvironment = createMongoEnvironment(); + public void init() throws MongobeeException { mongoDatabase = mongoEnvironment.getMongoDatabase(); when(changeEntryDao.connectMongoDb(any(MongoClientURI.class), anyString())) .thenReturn(mongoDatabase); diff --git a/src/test/java/com/github/mongobeej/resources/EnvironmentMock.java b/src/test/java/com/github/mongobeej/resources/EnvironmentMock.java index bc17042..8c69de0 100644 --- a/src/test/java/com/github/mongobeej/resources/EnvironmentMock.java +++ b/src/test/java/com/github/mongobeej/resources/EnvironmentMock.java @@ -1,77 +1,84 @@ package com.github.mongobeej.resources; import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; /** * Mock for Spring environment + * * @author lstolowski * @since 2014-09-19 */ public class EnvironmentMock implements Environment { - private String[] activeProfiles; - - public EnvironmentMock(String... activeProfiles) { - this.activeProfiles = activeProfiles; - } - - @Override - public String[] getActiveProfiles() { - return this.activeProfiles; - } - - @Override - public String[] getDefaultProfiles() { - return new String[0]; - } - - @Override - public boolean acceptsProfiles(String... strings) { - return false; - } - - @Override - public boolean containsProperty(String s) { - return false; - } - - @Override - public String getProperty(String s) { - return null; - } - - @Override - public String getProperty(String s, String s2) { - return null; - } - - @Override - public T getProperty(String s, Class tClass) { - return null; - } - - @Override - public T getProperty(String s, Class tClass, T t) { - return null; - } - - @Override - public String getRequiredProperty(String s) throws IllegalStateException { - return null; - } - - @Override - public T getRequiredProperty(String s, Class tClass) throws IllegalStateException { - return null; - } - - @Override - public String resolvePlaceholders(String s) { - return null; - } - - @Override - public String resolveRequiredPlaceholders(String s) throws IllegalArgumentException { - return null; - } + private String[] activeProfiles; + + public EnvironmentMock(String... activeProfiles) { + this.activeProfiles = activeProfiles; + } + + @Override + public String[] getActiveProfiles() { + return this.activeProfiles; + } + + @Override + public String[] getDefaultProfiles() { + return new String[0]; + } + + @Override + public boolean acceptsProfiles(String... strings) { + return false; + } + + @Override + public boolean acceptsProfiles(Profiles profiles) { + return false; + } + + @Override + public boolean containsProperty(String s) { + return false; + } + + @Override + public String getProperty(String s) { + return null; + } + + @Override + public String getProperty(String s, String s2) { + return null; + } + + @Override + public T getProperty(String s, Class tClass) { + return null; + } + + @Override + public T getProperty(String s, Class tClass, T t) { + return null; + } + + @Override + public String getRequiredProperty(String s) throws IllegalStateException { + return null; + } + + @Override + public T getRequiredProperty(String s, Class tClass) throws IllegalStateException { + return null; + } + + @Override + public String resolvePlaceholders(String s) { + return null; + } + + @Override + public String resolveRequiredPlaceholders(String s) throws IllegalArgumentException { + return null; + } } From 19f42b0beb13ae11ee3f9571df2acf53b043b7aa Mon Sep 17 00:00:00 2001 From: Pawel Nowak Date: Wed, 5 Aug 2020 21:53:00 +0200 Subject: [PATCH 2/4] format all classes --- .../java/com/github/mongobeej/Mongobee.java | 2 +- .../mongobeej/changeset/ChangeEntry.java | 5 +- .../github/mongobeej/changeset/ChangeLog.java | 16 +-- .../github/mongobeej/changeset/ChangeSet.java | 55 ++++++----- .../com/github/mongobeej/dao/LockDao.java | 99 +++++++++---------- .../exception/MongobeeChangeSetException.java | 6 +- .../MongobeeConfigurationException.java | 6 +- .../MongobeeConnectionException.java | 6 +- .../exception/MongobeeException.java | 12 +-- .../exception/MongobeeLockException.java | 6 +- .../mongobeej/utils/ChangeSetComparator.java | 12 +-- .../github/mongobeej/utils/ClassUtils.java | 36 +++---- .../com/github/mongobeej/MongobeeEnvTest.java | 1 - .../AnotherMongobeeTestResource.java | 61 ++++++------ .../EnvironmentDependentTestResource.java | 8 +- .../test/changelogs/MongobeeTestResource.java | 43 ++++---- .../test/changelogs/SpringDataChangelog.java | 10 +- .../profiles/def/UnProfiledChangeLog.java | 48 ++++----- .../profiles/dev/ProfiledDevChangeLog.java | 41 ++++---- .../utils/ChangeLogWithDuplicate.java | 24 ++--- src/test/resources/test.json | 4 +- 21 files changed, 257 insertions(+), 244 deletions(-) diff --git a/src/main/java/com/github/mongobeej/Mongobee.java b/src/main/java/com/github/mongobeej/Mongobee.java index f8dfab5..c92fb65 100644 --- a/src/main/java/com/github/mongobeej/Mongobee.java +++ b/src/main/java/com/github/mongobeej/Mongobee.java @@ -266,7 +266,7 @@ private MongoTemplate createMongoTemplate() { com.mongodb.client.MongoClient mongoClient; if (this.mongoClient != null) { mongoClient = this.mongoClient; - } else if (legacyMongoClient!= null) { + } else if (legacyMongoClient != null) { mongoClient = fromLegacyClient(); } else { mongoClient = MongoClients.create(mongoClientURI.toString()); diff --git a/src/main/java/com/github/mongobeej/changeset/ChangeEntry.java b/src/main/java/com/github/mongobeej/changeset/ChangeEntry.java index 548b654..4a78f9d 100644 --- a/src/main/java/com/github/mongobeej/changeset/ChangeEntry.java +++ b/src/main/java/com/github/mongobeej/changeset/ChangeEntry.java @@ -1,13 +1,12 @@ package com.github.mongobeej.changeset; -import java.util.Date; - import org.bson.Document; +import java.util.Date; + /** * Entry in the changes collection log {@link com.github.mongobeej.Mongobee#DEFAULT_CHANGELOG_COLLECTION_NAME} * Type: entity class. - * */ public class ChangeEntry { public static final String KEY_CHANGEID = "changeId"; diff --git a/src/main/java/com/github/mongobeej/changeset/ChangeLog.java b/src/main/java/com/github/mongobeej/changeset/ChangeLog.java index 8f33ad4..055d079 100644 --- a/src/main/java/com/github/mongobeej/changeset/ChangeLog.java +++ b/src/main/java/com/github/mongobeej/changeset/ChangeLog.java @@ -7,17 +7,19 @@ /** * Class containing particular changesets (@{@link ChangeSet}) + * * @author lstolowski - * @since 27/07/2014 * @see ChangeSet + * @since 27/07/2014 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ChangeLog { - /** - * Sequence that provide an order for changelog classes. - * If not set, then canonical name of the class is taken and sorted alphabetically, ascending. - * @return order - */ - String order() default ""; + /** + * Sequence that provide an order for changelog classes. + * If not set, then canonical name of the class is taken and sorted alphabetically, ascending. + * + * @return order + */ + String order() default ""; } diff --git a/src/main/java/com/github/mongobeej/changeset/ChangeSet.java b/src/main/java/com/github/mongobeej/changeset/ChangeSet.java index 195c63f..fdb425d 100644 --- a/src/main/java/com/github/mongobeej/changeset/ChangeSet.java +++ b/src/main/java/com/github/mongobeej/changeset/ChangeSet.java @@ -7,41 +7,46 @@ /** * Set of changes to be added to the DB. Many changesets are included in one changelog. + * * @author lstolowski - * @since 27/07/2014 * @see ChangeLog + * @since 27/07/2014 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ChangeSet { - /** - * Author of the changeset. - * Obligatory - * @return author - */ - String author(); // must be set + /** + * Author of the changeset. + * Obligatory + * + * @return author + */ + String author(); // must be set - /** - * Unique ID of the changeset. - * Obligatory - * @return unique id - */ - String id(); // must be set + /** + * Unique ID of the changeset. + * Obligatory + * + * @return unique id + */ + String id(); // must be set - /** - * Sequence that provide correct order for changesets. Sorted alphabetically, ascending. - * Obligatory. - * @return ordering - */ - String order(); // must be set + /** + * Sequence that provide correct order for changesets. Sorted alphabetically, ascending. + * Obligatory. + * + * @return ordering + */ + String order(); // must be set - /** - * Executes the change set on every mongobeej's execution, even if it has been run before. - * Optional (default is false) - * @return should run always? - */ - boolean runAlways() default false; + /** + * Executes the change set on every mongobeej's execution, even if it has been run before. + * Optional (default is false) + * + * @return should run always? + */ + boolean runAlways() default false; // // /** // * Executes the change the first time it is seen and each time the change set has been changed.
diff --git a/src/main/java/com/github/mongobeej/dao/LockDao.java b/src/main/java/com/github/mongobeej/dao/LockDao.java index 91e3c5a..850e84f 100644 --- a/src/main/java/com/github/mongobeej/dao/LockDao.java +++ b/src/main/java/com/github/mongobeej/dao/LockDao.java @@ -1,76 +1,75 @@ package com.github.mongobeej.dao; -import org.bson.Document; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.mongodb.ErrorCategory; import com.mongodb.MongoWriteException; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.IndexOptions; +import org.bson.Document; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @author colsson11 * @since 13.01.15 */ public class LockDao { - private static final Logger logger = LoggerFactory.getLogger(LockDao.class); - private static final String KEY_PROP_NAME = "key"; + private static final Logger logger = LoggerFactory.getLogger(LockDao.class); + private static final String KEY_PROP_NAME = "key"; - private static final int INDEX_SORT_ASC = 1; + private static final int INDEX_SORT_ASC = 1; - private static final String LOCK_ENTRY_KEY_VAL = "LOCK"; - private String lockCollectionName; - - public LockDao(String lockCollectionName) { - this.lockCollectionName = lockCollectionName; - } + private static final String LOCK_ENTRY_KEY_VAL = "LOCK"; + private String lockCollectionName; - public void intitializeLock(MongoDatabase db) { - createCollectionAndUniqueIndexIfNotExists(db); - } + public LockDao(String lockCollectionName) { + this.lockCollectionName = lockCollectionName; + } + + public void intitializeLock(MongoDatabase db) { + createCollectionAndUniqueIndexIfNotExists(db); + } - private void createCollectionAndUniqueIndexIfNotExists(MongoDatabase db) { - Document indexKeys = new Document(KEY_PROP_NAME, INDEX_SORT_ASC); - IndexOptions indexOptions = new IndexOptions().unique(true).name("mongobeelock_key_idx"); + private void createCollectionAndUniqueIndexIfNotExists(MongoDatabase db) { + Document indexKeys = new Document(KEY_PROP_NAME, INDEX_SORT_ASC); + IndexOptions indexOptions = new IndexOptions().unique(true).name("mongobeelock_key_idx"); - db.getCollection(lockCollectionName).createIndex(indexKeys, indexOptions); - } + db.getCollection(lockCollectionName).createIndex(indexKeys, indexOptions); + } - public boolean acquireLock(MongoDatabase db) { + public boolean acquireLock(MongoDatabase db) { - Document insertObj = new Document(KEY_PROP_NAME, LOCK_ENTRY_KEY_VAL).append("status", "LOCK_HELD"); + Document insertObj = new Document(KEY_PROP_NAME, LOCK_ENTRY_KEY_VAL).append("status", "LOCK_HELD"); - // acquire lock by attempting to insert the same value in the collection - if it already exists (i.e. lock held) - // there will be an exception - try { - db.getCollection(lockCollectionName).insertOne(insertObj); - } catch (MongoWriteException ex) { - if (ex.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) { - logger.warn("Duplicate key exception while acquireLock. Probably the lock has been already acquired."); - } - return false; + // acquire lock by attempting to insert the same value in the collection - if it already exists (i.e. lock held) + // there will be an exception + try { + db.getCollection(lockCollectionName).insertOne(insertObj); + } catch (MongoWriteException ex) { + if (ex.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) { + logger.warn("Duplicate key exception while acquireLock. Probably the lock has been already acquired."); + } + return false; + } + return true; } - return true; - } - public void releaseLock(MongoDatabase db) { - // release lock by deleting collection entry - db.getCollection(lockCollectionName).deleteMany(new Document(KEY_PROP_NAME, LOCK_ENTRY_KEY_VAL)); - } + public void releaseLock(MongoDatabase db) { + // release lock by deleting collection entry + db.getCollection(lockCollectionName).deleteMany(new Document(KEY_PROP_NAME, LOCK_ENTRY_KEY_VAL)); + } - /** - * Check if the lock is held. Could be used by external process for example. - * - * @param db MongoDatabase object - * @return true if the lock is currently held - */ - public boolean isLockHeld(MongoDatabase db) { - return db.getCollection(lockCollectionName).count() == 1; - } + /** + * Check if the lock is held. Could be used by external process for example. + * + * @param db MongoDatabase object + * @return true if the lock is currently held + */ + public boolean isLockHeld(MongoDatabase db) { + return db.getCollection(lockCollectionName).count() == 1; + } - public void setLockCollectionName(String lockCollectionName) { - this.lockCollectionName = lockCollectionName; - } + public void setLockCollectionName(String lockCollectionName) { + this.lockCollectionName = lockCollectionName; + } } diff --git a/src/main/java/com/github/mongobeej/exception/MongobeeChangeSetException.java b/src/main/java/com/github/mongobeej/exception/MongobeeChangeSetException.java index 064490b..1f3b693 100644 --- a/src/main/java/com/github/mongobeej/exception/MongobeeChangeSetException.java +++ b/src/main/java/com/github/mongobeej/exception/MongobeeChangeSetException.java @@ -5,7 +5,7 @@ * @since 27/07/2014 */ public class MongobeeChangeSetException extends MongobeeException { - public MongobeeChangeSetException(String message) { - super(message); - } + public MongobeeChangeSetException(String message) { + super(message); + } } diff --git a/src/main/java/com/github/mongobeej/exception/MongobeeConfigurationException.java b/src/main/java/com/github/mongobeej/exception/MongobeeConfigurationException.java index 3aa42ef..3fe5ea93 100644 --- a/src/main/java/com/github/mongobeej/exception/MongobeeConfigurationException.java +++ b/src/main/java/com/github/mongobeej/exception/MongobeeConfigurationException.java @@ -5,7 +5,7 @@ * @since 01.08.14 */ public class MongobeeConfigurationException extends MongobeeException { - public MongobeeConfigurationException(String message) { - super(message); - } + public MongobeeConfigurationException(String message) { + super(message); + } } diff --git a/src/main/java/com/github/mongobeej/exception/MongobeeConnectionException.java b/src/main/java/com/github/mongobeej/exception/MongobeeConnectionException.java index 3ad01f3..89d82ae 100644 --- a/src/main/java/com/github/mongobeej/exception/MongobeeConnectionException.java +++ b/src/main/java/com/github/mongobeej/exception/MongobeeConnectionException.java @@ -7,7 +7,7 @@ * @since 27/07/2014 */ public class MongobeeConnectionException extends MongobeeException { - public MongobeeConnectionException(String message, Exception baseException) { - super(message, baseException); - } + public MongobeeConnectionException(String message, Exception baseException) { + super(message, baseException); + } } diff --git a/src/main/java/com/github/mongobeej/exception/MongobeeException.java b/src/main/java/com/github/mongobeej/exception/MongobeeException.java index 60f61e8..1743f42 100644 --- a/src/main/java/com/github/mongobeej/exception/MongobeeException.java +++ b/src/main/java/com/github/mongobeej/exception/MongobeeException.java @@ -4,11 +4,11 @@ * @author abelski */ public class MongobeeException extends Exception { - public MongobeeException(String message) { - super(message); - } + public MongobeeException(String message) { + super(message); + } - public MongobeeException(String message, Throwable cause) { - super(message, cause); - } + public MongobeeException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/src/main/java/com/github/mongobeej/exception/MongobeeLockException.java b/src/main/java/com/github/mongobeej/exception/MongobeeLockException.java index 4fa4afd..a317da6 100644 --- a/src/main/java/com/github/mongobeej/exception/MongobeeLockException.java +++ b/src/main/java/com/github/mongobeej/exception/MongobeeLockException.java @@ -4,7 +4,7 @@ * Error while can not obtain process lock */ public class MongobeeLockException extends MongobeeException { - public MongobeeLockException(String message) { - super(message); - } + public MongobeeLockException(String message) { + super(message); + } } diff --git a/src/main/java/com/github/mongobeej/utils/ChangeSetComparator.java b/src/main/java/com/github/mongobeej/utils/ChangeSetComparator.java index 80e1ddf..34a71c4 100644 --- a/src/main/java/com/github/mongobeej/utils/ChangeSetComparator.java +++ b/src/main/java/com/github/mongobeej/utils/ChangeSetComparator.java @@ -7,10 +7,10 @@ import java.util.Comparator; class ChangeSetComparator implements Comparator, Serializable { - @Override - public int compare(Method left, Method right) { - ChangeSet leftChangeSet = left.getAnnotation(ChangeSet.class); - ChangeSet rightChangeSet = right.getAnnotation(ChangeSet.class); - return leftChangeSet.order().compareTo(rightChangeSet.order()); - } + @Override + public int compare(Method left, Method right) { + ChangeSet leftChangeSet = left.getAnnotation(ChangeSet.class); + ChangeSet rightChangeSet = right.getAnnotation(ChangeSet.class); + return leftChangeSet.order().compareTo(rightChangeSet.order()); + } } diff --git a/src/main/java/com/github/mongobeej/utils/ClassUtils.java b/src/main/java/com/github/mongobeej/utils/ClassUtils.java index d035bfb..1477a62 100644 --- a/src/main/java/com/github/mongobeej/utils/ClassUtils.java +++ b/src/main/java/com/github/mongobeej/utils/ClassUtils.java @@ -20,24 +20,24 @@ */ class ClassUtils { - /** - * Determine whether the {@link Class} identified by the supplied name is present - * and can be loaded. Will return {@code false} if either the class or - * one of its dependencies is not present or cannot be loaded. - * @param className the name of the class to check - * @param classLoader the class loader to use - * (may be {@code null}, which indicates the default class loader) - * @return whether the specified class is present - */ - static boolean isPresent(String className, ClassLoader classLoader) { - try { - Class.forName(className); - return true; + /** + * Determine whether the {@link Class} identified by the supplied name is present + * and can be loaded. Will return {@code false} if either the class or + * one of its dependencies is not present or cannot be loaded. + * + * @param className the name of the class to check + * @param classLoader the class loader to use + * (may be {@code null}, which indicates the default class loader) + * @return whether the specified class is present + */ + static boolean isPresent(String className, ClassLoader classLoader) { + try { + Class.forName(className); + return true; + } catch (Throwable ex) { + // Class or one of its dependencies is not present... + return false; + } } - catch (Throwable ex) { - // Class or one of its dependencies is not present... - return false; - } - } } diff --git a/src/test/java/com/github/mongobeej/MongobeeEnvTest.java b/src/test/java/com/github/mongobeej/MongobeeEnvTest.java index e924e8a..9bab574 100644 --- a/src/test/java/com/github/mongobeej/MongobeeEnvTest.java +++ b/src/test/java/com/github/mongobeej/MongobeeEnvTest.java @@ -3,7 +3,6 @@ import com.github.mongobeej.changeset.ChangeEntry; import com.github.mongobeej.resources.EnvironmentMock; import com.github.mongobeej.test.changelogs.EnvironmentDependentTestResource; -import org.bson.Document; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; diff --git a/src/test/java/com/github/mongobeej/test/changelogs/AnotherMongobeeTestResource.java b/src/test/java/com/github/mongobeej/test/changelogs/AnotherMongobeeTestResource.java index bbd49c9..d6465bf 100644 --- a/src/test/java/com/github/mongobeej/test/changelogs/AnotherMongobeeTestResource.java +++ b/src/test/java/com/github/mongobeej/test/changelogs/AnotherMongobeeTestResource.java @@ -1,10 +1,10 @@ package com.github.mongobeej.test.changelogs; import com.github.mongobeej.changeset.ChangeLog; -import com.mongodb.DB; -import org.jongo.Jongo; import com.github.mongobeej.changeset.ChangeSet; +import com.mongodb.DB; import com.mongodb.client.MongoDatabase; +import org.jongo.Jongo; /** * @author lstolowski @@ -13,33 +13,34 @@ @ChangeLog(order = "2") public class AnotherMongobeeTestResource { - @ChangeSet(author = "testuser", id = "Btest1", order = "01") - public void testChangeSet(){ - System.out.println("invoked B1"); - } - @ChangeSet(author = "testuser", id = "Btest2", order = "02") - public void testChangeSet2(){ - System.out.println("invoked B2"); - } - - @ChangeSet(author = "testuser", id = "Btest3", order = "03") - public void testChangeSet3(DB db){ - System.out.println("invoked B3 with db=" + db.toString()); - } - - @ChangeSet(author = "testuser", id = "Btest4", order = "04") - public void testChangeSet4(Jongo jongo){ - System.out.println("invoked B4 with jongo=" + jongo.toString()); - } - - @ChangeSet(author = "testuser", id = "Btest5", order = "05", runAlways = true) - public void testChangeSetWithAlways(Jongo jongo){ - System.out.println("invoked B5 with always + jongo=" + jongo.getDatabase()); - } - - @ChangeSet(author = "testuser", id = "Btest6", order = "06") - public void testChangeSet6(MongoDatabase mongoDatabase) { - System.out.println("invoked B6 with db=" + mongoDatabase.toString()); - } + @ChangeSet(author = "testuser", id = "Btest1", order = "01") + public void testChangeSet() { + System.out.println("invoked B1"); + } + + @ChangeSet(author = "testuser", id = "Btest2", order = "02") + public void testChangeSet2() { + System.out.println("invoked B2"); + } + + @ChangeSet(author = "testuser", id = "Btest3", order = "03") + public void testChangeSet3(DB db) { + System.out.println("invoked B3 with db=" + db.toString()); + } + + @ChangeSet(author = "testuser", id = "Btest4", order = "04") + public void testChangeSet4(Jongo jongo) { + System.out.println("invoked B4 with jongo=" + jongo.toString()); + } + + @ChangeSet(author = "testuser", id = "Btest5", order = "05", runAlways = true) + public void testChangeSetWithAlways(Jongo jongo) { + System.out.println("invoked B5 with always + jongo=" + jongo.getDatabase()); + } + + @ChangeSet(author = "testuser", id = "Btest6", order = "06") + public void testChangeSet6(MongoDatabase mongoDatabase) { + System.out.println("invoked B6 with db=" + mongoDatabase.toString()); + } } diff --git a/src/test/java/com/github/mongobeej/test/changelogs/EnvironmentDependentTestResource.java b/src/test/java/com/github/mongobeej/test/changelogs/EnvironmentDependentTestResource.java index a2a7c45..8ef3aec 100644 --- a/src/test/java/com/github/mongobeej/test/changelogs/EnvironmentDependentTestResource.java +++ b/src/test/java/com/github/mongobeej/test/changelogs/EnvironmentDependentTestResource.java @@ -7,8 +7,8 @@ @ChangeLog(order = "3") public class EnvironmentDependentTestResource { - @ChangeSet(author = "testuser", id = "Envtest1", order = "01") - public void testChangeSet7WithEnvironment(MongoTemplate template, Environment env) { - System.out.println("invoked Envtest1 with mongotemplate=" + template.toString() + " and Environment " + env); - } + @ChangeSet(author = "testuser", id = "Envtest1", order = "01") + public void testChangeSet7WithEnvironment(MongoTemplate template, Environment env) { + System.out.println("invoked Envtest1 with mongotemplate=" + template.toString() + " and Environment " + env); + } } diff --git a/src/test/java/com/github/mongobeej/test/changelogs/MongobeeTestResource.java b/src/test/java/com/github/mongobeej/test/changelogs/MongobeeTestResource.java index 5c7135f..634ed01 100644 --- a/src/test/java/com/github/mongobeej/test/changelogs/MongobeeTestResource.java +++ b/src/test/java/com/github/mongobeej/test/changelogs/MongobeeTestResource.java @@ -1,11 +1,10 @@ package com.github.mongobeej.test.changelogs; -import org.jongo.Jongo; - import com.github.mongobeej.changeset.ChangeLog; import com.github.mongobeej.changeset.ChangeSet; import com.mongodb.DB; import com.mongodb.client.MongoDatabase; +import org.jongo.Jongo; /** * @author lstolowski @@ -14,39 +13,39 @@ @ChangeLog(order = "1") public class MongobeeTestResource { - @ChangeSet(author = "testuser", id = "test1", order = "01") - public void testChangeSet() { + @ChangeSet(author = "testuser", id = "test1", order = "01") + public void testChangeSet() { - System.out.println("invoked 1"); + System.out.println("invoked 1"); - } + } - @ChangeSet(author = "testuser", id = "test2", order = "02") - public void testChangeSet2() { + @ChangeSet(author = "testuser", id = "test2", order = "02") + public void testChangeSet2() { - System.out.println("invoked 2"); + System.out.println("invoked 2"); - } + } - @ChangeSet(author = "testuser", id = "test3", order = "03") - public void testChangeSet3(DB db) { + @ChangeSet(author = "testuser", id = "test3", order = "03") + public void testChangeSet3(DB db) { - System.out.println("invoked 3 with db=" + db.toString()); + System.out.println("invoked 3 with db=" + db.toString()); - } + } - @ChangeSet(author = "testuser", id = "test4", order = "04") - public void testChangeSet4(Jongo jongo) { + @ChangeSet(author = "testuser", id = "test4", order = "04") + public void testChangeSet4(Jongo jongo) { - System.out.println("invoked 4 with jongo=" + jongo.toString()); + System.out.println("invoked 4 with jongo=" + jongo.toString()); - } + } - @ChangeSet(author = "testuser", id = "test5", order = "05") - public void testChangeSet5(MongoDatabase mongoDatabase) { + @ChangeSet(author = "testuser", id = "test5", order = "05") + public void testChangeSet5(MongoDatabase mongoDatabase) { - System.out.println("invoked 5 with mongoDatabase=" + mongoDatabase.toString()); + System.out.println("invoked 5 with mongoDatabase=" + mongoDatabase.toString()); - } + } } diff --git a/src/test/java/com/github/mongobeej/test/changelogs/SpringDataChangelog.java b/src/test/java/com/github/mongobeej/test/changelogs/SpringDataChangelog.java index 2fa6238..b98cce2 100644 --- a/src/test/java/com/github/mongobeej/test/changelogs/SpringDataChangelog.java +++ b/src/test/java/com/github/mongobeej/test/changelogs/SpringDataChangelog.java @@ -9,9 +9,9 @@ */ @ChangeLog public class SpringDataChangelog { - @ChangeSet(author = "abelski", id = "spring_test4", order = "04") - public void testChangeSet(MongoTemplate mongoTemplate) { - System.out.println("invoked with mongoTemplate=" + mongoTemplate.toString()); - System.out.println("invoked with mongoTemplate=" + mongoTemplate.getCollectionNames()); - } + @ChangeSet(author = "abelski", id = "spring_test4", order = "04") + public void testChangeSet(MongoTemplate mongoTemplate) { + System.out.println("invoked with mongoTemplate=" + mongoTemplate.toString()); + System.out.println("invoked with mongoTemplate=" + mongoTemplate.getCollectionNames()); + } } diff --git a/src/test/java/com/github/mongobeej/test/profiles/def/UnProfiledChangeLog.java b/src/test/java/com/github/mongobeej/test/profiles/def/UnProfiledChangeLog.java index 03893d2..5212f7f 100644 --- a/src/test/java/com/github/mongobeej/test/profiles/def/UnProfiledChangeLog.java +++ b/src/test/java/com/github/mongobeej/test/profiles/def/UnProfiledChangeLog.java @@ -10,26 +10,30 @@ */ @ChangeLog public class UnProfiledChangeLog { - @ChangeSet(author = "testuser", id = "Pdev1", order = "01") - public void testChangeSet(){ - System.out.println("invoked Pdev1"); - } - @ChangeSet(author = "testuser", id = "Pdev2", order = "02") - public void testChangeSet2(){ - System.out.println("invoked Pdev2"); - } - @ChangeSet(author = "testuser", id = "Pdev3", order = "03") - public void testChangeSet3(){ - System.out.println("invoked Pdev3"); - } - @ChangeSet(author = "testuser", id = "Pdev4", order = "04") - @Profile("pro") - public void testChangeSet4(){ - System.out.println("invoked Pdev4"); - } - @ChangeSet(author = "testuser", id = "Pdev5", order = "05") - @Profile("!pro") - public void testChangeSet5() { - System.out.println("invoked Pdev5"); - } + @ChangeSet(author = "testuser", id = "Pdev1", order = "01") + public void testChangeSet() { + System.out.println("invoked Pdev1"); + } + + @ChangeSet(author = "testuser", id = "Pdev2", order = "02") + public void testChangeSet2() { + System.out.println("invoked Pdev2"); + } + + @ChangeSet(author = "testuser", id = "Pdev3", order = "03") + public void testChangeSet3() { + System.out.println("invoked Pdev3"); + } + + @ChangeSet(author = "testuser", id = "Pdev4", order = "04") + @Profile("pro") + public void testChangeSet4() { + System.out.println("invoked Pdev4"); + } + + @ChangeSet(author = "testuser", id = "Pdev5", order = "05") + @Profile("!pro") + public void testChangeSet5() { + System.out.println("invoked Pdev5"); + } } diff --git a/src/test/java/com/github/mongobeej/test/profiles/dev/ProfiledDevChangeLog.java b/src/test/java/com/github/mongobeej/test/profiles/dev/ProfiledDevChangeLog.java index 88d217e..7e1aadf 100644 --- a/src/test/java/com/github/mongobeej/test/profiles/dev/ProfiledDevChangeLog.java +++ b/src/test/java/com/github/mongobeej/test/profiles/dev/ProfiledDevChangeLog.java @@ -12,24 +12,27 @@ @Profile(value = "dev") public class ProfiledDevChangeLog { - @ChangeSet(author = "testuser", id = "Pdev1", order = "01") - public void testChangeSet(){ - System.out.println("invoked Pdev1"); - } - @ChangeSet(author = "testuser", id = "Pdev2", order = "02") - @Profile("pro") - public void testChangeSet2(){ - System.out.println("invoked Pdev2"); - } - @ChangeSet(author = "testuser", id = "Pdev3", order = "03") - @Profile("default") - public void testChangeSet3(){ - System.out.println("invoked Pdev3"); - } - @ChangeSet(author = "testuser", id = "Pdev4", order = "04") - @Profile("dev") - public void testChangeSet4(){ - System.out.println("invoked Pdev4"); - } + @ChangeSet(author = "testuser", id = "Pdev1", order = "01") + public void testChangeSet() { + System.out.println("invoked Pdev1"); + } + + @ChangeSet(author = "testuser", id = "Pdev2", order = "02") + @Profile("pro") + public void testChangeSet2() { + System.out.println("invoked Pdev2"); + } + + @ChangeSet(author = "testuser", id = "Pdev3", order = "03") + @Profile("default") + public void testChangeSet3() { + System.out.println("invoked Pdev3"); + } + + @ChangeSet(author = "testuser", id = "Pdev4", order = "04") + @Profile("dev") + public void testChangeSet4() { + System.out.println("invoked Pdev4"); + } } diff --git a/src/test/java/com/github/mongobeej/utils/ChangeLogWithDuplicate.java b/src/test/java/com/github/mongobeej/utils/ChangeLogWithDuplicate.java index 98cee93..116f8e1 100644 --- a/src/test/java/com/github/mongobeej/utils/ChangeLogWithDuplicate.java +++ b/src/test/java/com/github/mongobeej/utils/ChangeLogWithDuplicate.java @@ -5,18 +5,18 @@ @ChangeLog public class ChangeLogWithDuplicate { - @ChangeSet(author = "testuser", id = "Btest1", order = "01") - public void testChangeSet() { - System.out.println("invoked B1"); - } + @ChangeSet(author = "testuser", id = "Btest1", order = "01") + public void testChangeSet() { + System.out.println("invoked B1"); + } - @ChangeSet(author = "testuser", id = "Btest2", order = "02") - public void testChangeSet2() { - System.out.println("invoked B2"); - } + @ChangeSet(author = "testuser", id = "Btest2", order = "02") + public void testChangeSet2() { + System.out.println("invoked B2"); + } - @ChangeSet(author = "testuser", id = "Btest2", order = "03") - public void testChangeSet3() { - System.out.println("invoked B3"); - } + @ChangeSet(author = "testuser", id = "Btest2", order = "03") + public void testChangeSet3() { + System.out.println("invoked B3"); + } } diff --git a/src/test/resources/test.json b/src/test/resources/test.json index 69da3ec..3beeaad 100644 --- a/src/test/resources/test.json +++ b/src/test/resources/test.json @@ -1 +1,3 @@ -{"test":"test"} \ No newline at end of file +{ + "test": "test" +} \ No newline at end of file From 4ef9e71dc709b981acec00740106c732a9936042 Mon Sep 17 00:00:00 2001 From: Pawel Nowak Date: Wed, 5 Aug 2020 21:53:30 +0200 Subject: [PATCH 3/4] upgrade version --- pom.xml | 2 +- src/main/java/com/github/mongobeej/Mongobee.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 4e010fc..d1f09cb 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ com.github.cybuch mongobeej - 0.17 + 0.18-SNAPSHOT diff --git a/src/main/java/com/github/mongobeej/Mongobee.java b/src/main/java/com/github/mongobeej/Mongobee.java index c92fb65..3938fc3 100644 --- a/src/main/java/com/github/mongobeej/Mongobee.java +++ b/src/main/java/com/github/mongobeej/Mongobee.java @@ -82,7 +82,7 @@ public Mongobee(MongoClientURI mongoClientURI) { /** *

Constructor takes db.mongodb.MongoClient object as a parameter. - *

For more details about MongoClient please see com.mongodb.MongoClient docs + *

For more details about {@link MongoClient} please see com.mongodb.MongoClient docs *

* * @param legacyMongoClient database connection client @@ -124,7 +124,7 @@ public Mongobee(String mongoURI) { /** *

Constructor takes db.mongodb.client.MongoClient object as a parameter. - *

For more details about MongoClient please see com.mongodb.client.MongoClient docs + *

For more details about {@link com.mongodb.client.MongoClient} please see com.mongodb.client.MongoClient docs *

* * @param mongoClient database connection client From c21834ca2414ef01cafc8fb42e8fb1614f652bf6 Mon Sep 17 00:00:00 2001 From: Pawel Nowak Date: Sat, 8 Aug 2020 10:19:31 +0200 Subject: [PATCH 4/4] delete jongo and com.mongodb.DB support --- README.md | 61 +++++++++---------- pom.xml | 9 +-- .../java/com/github/mongobeej/Mongobee.java | 42 +++---------- .../github/mongobeej/dao/ChangeEntryDao.java | 42 +++++++------ .../github/mongobeej/MongobeeBaseTest.java | 5 ++ .../github/mongobeej/MongobeeProfileTest.java | 3 +- .../com/github/mongobeej/MongobeeTest.java | 32 +++------- .../AnotherMongobeeTestResource.java | 21 ++----- .../test/changelogs/MongobeeTestResource.java | 22 +------ .../mongobeej/utils/ChangeServiceTest.java | 4 +- 10 files changed, 88 insertions(+), 153 deletions(-) diff --git a/README.md b/README.md index 5c0a176..405e965 100644 --- a/README.md +++ b/README.md @@ -20,12 +20,12 @@ With Maven com.github.cybuch mongobeej - 0.17 + 1.0.0 ``` With Gradle ```groovy -compile 'com.github.cybuch:mongobeej:0.17' +compile 'com.github.cybuch:mongobeej:1.0.0' ``` ### Migrating from Mongobee @@ -38,9 +38,22 @@ In this case the migration process will be executed automatically on startup. ```java @Bean -public Mongobee mongobee(){ +public Mongobee mongobee() { Mongobee runner = new Mongobee("mongodb://YOUR_DB_HOST:27017/DB_NAME"); - runner.setDbName("yourDbName"); // host must be set if not set in URI + runner.setDbName("yourDbName"); // db name must be set if not set in URI + runner.setChangeLogsScanPackage( + "com.example.yourapp.changelogs"); // the package to be scanned for changesets + return runner; +} +``` + +or + +```java +@Bean +public Mongobee mongobee(MongoClient mongoClient) { + Mongobee runner = new MongobeemongoClient); + runner.setDbName("yourDbName"); // db name must be set runner.setChangeLogsScanPackage( "com.example.yourapp.changelogs"); // the package to be scanned for changesets return runner; @@ -53,7 +66,7 @@ Using mongobee without a spring context has similar configuration but you have t ```java Mongobee runner = new Mongobee("mongodb://YOUR_DB_HOST:27017/DB_NAME"); -runner.setDbName("yourDbName"); // host must be set if not set in URI +runner.setDbName("yourDbName"); // db name must be set if not set in URI runner.setChangeLogsScanPackage( "com.example.yourapp.changelogs"); // package to scan for changesets runner.execute(); // ------> starts migration changesets @@ -71,7 +84,7 @@ MongoDB URI format: ``` mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database[.collection]][?options]] ``` -[More about URI](http://mongodb.github.io/mongo-java-driver/3.5/javadoc/) +[More about URI](https://docs.mongodb.com/manual/reference/connection-string/) ### Creating change logs @@ -85,7 +98,7 @@ package com.example.yourapp.changelogs; public class DatabaseChangelog { @ChangeSet(order = "001", id = "someChangeId", author = "testAuthor") - public void importantWorkToDo(DB db){ + public void importantWorkToDo(MongoTemplate mongoTemplate) { // task implementation } } @@ -134,34 +147,16 @@ public void someChange2(MongoDatabase db) { mycollection.insertOne(doc); } -@ChangeSet(order = "003", id = "someChangeWithDb", author = "testAuthor") -public void someChange3(DB db) { - // This is deprecated in mongo-java-driver 3.x, use MongoDatabase instead - // type: com.mongodb.DB : original MongoDB driver v. 2.x, operations allowed by driver are possible - // example: - DBCollection mycollection = db.getCollection("mycollection"); - BasicDBObject doc = new BasicDBObject().append("test", "1"); - mycollection .insert(doc); -} - -@ChangeSet(order = "004", id = "someChangeWithJongo", author = "testAuthor") -public void someChange4(Jongo jongo) { - // type: org.jongo.Jongo : Jongo driver can be used, used for simpler notation - // example: - MongoCollection mycollection = jongo.getCollection("mycollection"); - mycollection.insert("{test : 1}"); -} - -@ChangeSet(order = "005", id = "someChangeWithSpringDataTemplate", author = "testAuthor") -public void someChange5(MongoTemplate mongoTemplate) { +@ChangeSet(order = "003", id = "someChangeWithSpringDataTemplate", author = "testAuthor") +public void someChange3(MongoTemplate mongoTemplate) { // type: org.springframework.data.mongodb.core.MongoTemplate // Spring Data integration allows using MongoTemplate in the ChangeSet // example: mongoTemplate.save(myEntity); } -@ChangeSet(order = "006", id = "someChangeWithSpringDataTemplate", author = "testAuthor") -public void someChange5(MongoTemplate mongoTemplate, Environment environment) { +@ChangeSet(order = "004", id = "someChangeWithSpringDataTemplate", author = "testAuthor") +public void someChange4(MongoTemplate mongoTemplate, Environment environment) { // type: org.springframework.data.mongodb.core.MongoTemplate // type: org.springframework.core.env.Environment // Spring Data integration allows using MongoTemplate and Environment in the ChangeSet @@ -177,7 +172,7 @@ _Example 1_: annotated change set will be invoked for a `dev` profile ```java @Profile("dev") @ChangeSet(author = "testuser", id = "myDevChangest", order = "01") -public void devEnvOnly(DB db){ +public void devEnvOnly(MongoTemplate mongoTemplate) { // ... } ``` @@ -187,7 +182,7 @@ _Example 2_: all change sets in a changelog will be invoked for a `test` profile @Profile("test") public class ChangelogForTestEnv{ @ChangeSet(author = "testuser", id = "myTestChangest", order = "01") - public void testingEnvOnly(DB db){ + public void testingEnvOnly(MongoTemplate mongoTemplate) { // ... } } @@ -226,13 +221,13 @@ You can exclude mongo-java-driver from **mongobeeJ** and use your dependency on org.mongodb mongo-java-driver - 3.0.0 + 3.12.7 com.github.mongobeej mongobeej - 0.17 + 1.0.0 org.mongodb diff --git a/pom.xml b/pom.xml index d1f09cb..516c548 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ com.github.cybuch mongobeej - 0.18-SNAPSHOT + 1.0.0 @@ -54,7 +54,7 @@ org.mongodb mongo-java-driver - 3.9.1 + 3.12.7 org.springframework @@ -71,11 +71,6 @@ reflections 0.9.11 - - org.jongo - jongo - 1.4.0 - org.springframework.data spring-data-mongodb diff --git a/src/main/java/com/github/mongobeej/Mongobee.java b/src/main/java/com/github/mongobeej/Mongobee.java index 3938fc3..5b37178 100644 --- a/src/main/java/com/github/mongobeej/Mongobee.java +++ b/src/main/java/com/github/mongobeej/Mongobee.java @@ -7,10 +7,12 @@ import com.github.mongobeej.exception.MongobeeConnectionException; import com.github.mongobeej.exception.MongobeeException; import com.github.mongobeej.utils.ChangeService; -import com.mongodb.*; +import com.mongodb.MongoClient; +import com.mongodb.MongoClientOptions; +import com.mongodb.MongoClientSettings; +import com.mongodb.MongoClientURI; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; -import org.jongo.Jongo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; @@ -41,9 +43,7 @@ public class Mongobee implements InitializingBean { private static final long DEFAULT_CHANGE_LOG_LOCK_WAIT_TIME = 5L; private static final long DEFAULT_CHANGE_LOG_LOCK_POLL_RATE = 10L; private static final boolean DEFAULT_THROW_EXCEPTION_IF_CANNOT_OBTAIN_LOCK = false; - private ChangeEntryDao dao; - private boolean enabled = true; private String changeLogsScanPackage; private MongoClientURI mongoClientURI; @@ -51,9 +51,7 @@ public class Mongobee implements InitializingBean { private com.mongodb.client.MongoClient mongoClient; private String dbName; private Environment springEnvironment; - private MongoTemplate mongoTemplate; - private Jongo jongo; /** @@ -159,7 +157,9 @@ public void execute() throws MongobeeException { validateConfig(); - if (this.legacyMongoClient != null) { + if (mongoClient != null) { + dao.connectMongoDb(mongoClient, dbName); + } else if (this.legacyMongoClient != null) { dao.connectMongoDb(this.legacyMongoClient, dbName); } else { dao.connectMongoDb(this.mongoClientURI, dbName); @@ -188,7 +188,7 @@ private void executeMigration() throws MongobeeConnectionException, MongobeeExce for (Class changelogClass : service.fetchChangeLogs()) { - Object changelogInstance = null; + Object changelogInstance; try { changelogInstance = changelogClass.getConstructor().newInstance(); List changesetMethods = service.fetchChangeSets(changelogInstance.getClass()); @@ -198,11 +198,11 @@ private void executeMigration() throws MongobeeConnectionException, MongobeeExce try { if (dao.isNewChange(changeEntry)) { - executeChangeSetMethod(changesetMethod, changelogInstance, dao.getDb(), dao.getMongoDatabase()); + executeChangeSetMethod(changesetMethod, changelogInstance, dao.getMongoDatabase()); dao.save(changeEntry); logger.info(changeEntry + " applied"); } else if (service.isRunAlwaysChangeSet(changesetMethod)) { - executeChangeSetMethod(changesetMethod, changelogInstance, dao.getDb(), dao.getMongoDatabase()); + executeChangeSetMethod(changesetMethod, changelogInstance, dao.getMongoDatabase()); logger.info(changeEntry + " reapplied"); } else { logger.info(changeEntry + " passed over"); @@ -223,20 +223,9 @@ private void executeMigration() throws MongobeeConnectionException, MongobeeExce private Object executeChangeSetMethod( Method changeSetMethod, Object changeLogInstance, - DB db, MongoDatabase mongoDatabase ) throws IllegalAccessException, InvocationTargetException, MongobeeChangeSetException { if (changeSetMethod.getParameterTypes().length == 1 - && changeSetMethod.getParameterTypes()[0].equals(DB.class)) { - logger.debug("method with DB argument"); - - return changeSetMethod.invoke(changeLogInstance, db); - } else if (changeSetMethod.getParameterTypes().length == 1 - && changeSetMethod.getParameterTypes()[0].equals(Jongo.class)) { - logger.debug("method with Jongo argument"); - - return changeSetMethod.invoke(changeLogInstance, jongo != null ? jongo : new Jongo(db)); - } else if (changeSetMethod.getParameterTypes().length == 1 && changeSetMethod.getParameterTypes()[0].equals(MongoTemplate.class)) { logger.debug("method with MongoTemplate argument"); @@ -455,17 +444,6 @@ public Mongobee setMongoTemplate(MongoTemplate mongoTemplate) { return this; } - /** - * Sets pre-configured {@link MongoTemplate} instance to use by the Mongobee - * - * @param jongo {@link Jongo} instance - * @return Mongobee object for fluent interface - */ - public Mongobee setJongo(Jongo jongo) { - this.jongo = jongo; - return this; - } - /** * Overwrites a default mongobeej changelog collection hardcoded in DEFAULT_CHANGELOG_COLLECTION_NAME. *

diff --git a/src/main/java/com/github/mongobeej/dao/ChangeEntryDao.java b/src/main/java/com/github/mongobeej/dao/ChangeEntryDao.java index 5207fff..fcf5549 100644 --- a/src/main/java/com/github/mongobeej/dao/ChangeEntryDao.java +++ b/src/main/java/com/github/mongobeej/dao/ChangeEntryDao.java @@ -4,9 +4,9 @@ import com.github.mongobeej.exception.MongobeeConfigurationException; import com.github.mongobeej.exception.MongobeeConnectionException; import com.github.mongobeej.exception.MongobeeLockException; -import com.mongodb.DB; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; @@ -21,8 +21,8 @@ public class ChangeEntryDao { private static final Logger logger = LoggerFactory.getLogger("Mongobee dao"); private MongoDatabase mongoDatabase; - private DB db; // only for Jongo driver compatibility - do not use in other contexts - private MongoClient mongoClient; + private com.mongodb.client.MongoClient mongoClient; + private MongoClient legacyMongoClient; private ChangeEntryIndexDao indexDao; private String changelogCollectionName; private boolean waitForLock; @@ -52,24 +52,26 @@ public MongoDatabase getMongoDatabase() { return mongoDatabase; } - /** - * @return com.mongodb.DB - * @deprecated implemented only for Jongo driver compatibility and backward compatibility - do not use in other contexts - */ - public DB getDb() { - return db; + public MongoDatabase connectMongoDb(com.mongodb.client.MongoClient mongoClient, String dbName) throws MongobeeConfigurationException { + if (!hasText(dbName)) { + throw new MongobeeConfigurationException("DB name is not set. Should be defined in MongoDB URI or via setter"); + } else { + this.mongoClient = mongoClient; + mongoDatabase = mongoClient.getDatabase(dbName); + ensureChangeLogCollectionIndex(mongoDatabase.getCollection(changelogCollectionName)); + initializeLock(); + return mongoDatabase; + } } + + @Deprecated public MongoDatabase connectMongoDb(MongoClient mongo, String dbName) throws MongobeeConfigurationException { if (!hasText(dbName)) { throw new MongobeeConfigurationException("DB name is not set. Should be defined in MongoDB URI or via setter"); } else { - - this.mongoClient = mongo; - - db = mongo.getDB(dbName); // for Jongo driver and backward compatibility (constructor has required parameter Jongo(DB) ) + this.legacyMongoClient = mongo; mongoDatabase = mongo.getDatabase(dbName); - ensureChangeLogCollectionIndex(mongoDatabase.getCollection(changelogCollectionName)); initializeLock(); return mongoDatabase; @@ -77,9 +79,8 @@ public MongoDatabase connectMongoDb(MongoClient mongo, String dbName) throws Mon } public MongoDatabase connectMongoDb(MongoClientURI mongoClientURI, String dbName) - throws MongobeeConfigurationException, MongobeeConnectionException { - - final MongoClient mongoClient = new MongoClient(mongoClientURI); + throws MongobeeConfigurationException { + final com.mongodb.client.MongoClient mongoClient = MongoClients.create(mongoClientURI.toString()); final String database = (!hasText(dbName)) ? mongoClientURI.getDatabase() : dbName; return this.connectMongoDb(mongoClient, database); } @@ -166,7 +167,12 @@ private void ensureChangeLogCollectionIndex(MongoCollection collection } public void close() { - this.mongoClient.close(); + if (legacyMongoClient != null) { + legacyMongoClient.close(); + } + if (mongoClient != null) { + mongoClient.close(); + } } private void initializeLock() { diff --git a/src/test/java/com/github/mongobeej/MongobeeBaseTest.java b/src/test/java/com/github/mongobeej/MongobeeBaseTest.java index 6bdcb47..adf01ca 100644 --- a/src/test/java/com/github/mongobeej/MongobeeBaseTest.java +++ b/src/test/java/com/github/mongobeej/MongobeeBaseTest.java @@ -4,6 +4,7 @@ import com.github.mongobeej.dao.ChangeEntryDao; import com.github.mongobeej.dao.ChangeEntryIndexDao; import com.github.mongobeej.utils.MongoEnvironmentCreator; +import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoDatabase; import org.junit.Before; @@ -31,6 +32,10 @@ public void init() throws Exception { mongoDatabase = mongoEnvironment.getMongoDatabase(); when(changeEntryDao.connectMongoDb(any(MongoClientURI.class), anyString())) .thenReturn(mongoDatabase); + when(changeEntryDao.connectMongoDb(any(com.mongodb.client.MongoClient.class), anyString())) + .thenReturn(mongoDatabase); + when(changeEntryDao.connectMongoDb(any(MongoClient.class), anyString())) + .thenReturn(mongoDatabase); when(changeEntryDao.getMongoDatabase()).thenReturn(mongoDatabase); when(changeEntryDao.acquireProcessLock()).thenReturn(true); doCallRealMethod().when(changeEntryDao).save(any(ChangeEntry.class)); diff --git a/src/test/java/com/github/mongobeej/MongobeeProfileTest.java b/src/test/java/com/github/mongobeej/MongobeeProfileTest.java index a0f3887..c3930ed 100644 --- a/src/test/java/com/github/mongobeej/MongobeeProfileTest.java +++ b/src/test/java/com/github/mongobeej/MongobeeProfileTest.java @@ -18,7 +18,7 @@ @RunWith(MockitoJUnitRunner.class) public class MongobeeProfileTest extends MongobeeBaseTest { - private static final int CHANGELOG_COUNT = 13; + private static final int CHANGELOG_COUNT = 10; @Test public void shouldRunDevProfileAndNonAnnotated() throws Exception { @@ -133,6 +133,5 @@ public void shouldRunAllChangeSets() throws Exception { @After public void cleanUp() { mongobee.setMongoTemplate(null); - mongobee.setJongo(null); } } diff --git a/src/test/java/com/github/mongobeej/MongobeeTest.java b/src/test/java/com/github/mongobeej/MongobeeTest.java index 3c08a5c..ca38fe9 100644 --- a/src/test/java/com/github/mongobeej/MongobeeTest.java +++ b/src/test/java/com/github/mongobeej/MongobeeTest.java @@ -7,11 +7,10 @@ import com.github.mongobeej.exception.MongobeeException; import com.github.mongobeej.test.changelogs.MongobeeTestResource; import com.github.mongobeej.utils.MongoEnvironmentCreator.MongoEnvironment; -import com.mongodb.DB; +import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoDatabase; import org.bson.Document; -import org.jongo.Jongo; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -42,8 +41,6 @@ public class MongobeeTest { private ChangeEntryDao changeEntryDao; @Mock private ChangeEntryIndexDao indexDao; - @Mock - private DB db; private MongoDatabase mongoDatabase; @Before @@ -51,9 +48,10 @@ public void init() throws MongobeeException { mongoDatabase = mongoEnvironment.getMongoDatabase(); when(changeEntryDao.connectMongoDb(any(MongoClientURI.class), anyString())) .thenReturn(mongoDatabase); - when(changeEntryDao.getDb()).thenReturn(db); - when(db.getMongo()).thenReturn(mongoEnvironment.getMongoClient()); - when(db.getName()).thenReturn(DB_NAME); + when(changeEntryDao.connectMongoDb(any(com.mongodb.client.MongoClient.class), anyString())) + .thenReturn(mongoDatabase); + when(changeEntryDao.connectMongoDb(any(MongoClient.class), anyString())) + .thenReturn(mongoDatabase); when(changeEntryDao.getMongoDatabase()).thenReturn(mongoDatabase); doCallRealMethod().when(changeEntryDao).save(any(ChangeEntry.class)); doCallRealMethod().when(changeEntryDao).setChangelogCollectionName(anyString()); @@ -83,7 +81,7 @@ public void shouldExecuteAllChangeSets() throws Exception { mongobee.execute(); // then - verify(changeEntryDao, times(13)).save(any(ChangeEntry.class)); // 13 changesets saved to dbchangelog + verify(changeEntryDao, times(10)).save(any(ChangeEntry.class)); // 10 changesets saved to dbchangelog // dbchangelog collection checking long change1 = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME) @@ -98,12 +96,9 @@ public void shouldExecuteAllChangeSets() throws Exception { long change4 = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME) .count(changeQuery("test4")); assertEquals(1, change4); - long change5 = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME) - .count(changeQuery("test5")); - assertEquals(1, change5); long changeAll = mongoDatabase.getCollection(CHANGELOG_COLLECTION_NAME) .count(new Document().append(ChangeEntry.KEY_AUTHOR, "testuser")); - assertEquals(12, changeAll); + assertEquals(9, changeAll); } @Test @@ -129,16 +124,6 @@ public void shouldUsePreConfiguredMongoTemplate() throws Exception { verify(mt).getCollectionNames(); } - @Test - public void shouldUsePreConfiguredJongo() throws Exception { - Jongo jongo = mock(Jongo.class); - when(changeEntryDao.acquireProcessLock()).thenReturn(true); - when(jongo.getDatabase()).thenReturn(null); - mongobee.setJongo(jongo); - mongobee.afterPropertiesSet(); - verify(jongo).getDatabase(); - } - @Test public void shouldExecuteProcessWhenLockAcquired() throws Exception { // given @@ -180,6 +165,7 @@ public void shouldReturnExecutionStatusBasedOnDao() throws Exception { // given when(changeEntryDao.isProccessLockHeld()).thenReturn(true); + //when boolean inProgress = mongobee.isExecutionInProgress(); // then @@ -210,7 +196,5 @@ public void shouldReleaseLockWhenExceptionInMigration() throws Exception { @After public void cleanUp() { mongobee.setMongoTemplate(null); - mongobee.setJongo(null); } - } diff --git a/src/test/java/com/github/mongobeej/test/changelogs/AnotherMongobeeTestResource.java b/src/test/java/com/github/mongobeej/test/changelogs/AnotherMongobeeTestResource.java index d6465bf..560c1be 100644 --- a/src/test/java/com/github/mongobeej/test/changelogs/AnotherMongobeeTestResource.java +++ b/src/test/java/com/github/mongobeej/test/changelogs/AnotherMongobeeTestResource.java @@ -2,9 +2,8 @@ import com.github.mongobeej.changeset.ChangeLog; import com.github.mongobeej.changeset.ChangeSet; -import com.mongodb.DB; import com.mongodb.client.MongoDatabase; -import org.jongo.Jongo; +import org.springframework.data.mongodb.core.MongoTemplate; /** * @author lstolowski @@ -23,22 +22,12 @@ public void testChangeSet2() { System.out.println("invoked B2"); } - @ChangeSet(author = "testuser", id = "Btest3", order = "03") - public void testChangeSet3(DB db) { - System.out.println("invoked B3 with db=" + db.toString()); + @ChangeSet(author = "testuser", id = "Btest5", order = "03", runAlways = true) + public void testChangeSetWithAlways(MongoTemplate mongoTemplate) { + System.out.println("invoked B5 with always + mongoTemplate=" + mongoTemplate.toString()); } - @ChangeSet(author = "testuser", id = "Btest4", order = "04") - public void testChangeSet4(Jongo jongo) { - System.out.println("invoked B4 with jongo=" + jongo.toString()); - } - - @ChangeSet(author = "testuser", id = "Btest5", order = "05", runAlways = true) - public void testChangeSetWithAlways(Jongo jongo) { - System.out.println("invoked B5 with always + jongo=" + jongo.getDatabase()); - } - - @ChangeSet(author = "testuser", id = "Btest6", order = "06") + @ChangeSet(author = "testuser", id = "Btest6", order = "04") public void testChangeSet6(MongoDatabase mongoDatabase) { System.out.println("invoked B6 with db=" + mongoDatabase.toString()); } diff --git a/src/test/java/com/github/mongobeej/test/changelogs/MongobeeTestResource.java b/src/test/java/com/github/mongobeej/test/changelogs/MongobeeTestResource.java index 634ed01..8f850f5 100644 --- a/src/test/java/com/github/mongobeej/test/changelogs/MongobeeTestResource.java +++ b/src/test/java/com/github/mongobeej/test/changelogs/MongobeeTestResource.java @@ -2,9 +2,8 @@ import com.github.mongobeej.changeset.ChangeLog; import com.github.mongobeej.changeset.ChangeSet; -import com.mongodb.DB; import com.mongodb.client.MongoDatabase; -import org.jongo.Jongo; +import org.springframework.data.mongodb.core.MongoTemplate; /** * @author lstolowski @@ -15,37 +14,22 @@ public class MongobeeTestResource { @ChangeSet(author = "testuser", id = "test1", order = "01") public void testChangeSet() { - System.out.println("invoked 1"); - } @ChangeSet(author = "testuser", id = "test2", order = "02") public void testChangeSet2() { - System.out.println("invoked 2"); - } @ChangeSet(author = "testuser", id = "test3", order = "03") - public void testChangeSet3(DB db) { - - System.out.println("invoked 3 with db=" + db.toString()); - + public void testChangeSet4(MongoTemplate mongoTemplate) { + System.out.println("invoked 4 with mongoTemplate=" + mongoTemplate.toString()); } @ChangeSet(author = "testuser", id = "test4", order = "04") - public void testChangeSet4(Jongo jongo) { - - System.out.println("invoked 4 with jongo=" + jongo.toString()); - - } - - @ChangeSet(author = "testuser", id = "test5", order = "05") public void testChangeSet5(MongoDatabase mongoDatabase) { - System.out.println("invoked 5 with mongoDatabase=" + mongoDatabase.toString()); - } } diff --git a/src/test/java/com/github/mongobeej/utils/ChangeServiceTest.java b/src/test/java/com/github/mongobeej/utils/ChangeServiceTest.java index 14e173f..853d572 100644 --- a/src/test/java/com/github/mongobeej/utils/ChangeServiceTest.java +++ b/src/test/java/com/github/mongobeej/utils/ChangeServiceTest.java @@ -35,7 +35,7 @@ public void shouldFindChangeSetMethods() throws MongobeeChangeSetException { List foundMethods = changeService.fetchChangeSets(MongobeeTestResource.class); // then - assertTrue(foundMethods != null && foundMethods.size() == 5); + assertTrue(foundMethods != null && foundMethods.size() == 4); } @Test @@ -44,7 +44,7 @@ public void shouldFindAnotherChangeSetMethods() throws MongobeeChangeSetExceptio List foundMethods = changeService.fetchChangeSets(AnotherMongobeeTestResource.class); // then - assertTrue(foundMethods != null && foundMethods.size() == 6); + assertTrue(foundMethods != null && foundMethods.size() == 4); }