Java Code Examples for liquibase.database.Database#getConnection()

The following examples show how to use liquibase.database.Database#getConnection() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GenerateRestrictionUUIDs.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {         
      PreparedStatement getRestrictions =
         databaseConnection.prepareStatement ("SELECT ID FROM ACCESS_RESTRICTION");
      ResultSet res = getRestrictions.executeQuery ();
      while (res.next ())
      {
         String uuid = UUID.randomUUID ().toString ();
         PreparedStatement updateRestrictions =
            databaseConnection
               .prepareStatement ("UPDATE ACCESS_RESTRICTION SET UUID = '" + uuid +
                  "' WHERE ID = " + res.getObject ("ID"));
         updateRestrictions.execute ();
         updateRestrictions.close ();

         PreparedStatement updateUserRestricitons =
            databaseConnection
               .prepareStatement ("UPDATE USER_RESTRICTIONS SET RESTRICTION_UUID = '" +
                  uuid + "' WHERE RESTRICTION_ID = " + res.getObject ("ID"));
         updateUserRestricitons.execute ();
         updateUserRestricitons.close ();
      }
      getRestrictions.close ();
   }
   catch (Exception e)
   {
      e.printStackTrace ();
   }
   
}
 
Example 2
Source File: GeometryColumnsUtils.java    From liquibase-spatial with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if the given table is in <code>GEOMETRY_COLUMNS</code> and,
 * therefore, has a geometry column.
 * 
 * @param database
 *           the database to query.
 * @param schemaName
 *           the schema name.
 * @param tableName
 *           the table name to check.
 * @return <code>true</code> if the table has a geometry column.
 */
public static boolean hasGeometryColumn(final Database database,
      final String schemaName, final String tableName) {
   boolean isSpatialColumn = false;
   Statement jdbcStatement = null;
   try {
      if (geometryColumnsExists(database)) {
         final String query = "SELECT * FROM geometry_columns WHERE f_table_schema = '"
               + (schemaName == null ? database.getDefaultSchemaName()
                     : schemaName)
               + "' AND f_table_name = '"
               + tableName
               + "'";
         final DatabaseConnection databaseConnection = database
               .getConnection();
         final JdbcConnection jdbcConnection = (JdbcConnection) databaseConnection;
         jdbcStatement = jdbcConnection.getUnderlyingConnection()
               .createStatement();
         final ResultSet rs = jdbcStatement.executeQuery(query);
         isSpatialColumn = rs.next();
      }
   } catch (final SQLException e) {
      throw new UnexpectedLiquibaseException(
            "Failed to determine if the table has a geometry column", e);
   } finally {
      if (jdbcStatement != null) {
         try {
            jdbcStatement.close();
         } catch (final SQLException ignore) {
         }
      }
   }
   return isSpatialColumn;
}
 
Example 3
Source File: GeometryColumnsUtils.java    From liquibase-spatial with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if the given column is in <code>GEOMETRY_COLUMNS</code>.
 * 
 * @param database
 *           the database to query.
 * @param schemaName
 *           the schema name.
 * @param tableName
 *           the table name.
 * @param columnName
 *           the column name.
 * @return <code>true</code> if the column is a geometry column.
 */
public static boolean isGeometryColumn(final Database database,
      final String schemaName, final String tableName,
      final String columnName) {
   boolean isSpatialColumn = false;
   Statement jdbcStatement = null;
   try {
      if (geometryColumnsExists(database)) {
         final String query = "SELECT * FROM geometry_columns WHERE f_table_schema = '"
               + (schemaName == null ? database.getDefaultSchemaName()
                     : schemaName)
               + "' AND f_table_name = '"
               + tableName
               + "' AND upper(f_geometry_column) = '"
               + columnName.toUpperCase() + "'";
         final DatabaseConnection databaseConnection = database
               .getConnection();
         final JdbcConnection jdbcConnection = (JdbcConnection) databaseConnection;
         jdbcStatement = jdbcConnection.getUnderlyingConnection()
               .createStatement();
         final ResultSet rs = jdbcStatement.executeQuery(query);
         isSpatialColumn = rs.next();
      }
   } catch (final SQLException e) {
      throw new UnexpectedLiquibaseException(
            "Failed to determine if the column to be dropped is a geometry column",
            e);
   } finally {
      if (jdbcStatement != null) {
         try {
            jdbcStatement.close();
         } catch (final SQLException ignore) {
         }
      }
   }
   return isSpatialColumn;
}
 
Example 4
Source File: PTOnlineSchemaChangeStatement.java    From liquibase-percona with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the command line arguments that will be executed.
 * @param database the database - needed to get the connection info.
 * @return the command line arguments including {@link #COMMAND}
 */
List<String> buildCommand(Database database) {
    List<String> commands = new ArrayList<String>();
    commands.add(getFullToolkitPath());

    // must be the first on the command line, otherwise "--config" cannot be used
    if (!Configuration.getAdditionalOptions().isEmpty()) {
        commands.addAll(tokenize(Configuration.getAdditionalOptions()));
    }

    commands.add("--alter=" + alterStatement);

    if (database.getConnection() != null) {
        DatabaseConnectionUtil connection = new DatabaseConnectionUtil(database.getConnection());
        commands.add("--host=" + connection.getHost());
        commands.add("--port=" + connection.getPort());
        commands.add("--user=" + connection.getUser());
        String pw = connection.getPassword();
        if (pw != null) {
            commands.add("--password=" + pw);
        }
    }

    commands.add("--execute");
    if (databaseName != null) {
        commands.add("D=" + databaseName + ",t=" + tableName);
    } else {
        commands.add("D=" + database.getLiquibaseSchemaName() + ",t=" + tableName);
    }
    return commands;
}
 
Example 5
Source File: PerconaChangeUtil.java    From liquibase-percona with Apache License 2.0 5 votes vote down vote up
public static boolean isConnected(Database database) {
    try {
        if (database.getConnection() != null) {
            return !database.getConnection().isClosed();
        }
        return false;
    } catch (DatabaseException e) {
        return false;
    }
}
 
Example 6
Source File: CustomKeycloakTask.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public SqlStatement[] generateStatements(Database database) throws CustomChangeException {
    this.database = database;
    jdbcConnection = (JdbcConnection) database.getConnection();
    connection = jdbcConnection.getWrappedConnection();

    if (isApplicable()) {
        confirmationMessage.append(getTaskId() + ": ");
        generateStatementsImpl();
    } else {
        confirmationMessage.append(getTaskId() + ": no update applicable for this task");
    }

    return statements.toArray(new SqlStatement[statements.size()]);
}
 
Example 7
Source File: MoveOwnerInProduct.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {
      PreparedStatement getOwners =
         databaseConnection
            .prepareStatement ("SELECT o.USER_ID, p.ID FROM OWNER o, " +
                  "PRODUCTS p WHERE o.OWNEROFPRODUCT = p.IDENTIFIER");
      ResultSet res = getOwners.executeQuery ();

      while (res.next ())
      {
         Long productIdentifier = (Long) res.getObject ("ID");   
         Long userIdentifier = (Long) res.getObject ("USER_ID");  
         PreparedStatement updateOwner =
            databaseConnection
               .prepareStatement ("UPDATE PRODUCTS SET OWNER_ID = " +
                     userIdentifier+" WHERE ID = "+productIdentifier);
         updateOwner.execute ();
         updateOwner.close();
      }
      getOwners.close ();
   }
   catch (Exception e)
   {
      LOGGER.error("Error during liquibase update 'MoveOwnerInProduct'", e);
   }
}
 
Example 8
Source File: GenerateCartUUIDs.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {         
      PreparedStatement getCarts =
         databaseConnection.prepareStatement ("SELECT ID FROM PRODUCTCARTS");
      ResultSet res = getCarts.executeQuery ();
      while (res.next ())
      {
         String uuid = UUID.randomUUID ().toString ();
         PreparedStatement updateCart =
            databaseConnection
               .prepareStatement ("UPDATE PRODUCTCARTS SET UUID = '" + uuid +
                  "' WHERE ID = " + res.getObject ("ID"));
         updateCart.execute ();
         updateCart.close ();

         PreparedStatement updateProductsLink =
            databaseConnection
               .prepareStatement ("UPDATE CART_PRODUCTS SET CART_UUID = '" +
                  uuid + "' WHERE CART_ID = " + res.getObject ("ID"));
         updateProductsLink.execute ();
         updateProductsLink.close ();
      }
      getCarts.close ();
   }
   catch (Exception e)
   {
      e.printStackTrace ();
   }
   
}
 
Example 9
Source File: RemoveLFUStrategy.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {
      PreparedStatement getEvictions =
         databaseConnection
            .prepareStatement ("SELECT ID,STRATEGY FROM EVICTION");
      ResultSet res = getEvictions.executeQuery ();
      
      while (res.next ())
      {
         Integer strategy = (Integer) res.getObject ("STRATEGY");
         if (strategy == 2)
         {
            // 2 (old LFU) -> 0 (None)
            strategy = 0;
         }
         if (strategy == 3)
         {
            // 3 (old FIFO) -> 2 (new FIFO)
            strategy = 2;
         }
         PreparedStatement updateStrategy =
            databaseConnection
               .prepareStatement ("UPDATE EVICTION SET STRATEGY = '" +
                     strategy+"' WHERE ID = "+res.getObject ("ID"));
         updateStrategy.execute ();
         updateStrategy.close ();
      }
      getEvictions.close ();         
   }
   catch (Exception e)
   {
      LOGGER.error("Error during liquibase update 'removeLFUStrategy'", e);
   }
}
 
Example 10
Source File: GenerateSearchUUIDs.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {         
      PreparedStatement getSearches =
         databaseConnection.prepareStatement ("SELECT ID FROM SEARCHES");
      ResultSet res = getSearches.executeQuery ();
      while (res.next ())
      {
         String uuid = UUID.randomUUID ().toString ();
         PreparedStatement updateSearch =
            databaseConnection
               .prepareStatement ("UPDATE SEARCHES SET UUID = '" + uuid +
                  "' WHERE ID = " + res.getObject ("ID"));
         updateSearch.execute ();
         updateSearch.close ();

         PreparedStatement updateAdvanced =
            databaseConnection
               .prepareStatement ("UPDATE SEARCH_ADVANCED SET SEARCH_UUID = '" +
                  uuid + "' WHERE SEARCH_ID = " + res.getObject ("ID"));
         updateAdvanced.execute ();
         updateAdvanced.close ();

         PreparedStatement updatePreferences =
            databaseConnection
               .prepareStatement ("UPDATE SEARCH_PREFERENCES SET SEARCHES_UUID = '" +
                  uuid + "' WHERE SEARCHES_ID = " + res.getObject ("ID"));
         updatePreferences.execute ();
         updatePreferences.close ();
      }
      getSearches.close ();
   }
   catch (Exception e)
   {
      e.printStackTrace ();
   }
   
}
 
Example 11
Source File: GeneratePreferenceUUIDs.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {         
      PreparedStatement getPreferences =
         databaseConnection.prepareStatement ("SELECT ID FROM PREFERENCES");
      ResultSet res = getPreferences.executeQuery ();
      while (res.next ())
      {
         String uuid = UUID.randomUUID ().toString ();
         PreparedStatement updatePreferences =
            databaseConnection
               .prepareStatement ("UPDATE PREFERENCES SET UUID = '" + uuid +
                  "' WHERE ID = " + res.getObject ("ID"));
         updatePreferences.execute ();
         updatePreferences.close ();

         PreparedStatement updateUsers =
            databaseConnection
               .prepareStatement ("UPDATE USERS SET PREFERENCES_UUID = '" +
                  uuid + "' WHERE PREFERENCES_ID = " + res.getObject ("ID"));
         updateUsers.execute ();
         updateUsers.close ();

         PreparedStatement updateFilescanner =
            databaseConnection
               .prepareStatement ("UPDATE FILE_SCANNER_PREFERENCES SET PREFERENCE_UUID = '" +
                  uuid + "' WHERE PREFERENCE_ID = " + res.getObject ("ID"));
         updateFilescanner.execute ();
         updateFilescanner.close ();
         
         PreparedStatement updateSearches =
            databaseConnection
               .prepareStatement ("UPDATE SEARCH_PREFERENCES SET PREFERENCE_UUID = '" +
                  uuid + "' WHERE PREFERENCE_ID = " + res.getObject ("ID"));
         updateSearches.execute ();
         updateSearches.close ();
      }
      getPreferences.close ();
   }
   catch (Exception e)
   {
      e.printStackTrace ();
   }
   
}
 
Example 12
Source File: ForceEncryptPassword.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   try
   {
      JdbcConnection jdbc = (JdbcConnection) database.getConnection ();
      String sql;
      Statement statement;
      ResultSet resultSet;

      // Retrieve unencrypted user password
      sql = "SELECT LOGIN, PASSWORD FROM USERS " +
            "WHERE PASSWORD_ENCRYPTION = 'NONE'";
      statement = jdbc.createStatement ();
      HashMap<String, String> unencrypted_user = new HashMap<> ();
      resultSet = statement.executeQuery (sql);
      while (resultSet.next ())
      {
         unencrypted_user.put (resultSet.getString ("LOGIN"),
               resultSet.getString ("PASSWORD"));
      }
      resultSet.close ();
      statement.close ();

      // Encrypt user password and update user
      MessageDigest md = MessageDigest.getInstance ("MD5");
      sql = "UPDATE USERS SET PASSWORD_ENCRYPTION = 'MD5', PASSWORD = '%s'" +
            " WHERE LOGIN = '%s'";
      String query;
      String password;
      for (String login : unencrypted_user.keySet ())
      {
         password = unencrypted_user.get (login);
         password = new String (
               Hex.encode (md.digest (password.getBytes ("UTF-8"))));
         query = String.format (sql, password, login);
         statement = jdbc.createStatement ();
         int updated =  statement.executeUpdate (query);
         if (updated != 1)
         {
            LOGGER.warn(updated + " encryption update perform on user : " + login);
         }
         statement.close ();
      }
      unencrypted_user.clear ();
   }
   catch (Exception e)
   {
      throw new CustomChangeException (
            "An error occurred during forceEncryptPassword changelog", e);
   }
}
 
Example 13
Source File: StoreProductQLAndThumbSizes.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
// contentStart contentEnd ingestionDate download.size
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {
      PreparedStatement getProducts =
         databaseConnection
            .prepareStatement ("SELECT ID, QUICKLOOK_PATH, " +
                  "THUMBNAIL_PATH FROM Products");
      ResultSet res = getProducts.executeQuery ();
      while (res.next ())
      {
         Long productId = (Long) res.getObject("ID");
         String thumbnail = (String) res.getObject ("THUMBNAIL_PATH");  
         String quicklook = (String) res.getObject ("QUICKLOOK_PATH");  
         Long tbSize = null;
         Long qlSize = null;
         if (thumbnail != null)
         {
            File tbFile = new File (thumbnail);
            if (tbFile.exists ())
            {
               tbSize = tbFile.length ();
            }
         }
         if (quicklook != null)
         {
            File qlFile = new File (quicklook);
            if (qlFile.exists ())
            {
               qlSize = qlFile.length ();
            }
         }
         
         PreparedStatement updateProduct =
               databaseConnection.prepareStatement ("UPDATE PRODUCTS SET" +
                     " QUICKLOOK_SIZE = " + qlSize +
                     ", THUMBNAIL_SIZE = "+tbSize+" WHERE ID = "+productId);
         updateProduct.execute ();
         updateProduct.close();
      }
      getProducts.close ();
   }
   catch (Exception e)
   {
      LOGGER.error("Error during liquibase update " +
            "'ExtractProductDatesAndDownloadSize'", e);
   }
}
 
Example 14
Source File: FlatCollection.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   String rootName = CollectionDao.COLLECTION_ROOT_NAME;
   String rootId = "SELECT UUID FROM COLLECTIONS WHERE NAME='%s'";
   String auth = "DELETE FROM COLLECTION_USER_AUTH WHERE COLLECTIONS_UUID='%s'";
   String delete = "DELETE FROM COLLECTIONS WHERE NAME='%s'";
   try
   {
      String cid = null;
      String sql;
      PreparedStatement statement;
      JdbcConnection connection = (JdbcConnection) database.getConnection ();

      // get root collection id
      sql = String.format (rootId, rootName);
      statement = connection.prepareStatement (sql);
      statement.execute ();
      ResultSet resultSet = statement.getResultSet ();
      if (resultSet.next ())
      {
         cid = resultSet.getString (1);
      }
      statement.close ();

      if (cid != null)
      {
         // remove default authorization on root collection
         sql = String.format (auth, cid);
         statement = connection.prepareStatement (sql);
         statement.execute ();
         statement.close ();

         // delete root collection
         sql = String.format (delete, rootName);
         statement = connection.prepareStatement (sql);
         statement.execute ();
         statement.close ();
      }
   }
   catch (DatabaseException | SQLException e)
   {
      throw new CustomChangeException (e);
   }
}
 
Example 15
Source File: GenerateCollectionUUIDs.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {         
      PreparedStatement getCollections =
         databaseConnection.prepareStatement ("SELECT ID FROM COLLECTIONS");
      ResultSet res = getCollections.executeQuery ();
      while (res.next ())
      {
         String uuid = UUID.randomUUID ().toString ();
         PreparedStatement updateCollections =
            databaseConnection
               .prepareStatement ("UPDATE COLLECTIONS SET UUID = '" + uuid +
                  "' WHERE ID = " + res.getObject ("ID"));
         updateCollections.execute ();
         updateCollections.close ();
         
         PreparedStatement updateParentCollections =
            databaseConnection
               .prepareStatement ("UPDATE COLLECTIONS SET PARENT_COLLECTION_UUID = '" + uuid +
                  "' WHERE PARENT_COLLECTION_ID = " + res.getObject ("ID"));
         updateParentCollections.execute ();
         updateParentCollections.close ();

         PreparedStatement updateCollectionProducts =
            databaseConnection
               .prepareStatement ("UPDATE COLLECTION_PRODUCT SET COLLECTIONS_UUID = '" +
                  uuid + "' WHERE COLLECTIONS_ID = " + res.getObject ("ID"));
         updateCollectionProducts.execute ();
         updateCollectionProducts.close ();

         PreparedStatement updateCollectionuser =
            databaseConnection
               .prepareStatement ("UPDATE COLLECTION_USER_AUTH SET COLLECTIONS_UUID = '" +
                  uuid + "' WHERE COLLECTIONS_ID = " + res.getObject ("ID"));
         updateCollectionuser.execute ();
         updateCollectionuser.close ();
         
         PreparedStatement updateCollectionFileScanner =
            databaseConnection
               .prepareStatement ("UPDATE FILESCANNER_COLLECTIONS SET COLLECTIONS_UUID = '" +
                  uuid + "' WHERE COLLECTIONS_ID = " + res.getObject ("ID"));
         updateCollectionFileScanner.execute ();
         updateCollectionFileScanner.close ();
      }
      getCollections.close ();         
   }
   catch (Exception e)
   {
      e.printStackTrace ();
   }
   
}
 
Example 16
Source File: RemoveDuplicateRoles.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   String searchDuplicate = "SELECT USER_ID, ROLES, count(ROLES) " +
         "FROM USER_ROLES " +
         "GROUP BY USER_ID, ROLES " +
         "HAVING count(ROLES) > 1";

   String deleteDuplicate =
         "DELETE FROM USER_ROLES WHERE USER_ID=%d AND ROLES='%s'";

   String resetRole = "INSERT INTO USER_ROLES VALUES(%d, '%s')";

   try
   {
      JdbcConnection jdbc = (JdbcConnection) database.getConnection ();
      PreparedStatement getDuplicate = jdbc.prepareStatement (
            searchDuplicate);
      ResultSet result = getDuplicate.executeQuery ();

      while (result.next ())
      {
         int u = result.getInt (1);
         String r = result.getString (2);

         PreparedStatement delete =
               jdbc.prepareStatement (String.format (deleteDuplicate, u, r));
         delete.executeUpdate ();

         PreparedStatement reset =
               jdbc.prepareStatement (String.format (resetRole, u, r));
         reset.executeUpdate ();
      }
      result.close ();
      getDuplicate.close ();
   }
   catch (DatabaseException | SQLException e)
   {
      LOGGER.error ("An error occurred during removeDuplicationRoles", e);
   }
}
 
Example 17
Source File: TransformUserCountry.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {
      PreparedStatement getUsers =
         databaseConnection
            .prepareStatement ("SELECT ID, LOGIN, COUNTRY FROM USERS");
      ResultSet res = getUsers.executeQuery ();  
      
      while (res.next ())
      {
         String country = (String) res.getObject ("COUNTRY");
         String country2 = country.replaceAll(
               "[-\\[(){},.;!?><_|\\/%*^$\\]]", "");
         String found = null;
         
         PreparedStatement getCountries=databaseConnection.prepareStatement(
            "SELECT NAME, ALPHA2, ALPHA3 FROM COUNTRIES");
         ResultSet countries = getCountries.executeQuery ();
         while (countries.next ())
         {
            String ref = (String) countries.getObject ("NAME");
            String a2 = (String) countries.getObject ("ALPHA2");
            String a3 = (String) countries.getObject ("ALPHA3");
            if (ref.toLowerCase ().equals (country.toLowerCase ()) || 
                 a2.toLowerCase ().equals (country.toLowerCase ()) || 
                 a3.toLowerCase ().equals (country.toLowerCase ()) || 
                 ref.toLowerCase ().equals (country2.toLowerCase ()) || 
                 a2.toLowerCase ().equals (country2.toLowerCase ()) || 
                 a3.toLowerCase ().equals (country2.toLowerCase ()))
            {
               found = ref;
               break;
            }
         }
         if (found != null)
         {
            PreparedStatement updateUser = databaseConnection.
               prepareStatement("UPDATE USERS SET COUNTRY=? WHERE ID=?");
            
            updateUser.setString (1, found);
            updateUser.setLong (2, (Long)res.getObject ("ID"));
            
            updateUser.execute ();
            updateUser.close ();
         }
         else
         {
            LOGGER.warn("Unknown country for '"+res.getObject ("LOGIN")+"' : "+country);
         }
         getCountries.close ();
      }
      getUsers.close ();
   }
   catch (Exception e)
   {
      LOGGER.error(
            "Error during liquibase update 'TransformUserCountry'", e);
   }
}
 
Example 18
Source File: GenerateUserUUIDs.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {         
      PreparedStatement getUsers =
         databaseConnection.prepareStatement ("SELECT ID FROM USERS");
      ResultSet res = getUsers.executeQuery ();
      while (res.next ())
      {
         String uuid = UUID.randomUUID ().toString ();
         PreparedStatement updateUsers =
            databaseConnection
               .prepareStatement ("UPDATE USERS SET UUID = '" + uuid +
                  "' WHERE ID = " + res.getObject ("ID"));
         updateUsers.execute ();
         updateUsers.close ();
                     
         PreparedStatement updateNetworkUsage =
            databaseConnection
               .prepareStatement ("UPDATE NETWORK_USAGE SET USER_UUID = '" + uuid +
                  "' WHERE USER_ID = " + res.getObject ("ID"));
         updateNetworkUsage.execute ();
         updateNetworkUsage.close ();

         PreparedStatement updateProducts =
            databaseConnection
               .prepareStatement ("UPDATE PRODUCTS SET OWNER_UUID = '" +
                  uuid + "' WHERE OWNER_ID = " + res.getObject ("ID"));
         updateProducts.execute ();
         updateProducts.close ();

         PreparedStatement updateCollectionuser =
            databaseConnection
               .prepareStatement ("UPDATE COLLECTION_USER_AUTH SET USERS_UUID = '" +
                  uuid + "' WHERE USERS_ID = " + res.getObject ("ID"));
         updateCollectionuser.execute ();
         updateCollectionuser.close ();
         
         PreparedStatement updateProductCarts =
            databaseConnection
               .prepareStatement ("UPDATE PRODUCTCARTS SET USER_UUID = '" +
                  uuid + "' WHERE USER_ID = " + res.getObject ("ID"));
         updateProductCarts.execute ();
         updateProductCarts.close ();

         PreparedStatement updateProductUser =
            databaseConnection
               .prepareStatement ("UPDATE PRODUCT_USER_AUTH SET USERS_UUID = '" +
                  uuid + "' WHERE USERS_ID = " + res.getObject ("ID"));
         updateProductUser.execute ();
         updateProductUser.close ();

         PreparedStatement updateRestrictions =
            databaseConnection
               .prepareStatement ("UPDATE USER_RESTRICTIONS SET USER_UUID = '" +
                  uuid + "' WHERE USER_ID = " + res.getObject ("ID"));
         updateRestrictions.execute ();
         updateRestrictions.close ();

         PreparedStatement updateRoles =
            databaseConnection
               .prepareStatement ("UPDATE USER_ROLES SET USER_UUID = '" +
                  uuid + "' WHERE USER_ID = " + res.getObject ("ID"));
         updateRoles.execute ();
         updateRoles.close ();
      }
      getUsers.close ();         
   }
   catch (Exception e)
   {
      e.printStackTrace ();
   }
   
}
 
Example 19
Source File: CorrectsIngestionDate.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   SimpleDateFormat metaSdf =
         new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
   SimpleDateFormat productSdf =
         new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSS");
   String query =
         "SELECT p.ID, m.VALUE, p.INGESTIONDATE " +
               "FROM PRODUCTS p LEFT OUTER JOIN " +
               "METADATA_INDEXES m ON p.ID = m.PRODUCT_ID " +
               "WHERE m.NAME = 'Ingestion Date'";
   try
   {
      JdbcConnection connection = (JdbcConnection) database.getConnection ();
      PreparedStatement statement = connection.prepareStatement (query);
      ResultSet result = statement.executeQuery ();
      while (result.next ())
      {
         Date validIngestionDate = metaSdf.parse (result.getString (2));
         Date ingestionDate = productSdf.parse (result.getString (3));
         long diffMilli =
               validIngestionDate.getTime () - ingestionDate.getTime ();
         long diffHour = diffMilli / (1000 * 60 * 60);
         if (diffHour >= 11.0)
         {
            StringBuilder sb = new StringBuilder ();
            sb.append ("UPDATE PRODUCTS ");
            sb.append ("SET INGESTIONDATE = '").append (
                  productSdf.format (validIngestionDate)).append ("' ");
            sb.append ("WHERE ID = ").append (result.getLong (1));
            PreparedStatement update =
                  connection.prepareStatement (sb.toString ());
            if (update.executeUpdate () != 1)
            {
               LOGGER.warn("Cannot change ingestion date for product#" +
                     result.getLong (1));
            }
         }
      }
      result.close ();
      statement.close ();
   }
   catch (DatabaseException | SQLException | ParseException e)
   {
      throw new CustomChangeException (
            "An error occurred during liquibase execution: ", e);
   }
}
 
Example 20
Source File: ReplaceSystemByConfigurationObject.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection = (JdbcConnection) database
         .getConnection ();
   try
   {
      PreparedStatement system = databaseConnection.prepareStatement (
         "SELECT * FROM SYSTEM");
      ResultSet system_res = system.executeQuery ();
      
      while (system_res.next ())
      {
         Integer qlWidth = (Integer) system_res.getObject (
               "proc_quicklook_width");
         Integer qlHeight = (Integer) system_res.getObject (
               "proc_quicklook_height");
         Boolean qlCutting = (Boolean) system_res.getObject (
               "proc_quicklook_cutting");
         Integer tnWidth = (Integer) system_res.getObject (
               "proc_thumbnail_width");
         Integer tnHeight = (Integer) system_res.getObject (
               "proc_thumbnail_height");
         Boolean tnCutting = (Boolean) system_res.getObject (
               "proc_thumbnail_cutting");
         String fromMail = (String) system_res.getObject (
               "MAIL_FROM_EMAIL");
         String fromName = (String) system_res.getObject (
               "MAIL_FROM_NAME");
         String replyTo = (String) system_res.getObject (
               "MAIL_REPLY_TO");
         String serverHost = (String) system_res.getObject (
               "MAIL_SERVER_HOSTNAME");
         Integer serverPort = (Integer) system_res.getObject (
               "MAIL_SERVER_PORT");
         Boolean serverTls = (Boolean) system_res.getObject (
               "MAIL_SERVER_TLS");
         String serverUser = (String) system_res.getObject (
               "MAIL_SERVER_USERNAME");
         String serverPassword = (String) system_res.getObject (
               "MAIL_SERVER_PASSWORD");
         String supportMail = (String) system_res.getObject (
               "SYSTEM_SUPPORT_MAIL");
         String supportName = (String) system_res.getObject (
               "SYSTEM_SUPPORT_NAME");
         Boolean mailCreate = (Boolean) system_res.getObject (
               "USER_EMAIL_ON_CREATE");
         Boolean mailUpdate = (Boolean) system_res.getObject (
               "USER_EMAIL_ON_UPDATE");
         Boolean mailDelete = (Boolean) system_res.getObject (
               "USER_EMAIL_ON_DELETE");

         PreparedStatement updateConfiguration =
            databaseConnection
               .prepareStatement ("INSERT INTO CONFIGURATION " +
                     "(QUICKLOOK_CUTTING, QUICKLOOK_HEIGHT, " +
                     "QUICKLOOK_WIDTH, THUMBNAIL_CUTTING, " +
                     "THUMBNAIL_HEIGHT, " + "THUMBNAIL_WIDTH, " +
                     "MAILSERVER_FROMADDRESS, MAILSERVER_FROMNAME, " +
                     "MAILSERVER_REPLYTO, MAILSERVER_SMTP, " +
                     "MAILSERVER_PORT, MAILSERVER_TLS, " +
                     "MAILSERVER_USERNAME, MAILSERVER_PASSWORD, " +
                     "SYSTEM_SUPPORTMAIL, SYSTEM_SUPPORTNAME, " +
                     "MAIL_ONUSERCREATE, MAIL_ONUSERUPDATE, " +
                     "MAIL_ONUSERDELETE) VALUES ('"+qlCutting+"', " +
                     "'" + qlHeight + "', '" + qlWidth + "', '" + tnCutting +
                     "', " + "'" + tnHeight + "', '" + tnWidth + "', '" +
                     fromMail + "', '" + fromName + "', '" + replyTo +
                     "', '" + serverHost + "', '" + serverPort + "', '" +
                     serverTls + "', '" + serverUser + "', '" +
                     serverPassword + "', '" + supportMail + "', '" +
                     supportName + "', '" + mailCreate + "', '" +
                     mailUpdate + "', '" + mailDelete + "')");
         updateConfiguration.execute ();
         updateConfiguration.close();
      }
      system.close();
   }
   catch (Exception e)
   {
      LOGGER.error("Error during liquibase update " +
            "'ReplaceSystemByConfigurationObject'", e);
   }
}