Example usage for org.hibernate.cfg Configuration getProperties

List of usage examples for org.hibernate.cfg Configuration getProperties

Introduction

In this page you can find the example usage for org.hibernate.cfg Configuration getProperties.

Prototype

public Properties getProperties() 

Source Link

Document

Get all properties

Usage

From source file:openones.tms.account.hibernatedao.HibernateUtil.java

License:Apache License

public static SessionFactory getSessionFactory() {
    try {/*w ww  .  ja va  2 s  .  c om*/
        // Create the SessionFactory from hibernate.cfg.xml
        Configuration configuration = new Configuration();

        configuration.configure();

        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).buildServiceRegistry();
        return configuration.buildSessionFactory(serviceRegistry);
    } catch (Exception ex) {
        log.error("Could not locate SessionFactory", ex);
        throw new IllegalStateException("Could not locate SessionFactory");
    }
}

From source file:org.alfresco.hibernate.DialectFactoryBean.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override//from   w w  w  .j  a v a  2  s  .  com
public Dialect getObject() throws SQLException {
    Session session = ((SessionFactory) this.localSessionFactory.getObject()).openSession();
    Configuration cfg = this.localSessionFactory.getConfiguration();
    Connection con = null;
    try {
        // make sure that we AUTO-COMMIT
        con = session.connection();
        con.setAutoCommit(true);
        DatabaseMetaData meta = con.getMetaData();
        Dialect dialect = DialectFactory.buildDialect(cfg.getProperties(), meta.getDatabaseProductName(),
                meta.getDatabaseMajorVersion());
        dialect = changeDialect(cfg, dialect);
        return dialect;
    } finally {
        try {
            con.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.alfresco.repo.domain.schema.SchemaBootstrap.java

License:Open Source License

/**
 * Builds the schema from scratch or applies the necessary patches to the schema.
 *//*from ww w  .j a  v a  2 s. co m*/
private boolean updateSchema(Configuration cfg, Session session, Connection connection) throws Exception {
    boolean create = false;
    try {
        countAppliedPatches(cfg, connection);
    } catch (NoSchemaException e) {
        create = true;
    }
    // Get the dialect
    final Dialect dialect = Dialect.getDialect(cfg.getProperties());
    String dialectStr = dialect.getClass().getSimpleName();

    if (create) {
        long start = System.currentTimeMillis();

        // execute pre-create scripts (not patches)
        for (String scriptUrl : this.preCreateScriptUrls) {
            executeScriptUrl(cfg, connection, scriptUrl);
        }
        // Build and execute changes generated by Hibernate
        File tempFile = null;
        Writer writer = null;
        try {
            DatabaseMetadata metadata = new DatabaseMetadata(connection, dialect);
            String[] sqls = cfg.generateSchemaUpdateScript(dialect, metadata);
            if (sqls.length > 0) {
                tempFile = TempFileProvider.createTempFile("AlfrescoSchema-" + dialectStr + "-Update-", ".sql");
                writer = new BufferedWriter(new FileWriter(tempFile));
                for (String sql : sqls) {
                    writer.append(sql);
                    writer.append(";\n");
                }
                try {
                    writer.close();
                } catch (Throwable e) {
                }
                executeScriptFile(cfg, connection, tempFile, null);
            }
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Throwable e) {
                }
            }
        }
        // execute post-create scripts (not patches)
        for (String scriptUrl : this.postCreateScriptUrls) {
            executeScriptUrl(cfg, connection, scriptUrl);
        }

        if (logger.isInfoEnabled()) {
            logger.info("Create scripts executed in " + (System.currentTimeMillis() - start) + " ms");
        }
    } else {
        // Execute any pre-auto-update scripts
        checkSchemaPatchScripts(cfg, connection, preUpdateScriptPatches, true);

        // Build and execute changes generated by Hibernate
        File tempFile = null;
        Writer writer = null;
        try {
            DatabaseMetadata metadata = new DatabaseMetadata(connection, dialect);
            String[] sqls = cfg.generateSchemaUpdateScript(dialect, metadata);
            if (sqls.length > 0) {
                tempFile = TempFileProvider.createTempFile("AlfrescoSchema-" + dialectStr + "-Update-", ".sql");
                writer = new BufferedWriter(new FileWriter(tempFile));
                for (String sql : sqls) {
                    writer.append(sql);
                    writer.append(";\n");
                }
            }
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Throwable e) {
                }
            }
        }
        // execute if there were changes raised by Hibernate
        if (tempFile != null) {
            executeScriptFile(cfg, connection, tempFile, null);
        }

        // Execute any post-auto-update scripts
        checkSchemaPatchScripts(cfg, connection, postUpdateScriptPatches, true);
    }

    // Initialise Activiti DB, using an unclosable connection
    boolean activitiTablesExist = checkActivitiTablesExist(connection);
    if (!activitiTablesExist) {
        // Activiti DB updates are performed as patches in alfresco, only give
        // control to activiti when creating new one.
        initialiseActivitiDBSchema(new UnclosableConnection(connection));

        // ALF-18996: Upgrade from 3.4.12 to 4.2.0 fails: Activiti tables have not been bootstrapped
        // The Activiti bootstrap is effectively doing the work of all the other patches,
        // which should be considered complete.
        int installedSchemaNumber = getInstalledSchemaNumber(connection);
        for (Patch activitiScriptPatch : updateActivitiScriptPatches) {
            AppliedPatch appliedPatch = new AppliedPatch();
            appliedPatch.setId(activitiScriptPatch.getId());
            appliedPatch.setDescription(activitiScriptPatch.getDescription());
            appliedPatch.setFixesFromSchema(activitiScriptPatch.getFixesFromSchema());
            appliedPatch.setFixesToSchema(activitiScriptPatch.getFixesToSchema());
            appliedPatch.setTargetSchema(activitiScriptPatch.getTargetSchema());
            appliedPatch.setAppliedToSchema(installedSchemaNumber);
            appliedPatch.setAppliedToServer("UNKNOWN");
            appliedPatch.setAppliedOnDate(new Date()); // the date applied
            appliedPatch.setSucceeded(true);
            appliedPatch.setWasExecuted(false);
            appliedPatch.setReport("Placeholder for Activiti bootstrap at schema " + installedSchemaNumber);
            appliedPatchDAO.createAppliedPatch(appliedPatch);
        }
    } else {
        // Execute any auto-update scripts for Activiti tables
        checkSchemaPatchScripts(cfg, connection, updateActivitiScriptPatches, true);

        // verify that all Activiti patches have been applied correctly
        checkSchemaPatchScripts(cfg, connection, updateActivitiScriptPatches, false);
    }

    return create;
}

From source file:org.alfresco.repo.domain.schema.SchemaBootstrap.java

License:Open Source License

private void executeScriptUrl(Configuration cfg, Connection connection, String scriptUrl) throws Exception {
    Dialect dialect = Dialect.getDialect(cfg.getProperties());
    String dialectStr = dialect.getClass().getSimpleName();
    InputStream scriptInputStream = getScriptInputStream(dialect.getClass(), scriptUrl);
    // check that it exists
    if (scriptInputStream == null) {
        throw AlfrescoRuntimeException.create(ERR_SCRIPT_NOT_FOUND, scriptUrl);
    }//  w  w  w . j av a  2 s.  co  m
    // write the script to a temp location for future and failure reference
    File tempFile = null;
    try {
        tempFile = TempFileProvider.createTempFile("AlfrescoSchema-" + dialectStr + "-Update-", ".sql");
        ContentWriter writer = new FileContentWriter(tempFile);
        writer.putContent(scriptInputStream);
    } finally {
        try {
            scriptInputStream.close();
        } catch (Throwable e) {
        } // usually a duplicate close
    }
    // now execute it
    String dialectScriptUrl = scriptUrl.replaceAll(PLACEHOLDER_DIALECT, dialect.getClass().getName());
    // Replace the script placeholders
    executeScriptFile(cfg, connection, tempFile, dialectScriptUrl);
}

From source file:org.alfresco.repo.domain.schema.SchemaBootstrap.java

License:Open Source License

/**
 * @param cfg           the Hibernate configuration
 * @param connection    the DB connection to use
 * @param scriptFile    the file containing the statements
 * @param scriptUrl     the URL of the script to report.  If this is null, the script
 *                      is assumed to have been auto-generated.
 */// w w  w .j a v a2s  .co  m
private void executeScriptFile(Configuration cfg, Connection connection, File scriptFile, String scriptUrl)
        throws Exception {
    final Dialect dialect = Dialect.getDialect(cfg.getProperties());

    StringBuilder executedStatements = executedStatementsThreadLocal.get();
    if (executedStatements == null) {
        // Validate the schema, pre-upgrade
        validateSchema("Alfresco-{0}-Validation-Pre-Upgrade-{1}-", null);

        dumpSchema("pre-upgrade");

        // There is no lock at this stage.  This process can fall out if the lock can't be applied.
        setBootstrapStarted(connection);
        executedStatements = new StringBuilder(8094);
        executedStatementsThreadLocal.set(executedStatements);
    }

    if (scriptUrl == null) {
        LogUtil.info(logger, MSG_EXECUTING_GENERATED_SCRIPT, scriptFile);
    } else {
        LogUtil.info(logger, MSG_EXECUTING_COPIED_SCRIPT, scriptFile, scriptUrl);
    }

    InputStream scriptInputStream = new FileInputStream(scriptFile);
    BufferedReader reader = new BufferedReader(new InputStreamReader(scriptInputStream, "UTF-8"));
    try {
        int line = 0;
        // loop through all statements
        StringBuilder sb = new StringBuilder(1024);
        String fetchVarName = null;
        String fetchColumnName = null;
        Object defaultFetchValue = null;
        boolean doBatch = false;
        int batchUpperLimit = 0;
        int batchSize = 1;
        Map<String, Object> varAssignments = new HashMap<String, Object>(13);
        String delimiter = ";";
        // Special variable assignments:
        if (dialect instanceof PostgreSQLDialect) {
            // Needs 1/0 for true/false
            varAssignments.put("true", "true");
            varAssignments.put("false", "false");
            varAssignments.put("TRUE", "TRUE");
            varAssignments.put("FALSE", "FALSE");
        } else {
            // Needs true/false as strings
            varAssignments.put("true", "1");
            varAssignments.put("false", "0");
            varAssignments.put("TRUE", "1");
            varAssignments.put("FALSE", "0");
        }
        long now = System.currentTimeMillis();
        varAssignments.put("now", new Long(now).toString());
        varAssignments.put("NOW", new Long(now).toString());

        while (true) {
            String sqlOriginal = reader.readLine();
            line++;

            if (sqlOriginal == null) {
                // nothing left in the file
                break;
            }

            // trim it
            String sql = sqlOriginal.trim();
            // Check of includes
            if (sql.startsWith("--INCLUDE:")) {
                if (sb.length() > 0) {
                    // This can only be set before a new SQL statement
                    throw AlfrescoRuntimeException.create(ERR_STATEMENT_INCLUDE_BEFORE_SQL, (line - 1),
                            scriptUrl);
                }
                String includedScriptUrl = sql.substring(10, sql.length());
                // Execute the script in line
                executeScriptUrl(cfg, connection, includedScriptUrl);
            }
            // Check for variable assignment
            else if (sql.startsWith("--ASSIGN:")) {
                if (sb.length() > 0) {
                    // This can only be set before a new SQL statement
                    throw AlfrescoRuntimeException.create(ERR_STATEMENT_VAR_ASSIGNMENT_BEFORE_SQL, (line - 1),
                            scriptUrl);
                }
                String assignStr = sql.substring(9, sql.length());
                String[] fetchMapping = assignStr.split("!");
                String[] assigns = fetchMapping[0].split("=");
                if (assigns.length != 2 || assigns[0].length() == 0 || assigns[1].length() == 0) {
                    throw AlfrescoRuntimeException.create(ERR_STATEMENT_VAR_ASSIGNMENT_FORMAT, (line - 1),
                            scriptUrl);
                }
                fetchVarName = assigns[0];
                fetchColumnName = assigns[1];
                if (fetchMapping.length > 1 && fetchMapping[1].length() > 0) {
                    defaultFetchValue = fetchMapping[1];
                }
                continue;
            }
            // Handle looping control
            else if (sql.startsWith("--FOREACH")) {
                // --FOREACH table.column batch.size.property
                String[] args = sql.split("[ \\t]+");
                int sepIndex;
                if (args.length == 3 && (sepIndex = args[1].indexOf('.')) != -1) {
                    doBatch = true;
                    // Select the upper bound of the table column
                    String stmt = "SELECT MAX(" + args[1].substring(sepIndex + 1) + ") AS upper_limit FROM "
                            + args[1].substring(0, sepIndex);
                    Object fetchedVal = executeStatement(connection, stmt, "upper_limit", false, line,
                            scriptFile);
                    if (fetchedVal instanceof Number) {
                        batchUpperLimit = ((Number) fetchedVal).intValue();
                        // Read the batch size from the named property
                        String batchSizeString = globalProperties.getProperty(args[2]);
                        // Fall back to the default property
                        if (batchSizeString == null) {
                            batchSizeString = globalProperties.getProperty(PROPERTY_DEFAULT_BATCH_SIZE);
                        }
                        batchSize = batchSizeString == null ? 10000 : Integer.parseInt(batchSizeString);
                    }
                }
                continue;
            }
            // Allow transaction delineation
            else if (sql.startsWith("--BEGIN TXN")) {
                connection.setAutoCommit(false);
                continue;
            } else if (sql.startsWith("--END TXN")) {
                connection.commit();
                connection.setAutoCommit(true);
                continue;
            } else if (sql.startsWith("--SET-DELIMITER:")) {
                if (sb.length() > 0) {
                    // This can only be set before a new SQL statement
                    throw AlfrescoRuntimeException.create(ERR_DELIMITER_SET_BEFORE_SQL, (line - 1), scriptUrl);
                }

                // We're good...so set the new delimiter
                String newDelim = sql.substring(16).trim();
                if (newDelim.length() == 0) {
                    throw AlfrescoRuntimeException.create(ERR_DELIMITER_INVALID, (line - 1), scriptUrl);
                }
                delimiter = newDelim;
            }

            // Check for comments
            if (sql.length() == 0 || sql.startsWith("--") || sql.startsWith("//") || sql.startsWith("/*")) {
                if (sb.length() > 0) {
                    // we have an unterminated statement
                    throw AlfrescoRuntimeException.create(ERR_STATEMENT_TERMINATOR, delimiter, (line - 1),
                            scriptUrl);
                }
                // there has not been anything to execute - it's just a comment line
                continue;
            }
            // have we reached the end of a statement?
            boolean execute = false;
            boolean optional = false;
            if (sql.endsWith(delimiter)) {
                sql = sql.substring(0, sql.length() - 1);
                execute = true;
                optional = false;
            } else if (sql.endsWith("(optional)") || sql.endsWith("(OPTIONAL)")) {
                // Get the end of statement
                int endIndex = sql.lastIndexOf(delimiter);
                if (endIndex > -1) {
                    sql = sql.substring(0, endIndex);
                    execute = true;
                    optional = true;
                } else {
                    // Ends with "(optional)" but there is no semi-colon.
                    // Just take it at face value and probably fail.
                }
            }
            // Add newline
            if (sb.length() > 0) {
                sb.append("\n");
            }
            // Add leading whitespace for formatting
            int whitespaceCount = sqlOriginal.indexOf(sql);
            for (int i = 0; i < whitespaceCount; i++) {
                sb.append(" ");
            }
            // append to the statement being built up
            sb.append(sql);
            // execute, if required
            if (execute) {
                // Now substitute and execute the statement the appropriate number of times
                String unsubstituted = sb.toString();
                for (int lowerBound = 0; lowerBound <= batchUpperLimit; lowerBound += batchSize) {
                    sql = unsubstituted;

                    // Substitute in the next pair of range parameters
                    if (doBatch) {
                        varAssignments.put("LOWERBOUND", String.valueOf(lowerBound));
                        varAssignments.put("UPPERBOUND", String.valueOf(lowerBound + batchSize - 1));
                    }

                    // Perform variable replacement using the ${var} format
                    for (Map.Entry<String, Object> entry : varAssignments.entrySet()) {
                        String var = entry.getKey();
                        Object val = entry.getValue();
                        sql = sql.replaceAll("\\$\\{" + var + "\\}", val.toString());
                    }

                    // Handle the 0/1 values that PostgreSQL doesn't translate to TRUE
                    if (this.dialect != null && this.dialect instanceof PostgreSQLDialect) {
                        sql = sql.replaceAll("\\$\\{TRUE\\}", "TRUE");
                    } else {
                        sql = sql.replaceAll("\\$\\{TRUE\\}", "1");
                    }

                    if (this.dialect != null && this.dialect instanceof MySQLInnoDBDialect) {
                        // note: enable bootstrap on MySQL 5.5 (eg. for auto-generated SQL, such as JBPM)
                        sql = sql.replaceAll("(?i)TYPE=InnoDB", "ENGINE=InnoDB");
                    }

                    if (this.dialect != null && this.dialect instanceof AlfrescoMySQLClusterNDBDialect) {
                        // note: enable bootstrap on MySQL Cluster NDB
                        /*
                        * WARNING: Experimental/unsupported - see AlfrescoMySQLClusterNDBDialect !
                        */
                        sql = sql.replaceAll("(?i)TYPE=InnoDB", "ENGINE=NDB"); // belts-and-braces
                        sql = sql.replaceAll("(?i)ENGINE=InnoDB", "ENGINE=NDB");

                        sql = sql.replaceAll("(?i) BIT ", " BOOLEAN ");
                        sql = sql.replaceAll("(?i) BIT,", " BOOLEAN,");

                        sql = sql.replaceAll("(?i) string_value text",
                                " string_value VARCHAR(" + DEFAULT_MAX_STRING_LENGTH_NDB + ")");

                        sql = sql.replaceAll("(?i) VARCHAR(4000)", "TEXT(4000)");
                    }

                    Object fetchedVal = executeStatement(connection, sql, fetchColumnName, optional, line,
                            scriptFile);
                    if (fetchVarName != null && fetchColumnName != null) {
                        if (fetchedVal != null) {
                            varAssignments.put(fetchVarName, fetchedVal);
                        } else {
                            varAssignments.put(fetchVarName, defaultFetchValue);
                        }
                    }
                }
                sb.setLength(0);
                fetchVarName = null;
                fetchColumnName = null;
                defaultFetchValue = null;
                doBatch = false;
                batchUpperLimit = 0;
                batchSize = 1;
            }
        }
    } finally {
        try {
            reader.close();
        } catch (Throwable e) {
        }
        try {
            scriptInputStream.close();
        } catch (Throwable e) {
        }
    }
}

From source file:org.alfresco.repo.domain.schema.script.ScriptExecutorImpl.java

License:Open Source License

/**
 * @param cfg           the Hibernate configuration
 * @param connection    the DB connection to use
 * @param scriptFile    the file containing the statements
 * @param scriptUrl     the URL of the script to report.  If this is null, the script
 *                      is assumed to have been auto-generated.
 *//*from  w w w . j  ava2  s .  c om*/
private void executeScriptFile(Configuration cfg, Connection connection, File scriptFile, String scriptUrl)
        throws Exception {
    final Dialect dialect = Dialect.getDialect(cfg.getProperties());

    StringBuilder executedStatements = executedStatementsThreadLocal.get();
    if (executedStatements == null) {
        executedStatements = new StringBuilder(8094);
        executedStatementsThreadLocal.set(executedStatements);
    }

    if (scriptUrl == null) {
        LogUtil.info(logger, MSG_EXECUTING_GENERATED_SCRIPT, scriptFile);
    } else {
        LogUtil.info(logger, MSG_EXECUTING_COPIED_SCRIPT, scriptFile, scriptUrl);
    }

    InputStream scriptInputStream = new FileInputStream(scriptFile);
    BufferedReader reader = new BufferedReader(new InputStreamReader(scriptInputStream, "UTF-8"));
    try {
        int line = 0;
        // loop through all statements
        StringBuilder sb = new StringBuilder(1024);
        String fetchVarName = null;
        String fetchColumnName = null;
        Object defaultFetchValue = null;
        String batchTableName = null;
        boolean doBatch = false;
        int batchUpperLimit = 0;
        int batchSize = 1;
        Map<String, Object> varAssignments = new HashMap<String, Object>(13);
        String delimiter = ";";
        // Special variable assignments:
        if (dialect instanceof PostgreSQLDialect) {
            // Needs 1/0 for true/false
            varAssignments.put("true", "true");
            varAssignments.put("false", "false");
            varAssignments.put("TRUE", "TRUE");
            varAssignments.put("FALSE", "FALSE");
        } else {
            // Needs true/false as strings
            varAssignments.put("true", "1");
            varAssignments.put("false", "0");
            varAssignments.put("TRUE", "1");
            varAssignments.put("FALSE", "0");
        }
        long now = System.currentTimeMillis();
        varAssignments.put("now", new Long(now).toString());
        varAssignments.put("NOW", new Long(now).toString());

        while (true) {
            String sqlOriginal = reader.readLine();
            line++;

            if (sqlOriginal == null) {
                // nothing left in the file
                break;
            }

            // trim it
            String sql = sqlOriginal.trim();
            // Check of includes
            if (sql.startsWith("--INCLUDE:")) {
                if (sb.length() > 0) {
                    // This can only be set before a new SQL statement
                    throw AlfrescoRuntimeException.create(ERR_STATEMENT_INCLUDE_BEFORE_SQL, (line - 1),
                            scriptUrl);
                }
                String includedScriptUrl = sql.substring(10, sql.length());
                // Execute the script in line
                executeScriptUrl(cfg, connection, includedScriptUrl);
            }
            // Check for variable assignment
            else if (sql.startsWith("--ASSIGN:")) {
                if (sb.length() > 0) {
                    // This can only be set before a new SQL statement
                    throw AlfrescoRuntimeException.create(ERR_STATEMENT_VAR_ASSIGNMENT_BEFORE_SQL, (line - 1),
                            scriptUrl);
                }
                String assignStr = sql.substring(9, sql.length());
                String[] fetchMapping = assignStr.split("!");
                String[] assigns = fetchMapping[0].split("=");
                if (assigns.length != 2 || assigns[0].length() == 0 || assigns[1].length() == 0) {
                    throw AlfrescoRuntimeException.create(ERR_STATEMENT_VAR_ASSIGNMENT_FORMAT, (line - 1),
                            scriptUrl);
                }
                fetchVarName = assigns[0];
                fetchColumnName = assigns[1];
                if (fetchMapping.length > 1 && fetchMapping[1].length() > 0) {
                    defaultFetchValue = fetchMapping[1];
                }
                continue;
            }
            // Handle looping control
            else if (sql.startsWith("--FOREACH")) {
                // --FOREACH table.column batch.size.property
                String[] args = sql.split("[ \\t]+");
                int sepIndex;
                if (args.length == 3 && (sepIndex = args[1].indexOf('.')) != -1) {
                    doBatch = true;
                    // Select the upper bound of the table column
                    batchTableName = args[1].substring(0, sepIndex);
                    String stmt = "SELECT MAX(" + args[1].substring(sepIndex + 1) + ") AS upper_limit FROM "
                            + batchTableName;
                    Object fetchedVal = executeStatement(connection, stmt, "upper_limit", false, line,
                            scriptFile);
                    if (fetchedVal instanceof Number) {
                        batchUpperLimit = ((Number) fetchedVal).intValue();
                        // Read the batch size from the named property
                        String batchSizeString = globalProperties.getProperty(args[2]);
                        // Fall back to the default property
                        if (batchSizeString == null) {
                            batchSizeString = globalProperties.getProperty(PROPERTY_DEFAULT_BATCH_SIZE);
                        }
                        batchSize = batchSizeString == null ? 10000 : Integer.parseInt(batchSizeString);
                    }
                }
                continue;
            }
            // Allow transaction delineation
            else if (sql.startsWith("--BEGIN TXN")) {
                connection.setAutoCommit(false);
                continue;
            } else if (sql.startsWith("--END TXN")) {
                connection.commit();
                connection.setAutoCommit(true);
                continue;
            } else if (sql.startsWith("--SET-DELIMITER:")) {
                if (sb.length() > 0) {
                    // This can only be set before a new SQL statement
                    throw AlfrescoRuntimeException.create(ERR_DELIMITER_SET_BEFORE_SQL, (line - 1), scriptUrl);
                }

                // We're good...so set the new delimiter
                String newDelim = sql.substring(16).trim();
                if (newDelim.length() == 0) {
                    throw AlfrescoRuntimeException.create(ERR_DELIMITER_INVALID, (line - 1), scriptUrl);
                }
                delimiter = newDelim;
            }

            // Check for comments
            if (sql.length() == 0 || sql.startsWith("--") || sql.startsWith("//") || sql.startsWith("/*")) {
                if (sb.length() > 0) {
                    // we have an unterminated statement
                    throw AlfrescoRuntimeException.create(ERR_STATEMENT_TERMINATOR, delimiter, (line - 1),
                            scriptUrl);
                }
                // there has not been anything to execute - it's just a comment line
                continue;
            }
            // have we reached the end of a statement?
            boolean execute = false;
            boolean optional = false;
            if (sql.endsWith(delimiter)) {
                sql = sql.substring(0, sql.length() - 1);
                execute = true;
                optional = false;
            } else if (sql.endsWith("(optional)") || sql.endsWith("(OPTIONAL)")) {
                // Get the end of statement
                int endIndex = sql.lastIndexOf(delimiter);
                if (endIndex > -1) {
                    sql = sql.substring(0, endIndex);
                    execute = true;
                    optional = true;
                } else {
                    // Ends with "(optional)" but there is no semi-colon.
                    // Just take it at face value and probably fail.
                }
            }
            // Add newline
            if (sb.length() > 0) {
                sb.append("\n");
            }
            // Add leading whitespace for formatting
            int whitespaceCount = sqlOriginal.indexOf(sql);
            for (int i = 0; i < whitespaceCount; i++) {
                sb.append(" ");
            }
            // append to the statement being built up
            sb.append(sql);
            // execute, if required
            if (execute) {
                // Now substitute and execute the statement the appropriate number of times
                String unsubstituted = sb.toString();
                for (int lowerBound = 0; lowerBound <= batchUpperLimit; lowerBound += batchSize) {
                    sql = unsubstituted;

                    // Substitute in the next pair of range parameters
                    if (doBatch) {
                        logger.info("Processing from " + lowerBound + " to " + (lowerBound + batchSize)
                                + " rows of " + batchUpperLimit + " rows from table " + batchTableName + ".");
                        varAssignments.put("LOWERBOUND", String.valueOf(lowerBound));
                        varAssignments.put("UPPERBOUND", String.valueOf(lowerBound + batchSize - 1));
                    }

                    // Perform variable replacement using the ${var} format
                    for (Map.Entry<String, Object> entry : varAssignments.entrySet()) {
                        String var = entry.getKey();
                        Object val = entry.getValue();
                        sql = sql.replaceAll("\\$\\{" + var + "\\}", val.toString());
                    }

                    // Handle the 0/1 values that PostgreSQL doesn't translate to TRUE
                    if (this.dialect != null && this.dialect instanceof PostgreSQLDialect) {
                        sql = sql.replaceAll("\\$\\{TRUE\\}", "TRUE");
                    } else {
                        sql = sql.replaceAll("\\$\\{TRUE\\}", "1");
                    }

                    if (this.dialect != null && this.dialect instanceof MySQLInnoDBDialect) {
                        // note: enable bootstrap on MySQL 5.5 (eg. for auto-generated SQL, such as JBPM)
                        sql = sql.replaceAll("(?i)TYPE=InnoDB", "ENGINE=InnoDB");
                    }

                    if (this.dialect != null && this.dialect instanceof AlfrescoMySQLClusterNDBDialect) {
                        // note: enable bootstrap on MySQL Cluster NDB
                        /*
                        * WARNING: Experimental/unsupported - see AlfrescoMySQLClusterNDBDialect !
                        */
                        sql = sql.replaceAll("(?i)TYPE=InnoDB", "ENGINE=NDB"); // belts-and-braces
                        sql = sql.replaceAll("(?i)ENGINE=InnoDB", "ENGINE=NDB");

                        sql = sql.replaceAll("(?i) BIT ", " BOOLEAN ");
                        sql = sql.replaceAll("(?i) BIT,", " BOOLEAN,");

                        sql = sql.replaceAll("(?i) string_value text",
                                " string_value VARCHAR(" + DEFAULT_MAX_STRING_LENGTH_NDB + ")");

                        sql = sql.replaceAll("(?i) VARCHAR(4000)", "TEXT(4000)");
                    }

                    Object fetchedVal = executeStatement(connection, sql, fetchColumnName, optional, line,
                            scriptFile);
                    if (fetchVarName != null && fetchColumnName != null) {
                        if (fetchedVal == null) {
                            fetchedVal = defaultFetchValue;
                        }
                        // We must have some value
                        if (fetchedVal == null) {
                            // The variable is null (not even empty)
                            throw AlfrescoRuntimeException.create(ERR_STATEMENT_VAR_ASSIGNMENT_NULL,
                                    fetchVarName, fetchVarName, (line - 1), scriptUrl);
                        }
                        varAssignments.put(fetchVarName, fetchedVal);
                    }
                }
                sb.setLength(0);
                fetchVarName = null;
                fetchColumnName = null;
                defaultFetchValue = null;
                batchTableName = null;
                doBatch = false;
                batchUpperLimit = 0;
                batchSize = 1;
            }
        }
    } finally {
        try {
            reader.close();
        } catch (Throwable e) {
        }
        try {
            scriptInputStream.close();
        } catch (Throwable e) {
        }
    }
}

From source file:org.apacheextras.camel.component.hibernate.QueryBuilderHibernateTest.java

License:Open Source License

@Before
public void setUp() {
    Configuration configuration = new Configuration()
            .setProperty(Environment.DIALECT, "org.hibernate.dialect.DerbyDialect")
            .setProperty(Environment.URL, "jdbc:derby:target/testdb;create=true")
            .setProperty(Environment.USER, "").setProperty(Environment.PASS, "")
            .setProperty(Environment.HBM2DDL_AUTO, "create")
            .addResource("org/apacheextras/camel/examples/SendEmail.hbm.xml");
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
            .buildServiceRegistry();//from  www  . java2 s  .c  om
    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    session = sessionFactory.openSession();

    session.save(new SendEmail(address));
}

From source file:org.application.util.HibernateUtil.java

public static SessionFactory createSessionFactory() {
    Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
    return configuration.buildSessionFactory(
            new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build());

}

From source file:org.archiviststoolkit.hibernate.SessionFactory.java

License:Open Source License

/**
 * As this is a singleton the constructor is private.
 * In here we initialise and configure the hibernate session factory
 * making sure that it happens only once
 *///  ww  w  . j  a  v  a 2 s . co  m

private SessionFactory() {

    try {
        Configuration config = new Configuration().configure();
        Properties properties = config.getProperties();
        properties.setProperty("hibernate.connection.driver_class", driverClass);
        if (SessionFactory.databaseType.equals(DATABASE_TYPE_MYSQL)) {
            properties.setProperty("hibernate.connection.url",
                    getDatabaseUrl() + "?useUnicode=yes&characterEncoding=utf8");
        } else {
            properties.setProperty("hibernate.connection.url", getDatabaseUrl());
        }

        //deal with oracle specific settings
        if (SessionFactory.databaseType.equals(DATABASE_TYPE_ORACLE)) {
            properties.setProperty("hibernate.jdbc.batch_size", "0");
            properties.setProperty("hibernate.jdbc.use_streams_for_binary", "true");
            properties.setProperty("SetBigStringTryClob", "true");
        }
        properties.setProperty("hibernate.connection.username", getUserName());
        properties.setProperty("hibernate.connection.password", getPassword());
        properties.setProperty("hibernate.dialect", getHibernateDialect());
        if (SessionFactory.updateStructure) {
            properties.setProperty("hibernate.hbm2ddl.auto", "update");
        }
        config.setProperties(properties);
        sessionFactory = config.buildSessionFactory();
        //test the session factory to make sure it is working
    } catch (Exception hibernateException) {
        logger.log(Level.SEVERE, "Failed to startup hibernate engine", hibernateException);
        throw new RuntimeException(hibernateException);
        //            ErrorDialog dialog = new ErrorDialog("There is a problem initializing hibernate.",
        //                    StringHelper.getStackTrace(hibernateException));
        //            dialog.showDialog();
        //            System.exit(1);
    }
}

From source file:org.archiviststoolkit.plugin.dbdialog.RemoteDBConnectDialog.java

/**
 * Connect to the AT database at the given location. This does not check database version
 * so the it should be able to work with version 1.5 and 1.5.7
 *//*from w  w w  .  j  a va2 s .c om*/
private boolean connectToDatabase2() {
    // based on the database type set the driver and hibernate dialect
    String databaseType = (String) comboBox2.getSelectedItem();
    String driverClass = "";
    String hibernateDialect = "";

    if (databaseType.equals(SessionFactory.DATABASE_TYPE_MYSQL)) {
        driverClass = "com.mysql.jdbc.Driver";
        hibernateDialect = "org.hibernate.dialect.MySQLInnoDBDialect";
    } else if (databaseType.equals(SessionFactory.DATABASE_TYPE_MICROSOFT_SQL_SERVER)) {
        driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        hibernateDialect = "org.hibernate.dialect.SQLServerDialect";
    } else if (databaseType.equals(SessionFactory.DATABASE_TYPE_ORACLE)) {
        driverClass = "oracle.jdbc.OracleDriver";
        hibernateDialect = "org.hibernate.dialect.Oracle10gDialect";
    } else if (databaseType.equals(SessionFactory.DATABASE_TYPE_INTERNAL)) {
        driverClass = "org.hsqldb.jdbcDriver";
        hibernateDialect = "org.hibernate.dialect.HSQLDialect";
    } else { // should never get here
        System.out.println("Unknown database type : " + databaseType);
        return false;
    }

    // now attempt to build the session factory
    String databaseUrl = (String) connectionUrl.getSelectedItem();
    String userName = textField1.getText();
    String password = new String(passwordField1.getPassword());

    try {
        Configuration config = new Configuration().configure();
        Properties properties = config.getProperties();
        properties.setProperty("hibernate.connection.driver_class", driverClass);
        if (databaseType.equals(SessionFactory.DATABASE_TYPE_MYSQL)) {
            properties.setProperty("hibernate.connection.url",
                    databaseUrl + "?useUnicode=yes&characterEncoding=utf8");
        } else {
            properties.setProperty("hibernate.connection.url", databaseUrl);
        }
        //deal with oracle specific settings
        if (databaseType.equals(SessionFactory.DATABASE_TYPE_ORACLE)) {
            properties.setProperty("hibernate.jdbc.batch_size", "0");
            properties.setProperty("hibernate.jdbc.use_streams_for_binary", "true");
            properties.setProperty("SetBigStringTryClob", "true");
        }
        properties.setProperty("hibernate.connection.username", userName);
        properties.setProperty("hibernate.connection.password", password);
        properties.setProperty("hibernate.dialect", hibernateDialect);
        config.setProperties(properties);
        sessionFactory = config.buildSessionFactory();

        //test the session factory to make sure it is working
        testHibernate();

        return true; // connected successfully so return true
    } catch (Exception hibernateException) {
        hibernateException.printStackTrace();

        JOptionPane.showMessageDialog(this, "Failed to start hibernate engine ...", "Hibernate Error",
                JOptionPane.ERROR_MESSAGE);

        return false;
    }
}