Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Index: src/main/java/org/hibernate/util/JDBCExceptionReporter.java
- ===================================================================
- --- src/main/java/org/hibernate/util/JDBCExceptionReporter.java (revision 0)
- +++ src/main/java/org/hibernate/util/JDBCExceptionReporter.java (revision 75353)
- @@ -0,0 +1,103 @@
- +//$Id: JDBCExceptionReporter.java 10669 2006-10-31 21:24:28Z epbernard $
- +package org.hibernate.util;
- +
- +import java.sql.Connection;
- +import java.sql.SQLException;
- +import java.sql.SQLWarning;
- +
- +import org.apache.commons.logging.Log;
- +import org.apache.commons.logging.LogFactory;
- +
- +public final class JDBCExceptionReporter {
- +
- + public static final Log log = LogFactory.getLog(JDBCExceptionReporter.class);
- + public static final String DEFAULT_EXCEPTION_MSG = "SQL Exception";
- + public static final String DEFAULT_WARNING_MSG = "SQL Warning";
- +
- + private JDBCExceptionReporter() {}
- +
- + public static void logAndClearWarnings(Connection connection) {
- + if ( log.isWarnEnabled() ) {
- + try {
- + logWarnings( connection.getWarnings() );
- + }
- + catch (SQLException sqle) {
- + //workaround for WebLogic
- + log.debug("could not log warnings", sqle);
- + }
- + }
- + try {
- + //Sybase fail if we don't do that, sigh...
- + connection.clearWarnings();
- + }
- + catch (SQLException sqle) {
- + log.debug("could not clear warnings", sqle);
- + }
- + }
- +
- + public static void logWarnings(SQLWarning warning) {
- + logWarnings(warning, null);
- + }
- +
- + public static void logWarnings(SQLWarning warning, String message) {
- + if ( log.isWarnEnabled() ) {
- + if ( log.isDebugEnabled() && warning != null ) {
- + message = StringHelper.isNotEmpty(message) ? message : DEFAULT_WARNING_MSG;
- + log.debug( message, warning );
- + }
- + while (warning != null) {
- + StringBuffer buf = new StringBuffer(30)
- + .append( "SQL Warning: ")
- + .append( warning.getErrorCode() )
- + .append( ", SQLState: ")
- + .append( warning.getSQLState() );
- + log.warn( buf.toString() );
- + log.warn( warning.getMessage() );
- + warning = warning.getNextWarning();
- + }
- + }
- + }
- +
- + public static void logExceptions(SQLException ex) {
- + logExceptions(ex, null);
- + }
- +
- + public static void logExceptions(SQLException ex, String message) {
- + if ( log.isErrorEnabled() ) {
- + if ( log.isDebugEnabled() ) {
- + message = StringHelper.isNotEmpty(message) ? message : DEFAULT_EXCEPTION_MSG;
- + log.debug( message, ex );
- + }
- + while (ex != null) {
- + StringBuffer buf = new StringBuffer(30)
- + .append( "SQL Error: " )
- + .append( ex.getErrorCode() )
- + .append( ", SQLState: " )
- + .append( ex.getSQLState() );
- + log.warn( buf.toString() );
- + log.error( ex.getMessage() );
- + ex = ex.getNextException();
- + }
- + }
- + }
- +
- +// public static JDBCException newJDBCException(String string, SQLException root, String sql) {
- +// string = string + " [" + sql + ']';
- +// log.error(string, root);
- +// logExceptions(root);
- +// return new JDBCException(string, root, sql);
- +// }
- +//
- +// public static JDBCException newJDBCException(String string, SQLException root) {
- +// log.error(string, root);
- +// logExceptions(root);
- +// return new JDBCException(string, root);
- +// }
- +
- +}
- +
- +
- +
- +
- +
- +
- Property changes on: src\main\java\org\hibernate\util\JDBCExceptionReporter.java
- ___________________________________________________________________
- Added: svn:mime-type
- + text/plain
- Index: src/main/java/org/hibernate/util/StringHelper.java
- ===================================================================
- --- src/main/java/org/hibernate/util/StringHelper.java (revision 0)
- +++ src/main/java/org/hibernate/util/StringHelper.java (revision 75353)
- @@ -0,0 +1,662 @@
- +/*
- + * Hibernate, Relational Persistence for Idiomatic Java
- + *
- + * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
- + * indicated by the @author tags or express copyright attribution
- + * statements applied by the authors. All third-party contributions are
- + * distributed under license by Red Hat Middleware LLC.
- + *
- + * This copyrighted material is made available to anyone wishing to use, modify,
- + * copy, or redistribute it subject to the terms and conditions of the GNU
- + * Lesser General Public License, as published by the Free Software Foundation.
- + *
- + * This program is distributed in the hope that it will be useful,
- + * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
- + * for more details.
- + *
- + * You should have received a copy of the GNU Lesser General Public License
- + * along with this distribution; if not, write to:
- + * Free Software Foundation, Inc.
- + * 51 Franklin Street, Fifth Floor
- + * Boston, MA 02110-1301 USA
- + *
- + */
- +package org.hibernate.util;
- +
- +import java.util.Iterator;
- +import java.util.StringTokenizer;
- +import java.util.ArrayList;
- +import java.util.Arrays;
- +import java.util.regex.Pattern;
- +
- +import org.hibernate.dialect.Dialect;
- +
- +public final class StringHelper {
- +
- + private static final int ALIAS_TRUNCATE_LENGTH = 10;
- + public static final String WHITESPACE = " \n\r\f\t";
- +
- + private StringHelper() { /* static methods only - hide constructor */
- + }
- +
- + /*public static boolean containsDigits(String string) {
- + for ( int i=0; i<string.length(); i++ ) {
- + if ( Character.isDigit( string.charAt(i) ) ) return true;
- + }
- + return false;
- + }*/
- +
- + public static int lastIndexOfLetter(String string) {
- + for ( int i=0; i<string.length(); i++ ) {
- + char character = string.charAt(i);
- + if ( !Character.isLetter(character) /*&& !('_'==character)*/ ) return i-1;
- + }
- + return string.length()-1;
- + }
- +
- + public static String join(String seperator, String[] strings) {
- + int length = strings.length;
- + if ( length == 0 ) return "";
- + StringBuffer buf = new StringBuffer( length * strings[0].length() )
- + .append( strings[0] );
- + for ( int i = 1; i < length; i++ ) {
- + buf.append( seperator ).append( strings[i] );
- + }
- + return buf.toString();
- + }
- +
- + public static String join(String seperator, Iterator objects) {
- + StringBuffer buf = new StringBuffer();
- + if ( objects.hasNext() ) buf.append( objects.next() );
- + while ( objects.hasNext() ) {
- + buf.append( seperator ).append( objects.next() );
- + }
- + return buf.toString();
- + }
- +
- + public static String[] add(String[] x, String sep, String[] y) {
- + String[] result = new String[x.length];
- + for ( int i = 0; i < x.length; i++ ) {
- + result[i] = x[i] + sep + y[i];
- + }
- + return result;
- + }
- +
- + public static String repeat(String string, int times) {
- + StringBuffer buf = new StringBuffer( string.length() * times );
- + for ( int i = 0; i < times; i++ ) buf.append( string );
- + return buf.toString();
- + }
- +
- + public static String repeat(char character, int times) {
- + char[] buffer = new char[times];
- + Arrays.fill( buffer, character );
- + return new String( buffer );
- + }
- +
- +
- + public static String replace(String template, String placeholder, String replacement) {
- + return replace( template, placeholder, replacement, false );
- + }
- +
- + public static String[] replace(String templates[], String placeholder, String replacement) {
- + String[] result = new String[templates.length];
- + for ( int i =0; i<templates.length; i++ ) {
- + result[i] = replace( templates[i], placeholder, replacement );
- + }
- + return result;
- + }
- +
- + public static String replace(String template, String placeholder, String replacement, boolean wholeWords) {
- + return replace( template, placeholder, replacement, wholeWords, false );
- + }
- +
- + public static String replace(String template,
- + String placeholder,
- + String replacement,
- + boolean wholeWords,
- + boolean encloseInParensIfNecessary) {
- + if ( template == null ) {
- + return template;
- + }
- + int loc = template.indexOf( placeholder );
- + if ( loc < 0 ) {
- + return template;
- + }
- + else {
- + String beforePlaceholder = template.substring( 0, loc );
- + String afterPlaceholder = template.substring( loc + placeholder.length() );
- + return replace( beforePlaceholder, afterPlaceholder, placeholder, replacement, wholeWords, encloseInParensIfNecessary );
- + }
- + }
- +
- +
- + public static String replace(String beforePlaceholder,
- + String afterPlaceholder,
- + String placeholder,
- + String replacement,
- + boolean wholeWords,
- + boolean encloseInParensIfNecessary) {
- + final boolean actuallyReplace =
- + ! wholeWords ||
- + afterPlaceholder.length() == 0 ||
- + ! Character.isJavaIdentifierPart( afterPlaceholder.charAt( 0 ) );
- + boolean encloseInParens =
- + actuallyReplace &&
- + encloseInParensIfNecessary &&
- + ! ( getLastNonWhitespaceCharacter( beforePlaceholder ) == '(' ) &&
- + ! ( getFirstNonWhitespaceCharacter( afterPlaceholder ) == ')' );
- + StringBuilder buf = new StringBuilder( beforePlaceholder );
- + if ( encloseInParens ) {
- + buf.append( '(' );
- + }
- + buf.append( actuallyReplace ? replacement : placeholder );
- + if ( encloseInParens ) {
- + buf.append( ')' );
- + }
- + buf.append(
- + replace(
- + afterPlaceholder,
- + placeholder,
- + replacement,
- + wholeWords,
- + encloseInParensIfNecessary
- + )
- + );
- + return buf.toString();
- + }
- +
- + public static char getLastNonWhitespaceCharacter(String str) {
- + if ( str != null && str.length() > 0 ) {
- + for ( int i = str.length() - 1 ; i >= 0 ; i-- ) {
- + char ch = str.charAt( i );
- + if ( ! Character.isWhitespace( ch ) ) {
- + return ch;
- + }
- + }
- + }
- + return '\0';
- + }
- +
- + public static char getFirstNonWhitespaceCharacter(String str) {
- + if ( str != null && str.length() > 0 ) {
- + for ( int i = 0 ; i < str.length() ; i++ ) {
- + char ch = str.charAt( i );
- + if ( ! Character.isWhitespace( ch ) ) {
- + return ch;
- + }
- + }
- + }
- + return '\0';
- + }
- +
- + public static String replaceOnce(String template, String placeholder, String replacement) {
- + if ( template == null ) {
- + return template; // returnign null!
- + }
- + int loc = template.indexOf( placeholder );
- + if ( loc < 0 ) {
- + return template;
- + }
- + else {
- + return new StringBuffer( template.substring( 0, loc ) )
- + .append( replacement )
- + .append( template.substring( loc + placeholder.length() ) )
- + .toString();
- + }
- + }
- +
- +
- + public static String[] split(String seperators, String list) {
- + return split( seperators, list, false );
- + }
- +
- + public static String[] split(String seperators, String list, boolean include) {
- + StringTokenizer tokens = new StringTokenizer( list, seperators, include );
- + String[] result = new String[ tokens.countTokens() ];
- + int i = 0;
- + while ( tokens.hasMoreTokens() ) {
- + result[i++] = tokens.nextToken();
- + }
- + return result;
- + }
- +
- + public static String unqualify(String qualifiedName) {
- + int loc = qualifiedName.lastIndexOf(".");
- + return ( loc < 0 ) ? qualifiedName : qualifiedName.substring( qualifiedName.lastIndexOf(".") + 1 );
- + }
- +
- + public static String qualifier(String qualifiedName) {
- + int loc = qualifiedName.lastIndexOf(".");
- + return ( loc < 0 ) ? "" : qualifiedName.substring( 0, loc );
- + }
- +
- + /**
- + * Collapses a name. Mainly intended for use with classnames, where an example might serve best to explain.
- + * Imagine you have a class named <samp>'org.hibernate.util.StringHelper'</samp>; calling collapse on that
- + * classname will result in <samp>'o.h.u.StringHelper'<samp>.
- + *
- + * @param name The name to collapse.
- + * @return The collapsed name.
- + */
- + public static String collapse(String name) {
- + if ( name == null ) {
- + return null;
- + }
- + int breakPoint = name.lastIndexOf( '.' );
- + if ( breakPoint < 0 ) {
- + return name;
- + }
- + return collapseQualifier( name.substring( 0, breakPoint ), true ) + name.substring( breakPoint ); // includes last '.'
- + }
- +
- + /**
- + * Given a qualifier, collapse it.
- + *
- + * @param qualifier The qualifier to collapse.
- + * @param includeDots Should we include the dots in the collapsed form?
- + *
- + * @return The collapsed form.
- + */
- + public static String collapseQualifier(String qualifier, boolean includeDots) {
- + StringTokenizer tokenizer = new StringTokenizer( qualifier, "." );
- + String collapsed = Character.toString( tokenizer.nextToken().charAt( 0 ) );
- + while ( tokenizer.hasMoreTokens() ) {
- + if ( includeDots ) {
- + collapsed += '.';
- + }
- + collapsed += tokenizer.nextToken().charAt( 0 );
- + }
- + return collapsed;
- + }
- +
- + /**
- + * Partially unqualifies a qualified name. For example, with a base of 'org.hibernate' the name
- + * 'org.hibernate.util.StringHelper' would become 'util.StringHelper'.
- + *
- + * @param name The (potentially) qualified name.
- + * @param qualifierBase The qualifier base.
- + *
- + * @return The name itself, or the partially unqualified form if it begins with the qualifier base.
- + */
- + public static String partiallyUnqualify(String name, String qualifierBase) {
- + if ( name == null || ! name.startsWith( qualifierBase ) ) {
- + return name;
- + }
- + return name.substring( qualifierBase.length() + 1 ); // +1 to start after the following '.'
- + }
- +
- + /**
- + * Cross between {@link #collapse} and {@link #partiallyUnqualify}. Functions much like {@link #collapse}
- + * except that only the qualifierBase is collapsed. For example, with a base of 'org.hibernate' the name
- + * 'org.hibernate.util.StringHelper' would become 'o.h.util.StringHelper'.
- + *
- + * @param name The (potentially) qualified name.
- + * @param qualifierBase The qualifier base.
- + *
- + * @return The name itself if it does not begin with the qualifierBase, or the properly collapsed form otherwise.
- + */
- + public static String collapseQualifierBase(String name, String qualifierBase) {
- + if ( name == null || ! name.startsWith( qualifierBase ) ) {
- + return collapse( name );
- + }
- + return collapseQualifier( qualifierBase, true ) + name.substring( qualifierBase.length() );
- + }
- +
- + public static String[] suffix(String[] columns, String suffix) {
- + if ( suffix == null ) return columns;
- + String[] qualified = new String[columns.length];
- + for ( int i = 0; i < columns.length; i++ ) {
- + qualified[i] = suffix( columns[i], suffix );
- + }
- + return qualified;
- + }
- +
- + private static String suffix(String name, String suffix) {
- + return ( suffix == null ) ? name : name + suffix;
- + }
- +
- + public static String root(String qualifiedName) {
- + int loc = qualifiedName.indexOf( "." );
- + return ( loc < 0 ) ? qualifiedName : qualifiedName.substring( 0, loc );
- + }
- +
- + public static String unroot(String qualifiedName) {
- + int loc = qualifiedName.indexOf( "." );
- + return ( loc < 0 ) ? qualifiedName : qualifiedName.substring( loc+1, qualifiedName.length() );
- + }
- +
- + public static boolean booleanValue(String tfString) {
- + String trimmed = tfString.trim().toLowerCase();
- + return trimmed.equals( "true" ) || trimmed.equals( "t" );
- + }
- +
- + public static String toString(Object[] array) {
- + int len = array.length;
- + if ( len == 0 ) return "";
- + StringBuffer buf = new StringBuffer( len * 12 );
- + for ( int i = 0; i < len - 1; i++ ) {
- + buf.append( array[i] ).append(", ");
- + }
- + return buf.append( array[len - 1] ).toString();
- + }
- +
- + public static String[] multiply(String string, Iterator placeholders, Iterator replacements) {
- + String[] result = new String[]{string};
- + while ( placeholders.hasNext() ) {
- + result = multiply( result, ( String ) placeholders.next(), ( String[] ) replacements.next() );
- + }
- + return result;
- + }
- +
- + private static String[] multiply(String[] strings, String placeholder, String[] replacements) {
- + String[] results = new String[replacements.length * strings.length];
- + int n = 0;
- + for ( int i = 0; i < replacements.length; i++ ) {
- + for ( int j = 0; j < strings.length; j++ ) {
- + results[n++] = replaceOnce( strings[j], placeholder, replacements[i] );
- + }
- + }
- + return results;
- + }
- +
- + public static int countUnquoted(String string, char character) {
- + if ( '\'' == character ) {
- + throw new IllegalArgumentException( "Unquoted count of quotes is invalid" );
- + }
- + if (string == null)
- + return 0;
- + // Impl note: takes advantage of the fact that an escpaed single quote
- + // embedded within a quote-block can really be handled as two seperate
- + // quote-blocks for the purposes of this method...
- + int count = 0;
- + int stringLength = string.length();
- + boolean inQuote = false;
- + for ( int indx = 0; indx < stringLength; indx++ ) {
- + char c = string.charAt( indx );
- + if ( inQuote ) {
- + if ( '\'' == c ) {
- + inQuote = false;
- + }
- + }
- + else if ( '\'' == c ) {
- + inQuote = true;
- + }
- + else if ( c == character ) {
- + count++;
- + }
- + }
- + return count;
- + }
- +
- + public static int[] locateUnquoted(String string, char character) {
- + if ( '\'' == character ) {
- + throw new IllegalArgumentException( "Unquoted count of quotes is invalid" );
- + }
- + if (string == null) {
- + return new int[0];
- + }
- +
- + ArrayList locations = new ArrayList( 20 );
- +
- + // Impl note: takes advantage of the fact that an escpaed single quote
- + // embedded within a quote-block can really be handled as two seperate
- + // quote-blocks for the purposes of this method...
- + int stringLength = string.length();
- + boolean inQuote = false;
- + for ( int indx = 0; indx < stringLength; indx++ ) {
- + char c = string.charAt( indx );
- + if ( inQuote ) {
- + if ( '\'' == c ) {
- + inQuote = false;
- + }
- + }
- + else if ( '\'' == c ) {
- + inQuote = true;
- + }
- + else if ( c == character ) {
- + locations.add( new Integer( indx ) );
- + }
- + }
- + return ArrayHelper.toIntArray( locations );
- + }
- +
- + public static boolean isNotEmpty(String string) {
- + return string != null && string.length() > 0;
- + }
- +
- + public static boolean isEmpty(String string) {
- + return string == null || string.length() == 0;
- + }
- +
- + public static String qualify(String prefix, String name) {
- + if ( name == null || prefix == null ) {
- + throw new NullPointerException();
- + }
- + return new StringBuffer( prefix.length() + name.length() + 1 )
- + .append(prefix)
- + .append('.')
- + .append(name)
- + .toString();
- + }
- +
- + public static String[] qualify(String prefix, String[] names) {
- + if ( prefix == null ) return names;
- + int len = names.length;
- + String[] qualified = new String[len];
- + for ( int i = 0; i < len; i++ ) {
- + qualified[i] = qualify( prefix, names[i] );
- + }
- + return qualified;
- + }
- +
- + public static int firstIndexOfChar(String sqlString, String string, int startindex) {
- + int matchAt = -1;
- + for ( int i = 0; i < string.length(); i++ ) {
- + int curMatch = sqlString.indexOf( string.charAt( i ), startindex );
- + if ( curMatch >= 0 ) {
- + if ( matchAt == -1 ) { // first time we find match!
- + matchAt = curMatch;
- + }
- + else {
- + matchAt = Math.min( matchAt, curMatch );
- + }
- + }
- + }
- + return matchAt;
- + }
- +
- + public static String truncate(String string, int length) {
- + if ( string.length() <= length ) {
- + return string;
- + }
- + else {
- + return string.substring( 0, length );
- + }
- + }
- +
- + public static String generateAlias(String description) {
- + return generateAliasRoot(description) + '_';
- + }
- +
- + /**
- + * Generate a nice alias for the given class name or collection role name and unique integer. Subclasses of
- + * Loader do <em>not</em> have to use aliases of this form.
- + *
- + * @param description The base name (usually an entity-name or collection-role)
- + * @param unique A uniquing value
- + *
- + * @return an alias of the form <samp>foo1_</samp>
- + */
- + public static String generateAlias(String description, int unique) {
- + return generateAliasRoot(description) +
- + Integer.toString(unique) +
- + '_';
- + }
- +
- + /**
- + * Generates a root alias by truncating the "root name" defined by
- + * the incoming decription and removing/modifying any non-valid
- + * alias characters.
- + *
- + * @param description The root name from which to generate a root alias.
- + * @return The generated root alias.
- + */
- + private static String generateAliasRoot(String description) {
- + String result = truncate( unqualifyEntityName(description), ALIAS_TRUNCATE_LENGTH )
- + .toLowerCase()
- + .replace( '/', '_' ) // entityNames may now include slashes for the representations
- + .replace( '$', '_' ); //classname may be an inner class
- + result = cleanAlias( result );
- + if ( Character.isDigit( result.charAt(result.length()-1) ) ) {
- + return result + "x"; //ick!
- + }
- + else {
- + return result;
- + }
- + }
- +
- + /**
- + * Clean the generated alias by removing any non-alpha characters from the
- + * beginning.
- + *
- + * @param alias The generated alias to be cleaned.
- + * @return The cleaned alias, stripped of any leading non-alpha characters.
- + */
- + private static String cleanAlias(String alias) {
- + char[] chars = alias.toCharArray();
- + // short cut check...
- + if ( !Character.isLetter( chars[0] ) ) {
- + for ( int i = 1; i < chars.length; i++ ) {
- + // as soon as we encounter our first letter, return the substring
- + // from that position
- + if ( Character.isLetter( chars[i] ) ) {
- + return alias.substring( i );
- + }
- + }
- + }
- + return alias;
- + }
- +
- + public static String unqualifyEntityName(String entityName) {
- + String result = unqualify(entityName);
- + int slashPos = result.indexOf( '/' );
- + if ( slashPos > 0 ) {
- + result = result.substring( 0, slashPos - 1 );
- + }
- + return result;
- + }
- +
- + public static String toUpperCase(String str) {
- + return str==null ? null : str.toUpperCase();
- + }
- +
- + public static String toLowerCase(String str) {
- + return str==null ? null : str.toLowerCase();
- + }
- +
- + public static String moveAndToBeginning(String filter) {
- + if ( filter.trim().length()>0 ){
- + filter += " and ";
- + if ( filter.startsWith(" and ") ) filter = filter.substring(4);
- + }
- + return filter;
- + }
- +
- + /**
- + * Determine if the given string is quoted (wrapped by '`' characters at beginning and end).
- + *
- + * @param name The name to check.
- + * @return True if the given string starts and ends with '`'; false otherwise.
- + */
- + public static boolean isQuoted(String name) {
- + return name != null && name.length() != 0 && name.charAt( 0 ) == '`' && name.charAt( name.length() - 1 ) == '`';
- + }
- +
- + /**
- + * Return a representation of the given name ensuring quoting (wrapped with '`' characters). If already wrapped
- + * return name.
- + *
- + * @param name The name to quote.
- + * @return The quoted version.
- + */
- + public static String quote(String name) {
- + if ( name == null || name.length() == 0 || isQuoted( name ) ) {
- + return name;
- + }
- + else {
- + return new StringBuffer( name.length() + 2 ).append('`').append( name ).append( '`' ).toString();
- + }
- + }
- +
- + /**
- + * Return the unquoted version of name (stripping the start and end '`' characters if present).
- + *
- + * @param name The name to be unquoted.
- + * @return The unquoted version.
- + */
- + public static String unquote(String name) {
- + if ( isQuoted( name ) ) {
- + return name.substring( 1, name.length() - 1 );
- + }
- + else {
- + return name;
- + }
- + }
- +
- + /**
- + * Determine if the given name is quoted. It is considered quoted if either:
- + * <ol>
- + * <li>starts AND ends with backticks (`)</li>
- + * <li>starts with dialect-specified {@link org.hibernate.dialect.Dialect#openQuote() open-quote}
- + * AND ends with dialect-specified {@link org.hibernate.dialect.Dialect#closeQuote() close-quote}</li>
- + * </ol>
- + *
- + * @param name The name to check
- + * @param dialect The dialect (to determine the "real" quoting chars).
- + *
- + * @return True if quoted, false otherwise
- + */
- + public static boolean isQuoted(String name, Dialect dialect) {
- + return name != null && name.length() != 0
- + && ( name.charAt( 0 ) == '`' && name.charAt( name.length() - 1 ) == '`'
- + || name.charAt( 0 ) == dialect.openQuote() && name.charAt( name.length() - 1 ) == dialect.closeQuote() );
- + }
- +
- + /**
- + * Return the unquoted version of name stripping the start and end quote characters.
- + *
- + * @param name The name to be unquoted.
- + * @param dialect The dialect (to determine the "real" quoting chars).
- + *
- + * @return The unquoted version.
- + */
- + public static String unquote(String name, Dialect dialect) {
- + if ( isQuoted( name, dialect ) ) {
- + return name.substring( 1, name.length() - 1 );
- + }
- + else {
- + return name;
- + }
- + }
- +
- + /**
- + * Return the unquoted version of name stripping the start and end quote characters.
- + *
- + * @param names The names to be unquoted.
- + * @param dialect The dialect (to determine the "real" quoting chars).
- + *
- + * @return The unquoted versions.
- + */
- + public static String[] unquote(String[] names, Dialect dialect) {
- + if ( names == null ) {
- + return null;
- + }
- + String[] unquoted = new String[ names.length ];
- + for ( int i = 0; i < names.length; i++ ) {
- + unquoted[i] = unquote( names[i], dialect );
- + }
- + return unquoted;
- + }
- +}
- Property changes on: src\main\java\org\hibernate\util\StringHelper.java
- ___________________________________________________________________
- Added: svn:mime-type
- + text/plain
- Index: src/main/java/org/hibernate/util/ArrayHelper.java
- ===================================================================
- --- src/main/java/org/hibernate/util/ArrayHelper.java (revision 0)
- +++ src/main/java/org/hibernate/util/ArrayHelper.java (revision 75353)
- @@ -0,0 +1,372 @@
- +/*
- + * Hibernate, Relational Persistence for Idiomatic Java
- + *
- + * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
- + * indicated by the @author tags or express copyright attribution
- + * statements applied by the authors. All third-party contributions are
- + * distributed under license by Red Hat Middleware LLC.
- + *
- + * This copyrighted material is made available to anyone wishing to use, modify,
- + * copy, or redistribute it subject to the terms and conditions of the GNU
- + * Lesser General Public License, as published by the Free Software Foundation.
- + *
- + * This program is distributed in the hope that it will be useful,
- + * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
- + * for more details.
- + *
- + * You should have received a copy of the GNU Lesser General Public License
- + * along with this distribution; if not, write to:
- + * Free Software Foundation, Inc.
- + * 51 Franklin Street, Fifth Floor
- + * Boston, MA 02110-1301 USA
- + *
- + */
- +package org.hibernate.util;
- +
- +import java.lang.reflect.Array;
- +import java.util.ArrayList;
- +import java.util.Arrays;
- +import java.util.Collection;
- +import java.util.Iterator;
- +import java.util.List;
- +
- +import org.hibernate.LockMode;
- +import org.hibernate.LockOptions;
- +import org.hibernate.type.Type;
- +
- +public final class ArrayHelper {
- +
- + /*public static boolean contains(Object[] array, Object object) {
- + for ( int i=0; i<array.length; i++ ) {
- + if ( array[i].equals(object) ) return true;
- + }
- + return false;
- + }*/
- +
- + public static int indexOf(Object[] array, Object object) {
- + for ( int i=0; i<array.length; i++ ) {
- + if ( array[i].equals(object) ) return i;
- + }
- + return -1;
- + }
- +
- + /*public static Object[] clone(Class elementClass, Object[] array) {
- + Object[] result = (Object[]) Array.newInstance( elementClass, array.length );
- + System.arraycopy(array, 0, result, 0, array.length);
- + return result;
- + }*/
- +
- + public static String[] toStringArray(Object[] objects) {
- + int length=objects.length;
- + String[] result = new String[length];
- + for (int i=0; i<length; i++) {
- + result[i] = objects[i].toString();
- + }
- + return result;
- + }
- +
- + public static String[] fillArray(String value, int length) {
- + String[] result = new String[length];
- + Arrays.fill(result, value);
- + return result;
- + }
- +
- + public static int[] fillArray(int value, int length) {
- + int[] result = new int[length];
- + Arrays.fill(result, value);
- + return result;
- + }
- +
- + public static LockMode[] fillArray(LockMode lockMode, int length) {
- + LockMode[] array = new LockMode[length];
- + Arrays.fill(array, lockMode);
- + return array;
- + }
- +
- + public static LockOptions[] fillArray(LockOptions lockOptions, int length) {
- + LockOptions[] array = new LockOptions[length];
- + Arrays.fill(array, lockOptions);
- + return array;
- + }
- +
- + public static String[] toStringArray(Collection coll) {
- + return (String[]) coll.toArray( new String[coll.size()] );
- + }
- +
- + public static String[][] to2DStringArray(Collection coll) {
- + return (String[][]) coll.toArray( new String[ coll.size() ][] );
- + }
- +
- + public static int[][] to2DIntArray(Collection coll) {
- + return (int[][]) coll.toArray( new int[ coll.size() ][] );
- + }
- +
- + public static Type[] toTypeArray(Collection coll) {
- + return (Type[]) coll.toArray( new Type[coll.size()] );
- + }
- +
- + public static int[] toIntArray(Collection coll) {
- + Iterator iter = coll.iterator();
- + int[] arr = new int[ coll.size() ];
- + int i=0;
- + while( iter.hasNext() ) {
- + arr[i++] = ( (Integer) iter.next() ).intValue();
- + }
- + return arr;
- + }
- +
- + public static boolean[] toBooleanArray(Collection coll) {
- + Iterator iter = coll.iterator();
- + boolean[] arr = new boolean[ coll.size() ];
- + int i=0;
- + while( iter.hasNext() ) {
- + arr[i++] = ( (Boolean) iter.next() ).booleanValue();
- + }
- + return arr;
- + }
- +
- + public static Object[] typecast(Object[] array, Object[] to) {
- + return java.util.Arrays.asList(array).toArray(to);
- + }
- +
- + //Arrays.asList doesn't do primitive arrays
- + public static List toList(Object array) {
- + if ( array instanceof Object[] ) return Arrays.asList( (Object[]) array ); //faster?
- + int size = Array.getLength(array);
- + ArrayList list = new ArrayList(size);
- + for (int i=0; i<size; i++) {
- + list.add( Array.get(array, i) );
- + }
- + return list;
- + }
- +
- + public static String[] slice(String[] strings, int begin, int length) {
- + String[] result = new String[length];
- + System.arraycopy( strings, begin, result, 0, length );
- + return result;
- + }
- +
- + public static Object[] slice(Object[] objects, int begin, int length) {
- + Object[] result = new Object[length];
- + System.arraycopy( objects, begin, result, 0, length );
- + return result;
- + }
- +
- + public static List toList(Iterator iter) {
- + List list = new ArrayList();
- + while ( iter.hasNext() ) {
- + list.add( iter.next() );
- + }
- + return list;
- + }
- +
- + public static String[] join(String[] x, String[] y) {
- + String[] result = new String[ x.length + y.length ];
- + System.arraycopy( x, 0, result, 0, x.length );
- + System.arraycopy( y, 0, result, x.length, y.length );
- + return result;
- + }
- +
- + public static String[] join(String[] x, String[] y, boolean[] use) {
- + String[] result = new String[ x.length + countTrue(use) ];
- + System.arraycopy( x, 0, result, 0, x.length );
- + int k = x.length;
- + for ( int i=0; i<y.length; i++ ) {
- + if ( use[i] ) {
- + result[k++] = y[i];
- + }
- + }
- + return result;
- + }
- +
- + public static int[] join(int[] x, int[] y) {
- + int[] result = new int[ x.length + y.length ];
- + System.arraycopy( x, 0, result, 0, x.length );
- + System.arraycopy( y, 0, result, x.length, y.length );
- + return result;
- + }
- +
- + public static final boolean[] TRUE = { true };
- + public static final boolean[] FALSE = { false };
- +
- + private ArrayHelper() {}
- +
- + public static String toString( Object[] array ) {
- + StringBuffer sb = new StringBuffer();
- + sb.append("[");
- + for (int i = 0; i < array.length; i++) {
- + sb.append( array[i] );
- + if( i<array.length-1 ) sb.append(",");
- + }
- + sb.append("]");
- + return sb.toString();
- + }
- +
- + public static boolean isAllNegative(int[] array) {
- + for ( int i=0; i<array.length; i++ ) {
- + if ( array[i] >=0 ) return false;
- + }
- + return true;
- + }
- +
- + public static boolean isAllTrue(boolean[] array) {
- + for ( int i=0; i<array.length; i++ ) {
- + if ( !array[i] ) return false;
- + }
- + return true;
- + }
- +
- + public static int countTrue(boolean[] array) {
- + int result=0;
- + for ( int i=0; i<array.length; i++ ) {
- + if ( array[i] ) result++;
- + }
- + return result;
- + }
- +
- + /*public static int countFalse(boolean[] array) {
- + int result=0;
- + for ( int i=0; i<array.length; i++ ) {
- + if ( !array[i] ) result++;
- + }
- + return result;
- + }*/
- +
- + public static boolean isAllFalse(boolean[] array) {
- + for ( int i=0; i<array.length; i++ ) {
- + if ( array[i] ) return false;
- + }
- + return true;
- + }
- +
- + public static void addAll(Collection collection, Object[] array) {
- + collection.addAll( Arrays.asList( array ) );
- + }
- +
- + public static final String[] EMPTY_STRING_ARRAY = {};
- + public static final int[] EMPTY_INT_ARRAY = {};
- + public static final boolean[] EMPTY_BOOLEAN_ARRAY = {};
- + public static final Class[] EMPTY_CLASS_ARRAY = {};
- + public static final Object[] EMPTY_OBJECT_ARRAY = {};
- + public static final Type[] EMPTY_TYPE_ARRAY = {};
- +
- + public static int[] getBatchSizes(int maxBatchSize) {
- + int batchSize = maxBatchSize;
- + int n=1;
- + while ( batchSize>1 ) {
- + batchSize = getNextBatchSize(batchSize);
- + n++;
- + }
- + int[] result = new int[n];
- + batchSize = maxBatchSize;
- + for ( int i=0; i<n; i++ ) {
- + result[i] = batchSize;
- + batchSize = getNextBatchSize(batchSize);
- + }
- + return result;
- + }
- +
- + private static int getNextBatchSize(int batchSize) {
- + if (batchSize<=10) {
- + return batchSize-1; //allow 9,8,7,6,5,4,3,2,1
- + }
- + else if (batchSize/2 < 10) {
- + return 10;
- + }
- + else {
- + return batchSize / 2;
- + }
- + }
- +
- + private static int SEED = 23;
- + private static int PRIME_NUMER = 37;
- +
- + /**
- + * calculate the array hash (only the first level)
- + */
- + public static int hash(Object[] array) {
- + int length = array.length;
- + int seed = SEED;
- + for (int index = 0 ; index < length ; index++) {
- + seed = hash( seed, array[index] == null ? 0 : array[index].hashCode() );
- + }
- + return seed;
- + }
- +
- + /**
- + * calculate the array hash (only the first level)
- + */
- + public static int hash(char[] array) {
- + int length = array.length;
- + int seed = SEED;
- + for (int index = 0 ; index < length ; index++) {
- + seed = hash( seed, (int) array[index] ) ;
- + }
- + return seed;
- + }
- +
- + /**
- + * calculate the array hash (only the first level)
- + */
- + public static int hash(byte[] bytes) {
- + int length = bytes.length;
- + int seed = SEED;
- + for (int index = 0 ; index < length ; index++) {
- + seed = hash( seed, (int) bytes[index] ) ;
- + }
- + return seed;
- + }
- +
- + private static int hash(int seed, int i) {
- + return PRIME_NUMER * seed + i;
- + }
- +
- + /**
- + * Compare 2 arrays only at the first level
- + */
- + public static boolean isEquals(Object[] o1, Object[] o2) {
- + if (o1 == o2) return true;
- + if (o1 == null || o2 == null) return false;
- + int length = o1.length;
- + if (length != o2.length) return false;
- + for (int index = 0 ; index < length ; index++) {
- + if ( ! o1[index].equals( o2[index] ) ) return false;
- + }
- + return true;
- + }
- +
- + /**
- + * Compare 2 arrays only at the first level
- + */
- + public static boolean isEquals(char[] o1, char[] o2) {
- + if (o1 == o2) return true;
- + if (o1 == null || o2 == null) return false;
- + int length = o1.length;
- + if (length != o2.length) return false;
- + for (int index = 0 ; index < length ; index++) {
- + if ( ! ( o1[index] == o2[index] ) ) return false;
- + }
- + return true;
- + }
- +
- + /**
- + * Compare 2 arrays only at the first level
- + */
- + public static boolean isEquals(byte[] b1, byte[] b2) {
- + if (b1 == b2) return true;
- + if (b1 == null || b2 == null) return false;
- + int length = b1.length;
- + if (length != b2.length) return false;
- + for (int index = 0 ; index < length ; index++) {
- + if ( ! ( b1[index] == b2[index] ) ) return false;
- + }
- + return true;
- + }
- +}
- +
- +
- +
- +
- +
- +
- Property changes on: src\main\java\org\hibernate\util\ArrayHelper.java
- ___________________________________________________________________
- Added: svn:mime-type
- + text/plain
- Index: src/main/java/org/jbpm/ant/ShutDownHsqldb.java
- ===================================================================
- --- src/main/java/org/jbpm/ant/ShutDownHsqldb.java (revision 65983)
- +++ src/main/java/org/jbpm/ant/ShutDownHsqldb.java (revision 75353)
- @@ -6,8 +6,8 @@
- import org.apache.tools.ant.BuildException;
- import org.apache.tools.ant.Task;
- -import org.hibernate.connection.ConnectionProvider;
- -import org.hibernate.impl.SessionFactoryImpl;
- +//import org.hibernate.connection.ConnectionProvider;
- +//import org.hibernate.impl.SessionFactoryImpl;
- import org.jbpm.JbpmConfiguration;
- import org.jbpm.JbpmContext;
- import org.jbpm.persistence.db.DbPersistenceServiceFactory;
- @@ -19,21 +19,21 @@
- Connection connection = null;
- JbpmConfiguration jbpmConfiguration = AntHelper.getJbpmConfiguration(null);
- JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
- - try {
- - DbPersistenceServiceFactory dbPersistenceServiceFactory = (DbPersistenceServiceFactory) jbpmContext.getServiceFactory(Services.SERVICENAME_PERSISTENCE);
- - SessionFactoryImpl sessionFactory = (SessionFactoryImpl) dbPersistenceServiceFactory.getSessionFactory();
- - ConnectionProvider connectionProvider = sessionFactory.getConnectionProvider();
- - connection = connectionProvider.getConnection();
- - Statement statement = connection.createStatement();
- - log("shutting down database");
- - statement.executeUpdate("SHUTDOWN");
- - connection.close();
- -
- - } catch (SQLException e) {
- - e.printStackTrace();
- - } finally {
- - jbpmContext.close();
- - }
- +// try {
- +// DbPersistenceServiceFactory dbPersistenceServiceFactory = (DbPersistenceServiceFactory) jbpmContext.getServiceFactory(Services.SERVICENAME_PERSISTENCE);
- +// SessionFactoryImpl sessionFactory = (SessionFactoryImpl) dbPersistenceServiceFactory.getSessionFactory();
- +// ConnectionProvider connectionProvider = sessionFactory.getConnectionProvider();
- +// connection = connectionProvider.getConnection();
- +// Statement statement = connection.createStatement();
- +// log("shutting down database");
- +// statement.executeUpdate("SHUTDOWN");
- +// connection.close();
- +//
- +// } catch (SQLException e) {
- +// e.printStackTrace();
- +// } finally {
- +// jbpmContext.close();
- +// }
- }
- }
- Index: src/main/java/org/jbpm/persistence/db/DbPersistenceService.java
- ===================================================================
- --- src/main/java/org/jbpm/persistence/db/DbPersistenceService.java (revision 65983)
- +++ src/main/java/org/jbpm/persistence/db/DbPersistenceService.java (revision 75353)
- @@ -22,6 +22,7 @@
- package org.jbpm.persistence.db;
- import java.sql.Connection;
- +import java.sql.SQLException;
- import javax.sql.DataSource;
- @@ -43,421 +44,463 @@
- import org.jbpm.svc.Service;
- import org.jbpm.svc.Services;
- import org.jbpm.tx.TxService;
- +import org.hibernate.jdbc.Work;
- public class DbPersistenceService implements Service, PersistenceService {
- -
- - private static final long serialVersionUID = 1L;
- +
- + private static final long serialVersionUID = 1L;
- +
- + protected DbPersistenceServiceFactory persistenceServiceFactory = null;
- +
- + protected Connection connection = null;
- + protected boolean mustConnectionBeClosed = false;
- +
- + protected Transaction transaction = null;
- + protected boolean isTransactionEnabled = true;
- + protected boolean isCurrentSessionEnabled = false;
- +
- + // boolean isRollbackOnly = false;
- +
- + protected Session session;
- + protected boolean mustSessionBeFlushed = false;
- + protected boolean mustSessionBeClosed = false;
- +
- + protected Services services = null;
- +
- + protected GraphSession graphSession = null;
- + protected TaskMgmtSession taskMgmtSession = null;
- + protected JobSession jobSession = null;
- + protected ContextSession contextSession = null;
- + protected LoggingSession loggingSession = null;
- +
- + public DbPersistenceService(DbPersistenceServiceFactory persistenceServiceFactory) {
- + this(persistenceServiceFactory, getCurrentServices());
- + }
- +
- + static Services getCurrentServices() {
- + Services services = null;
- + JbpmContext currentJbpmContext = JbpmContext.getCurrentJbpmContext();
- + if (currentJbpmContext != null) {
- + services = currentJbpmContext.getServices();
- + }
- + return services;
- + }
- - protected DbPersistenceServiceFactory persistenceServiceFactory = null;
- + DbPersistenceService(DbPersistenceServiceFactory persistenceServiceFactory, Services services) {
- + this.persistenceServiceFactory = persistenceServiceFactory;
- + this.isTransactionEnabled = persistenceServiceFactory.isTransactionEnabled();
- + this.isCurrentSessionEnabled = persistenceServiceFactory.isCurrentSessionEnabled();
- + this.services = services;
- + }
- - protected Connection connection = null;
- - protected boolean mustConnectionBeClosed = false;
- + public SessionFactory getSessionFactory() {
- + return persistenceServiceFactory.getSessionFactory();
- + }
- - protected Transaction transaction = null;
- - protected boolean isTransactionEnabled = true;
- - protected boolean isCurrentSessionEnabled = false;
- + public Session getSession() {
- + if ((session == null) && (getSessionFactory() != null)) {
- + Connection connection = getConnection(false);
- + if (isCurrentSessionEnabled) {
- + session = getSessionFactory().getCurrentSession();
- + log.debug("using current hibernate session " + session);
- + mustSessionBeClosed = false;
- + mustSessionBeFlushed = false;
- + mustConnectionBeClosed = false;
- + } else if (connection != null) {
- + log.debug("creating hibernate session with connection " + connection);
- + session = getSessionFactory().openSession();
- + session.reconnect(connection);
- + mustSessionBeClosed = true;
- + mustSessionBeFlushed = true;
- + mustConnectionBeClosed = false;
- + } else {
- + log.debug("creating hibernate session");
- + session = getSessionFactory().openSession();
- + mustSessionBeClosed = true;
- + mustSessionBeFlushed = true;
- + mustConnectionBeClosed = false;
- + }
- - // boolean isRollbackOnly = false;
- + if (isTransactionEnabled) {
- + beginTransaction();
- + }
- + }
- + return session;
- + }
- - protected Session session;
- - protected boolean mustSessionBeFlushed = false;
- - protected boolean mustSessionBeClosed = false;
- + public void beginTransaction() {
- + log.debug("beginning hibernate transaction");
- + transaction = session.beginTransaction();
- + log.debug("begun hibernate transaction " + transaction.toString());
- + }
- - protected Services services = null;
- + public void endTransaction() {
- + if ((isTransactionEnabled) && (transaction != null)) {
- + if (isRollbackOnly()) {
- + try {
- + log.debug("rolling back hibernate transaction " + transaction.toString());
- + mustSessionBeFlushed = false; // flushing updates that will
- + // be rolled back is not
- + // very clever :-)
- + transaction.rollback();
- + } catch (Exception e) {
- + // NOTE that Error's are not caught because that might halt
- + // the JVM and mask the original Error.
- + throw new JbpmPersistenceException("couldn't rollback hibernate session", e);
- + }
- + } else {
- + try {
- + log.debug("committing hibernate transaction " + transaction.toString());
- + mustSessionBeFlushed = false; // commit does a flush anyway
- + transaction.commit();
- + } catch (Exception e) {
- + // NOTE that Error's are not caught because that might halt
- + // the JVM and mask the original Error.
- + try {
- + // if the commit fails, we must do a rollback
- + transaction.rollback();
- + } catch (Exception e2) {
- + // if the rollback fails, we did what we could and
- + // you're in
- + // deep shit :-(
- + log.error("problem rolling back after failed commit", e2);
- + }
- + throw new JbpmPersistenceException("couldn't commit hibernate session", e);
- + }
- + }
- + }
- + }
- - protected GraphSession graphSession = null;
- - protected TaskMgmtSession taskMgmtSession = null;
- - protected JobSession jobSession = null;
- - protected ContextSession contextSession = null;
- - protected LoggingSession loggingSession = null;
- + public Connection getConnection() {
- + return getConnection(true);
- + }
- - public DbPersistenceService(DbPersistenceServiceFactory persistenceServiceFactory) {
- - this(persistenceServiceFactory, getCurrentServices());
- - }
- + public Connection getConnection(boolean resolveSession) {
- + if (connection == null) {
- + if (persistenceServiceFactory.getDataSource() != null) {
- + try {
- + log.debug("fetching jdbc connection from datasource");
- + connection = persistenceServiceFactory.getDataSource().getConnection();
- + mustConnectionBeClosed = true;
- + } catch (Exception e) {
- + // NOTE that Error's are not caught because that might halt
- + // the JVM and mask the original Error.
- + throw new JbpmException("couldn't obtain connection from datasource", e);
- + }
- + } else {
- + if (resolveSession) {
- + // initializes the session member
- + getSession();
- + }
- + if (session != null) {
- + GetConnectionWork work = new GetConnectionWork();
- + session.doWork(work);
- + connection = work.getConnection();
- + log.debug("fetching connection from hibernate session. this transfers responsibility for closing the jdbc connection to the user! "
- + + connection);
- + mustConnectionBeClosed = false;
- + }
- + }
- + }
- + return connection;
- + }
- - static Services getCurrentServices() {
- - Services services = null;
- - JbpmContext currentJbpmContext = JbpmContext.getCurrentJbpmContext();
- - if (currentJbpmContext!=null) {
- - services = currentJbpmContext.getServices();
- - }
- - return services;
- - }
- + public void close() {
- - DbPersistenceService(DbPersistenceServiceFactory persistenceServiceFactory, Services services) {
- - this.persistenceServiceFactory = persistenceServiceFactory;
- - this.isTransactionEnabled = persistenceServiceFactory.isTransactionEnabled();
- - this.isCurrentSessionEnabled = persistenceServiceFactory.isCurrentSessionEnabled();
- - this.services = services;
- - }
- + if ((session != null) && (transaction == null) && (isRollbackOnly())) {
- + throw new JbpmException(
- + "setRollbackOnly was invoked while configuration specifies user managed transactions");
- + }
- - public SessionFactory getSessionFactory() {
- - return persistenceServiceFactory.getSessionFactory();
- - }
- + if ((isTransactionEnabled) && (transaction != null)) {
- - public Session getSession() {
- - if ( (session==null)
- - && (getSessionFactory()!=null)
- - ) {
- - Connection connection = getConnection(false);
- - if (isCurrentSessionEnabled) {
- - session = getSessionFactory().getCurrentSession();
- - log.debug("using current hibernate session " + session);
- - mustSessionBeClosed = false;
- - mustSessionBeFlushed = false;
- - mustConnectionBeClosed = false;
- - } else if (connection!=null) {
- - log.debug("creating hibernate session with connection "+connection);
- - session = getSessionFactory().openSession(connection);
- - mustSessionBeClosed = true;
- - mustSessionBeFlushed = true;
- - mustConnectionBeClosed = false;
- - } else {
- - log.debug("creating hibernate session");
- - session = getSessionFactory().openSession();
- - mustSessionBeClosed = true;
- - mustSessionBeFlushed = true;
- - mustConnectionBeClosed = false;
- - }
- -
- - if (isTransactionEnabled) {
- - beginTransaction();
- - }
- - }
- - return session;
- - }
- + if (!isRollbackOnly()) {
- + Exception commitException = commit();
- + if (commitException != null) {
- + rollback();
- + closeSession();
- + closeConnection();
- + throw new JbpmPersistenceException("hibernate commit failed", commitException);
- + }
- - public void beginTransaction() {
- - log.debug("beginning hibernate transaction");
- - transaction = session.beginTransaction();
- - log.debug("begun hibernate transaction " + transaction.toString());
- - }
- + } else { // isRollbackOnly==true
- + Exception rollbackException = rollback();
- + if (rollbackException != null) {
- + closeSession();
- + closeConnection();
- + throw new JbpmPersistenceException("hibernate rollback failed", rollbackException);
- + }
- + }
- + }
- - public void endTransaction() {
- - if ( (isTransactionEnabled)
- - && (transaction!=null)
- - ) {
- - if (isRollbackOnly()) {
- - try {
- - log.debug("rolling back hibernate transaction " + transaction.toString());
- - mustSessionBeFlushed = false; // flushing updates that will be rolled back is not very clever :-)
- - transaction.rollback();
- - } catch (Exception e) {
- - // NOTE that Error's are not caught because that might halt the JVM and mask the original Error.
- - throw new JbpmPersistenceException("couldn't rollback hibernate session", e);
- - }
- - } else {
- - try {
- - log.debug("committing hibernate transaction " + transaction.toString());
- - mustSessionBeFlushed = false; // commit does a flush anyway
- - transaction.commit();
- - } catch (Exception e) {
- - // NOTE that Error's are not caught because that might halt the JVM and mask the original Error.
- - try {
- - // if the commit fails, we must do a rollback
- - transaction.rollback();
- - } catch (Exception e2) {
- - // if the rollback fails, we did what we could and you're in
- - // deep shit :-(
- - log.error("problem rolling back after failed commit", e2);
- - }
- - throw new JbpmPersistenceException("couldn't commit hibernate session", e);
- - }
- - }
- - }
- - }
- + Exception flushException = flushSession();
- + if (flushException != null) {
- + rollback();
- + closeSession();
- + closeConnection();
- + throw new JbpmPersistenceException("hibernate flush failed", flushException);
- + }
- - public Connection getConnection() {
- - return getConnection(true);
- - }
- + Exception closeSessionException = closeSession();
- + if (closeSessionException != null) {
- + closeConnection();
- + throw new JbpmPersistenceException("hibernate close session failed", closeSessionException);
- + }
- - public Connection getConnection(boolean resolveSession) {
- - if (connection==null) {
- - if (persistenceServiceFactory.getDataSource()!=null) {
- - try {
- - log.debug("fetching jdbc connection from datasource");
- - connection = persistenceServiceFactory.getDataSource().getConnection();
- - mustConnectionBeClosed = true;
- - } catch (Exception e) {
- - // NOTE that Error's are not caught because that might halt the JVM and mask the original Error.
- - throw new JbpmException("couldn't obtain connection from datasource", e);
- - }
- - } else {
- - if (resolveSession) {
- - // initializes the session member
- - getSession();
- - }
- - if (session!=null) {
- - connection = session.connection();
- - log.debug("fetching connection from hibernate session. this transfers responsibility for closing the jdbc connection to the user! "+connection);
- - mustConnectionBeClosed = false;
- - }
- - }
- - }
- - return connection;
- - }
- -
- - public void close() {
- + Exception closeConnectionException = closeConnection();
- + if (closeConnectionException != null) {
- + throw new JbpmPersistenceException("hibernate close connection failed", closeConnectionException);
- + }
- + }
- - if ( (session!=null)
- - && (transaction==null)
- - && (isRollbackOnly())
- - ) {
- - throw new JbpmException("setRollbackOnly was invoked while configuration specifies user managed transactions");
- - }
- -
- - if ( (isTransactionEnabled)
- - && (transaction!=null)
- - ) {
- + Exception commit() {
- + try {
- + log.debug("committing hibernate transaction " + transaction.toString());
- + mustSessionBeFlushed = false; // commit does a flush anyway
- + transaction.commit();
- + } catch (StaleObjectStateException e) {
- + log.info("optimistic locking failed");
- + StaleObjectLogConfigurer.staleObjectExceptionsLog.error("optimistic locking failed", e);
- + return e;
- + } catch (Exception e) {
- + log.error("hibernate commit failed", e);
- + return e;
- + }
- + return null;
- + }
- - if (! isRollbackOnly()) {
- - Exception commitException = commit();
- - if (commitException!=null) {
- - rollback();
- - closeSession();
- - closeConnection();
- - throw new JbpmPersistenceException("hibernate commit failed", commitException);
- - }
- + Exception flushSession() {
- + if (mustSessionBeFlushed) {
- + try {
- + log.debug("flushing hibernate session " + session.toString());
- + session.flush();
- + } catch (Exception e) {
- + log.error("hibernate flush failed", e);
- + return e;
- + }
- + }
- + return null;
- + }
- - } else { // isRollbackOnly==true
- - Exception rollbackException = rollback();
- - if (rollbackException!=null) {
- - closeSession();
- - closeConnection();
- - throw new JbpmPersistenceException("hibernate rollback failed", rollbackException);
- - }
- - }
- - }
- -
- - Exception flushException = flushSession();
- - if (flushException!=null) {
- - rollback();
- - closeSession();
- - closeConnection();
- - throw new JbpmPersistenceException("hibernate flush failed", flushException);
- - }
- + Exception closeConnection() {
- + if (mustConnectionBeClosed) {
- + try {
- + if ((connection != null) && (!connection.isClosed())) {
- + log.debug("closing jdbc connection");
- + connection.close();
- + } else {
- + log.warn("jdbc connection was already closed");
- + }
- + } catch (Exception e) {
- + log.error("hibernate session close failed", e);
- + return e;
- + }
- + }
- + return null;
- + }
- - Exception closeSessionException = closeSession();
- - if (closeSessionException!=null) {
- - closeConnection();
- - throw new JbpmPersistenceException("hibernate close session failed", closeSessionException);
- - }
- + Exception rollback() {
- + try {
- + log.debug("rolling back hibernate transaction");
- + mustSessionBeFlushed = false; // flushing updates that will be
- + // rolled back is not very clever
- + // :-)
- + transaction.rollback();
- + } catch (Exception e) {
- + log.error("hibernate rollback failed", e);
- + return e;
- + }
- + return null;
- + }
- - Exception closeConnectionException = closeConnection();
- - if (closeConnectionException!=null) {
- - throw new JbpmPersistenceException("hibernate close connection failed", closeConnectionException);
- - }
- - }
- + Exception closeSession() {
- + if (mustSessionBeClosed) {
- + try {
- + if (session.isOpen()) {
- + log.debug("closing hibernate session");
- + session.close();
- + } else {
- + log.warn("hibernate session was already closed");
- + }
- + } catch (Exception e) {
- + return e;
- + }
- + }
- + return null;
- + }
- - Exception commit() {
- - try {
- - log.debug("committing hibernate transaction " + transaction.toString());
- - mustSessionBeFlushed = false; // commit does a flush anyway
- - transaction.commit();
- - } catch (StaleObjectStateException e) {
- - log.info("optimistic locking failed");
- - StaleObjectLogConfigurer.staleObjectExceptionsLog.error("optimistic locking failed", e);
- - return e;
- - } catch (Exception e) {
- - log.error("hibernate commit failed", e);
- - return e;
- - }
- - return null;
- - }
- + public void assignId(Object object) {
- + try {
- + getSession().save(object);
- + } catch (Exception e) {
- + // NOTE that Error's are not caught because that might halt the JVM
- + // and mask the original Error.
- + throw new JbpmPersistenceException("couldn't assign id to " + object, e);
- + }
- + }
- - Exception flushSession() {
- - if (mustSessionBeFlushed) {
- - try {
- - log.debug("flushing hibernate session " + session.toString());
- - session.flush();
- - } catch (Exception e) {
- - log.error("hibernate flush failed", e);
- - return e;
- - }
- - }
- - return null;
- - }
- + // getters and setters
- + // //////////////////////////////////////////////////////
- - Exception closeConnection() {
- - if (mustConnectionBeClosed) {
- - try {
- - if ( (connection!=null)
- - && (! connection.isClosed())
- - ) {
- - log.debug("closing jdbc connection");
- - connection.close();
- - } else {
- - log.warn("jdbc connection was already closed");
- - }
- - } catch (Exception e) {
- - log.error("hibernate session close failed", e);
- - return e;
- - }
- - }
- - return null;
- - }
- + public GraphSession getGraphSession() {
- + if (graphSession == null) {
- + Session session = getSession();
- + if (session != null) {
- + graphSession = new GraphSession(session);
- + }
- + }
- + return graphSession;
- + }
- - Exception rollback() {
- - try {
- - log.debug("rolling back hibernate transaction");
- - mustSessionBeFlushed = false; // flushing updates that will be rolled back is not very clever :-)
- - transaction.rollback();
- - } catch (Exception e) {
- - log.error("hibernate rollback failed", e);
- - return e;
- - }
- - return null;
- - }
- + public LoggingSession getLoggingSession() {
- + if (loggingSession == null) {
- + Session session = getSession();
- + if (session != null) {
- + loggingSession = new LoggingSession(session);
- + }
- + }
- + return loggingSession;
- + }
- - Exception closeSession() {
- - if (mustSessionBeClosed) {
- - try {
- - if(session.isOpen()) {
- - log.debug("closing hibernate session");
- - session.close();
- - } else {
- - log.warn("hibernate session was already closed");
- - }
- - } catch (Exception e) {
- - return e;
- - }
- - }
- - return null;
- - }
- + public JobSession getJobSession() {
- + if (jobSession == null) {
- + Session session = getSession();
- + if (session != null) {
- + jobSession = new JobSession(session);
- + }
- + }
- + return jobSession;
- + }
- - public void assignId(Object object) {
- - try {
- - getSession().save(object);
- - } catch (Exception e) {
- - // NOTE that Error's are not caught because that might halt the JVM and mask the original Error.
- - throw new JbpmPersistenceException("couldn't assign id to "+object, e);
- - }
- - }
- + public ContextSession getContextSession() {
- + if (contextSession == null) {
- + Session session = getSession();
- + if (session != null) {
- + contextSession = new ContextSession(session);
- + }
- + }
- + return contextSession;
- + }
- - // getters and setters //////////////////////////////////////////////////////
- + public TaskMgmtSession getTaskMgmtSession() {
- + if (taskMgmtSession == null) {
- + Session session = getSession();
- + if (session != null) {
- + taskMgmtSession = new TaskMgmtSession(session);
- + }
- + }
- + return taskMgmtSession;
- + }
- - public GraphSession getGraphSession() {
- - if (graphSession==null) {
- - Session session = getSession();
- - if (session!=null) {
- - graphSession = new GraphSession(session);
- - }
- - }
- - return graphSession;
- - }
- - public LoggingSession getLoggingSession() {
- - if (loggingSession==null) {
- - Session session = getSession();
- - if (session!=null) {
- - loggingSession = new LoggingSession(session);
- - }
- - }
- - return loggingSession;
- - }
- - public JobSession getJobSession() {
- - if (jobSession==null) {
- - Session session = getSession();
- - if (session!=null) {
- - jobSession = new JobSession(session);
- - }
- - }
- - return jobSession;
- - }
- - public ContextSession getContextSession() {
- - if (contextSession==null) {
- - Session session = getSession();
- - if (session!=null) {
- - contextSession = new ContextSession(session);
- - }
- - }
- - return contextSession;
- - }
- - public TaskMgmtSession getTaskMgmtSession() {
- - if (taskMgmtSession==null) {
- - Session session = getSession();
- - if (session!=null) {
- - taskMgmtSession = new TaskMgmtSession(session);
- - }
- - }
- - return taskMgmtSession;
- - }
- + public DataSource getDataSource() {
- + return persistenceServiceFactory.dataSource;
- + }
- - public DataSource getDataSource() {
- - return persistenceServiceFactory.dataSource;
- - }
- + /**
- + * @deprecated use {@link org.jbpm.tx.TxService} instead.
- + */
- + public boolean isRollbackOnly() {
- + TxService txService = (services != null ? services.getTxService() : null);
- + if (txService == null) {
- + throw new JbpmException("no jbpm tx service configured");
- + }
- + return txService.isRollbackOnly();
- + }
- - /**
- - * @deprecated use {@link org.jbpm.tx.TxService} instead.
- - */
- - public boolean isRollbackOnly() {
- - TxService txService = (services!=null ? services.getTxService() : null);
- - if (txService==null) {
- - throw new JbpmException("no jbpm tx service configured");
- - }
- - return txService.isRollbackOnly();
- - }
- - /**
- - * @deprecated use {@link org.jbpm.tx.TxService} instead.
- - */
- - public void setRollbackOnly(boolean isRollbackOnly) {
- - throw new UnsupportedOperationException("method setRollbackOnly has been removed. Use TxService instead.");
- - }
- - /**
- - * @deprecated use {@link org.jbpm.tx.TxService} instead.
- - */
- - public void setRollbackOnly() {
- - TxService txService = (services!=null ? services.getTxService() : null);
- - if (txService==null) {
- - throw new JbpmException("no jbpm tx service configured");
- - }
- - txService.setRollbackOnly();
- - }
- + /**
- + * @deprecated use {@link org.jbpm.tx.TxService} instead.
- + */
- + public void setRollbackOnly(boolean isRollbackOnly) {
- + throw new UnsupportedOperationException("method setRollbackOnly has been removed. Use TxService instead.");
- + }
- - public void setSession(Session session) {
- - this.session = session;
- - log.debug("injecting a session disables transaction");
- - isTransactionEnabled = false;
- - }
- + /**
- + * @deprecated use {@link org.jbpm.tx.TxService} instead.
- + */
- + public void setRollbackOnly() {
- + TxService txService = (services != null ? services.getTxService() : null);
- + if (txService == null) {
- + throw new JbpmException("no jbpm tx service configured");
- + }
- + txService.setRollbackOnly();
- + }
- - public void setSessionWithoutDisablingTx(Session session) {
- - this.session = session;
- - }
- + public void setSession(Session session) {
- + this.session = session;
- + log.debug("injecting a session disables transaction");
- + isTransactionEnabled = false;
- + }
- - public void setConnection(Connection connection) {
- - this.connection = connection;
- - }
- - public void setContextSession(ContextSession contextSession) {
- - this.contextSession = contextSession;
- - }
- - public void setDataSource(DataSource dataSource) {
- - this.persistenceServiceFactory.dataSource = dataSource;
- - }
- - public void setGraphSession(GraphSession graphSession) {
- - this.graphSession = graphSession;
- - }
- - public void setLoggingSession(LoggingSession loggingSession) {
- - this.loggingSession = loggingSession;
- - }
- - public void setJobSession(JobSession jobSession) {
- - this.jobSession = jobSession;
- - }
- - public void setTaskMgmtSession(TaskMgmtSession taskMgmtSession) {
- - this.taskMgmtSession = taskMgmtSession;
- - }
- - public void setSessionFactory(SessionFactory sessionFactory) {
- - this.persistenceServiceFactory.sessionFactory = sessionFactory;
- - }
- - public Transaction getTransaction() {
- - return transaction;
- - }
- - public void setTransaction(Transaction transaction) {
- - this.transaction = transaction;
- - }
- - public boolean isTransactionEnabled() {
- - return isTransactionEnabled;
- - }
- - public void setTransactionEnabled(boolean isTransactionEnabled) {
- - this.isTransactionEnabled = isTransactionEnabled;
- - }
- - private static Log log = LogFactory.getLog(DbPersistenceService.class);
- + public void setSessionWithoutDisablingTx(Session session) {
- + this.session = session;
- + }
- +
- + public void setConnection(Connection connection) {
- + this.connection = connection;
- + }
- +
- + public void setContextSession(ContextSession contextSession) {
- + this.contextSession = contextSession;
- + }
- +
- + public void setDataSource(DataSource dataSource) {
- + this.persistenceServiceFactory.dataSource = dataSource;
- + }
- +
- + public void setGraphSession(GraphSession graphSession) {
- + this.graphSession = graphSession;
- + }
- +
- + public void setLoggingSession(LoggingSession loggingSession) {
- + this.loggingSession = loggingSession;
- + }
- +
- + public void setJobSession(JobSession jobSession) {
- + this.jobSession = jobSession;
- + }
- +
- + public void setTaskMgmtSession(TaskMgmtSession taskMgmtSession) {
- + this.taskMgmtSession = taskMgmtSession;
- + }
- +
- + public void setSessionFactory(SessionFactory sessionFactory) {
- + this.persistenceServiceFactory.sessionFactory = sessionFactory;
- + }
- +
- + public Transaction getTransaction() {
- + return transaction;
- + }
- +
- + public void setTransaction(Transaction transaction) {
- + this.transaction = transaction;
- + }
- +
- + public boolean isTransactionEnabled() {
- + return isTransactionEnabled;
- + }
- +
- + public void setTransactionEnabled(boolean isTransactionEnabled) {
- + this.isTransactionEnabled = isTransactionEnabled;
- + }
- +
- + private static Log log = LogFactory.getLog(DbPersistenceService.class);
- +
- + private class GetConnectionWork implements Work {
- +
- + private Connection connection = null;
- + /* (non-Javadoc)
- + * @see org.hibernate.jdbc.Work#execute(java.sql.Connection)
- + */
- + @Override
- + public void execute(Connection arg0) throws SQLException {
- + this.connection = arg0;
- + }
- + /**
- + * @return the connection
- + */
- + public Connection getConnection() {
- + return connection;
- + }
- +
- + }
- }
- Index: src/main/java/org/jbpm/persistence/jta/JtaDbPersistenceService.java
- ===================================================================
- --- src/main/java/org/jbpm/persistence/jta/JtaDbPersistenceService.java (revision 65983)
- +++ src/main/java/org/jbpm/persistence/jta/JtaDbPersistenceService.java (revision 75353)
- @@ -6,98 +6,106 @@
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- -import org.hibernate.engine.SessionFactoryImplementor;
- -import org.hibernate.util.JTAHelper;
- +import org.hibernate.engine.spi.SessionFactoryImplementor;
- import org.jbpm.JbpmContext;
- import org.jbpm.JbpmException;
- import org.jbpm.persistence.db.DbPersistenceService;
- import org.jbpm.persistence.db.DbPersistenceServiceFactory;
- +import javax.transaction.Status;
- public class JtaDbPersistenceService extends DbPersistenceService {
- - private static final long serialVersionUID = 1L;
- -
- - private static Log log = LogFactory.getLog(JbpmContext.class);
- -
- - boolean isJtaTxCreated = false;
- + private static final long serialVersionUID = 1L;
- +
- + private static Log log = LogFactory.getLog(JbpmContext.class);
- +
- + boolean isJtaTxCreated = false;
- +
- + public JtaDbPersistenceService(DbPersistenceServiceFactory persistenceServiceFactory) {
- + super(persistenceServiceFactory);
- - public JtaDbPersistenceService(DbPersistenceServiceFactory persistenceServiceFactory) {
- - super(persistenceServiceFactory);
- -
- - if (! isCurrentJtaTransactionAvailable()) {
- - beginJtaTransaction();
- - isJtaTxCreated = true;
- - }
- - }
- + if (!isCurrentJtaTransactionAvailable()) {
- + beginJtaTransaction();
- + isJtaTxCreated = true;
- + }
- + }
- - public void close() {
- - super.close();
- + public void close() {
- + super.close();
- - if (isJtaTxCreated) {
- - endJtaTransaction();
- - }
- - }
- + if (isJtaTxCreated) {
- + endJtaTransaction();
- + }
- + }
- - boolean isCurrentJtaTransactionAvailable() {
- - SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) persistenceServiceFactory.getSessionFactory();
- - return JTAHelper.isTransactionInProgress(sessionFactoryImplementor);
- - }
- + boolean isCurrentJtaTransactionAvailable() {
- + SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) persistenceServiceFactory
- + .getSessionFactory();
- + return sessionFactoryImplementor.getCurrentSession().getTransaction().isActive();
- + }
- - void beginJtaTransaction() {
- - try {
- - log.debug("start user JTA transaction");
- - getUserTransaction().begin();
- - } catch (Exception e) {
- - throw new JbpmException("couldn't start JTA transaction", e);
- - }
- - }
- + void beginJtaTransaction() {
- + try {
- + log.debug("start user JTA transaction");
- + getUserTransaction().begin();
- + } catch (Exception e) {
- + throw new JbpmException("couldn't start JTA transaction", e);
- + }
- + }
- - void endJtaTransaction() {
- - int status = -1;
- - log.debug("end user JTA transaction");
- - UserTransaction userTransaction = getUserTransaction();
- - try {
- - status = userTransaction.getStatus();
- - } catch (SystemException e) {
- - throw new JbpmException("couldn't get status for user transaction", e);
- - }
- -
- - boolean isRollback = JTAHelper.isRollback(status);
- - if (isRollback) {
- - log.debug("end jta transation with ROLLBACK");
- - try {
- - userTransaction.rollback();
- - } catch (Exception e) {
- - throw new JbpmException("couldn't rollback JTA transaction", e);
- - }
- - } else {
- - log.debug("end jta transation with COMMIT");
- - try {
- - userTransaction.commit();
- - } catch (Exception e) {
- - throw new JbpmException("couldn't commit JTA transaction", e);
- - }
- - }
- - }
- -
- - UserTransaction getUserTransaction() {
- - UserTransaction userTransaction = null;
- - if (userTransaction == null) {
- - String jndiName = "UserTransaction";
- - try {
- - userTransaction = (UserTransaction) new InitialContext().lookup(jndiName);
- - } catch (Exception e) {
- - throw new JbpmException("couldn't lookup UserTransaction in JNDI with name "+jndiName, e);
- - }
- - }
- - return userTransaction;
- - }
- + void endJtaTransaction() {
- + int status = -1;
- + log.debug("end user JTA transaction");
- + UserTransaction userTransaction = getUserTransaction();
- + try {
- + status = userTransaction.getStatus();
- + } catch (SystemException e) {
- + throw new JbpmException("couldn't get status for user transaction", e);
- + }
- + boolean isRollback = isRollback(status);
- + if (isRollback) {
- + log.debug("end jta transation with ROLLBACK");
- + try {
- + userTransaction.rollback();
- + } catch (Exception e) {
- + throw new JbpmException("couldn't rollback JTA transaction", e);
- + }
- + } else {
- + log.debug("end jta transation with COMMIT");
- + try {
- + userTransaction.commit();
- + } catch (Exception e) {
- + throw new JbpmException("couldn't commit JTA transaction", e);
- + }
- + }
- + }
- - public boolean isJtaTxCreated() {
- - return isJtaTxCreated;
- - }
- - public void setJtaTxCreated(boolean isJtaTxCreated) {
- - this.isJtaTxCreated = isJtaTxCreated;
- - }
- + UserTransaction getUserTransaction() {
- + UserTransaction userTransaction = null;
- + if (userTransaction == null) {
- + String jndiName = "UserTransaction";
- + try {
- + userTransaction = (UserTransaction) new InitialContext().lookup(jndiName);
- + } catch (Exception e) {
- + throw new JbpmException("couldn't lookup UserTransaction in JNDI with name " + jndiName, e);
- + }
- + }
- + return userTransaction;
- + }
- +
- + public boolean isJtaTxCreated() {
- + return isJtaTxCreated;
- + }
- +
- + public void setJtaTxCreated(boolean isJtaTxCreated) {
- + this.isJtaTxCreated = isJtaTxCreated;
- + }
- +
- + private boolean isRollback(int status) {
- + return status == Status.STATUS_MARKED_ROLLBACK
- + || status == Status.STATUS_ROLLING_BACK
- + || status == Status.STATUS_ROLLEDBACK;
- +
- + }
- }
- Index: src/main/java/org/jbpm/db/hibernate/Converters.java
- ===================================================================
- --- src/main/java/org/jbpm/db/hibernate/Converters.java (revision 65983)
- +++ src/main/java/org/jbpm/db/hibernate/Converters.java (revision 75353)
- @@ -35,101 +35,105 @@
- import org.jbpm.util.ClassLoaderUtil;
- /**
- - * provides access to the list of converters and ensures that the converter objects are unique.
- + * provides access to the list of converters and ensures that the converter
- + * objects are unique.
- */
- public abstract class Converters {
- -
- - static final int CONVERTERS_BY_CLASS_NAMES = 0;
- - static final int CONVERTERS_BY_DATABASE_ID = 1;
- - static final int CONVERTERS_IDS = 2;
- +
- + static final int CONVERTERS_BY_CLASS_NAMES = 0;
- + static final int CONVERTERS_BY_DATABASE_ID = 1;
- + static final int CONVERTERS_IDS = 2;
- - static Map converterMapsMap = new HashMap();
- -
- - // public methods
- + static Map converterMapsMap = new HashMap();
- - public static Converter getConverterByClassName(String className) {
- - Converter converter = (Converter) getConvertersByClassNames().get(className);
- - if (converter==null) {
- - throw new JbpmException("converter '"+className+"' is not declared in jbpm.converter.properties");
- - }
- - return converter;
- - }
- + // public methods
- - public static Converter getConverterByDatabaseId(String converterDatabaseId) {
- - return (Converter) getConvertersByDatabaseId().get(converterDatabaseId);
- - }
- + public static Converter getConverterByClassName(String className) {
- + Converter converter = (Converter) getConvertersByClassNames().get(className);
- + if (converter == null) {
- + throw new JbpmException("converter '" + className + "' is not declared in jbpm.converter.properties");
- + }
- + return converter;
- + }
- - public static String getConverterId(Converter converter) {
- - return (String) getConvertersIds().get(converter);
- - }
- + public static Converter getConverterByDatabaseId(String converterDatabaseId) {
- + return (Converter) getConvertersByDatabaseId().get(converterDatabaseId);
- + }
- - // maps class names to unique converter objects
- - static Map getConvertersByClassNames() {
- - return getConverterMaps()[CONVERTERS_BY_CLASS_NAMES];
- - }
- + public static String getConverterId(Converter converter) {
- + return (String) getConvertersIds().get(converter);
- + }
- - // maps converter database-id-strings to unique converter objects
- - static Map getConvertersByDatabaseId() {
- - return getConverterMaps()[CONVERTERS_BY_DATABASE_ID];
- - }
- -
- - // maps unique converter objects to their database-id-string
- - static Map getConvertersIds() {
- - return getConverterMaps()[CONVERTERS_IDS];
- - }
- + // maps class names to unique converter objects
- + static Map getConvertersByClassNames() {
- + return getConverterMaps()[CONVERTERS_BY_CLASS_NAMES];
- + }
- - static Map[] getConverterMaps() {
- - Map[] converterMaps = null;
- - synchronized(converterMapsMap) {
- - ObjectFactory objectFactory = JbpmConfiguration.Configs.getObjectFactory();
- - converterMaps = (Map[]) converterMapsMap.get(objectFactory);
- - if (converterMaps==null) {
- - converterMaps = createConverterMaps(objectFactory);
- - converterMapsMap.put(objectFactory, converterMaps);
- - }
- - }
- - return converterMaps;
- - }
- + // maps converter database-id-strings to unique converter objects
- + static Map getConvertersByDatabaseId() {
- + return getConverterMaps()[CONVERTERS_BY_DATABASE_ID];
- + }
- - static Map[] createConverterMaps(ObjectFactory objectFactory) {
- - Map[] converterMaps = new Map[3];
- - converterMaps[CONVERTERS_BY_CLASS_NAMES] = new HashMap();
- - converterMaps[CONVERTERS_BY_DATABASE_ID] = new HashMap();
- - converterMaps[CONVERTERS_IDS] = new HashMap();
- + // maps unique converter objects to their database-id-string
- + static Map getConvertersIds() {
- + return getConverterMaps()[CONVERTERS_IDS];
- + }
- - Map convertersByClassNames = converterMaps[CONVERTERS_BY_CLASS_NAMES];
- - Map convertersByDatabaseId = converterMaps[CONVERTERS_BY_DATABASE_ID];
- - Map convertersIds = converterMaps[CONVERTERS_IDS];
- + static Map[] getConverterMaps() {
- + Map[] converterMaps = null;
- + synchronized (converterMapsMap) {
- + ObjectFactory objectFactory = JbpmConfiguration.Configs.getObjectFactory();
- + converterMaps = (Map[]) converterMapsMap.get(objectFactory);
- + if (converterMaps == null) {
- + converterMaps = createConverterMaps(objectFactory);
- + converterMapsMap.put(objectFactory, converterMaps);
- + }
- + }
- + return converterMaps;
- + }
- - Properties converterProperties = null;
- - if (objectFactory.hasObject("resource.converter")) {
- - String resource = (String) objectFactory.createObject("resource.converter");
- - converterProperties = ClassLoaderUtil.getProperties(resource);
- - } else {
- - converterProperties = new Properties();
- - }
- + static Map[] createConverterMaps(ObjectFactory objectFactory) {
- + Map[] converterMaps = new Map[3];
- + converterMaps[CONVERTERS_BY_CLASS_NAMES] = new HashMap();
- + converterMaps[CONVERTERS_BY_DATABASE_ID] = new HashMap();
- + converterMaps[CONVERTERS_IDS] = new HashMap();
- - Iterator iter = converterProperties.keySet().iterator();
- - while (iter.hasNext()) {
- - String converterDatabaseId = (String) iter.next();
- - if (converterDatabaseId.length()!=1) throw new JbpmException("converter-ids must be of length 1 (to be stored in a char)");
- - if (convertersByDatabaseId.containsKey(converterDatabaseId)) throw new JbpmException("duplicate converter id : '"+converterDatabaseId+"'");
- - String converterClassName = converterProperties.getProperty(converterDatabaseId);
- - try {
- - Class converterClass = ClassLoaderUtil.loadClass(converterClassName);
- - Converter converter = (Converter) converterClass.newInstance();
- - log.debug("adding converter '"+converterDatabaseId+"', '"+converterClassName+"'");
- - convertersByClassNames.put(converterClassName, converter);
- - convertersByDatabaseId.put(converterDatabaseId, converter);
- - convertersIds.put(converter, converterDatabaseId);
- - } catch (Exception e) {
- - // NOTE that Error's are not caught because that might halt the JVM and mask the original Error.
- - log.debug("couldn't instantiate converter '"+converterClassName+"': "+e);
- - }
- - }
- + Map convertersByClassNames = converterMaps[CONVERTERS_BY_CLASS_NAMES];
- + Map convertersByDatabaseId = converterMaps[CONVERTERS_BY_DATABASE_ID];
- + Map convertersIds = converterMaps[CONVERTERS_IDS];
- - return converterMaps;
- - }
- + Properties converterProperties = null;
- + if (objectFactory.hasObject("resource.converter")) {
- + String resource = (String) objectFactory.createObject("resource.converter");
- + converterProperties = ClassLoaderUtil.getProperties(resource);
- + } else {
- + converterProperties = new Properties();
- + }
- - private static Log log = LogFactory.getLog(Converters.class);
- + Iterator iter = converterProperties.keySet().iterator();
- + while (iter.hasNext()) {
- + String converterDatabaseId = (String) iter.next();
- + if (converterDatabaseId.length() != 1)
- + throw new JbpmException("converter-ids must be of length 1 (to be stored in a char)");
- + if (convertersByDatabaseId.containsKey(converterDatabaseId))
- + throw new JbpmException("duplicate converter id : '" + converterDatabaseId + "'");
- + String converterClassName = converterProperties.getProperty(converterDatabaseId);
- + try {
- + Class converterClass = ClassLoaderUtil.loadClass(converterClassName);
- + Converter converter = (Converter) converterClass.newInstance();
- + log.debug("adding converter '" + converterDatabaseId + "', '" + converterClassName + "'");
- + convertersByClassNames.put(converterClassName, converter);
- + convertersByDatabaseId.put(converterDatabaseId, converter);
- + convertersIds.put(converter, converterDatabaseId);
- + } catch (Exception e) {
- + // NOTE that Error's are not caught because that might halt the
- + // JVM and mask the original Error.
- + log.debug("couldn't instantiate converter '" + converterClassName + "': " + e);
- + }
- + }
- +
- + return converterMaps;
- + }
- +
- + private static Log log = LogFactory.getLog(Converters.class);
- }
- Index: src/main/java/org/jbpm/db/hibernate/StringMax.java
- ===================================================================
- --- src/main/java/org/jbpm/db/hibernate/StringMax.java (revision 65983)
- +++ src/main/java/org/jbpm/db/hibernate/StringMax.java (revision 75353)
- @@ -20,7 +20,7 @@
- ) {
- value = string.substring(0, length);
- }
- - super.set(st, value, index);
- + //super.set(st, value, index);
- }
- public void setParameterValues(Properties parameters) {
- Index: src/main/java/org/jbpm/db/hibernate/ConverterEnumType.java
- ===================================================================
- --- src/main/java/org/jbpm/db/hibernate/ConverterEnumType.java (revision 65983)
- +++ src/main/java/org/jbpm/db/hibernate/ConverterEnumType.java (revision 75353)
- @@ -21,38 +21,101 @@
- */
- package org.jbpm.db.hibernate;
- -import java.io.*;
- -import java.sql.*;
- +
- +import java.io.Serializable;
- +import java.sql.PreparedStatement;
- +import java.sql.ResultSet;
- +import java.sql.SQLException;
- +import java.sql.Types;
- -import org.hibernate.*;
- -import org.hibernate.usertype.*;
- -import org.jbpm.context.exe.*;
- +import org.hibernate.HibernateException;
- +import org.hibernate.engine.spi.SessionImplementor;
- +import org.hibernate.usertype.UserType;
- +import org.jbpm.context.exe.Converter;
- +
- /**
- * is the hibernate UserType for storing converters as a char in the database.
- - * The conversion can be found (and customized) in the file jbpm.converter.properties.
- + * The conversion can be found (and customized) in the file
- + * jbpm.converter.properties.
- */
- public class ConverterEnumType implements UserType {
- - static final int[] SQLTYPES = new int[]{Types.CHAR};
- + static final int[] SQLTYPES = new int[] { Types.CHAR };
- +
- + public boolean equals(Object o1, Object o2) {
- + return (o1 == o2);
- + }
- +
- + public int hashCode(Object o) throws HibernateException {
- + return o.hashCode();
- + }
- +
- + public Object deepCopy(Object o) throws HibernateException {
- + return o;
- + }
- +
- + public boolean isMutable() {
- + return false;
- + }
- +
- + public Serializable disassemble(Object o) throws HibernateException {
- + return (Serializable) o;
- + }
- +
- + public Object assemble(Serializable s, Object o) throws HibernateException {
- + return s;
- + }
- +
- + public Object replace(Object original, Object target, Object owner) {
- + return target;
- + }
- +
- + public int[] sqlTypes() {
- + return SQLTYPES;
- + }
- - public boolean equals(Object o1, Object o2) { return (o1==o2); }
- - public int hashCode(Object o) throws HibernateException { return o.hashCode(); }
- - public Object deepCopy(Object o) throws HibernateException { return o; }
- - public boolean isMutable() { return false; }
- - public Serializable disassemble(Object o) throws HibernateException { return (Serializable) o; }
- - public Object assemble(Serializable s, Object o) throws HibernateException { return s; }
- - public Object replace(Object original, Object target, Object owner) { return target; }
- - public int[] sqlTypes() { return SQLTYPES; }
- - public Class returnedClass() { return Converter.class; }
- + public Class returnedClass() {
- + return Converter.class;
- + }
- - public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
- - String converterDatabaseId = resultSet.getString(names[0]);
- - return Converters.getConverterByDatabaseId(converterDatabaseId);
- - }
- + public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException,
- + SQLException {
- + String converterDatabaseId = resultSet.getString(names[0]);
- + return Converters.getConverterByDatabaseId(converterDatabaseId);
- + }
- - public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException, SQLException {
- - String converterDatabaseId = Converters.getConverterId((Converter) value);
- - preparedStatement.setString(index, converterDatabaseId);
- - }
- + public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException,
- + SQLException {
- + String converterDatabaseId = Converters.getConverterId((Converter) value);
- + preparedStatement.setString(index, converterDatabaseId);
- + }
- +
- + /*
- + * (non-Javadoc)
- + *
- + * @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet,
- + * java.lang.String[], org.hibernate.engine.spi.SessionImplementor,
- + * java.lang.Object)
- + */
- + @Override
- + public Object nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor session, Object owner)
- + throws HibernateException, SQLException {
- + String converterDatabaseId = resultSet.getString(names[0]);
- + return Converters.getConverterByDatabaseId(converterDatabaseId);
- + }
- +
- + /*
- + * (non-Javadoc)
- + *
- + * @see
- + * org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement,
- + * java.lang.Object, int, org.hibernate.engine.spi.SessionImplementor)
- + */
- + @Override
- + public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index, SessionImplementor session)
- + throws HibernateException, SQLException {
- + String converterDatabaseId = Converters.getConverterId((Converter) value);
- + preparedStatement.setString(index, converterDatabaseId);
- + }
- }
- Index: src/main/java/org/jbpm/db/JbpmSessionFactory.java
- ===================================================================
- --- src/main/java/org/jbpm/db/JbpmSessionFactory.java (revision 65983)
- +++ src/main/java/org/jbpm/db/JbpmSessionFactory.java (revision 75353)
- @@ -46,232 +46,241 @@
- import org.jbpm.util.ClassLoaderUtil;
- /**
- - * creates JbpmSessions.
- - * Obtain a JbpmSessionFactory with
- + * creates JbpmSessions. Obtain a JbpmSessionFactory with
- + *
- * <pre>
- * static JbpmSessionFactory jbpmSessionFactory = JbpmSessionFactory.buildJbpmSessionFactory();
- * </pre>
- - * and store it somewhere static. It takes quite some time to create a DbSessionFactory,
- - * but you only have to do it once. After that, creating DbSession's is really fast.
- *
- - * @deprecated use {@link org.jbpm.tc.ContextBuilder} and {@link org.jbpm.tc.db.JbpmSessionContext} instead.
- + * and store it somewhere static. It takes quite some time to create a
- + * DbSessionFactory, but you only have to do it once. After that, creating
- + * DbSession's is really fast.
- + *
- + * @deprecated use {@link org.jbpm.tc.ContextBuilder} and
- + * {@link org.jbpm.tc.db.JbpmSessionContext} instead.
- */
- public class JbpmSessionFactory implements Serializable {
- -
- - private static final long serialVersionUID = 1L;
- +
- + private static final long serialVersionUID = 1L;
- +
- + static String jndiName = getJndiName();
- - static String jndiName = getJndiName();
- - private static String getJndiName() {
- - String jndiName = null;
- - if (JbpmConfiguration.Configs.hasObject("jbpm.session.factory.jndi.name")) {
- - jndiName = JbpmConfiguration.Configs.getString("jbpm.session.factory.jndi.name");
- - }
- - return jndiName;
- - }
- + private static String getJndiName() {
- + String jndiName = null;
- + if (JbpmConfiguration.Configs.hasObject("jbpm.session.factory.jndi.name")) {
- + jndiName = JbpmConfiguration.Configs.getString("jbpm.session.factory.jndi.name");
- + }
- + return jndiName;
- + }
- - Configuration configuration = null;
- - SessionFactory sessionFactory = null;
- - Collection hibernatableLongIdClasses = null;
- - Collection hibernatableStringIdClasses = null;
- - JbpmSchema jbpmSchema = null;
- -
- - static JbpmSessionFactory instance = null;
- - /**
- - * a singleton is kept in JbpmSessionFactory as a convenient central location.
- - */
- - public static JbpmSessionFactory getInstance() {
- - if (instance==null) {
- -
- - // if there is a JNDI name configured
- - if (jndiName!=null) {
- - try {
- - // fetch the JbpmSessionFactory from JNDI
- - log.debug("fetching JbpmSessionFactory from '"+jndiName+"'");
- - InitialContext initialContext = new InitialContext();
- - Object o = initialContext.lookup(jndiName);
- - instance = (JbpmSessionFactory) PortableRemoteObject.narrow(o, JbpmSessionFactory.class);
- - } catch (Exception e) {
- - throw new JbpmException("couldn't fetch JbpmSessionFactory from jndi '"+jndiName+"'");
- - }
- -
- - } else { // else there is no JNDI name configured
- - // create a new default instance.
- - log.debug("building singleton JbpmSessionFactory");
- - instance = buildJbpmSessionFactory();
- - }
- - }
- - return instance;
- - }
- -
- - public JbpmSessionFactory(Configuration configuration) {
- - this( configuration, buildSessionFactory(configuration) );
- - }
- + Configuration configuration = null;
- + SessionFactory sessionFactory = null;
- + Collection hibernatableLongIdClasses = null;
- + Collection hibernatableStringIdClasses = null;
- + JbpmSchema jbpmSchema = null;
- - public JbpmSessionFactory(Configuration configuration, SessionFactory sessionFactory) {
- - this.configuration = configuration;
- - this.sessionFactory = sessionFactory;
- - }
- -
- - public static JbpmSessionFactory buildJbpmSessionFactory() {
- - return buildJbpmSessionFactory(getConfigResource());
- - }
- + static JbpmSessionFactory instance = null;
- - public static JbpmSessionFactory buildJbpmSessionFactory(String configResource) {
- - return buildJbpmSessionFactory(createConfiguration(configResource));
- - }
- -
- - public static JbpmSessionFactory buildJbpmSessionFactory(Configuration configuration) {
- - return new JbpmSessionFactory(configuration);
- - }
- + /**
- + * a singleton is kept in JbpmSessionFactory as a convenient central
- + * location.
- + */
- + public static JbpmSessionFactory getInstance() {
- + if (instance == null) {
- - private static String getConfigResource() {
- - return JbpmConfiguration.Configs.getString("resource.hibernate.cfg.xml");
- - }
- + // if there is a JNDI name configured
- + if (jndiName != null) {
- + try {
- + // fetch the JbpmSessionFactory from JNDI
- + log.debug("fetching JbpmSessionFactory from '" + jndiName + "'");
- + InitialContext initialContext = new InitialContext();
- + Object o = initialContext.lookup(jndiName);
- + instance = (JbpmSessionFactory) PortableRemoteObject.narrow(o, JbpmSessionFactory.class);
- + } catch (Exception e) {
- + throw new JbpmException("couldn't fetch JbpmSessionFactory from jndi '" + jndiName + "'");
- + }
- - public static Configuration createConfiguration() {
- - return createConfiguration(getConfigResource());
- - }
- + } else { // else there is no JNDI name configured
- + // create a new default instance.
- + log.debug("building singleton JbpmSessionFactory");
- + instance = buildJbpmSessionFactory();
- + }
- + }
- + return instance;
- + }
- - public static Configuration createConfiguration(String configResource) {
- - Configuration configuration = null;
- - // create the hibernate configuration
- - configuration = new Configuration();
- - if (configResource!=null) {
- - log.debug("using '"+configResource+"' as hibernate configuration for jbpm");
- - configuration.configure(configResource);
- - } else {
- - log.debug("using the default hibernate configuration file: hibernate.cfg.xml");
- - configuration.configure();
- - }
- -
- - // check if the properties in the hibernate.cfg.xml need to be overwritten by a separate properties file.
- - if (JbpmConfiguration.Configs.hasObject("resource.hibernate.properties")) {
- - String hibernatePropertiesResource = JbpmConfiguration.Configs.getString("resource.hibernate.properties");
- - Properties hibernateProperties = new Properties();
- - try {
- - hibernateProperties.load( ClassLoaderUtil.getStream(hibernatePropertiesResource) );
- - } catch (IOException e) {
- - e.printStackTrace();
- - throw new JbpmException("couldn't load the hibernate properties from resource '"+hibernatePropertiesResource+"'", e);
- - }
- - log.debug("overriding hibernate properties with "+ hibernateProperties);
- - configuration.setProperties(hibernateProperties);
- - }
- -
- - return configuration;
- - }
- + public JbpmSessionFactory(Configuration configuration) {
- + this(configuration, buildSessionFactory(configuration));
- + }
- - public static SessionFactory buildSessionFactory(Configuration configuration) {
- - SessionFactory sessionFactory = null;
- - // create the hibernate session factory
- - log.debug("building hibernate session factory");
- - sessionFactory = configuration.buildSessionFactory();
- - return sessionFactory;
- - }
- + public JbpmSessionFactory(Configuration configuration, SessionFactory sessionFactory) {
- + this.configuration = configuration;
- + this.sessionFactory = sessionFactory;
- + }
- - /**
- - * obtains a jdbc connection as specified in the hibernate configurations and
- - * creates a DbSession with it.
- - */
- - public JbpmSession openJbpmSession() {
- - return openJbpmSession((Connection)null);
- - }
- + public static JbpmSessionFactory buildJbpmSessionFactory() {
- + return buildJbpmSessionFactory(getConfigResource());
- + }
- - /**
- - * creates a DbSession around the given connection. Note that you are
- - * responsible for closing the connection so closing the DbSession will
- - * not close the jdbc connection.
- - */
- - public JbpmSession openJbpmSession(Connection jdbcConnection) {
- - JbpmSession dbSession = null;
- -
- - try {
- - Session session = null;
- -
- - if ( jdbcConnection == null ) {
- - // use the hibernate properties in the nwsp.properties file to
- - // create a jdbc connection for the created hibernate session.
- - session = getSessionFactory().openSession();
- - } else {
- - // use the client provided jdbc connection in
- - // the created hibernate session.
- - session = getSessionFactory().openSession(jdbcConnection);
- - }
- -
- - dbSession = new JbpmSession( this, session );
- -
- - } catch (HibernateException e) {
- - log.error( e );
- - throw new JbpmException( "couldn't create a hibernate persistence session", e );
- - }
- - return dbSession;
- - }
- + public static JbpmSessionFactory buildJbpmSessionFactory(String configResource) {
- + return buildJbpmSessionFactory(createConfiguration(configResource));
- + }
- - public JbpmSession openJbpmSession(Session session) {
- - return new JbpmSession(null, session);
- - }
- + public static JbpmSessionFactory buildJbpmSessionFactory(Configuration configuration) {
- + return new JbpmSessionFactory(configuration);
- + }
- - public JbpmSession openJbpmSessionAndBeginTransaction() {
- - JbpmSession dbSession = openJbpmSession((Connection)null);
- - dbSession.beginTransaction();
- - return dbSession;
- - }
- -
- - public SessionFactory getSessionFactory() {
- - return sessionFactory;
- - }
- -
- - public Configuration getConfiguration() {
- - return configuration;
- - }
- -
- - /**
- - * clears the process definitions from hibernate's second level cache.
- - public void evictCachedProcessDefinitions() {
- - sessionFactory.evict(ProcessDefinition.class);
- - }
- - */
- + private static String getConfigResource() {
- + return JbpmConfiguration.Configs.getString("resource.hibernate.cfg.xml");
- + }
- - /**
- - * checks if the given class is persistable with hibernate and has an id of type long.
- - */
- - public boolean isHibernatableWithLongId(Class clazz) {
- - if (hibernatableLongIdClasses==null) {
- - initHibernatableClasses();
- - }
- - return hibernatableLongIdClasses.contains(clazz);
- - }
- + public static Configuration createConfiguration() {
- + return createConfiguration(getConfigResource());
- + }
- - /**
- - * checks if the given class is persistable with hibernate and has an id of type string.
- - */
- - public boolean isHibernatableWithStringId(Class clazz) {
- - if (hibernatableStringIdClasses==null) {
- - initHibernatableClasses();
- - }
- - return hibernatableStringIdClasses.contains(clazz);
- - }
- -
- - public JbpmSchema getJbpmSchema() {
- - if (jbpmSchema==null) {
- - jbpmSchema = new JbpmSchema(configuration);
- - }
- - return jbpmSchema;
- - }
- + public static Configuration createConfiguration(String configResource) {
- + Configuration configuration = null;
- + // create the hibernate configuration
- + configuration = new Configuration();
- + if (configResource != null) {
- + log.debug("using '" + configResource + "' as hibernate configuration for jbpm");
- + configuration.configure(configResource);
- + } else {
- + log.debug("using the default hibernate configuration file: hibernate.cfg.xml");
- + configuration.configure();
- + }
- - void initHibernatableClasses() {
- - hibernatableLongIdClasses = new HashSet();
- - hibernatableStringIdClasses = new HashSet();
- - Iterator iter = configuration.getClassMappings();
- - while (iter.hasNext()) {
- - PersistentClass persistentClass = (PersistentClass) iter.next();
- - if (LongType.class==persistentClass.getIdentifier().getType().getClass()) {
- - hibernatableLongIdClasses.add( persistentClass.getMappedClass() );
- - } else if (StringType.class==persistentClass.getIdentifier().getType().getClass()) {
- - hibernatableStringIdClasses.add( persistentClass.getMappedClass() );
- - }
- - }
- - }
- + // check if the properties in the hibernate.cfg.xml need to be
- + // overwritten by a separate properties file.
- + if (JbpmConfiguration.Configs.hasObject("resource.hibernate.properties")) {
- + String hibernatePropertiesResource = JbpmConfiguration.Configs.getString("resource.hibernate.properties");
- + Properties hibernateProperties = new Properties();
- + try {
- + hibernateProperties.load(ClassLoaderUtil.getStream(hibernatePropertiesResource));
- + } catch (IOException e) {
- + e.printStackTrace();
- + throw new JbpmException("couldn't load the hibernate properties from resource '"
- + + hibernatePropertiesResource + "'", e);
- + }
- + log.debug("overriding hibernate properties with " + hibernateProperties);
- + configuration.setProperties(hibernateProperties);
- + }
- - private static final Log log = LogFactory.getLog(JbpmSessionFactory.class);
- + return configuration;
- + }
- +
- + public static SessionFactory buildSessionFactory(Configuration configuration) {
- + SessionFactory sessionFactory = null;
- + // create the hibernate session factory
- + log.debug("building hibernate session factory");
- + sessionFactory = configuration.buildSessionFactory();
- + return sessionFactory;
- + }
- +
- + /**
- + * obtains a jdbc connection as specified in the hibernate configurations
- + * and creates a DbSession with it.
- + */
- + public JbpmSession openJbpmSession() {
- + return openJbpmSession((Connection) null);
- + }
- +
- + /**
- + * creates a DbSession around the given connection. Note that you are
- + * responsible for closing the connection so closing the DbSession will not
- + * close the jdbc connection.
- + */
- + public JbpmSession openJbpmSession(Connection jdbcConnection) {
- + JbpmSession dbSession = null;
- +
- + try {
- + Session session = null;
- +
- + if (jdbcConnection == null) {
- + // use the hibernate properties in the nwsp.properties file to
- + // create a jdbc connection for the created hibernate session.
- + session = getSessionFactory().openSession();
- + } else {
- + // use the client provided jdbc connection in
- + // the created hibernate session.
- + session = getSessionFactory().openSession();
- + }
- +
- + dbSession = new JbpmSession(this, session);
- +
- + } catch (HibernateException e) {
- + log.error(e);
- + throw new JbpmException("couldn't create a hibernate persistence session", e);
- + }
- + return dbSession;
- + }
- +
- + public JbpmSession openJbpmSession(Session session) {
- + return new JbpmSession(null, session);
- + }
- +
- + public JbpmSession openJbpmSessionAndBeginTransaction() {
- + JbpmSession dbSession = openJbpmSession((Connection) null);
- + dbSession.beginTransaction();
- + return dbSession;
- + }
- +
- + public SessionFactory getSessionFactory() {
- + return sessionFactory;
- + }
- +
- + public Configuration getConfiguration() {
- + return configuration;
- + }
- +
- + /**
- + * clears the process definitions from hibernate's second level cache.
- + * public void evictCachedProcessDefinitions() {
- + * sessionFactory.evict(ProcessDefinition.class); }
- + */
- +
- + /**
- + * checks if the given class is persistable with hibernate and has an id of
- + * type long.
- + */
- + public boolean isHibernatableWithLongId(Class clazz) {
- + if (hibernatableLongIdClasses == null) {
- + initHibernatableClasses();
- + }
- + return hibernatableLongIdClasses.contains(clazz);
- + }
- +
- + /**
- + * checks if the given class is persistable with hibernate and has an id of
- + * type string.
- + */
- + public boolean isHibernatableWithStringId(Class clazz) {
- + if (hibernatableStringIdClasses == null) {
- + initHibernatableClasses();
- + }
- + return hibernatableStringIdClasses.contains(clazz);
- + }
- +
- + public JbpmSchema getJbpmSchema() {
- + if (jbpmSchema == null) {
- + jbpmSchema = new JbpmSchema(configuration);
- + }
- + return jbpmSchema;
- + }
- +
- + void initHibernatableClasses() {
- + hibernatableLongIdClasses = new HashSet();
- + hibernatableStringIdClasses = new HashSet();
- + Iterator iter = configuration.getClassMappings();
- + while (iter.hasNext()) {
- + PersistentClass persistentClass = (PersistentClass) iter.next();
- + if (LongType.class == persistentClass.getIdentifier().getType().getClass()) {
- + hibernatableLongIdClasses.add(persistentClass.getMappedClass());
- + } else if (StringType.class == persistentClass.getIdentifier().getType().getClass()) {
- + hibernatableStringIdClasses.add(persistentClass.getMappedClass());
- + }
- + }
- + }
- +
- + private static final Log log = LogFactory.getLog(JbpmSessionFactory.class);
- }
- Index: src/main/java/org/jbpm/db/JbpmSchema.java
- ===================================================================
- --- src/main/java/org/jbpm/db/JbpmSchema.java (revision 65983)
- +++ src/main/java/org/jbpm/db/JbpmSchema.java (revision 75353)
- @@ -41,305 +41,373 @@
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- +import org.hibernate.Session;
- +import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import org.hibernate.cfg.Environment;
- -import org.hibernate.connection.ConnectionProvider;
- -import org.hibernate.connection.ConnectionProviderFactory;
- import org.hibernate.dialect.Dialect;
- -import org.hibernate.engine.Mapping;
- +import org.hibernate.engine.spi.Mapping;
- import org.hibernate.mapping.ForeignKey;
- import org.hibernate.mapping.Table;
- import org.hibernate.tool.hbm2ddl.SchemaExport;
- import org.hibernate.util.JDBCExceptionReporter;
- import org.jbpm.JbpmException;
- +import org.hibernate.jdbc.Work;
- /**
- - * utilities for the jBPM database schema.
- + * utilities for the jBPM database schema.
- */
- public class JbpmSchema implements Serializable {
- -
- - private static final long serialVersionUID = 1L;
- +
- + private static final long serialVersionUID = 1L;
- +
- + static final String JBPM_TABLE_PREFIX = "JBPM_";
- +
- + Configuration configuration = null;
- + Properties properties = null;
- + Dialect dialect = null;
- + Mapping mapping = null;
- + String[] createSql = null;
- + String[] dropSql = null;
- + String[] cleanSql = null;
- +
- + public JbpmSchema(Configuration configuration) {
- + this.configuration = configuration;
- + this.properties = configuration.getProperties();
- + this.dialect = Dialect.getDialect(properties);
- + try {
- + // get the mapping field via reflection :-(
- + Field mappingField = Configuration.class.getDeclaredField("mapping");
- + mappingField.setAccessible(true);
- + this.mapping = (Mapping) mappingField.get(configuration);
- + } catch (Exception e) {
- + throw new JbpmException("couldn't get the hibernate mapping", e);
- + }
- + }
- - static final String JBPM_TABLE_PREFIX = "JBPM_";
- -
- - Configuration configuration = null;
- - Properties properties = null;
- - Dialect dialect = null;
- - Mapping mapping = null;
- - String[] createSql = null;
- - String[] dropSql = null;
- - String[] cleanSql = null;
- + public String[] getCreateSql() {
- + if (createSql == null) {
- + createSql = configuration.generateSchemaCreationScript(dialect);
- + }
- + return createSql;
- + }
- - ConnectionProvider connectionProvider = null;
- - Connection connection = null;
- - Statement statement = null;
- + public String[] getDropSql() {
- + if (dropSql == null) {
- + dropSql = configuration.generateDropSchemaScript(dialect);
- + }
- + return dropSql;
- + }
- - public JbpmSchema(Configuration configuration) {
- - this.configuration = configuration;
- - this.properties = configuration.getProperties();
- - this.dialect = Dialect.getDialect(properties);
- - try {
- - // get the mapping field via reflection :-(
- - Field mappingField = Configuration.class.getDeclaredField("mapping");
- - mappingField.setAccessible(true);
- - this.mapping = (Mapping) mappingField.get(configuration);
- - } catch (Exception e) {
- - throw new JbpmException("couldn't get the hibernate mapping", e);
- - }
- - }
- + public String[] getCleanSql() {
- + if (cleanSql == null) {
- + // loop over all foreign key constraints
- + List dropForeignKeysSql = new ArrayList();
- + List createForeignKeysSql = new ArrayList();
- + Iterator iter = configuration.getTableMappings();
- + while (iter.hasNext()) {
- + Table table = (Table) iter.next();
- + if (table.isPhysicalTable()) {
- + Iterator subIter = table.getForeignKeyIterator();
- + while (subIter.hasNext()) {
- + ForeignKey fk = (ForeignKey) subIter.next();
- + if (fk.isPhysicalConstraint()) {
- + // collect the drop foreign key constraint sql
- + dropForeignKeysSql.add(fk.sqlDropString(dialect,
- + properties.getProperty(Environment.DEFAULT_CATALOG),
- + properties.getProperty(Environment.DEFAULT_SCHEMA)));
- + // and collect the create foreign key constraint sql
- + createForeignKeysSql.add(fk.sqlCreateString(dialect, mapping,
- + properties.getProperty(Environment.DEFAULT_CATALOG),
- + properties.getProperty(Environment.DEFAULT_SCHEMA)));
- + }
- + }
- + }
- + }
- - public String[] getCreateSql() {
- - if (createSql==null) {
- - createSql = configuration.generateSchemaCreationScript(dialect);
- - }
- - return createSql;
- - }
- -
- - public String[] getDropSql() {
- - if (dropSql==null) {
- - dropSql = configuration.generateDropSchemaScript(dialect);
- - }
- - return dropSql;
- - }
- -
- - public String[] getCleanSql() {
- - if (cleanSql==null) {
- - // loop over all foreign key constraints
- - List dropForeignKeysSql = new ArrayList();
- - List createForeignKeysSql = new ArrayList();
- - Iterator iter = configuration.getTableMappings();
- - while ( iter.hasNext() ) {
- - Table table = ( Table ) iter.next();
- - if ( table.isPhysicalTable() ) {
- - Iterator subIter = table.getForeignKeyIterator();
- - while ( subIter.hasNext() ) {
- - ForeignKey fk = ( ForeignKey ) subIter.next();
- - if ( fk.isPhysicalConstraint() ) {
- - // collect the drop foreign key constraint sql
- - dropForeignKeysSql.add( fk.sqlDropString(
- - dialect,
- - properties.getProperty(Environment.DEFAULT_CATALOG),
- - properties.getProperty(Environment.DEFAULT_SCHEMA) ) );
- - // and collect the create foreign key constraint sql
- - createForeignKeysSql.add( fk.sqlCreateString(
- - dialect,
- - mapping,
- - properties.getProperty(Environment.DEFAULT_CATALOG),
- - properties.getProperty(Environment.DEFAULT_SCHEMA) ) );
- - }
- - }
- - }
- - }
- + List deleteSql = new ArrayList();
- + iter = configuration.getTableMappings();
- + while (iter.hasNext()) {
- + Table table = (Table) iter.next();
- + deleteSql.add("delete from " + table.getName());
- + }
- - List deleteSql = new ArrayList();
- - iter = configuration.getTableMappings();
- - while (iter.hasNext()) {
- - Table table = (Table) iter.next();
- - deleteSql.add("delete from "+table.getName());
- - }
- + // glue
- + // - drop foreign key constraints
- + // - delete contents of all tables
- + // - create foreign key constraints
- + // together to form the clean script
- + List cleanSqlList = new ArrayList();
- + cleanSqlList.addAll(dropForeignKeysSql);
- + cleanSqlList.addAll(deleteSql);
- + cleanSqlList.addAll(createForeignKeysSql);
- - // glue
- - // - drop foreign key constraints
- - // - delete contents of all tables
- - // - create foreign key constraints
- - // together to form the clean script
- - List cleanSqlList = new ArrayList();
- - cleanSqlList.addAll(dropForeignKeysSql);
- - cleanSqlList.addAll(deleteSql);
- - cleanSqlList.addAll(createForeignKeysSql);
- -
- - cleanSql = (String[]) cleanSqlList.toArray(new String[cleanSqlList.size()]);
- - }
- - return cleanSql;
- - }
- + cleanSql = (String[]) cleanSqlList.toArray(new String[cleanSqlList.size()]);
- + }
- + return cleanSql;
- + }
- - public boolean hasJbpmTables() {
- - return (getJbpmTables().size()>0);
- - }
- + public boolean hasJbpmTables() {
- + return (getJbpmTables().size() > 0);
- + }
- - public List getJbpmTables() {
- - // delete all the data in the jbpm tables
- - List jbpmTableNames = new ArrayList();
- - try {
- - createConnection();
- - ResultSet resultSet = connection.getMetaData().getTables(null, null, null, null);
- - while(resultSet.next()) {
- - String tableName = resultSet.getString("TABLE_NAME");
- - if ( (tableName!=null)
- - && (tableName.length()>5)
- - && (JBPM_TABLE_PREFIX.equalsIgnoreCase(tableName.substring(0,5))) ) {
- - jbpmTableNames.add(tableName);
- - }
- - }
- - } catch (SQLException e) {
- - throw new JbpmException("couldn't get the jbpm table names");
- - } finally {
- - closeConnection();
- - }
- - return jbpmTableNames;
- - }
- -
- - public void dropSchema() {
- - execute( getDropSql() );
- - }
- + public List getJbpmTables() {
- + // delete all the data in the jbpm tables
- + List jbpmTableNames = new ArrayList();
- + Session session = null;
- + try {
- + SessionFactory sessionFactory = configuration.buildSessionFactory();
- + session = sessionFactory.openSession();
- + JBPMTablesWork work = new JBPMTablesWork();
- + session.doWork(work);
- + jbpmTableNames = work.getJbpmTableNames();
- + } catch (Exception e) {
- + throw new JbpmException("couldn't get the jbpm table names");
- + } finally {
- + if (session != null) {
- + session.close();
- + }
- + }
- + return jbpmTableNames;
- + }
- - public void createSchema() {
- - execute( getCreateSql() );
- - }
- + public void dropSchema() {
- + execute(getDropSql());
- + }
- - public void cleanSchema() {
- - execute( getCleanSql() );
- - }
- + public void createSchema() {
- + execute(getCreateSql());
- + }
- - public void saveSqlScripts(String dir, String prefix) {
- - try {
- - new File(dir).mkdirs();
- - saveSqlScript(dir+"/"+prefix+".drop.sql", getDropSql());
- - saveSqlScript(dir+"/"+prefix+".create.sql", getCreateSql());
- - saveSqlScript(dir+"/"+prefix+".clean.sql", getCleanSql());
- - new SchemaExport(configuration)
- - .setDelimiter(getSqlDelimiter())
- - .setOutputFile(dir+"/"+prefix+".drop.create.sql")
- - .create(true, false);
- - } catch (Exception e) {
- - throw new JbpmException("couldn't generate scripts", e);
- - }
- - }
- + public void cleanSchema() {
- + execute(getCleanSql());
- + }
- - public static void main(String[] args) {
- - try {
- - if ( (args==null) || (args.length==0) ) {
- - throw new IllegalArgumentException();
- - }
- -
- - String cmd = args[0];
- -
- - if ("create".equalsIgnoreCase(cmd)) {
- - Configuration configuration = createConfiguration(args, 1);
- - new JbpmSchema(configuration).createSchema();
- - } else if ("drop".equalsIgnoreCase(cmd)) {
- - Configuration configuration = createConfiguration(args, 1);
- - new JbpmSchema(configuration).dropSchema();
- - } else if ("clean".equalsIgnoreCase(cmd)) {
- - Configuration configuration = createConfiguration(args, 1);
- - new JbpmSchema(configuration).cleanSchema();
- - } else if ("scripts".equalsIgnoreCase(cmd)) {
- - Configuration configuration = createConfiguration(args, 3);
- - new JbpmSchema(configuration).saveSqlScripts(args[1], args[2]);
- - }
- + public void saveSqlScripts(String dir, String prefix) {
- + try {
- + new File(dir).mkdirs();
- + saveSqlScript(dir + "/" + prefix + ".drop.sql", getDropSql());
- + saveSqlScript(dir + "/" + prefix + ".create.sql", getCreateSql());
- + saveSqlScript(dir + "/" + prefix + ".clean.sql", getCleanSql());
- + new SchemaExport(configuration).setDelimiter(getSqlDelimiter())
- + .setOutputFile(dir + "/" + prefix + ".drop.create.sql").create(true, false);
- + } catch (Exception e) {
- + throw new JbpmException("couldn't generate scripts", e);
- + }
- + }
- - } catch (IllegalArgumentException e) {
- - System.err.println("syntax: JbpmSchema create [<hibernate.cfg.xml> [<hibernate.properties>]]");
- - System.err.println("syntax: JbpmSchema drop [<hibernate.cfg.xml> [<hibernate.properties>]]");
- - System.err.println("syntax: JbpmSchema clean [<hibernate.cfg.xml> [<hibernate.properties>]]");
- - System.err.println("syntax: JbpmSchema scripts <dir> <prefix> [<hibernate.cfg.xml> [<hibernate.properties>]]");
- - } catch (Exception e) {
- - e.printStackTrace();
- - throw new JbpmException(e);
- - }
- - }
- -
- - static Configuration createConfiguration(String[] args, int index) {
- - String hibernateCfgXml = (args.length>index ? args[index] : "hibernate.cfg.xml");
- - String hibernateProperties = (args.length>(index+1) ? args[index+1] : null);
- -
- - Configuration configuration = new Configuration();
- - configuration.configure(new File(hibernateCfgXml));
- - if (hibernateProperties!=null) {
- - try {
- - Properties properties = new Properties();
- - InputStream inputStream = new FileInputStream(hibernateProperties);
- - properties.load(inputStream);
- - configuration.setProperties(properties);
- - } catch (Exception e) {
- - e.printStackTrace();
- - throw new JbpmException("couldn't load hibernate configuration", e);
- - }
- - }
- -
- - return configuration;
- - }
- + public static void main(String[] args) {
- + try {
- + if ((args == null) || (args.length == 0)) {
- + throw new IllegalArgumentException();
- + }
- - void saveSqlScript(String fileName, String[] sql) throws FileNotFoundException {
- - FileOutputStream fileOutputStream = new FileOutputStream(fileName);
- - try {
- - PrintStream printStream = new PrintStream(fileOutputStream);
- - for (int i=0; i<sql.length; i++) {
- - printStream.println(sql[i]+getSqlDelimiter());
- - }
- - } finally {
- - try {
- - fileOutputStream.close();
- - } catch (IOException e) {
- - e.printStackTrace();
- - }
- - }
- - }
- + String cmd = args[0];
- - public void execute(String[] sqls) {
- - String sql = null;
- - String showSqlText = properties.getProperty("hibernate.show_sql");
- - boolean showSql = ("true".equalsIgnoreCase(showSqlText));
- + if ("create".equalsIgnoreCase(cmd)) {
- + Configuration configuration = createConfiguration(args, 1);
- + new JbpmSchema(configuration).createSchema();
- + } else if ("drop".equalsIgnoreCase(cmd)) {
- + Configuration configuration = createConfiguration(args, 1);
- + new JbpmSchema(configuration).dropSchema();
- + } else if ("clean".equalsIgnoreCase(cmd)) {
- + Configuration configuration = createConfiguration(args, 1);
- + new JbpmSchema(configuration).cleanSchema();
- + } else if ("scripts".equalsIgnoreCase(cmd)) {
- + Configuration configuration = createConfiguration(args, 3);
- + new JbpmSchema(configuration).saveSqlScripts(args[1], args[2]);
- + }
- - try {
- - createConnection();
- - statement = connection.createStatement();
- -
- - for (int i=0; i<sqls.length; i++) {
- - sql = sqls[i];
- -
- - if (showSql) log.debug(sql);
- - statement.executeUpdate(sql);
- - }
- -
- - } catch (SQLException e) {
- - e.printStackTrace();
- - throw new JbpmException("couldn't execute sql '"+sql+"'", e);
- - } finally {
- - closeConnection();
- - }
- - }
- + } catch (IllegalArgumentException e) {
- + System.err.println("syntax: JbpmSchema create [<hibernate.cfg.xml> [<hibernate.properties>]]");
- + System.err.println("syntax: JbpmSchema drop [<hibernate.cfg.xml> [<hibernate.properties>]]");
- + System.err.println("syntax: JbpmSchema clean [<hibernate.cfg.xml> [<hibernate.properties>]]");
- + System.err
- + .println("syntax: JbpmSchema scripts <dir> <prefix> [<hibernate.cfg.xml> [<hibernate.properties>]]");
- + } catch (Exception e) {
- + e.printStackTrace();
- + throw new JbpmException(e);
- + }
- + }
- - void closeConnection() {
- - try {
- - if (statement!=null) statement.close();
- - if (connection!=null) {
- - JDBCExceptionReporter.logWarnings( connection.getWarnings() );
- - connection.clearWarnings();
- - connectionProvider.closeConnection(connection);
- - connectionProvider.close();
- - }
- - }
- - catch(Exception e) {
- - System.err.println( "Could not close connection" );
- - e.printStackTrace();
- - }
- - }
- + static Configuration createConfiguration(String[] args, int index) {
- + String hibernateCfgXml = (args.length > index ? args[index] : "hibernate.cfg.xml");
- + String hibernateProperties = (args.length > (index + 1) ? args[index + 1] : null);
- - void createConnection() throws SQLException {
- - connectionProvider = ConnectionProviderFactory.newConnectionProvider(properties);
- - connection = connectionProvider.getConnection();
- - if ( !connection.getAutoCommit() ) {
- - connection.commit();
- - connection.setAutoCommit(true);
- - }
- - }
- + Configuration configuration = new Configuration();
- + configuration.configure(new File(hibernateCfgXml));
- + if (hibernateProperties != null) {
- + try {
- + Properties properties = new Properties();
- + InputStream inputStream = new FileInputStream(hibernateProperties);
- + properties.load(inputStream);
- + configuration.setProperties(properties);
- + } catch (Exception e) {
- + e.printStackTrace();
- + throw new JbpmException("couldn't load hibernate configuration", e);
- + }
- + }
- - public Properties getProperties() {
- - return properties;
- - }
- + return configuration;
- + }
- - // sql delimiter ////////////////////////////////////////////////////////////
- -
- - static String sqlDelimiter = null;
- - synchronized String getSqlDelimiter() {
- - if (sqlDelimiter==null) {
- - sqlDelimiter = properties.getProperty("jbpm.sql.delimiter", ";");
- - }
- - return sqlDelimiter;
- - }
- + void saveSqlScript(String fileName, String[] sql) throws FileNotFoundException {
- + FileOutputStream fileOutputStream = new FileOutputStream(fileName);
- + try {
- + PrintStream printStream = new PrintStream(fileOutputStream);
- + for (int i = 0; i < sql.length; i++) {
- + printStream.println(sql[i] + getSqlDelimiter());
- + }
- + } finally {
- + try {
- + fileOutputStream.close();
- + } catch (IOException e) {
- + e.printStackTrace();
- + }
- + }
- + }
- - // logger ///////////////////////////////////////////////////////////////////
- + public void execute(String[] sqls) {
- + String sql = null;
- + String showSqlText = properties.getProperty("hibernate.show_sql");
- + boolean showSql = ("true".equalsIgnoreCase(showSqlText));
- + Session session = null;
- + try {
- + SessionFactory sessionFactory = configuration.buildSessionFactory();
- + session = sessionFactory.openSession();
- + Work work = new SQLWork(sqls, showSql);
- + session.doWork(work);
- + } catch (Exception e) {
- + e.printStackTrace();
- + throw new JbpmException("couldn't execute sql '" + sql + "'", e);
- + } finally {
- + if (session!=null) {
- + session.close();
- + }
- + }
- + }
- - private static final Log log = LogFactory.getLog(JbpmSchema.class);
- + // void closeConnection() {
- + // try {
- + // if (statement!=null) statement.close();
- + // if (connection!=null) {
- + // JDBCExceptionReporter.logWarnings( connection.getWarnings() );
- + // connection.clearWarnings();
- + // connectionProvider.closeConnection(connection);
- + // connectionProvider.close();
- + // }
- + // }
- + // catch(Exception e) {
- + // System.err.println( "Could not close connection" );
- + // e.printStackTrace();
- + // }
- + // }
- + //
- + // void createConnection() throws SQLException {
- + // connectionProvider =
- + // ConnectionProviderFactory.newConnectionProvider(properties);
- + // connection = connectionProvider.getConnection();
- + // if ( !connection.getAutoCommit() ) {
- + // connection.commit();
- + // connection.setAutoCommit(true);
- + // }
- + // }
- +
- + public Properties getProperties() {
- + return properties;
- + }
- +
- + // sql delimiter
- + // ////////////////////////////////////////////////////////////
- +
- + static String sqlDelimiter = null;
- +
- + synchronized String getSqlDelimiter() {
- + if (sqlDelimiter == null) {
- + sqlDelimiter = properties.getProperty("jbpm.sql.delimiter", ";");
- + }
- + return sqlDelimiter;
- + }
- +
- + // logger
- + // ///////////////////////////////////////////////////////////////////
- +
- + private static final Log log = LogFactory.getLog(JbpmSchema.class);
- +
- + // work definition for hibernate 4
- +
- + private class JBPMTablesWork implements Work {
- +
- + private final Log log = LogFactory.getLog(JBPMTablesWork.class);
- + private List jbpmTableNames = new ArrayList();
- +
- + /*
- + * (non-Javadoc)
- + *
- + * @see org.hibernate.jdbc.Work#execute(java.sql.Connection)
- + */
- + @Override
- + public void execute(Connection connection) throws SQLException {
- + try {
- + ResultSet resultSet = connection.getMetaData().getTables(null, null, null, null);
- + while (resultSet.next()) {
- + String tableName = resultSet.getString("TABLE_NAME");
- + if ((tableName != null) && (tableName.length() > 5)
- + && (JBPM_TABLE_PREFIX.equalsIgnoreCase(tableName.substring(0, 5)))) {
- + jbpmTableNames.add(tableName);
- + }
- + }
- + } catch (SQLException e) {
- + log.error(e);
- + throw e;
- + }
- + }
- +
- + /**
- + * @return the jbpmTableNames
- + */
- + public List getJbpmTableNames() {
- + return jbpmTableNames;
- + }
- +
- + }
- +
- + private class SQLWork implements Work {
- +
- + private String[] script;
- + private boolean showSql;
- +
- + public SQLWork(String[] sqls, boolean showSqlContent) {
- + super();
- + script = sqls;
- + showSql = showSqlContent;
- + }
- +
- + /*
- + * (non-Javadoc)
- + *
- + * @see org.hibernate.jdbc.Work#execute(java.sql.Connection)
- + */
- + public void execute(Connection connection) throws SQLException {
- + try {
- + Statement statement = connection.createStatement();
- + try {
- + for (int i = 0; i < script.length; i++) {
- + String sql = script[i];
- + if (showSql) {
- + System.out.println(sql);
- + }
- + statement.executeUpdate(sql);
- + }
- + } finally {
- + statement.close();
- + }
- + } catch (SQLException e) {
- + throw new JbpmException("failed to execute sql", e);
- + } finally {
- + // sth todo
- + }
- + }
- +
- + }
- }
- Index: src/main/java/org/jbpm/db/compatibility/JbpmSchemaUpdate.java
- ===================================================================
- --- src/main/java/org/jbpm/db/compatibility/JbpmSchemaUpdate.java (revision 65983)
- +++ src/main/java/org/jbpm/db/compatibility/JbpmSchemaUpdate.java (revision 75353)
- @@ -17,11 +17,9 @@
- import org.hibernate.cfg.Configuration;
- import org.hibernate.cfg.NamingStrategy;
- import org.hibernate.cfg.Settings;
- -import org.hibernate.connection.ConnectionProvider;
- -import org.hibernate.connection.ConnectionProviderFactory;
- import org.hibernate.dialect.Dialect;
- import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
- -import org.hibernate.util.ReflectHelper;
- +//import org.hibernate.util.ReflectHelper;
- /**
- * This is a modified version of the hibernate tools schema update.
- @@ -33,7 +31,6 @@
- public class JbpmSchemaUpdate {
- private static final Log log = LogFactory.getLog(JbpmSchemaUpdate.class);
- - private ConnectionProvider connectionProvider;
- private Configuration configuration;
- private Dialect dialect;
- private List exceptions;
- @@ -48,14 +45,14 @@
- Properties props = new Properties();
- props.putAll( dialect.getDefaultProperties() );
- props.putAll(connectionProperties);
- - connectionProvider = ConnectionProviderFactory.newConnectionProvider(props);
- +// connectionProvider = ConnectionProviderFactory.newConnectionProvider(props);
- exceptions = new ArrayList();
- }
- public JbpmSchemaUpdate(Configuration cfg, Settings settings) throws HibernateException {
- this.configuration = cfg;
- - dialect = settings.getDialect();
- - connectionProvider = settings.getConnectionProvider();
- +// dialect = settings.getDialect();
- +// connectionProvider = settings.getConnectionProvider();
- exceptions = new ArrayList();
- }
- @@ -85,9 +82,9 @@
- doUpdate = false;
- }
- else if ( args[i].startsWith("--naming=") ) {
- - cfg.setNamingStrategy(
- - (NamingStrategy) ReflectHelper.classForName( args[i].substring(9) ).newInstance()
- - );
- +// cfg.setNamingStrategy(
- +// (NamingStrategy) ReflectHelper.classForName( args[i].substring(9) ).newInstance()
- +// );
- }
- else if (args[i].startsWith("--output=")) {
- out = new File(args[i].substring(9));
- @@ -144,7 +141,7 @@
- DatabaseMetadata meta;
- try {
- log.info("fetching database metadata");
- - connection = connectionProvider.getConnection();
- +// connection = connectionProvider.getConnection();
- if ( !connection.getAutoCommit() ) {
- connection.commit();
- connection.setAutoCommit(true);
- @@ -201,7 +198,7 @@
- if (stmt!=null) stmt.close();
- if (!autoCommitWasEnabled) connection.setAutoCommit(false);
- if (connection!=null) connection.close();
- - if (connectionProvider!=null) connectionProvider.close();
- +// if (connectionProvider!=null) connectionProvider.close();
- }
- catch (Exception e) {
- exceptions.add(e);
- Index: src/main/java/org/jbpm/db/JbpmSession.java
- ===================================================================
- --- src/main/java/org/jbpm/db/JbpmSession.java (revision 65983)
- +++ src/main/java/org/jbpm/db/JbpmSession.java (revision 75353)
- @@ -98,15 +98,15 @@
- return jbpmSessionFactory;
- }
- - public Connection getConnection() {
- - try {
- - return session.connection();
- - } catch (Exception e) {
- - log.error(e);
- - handleException();
- - throw new JbpmException( "couldn't get the jdbc connection from hibernate", e );
- - }
- - }
- +// public Connection getConnection() {
- +// try {
- +// return session.connection();
- +// } catch (Exception e) {
- +// log.error(e);
- +// handleException();
- +// throw new JbpmException( "couldn't get the jdbc connection from hibernate", e );
- +// }
- +// }
- public Session getSession() {
- return session;
- Index: src/main/java/org/jbpm/graph/node/Join.java
- ===================================================================
- --- src/main/java/org/jbpm/graph/node/Join.java (revision 65983)
- +++ src/main/java/org/jbpm/graph/node/Join.java (revision 75353)
- @@ -110,7 +110,7 @@
- if (session!=null) {
- LockMode lockMode = LockMode.FORCE;
- if (parentLockMode!=null) {
- - lockMode = LockMode.parse(parentLockMode);
- + lockMode = LockMode.valueOf(parentLockMode);
- }
- log.debug("forcing version increment on parent token "+parentToken);
- session.lock(parentToken, lockMode);
- Index: src/main/resources/org/jbpm/context/exe/TokenVariableMap.hbm.xml
- ===================================================================
- --- src/main/resources/org/jbpm/context/exe/TokenVariableMap.hbm.xml (revision 65983)
- +++ src/main/resources/org/jbpm/context/exe/TokenVariableMap.hbm.xml (revision 75353)
- @@ -1,8 +1,7 @@
- <?xml version="1.0"?>
- -<!DOCTYPE hibernate-mapping PUBLIC
- - "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- +"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping auto-import="false" default-access="field">
- <class name="org.jbpm.context.exe.TokenVariableMap"
- Index: src/main/resources/org/jbpm/context/exe/variableinstance/StringInstance.hbm.xml
- ===================================================================
- --- src/main/resources/org/jbpm/context/exe/variableinstance/StringInstance.hbm.xml (revision 65983)
- +++ src/main/resources/org/jbpm/context/exe/variableinstance/StringInstance.hbm.xml (revision 75353)
- @@ -1,8 +1,7 @@
- <?xml version="1.0"?>
- -<!DOCTYPE hibernate-mapping PUBLIC
- - "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- +"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping auto-import="false" default-access="field">
- <subclass name="org.jbpm.context.exe.variableinstance.StringInstance"
- Index: src/main/resources/org/jbpm/context/exe/variableinstance/HibernateStringInstance.hbm.xml
- ===================================================================
- --- src/main/resources/org/jbpm/context/exe/variableinstance/HibernateStringInstance.hbm.xml (revision 65983)
- +++ src/main/resources/org/jbpm/context/exe/variableinstance/HibernateStringInstance.hbm.xml (revision 75353)
- @@ -1,8 +1,7 @@
- <?xml version="1.0"?>
- -<!DOCTYPE hibernate-mapping PUBLIC
- - "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- +"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping auto-import="false" default-access="field">
- <subclass name="org.jbpm.context.exe.variableinstance.HibernateStringInstance"
- Index: src/main/resources/org/jbpm/context/exe/variableinstance/DoubleInstance.hbm.xml
- ===================================================================
- --- src/main/resources/org/jbpm/context/exe/variableinstance/DoubleInstance.hbm.xml (revision 65983)
- +++ src/main/resources/org/jbpm/context/exe/variableinstance/DoubleInstance.hbm.xml (revision 75353)
- @@ -1,8 +1,7 @@
- <?xml version="1.0"?>
- -<!DOCTYPE hibernate-mapping PUBLIC
- - "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- +"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping auto-import="false" default-access="field">
- <subclass name="org.jbpm.context.exe.variableinstance.DoubleInstance"
- Index: src/main/resources/org/jbpm/context/exe/variableinstance/NullInstance.hbm.xml
- ===================================================================
- --- src/main/resources/org/jbpm/context/exe/variableinstance/NullInstance.hbm.xml (revision 65983)
- +++ src/main/resources/org/jbpm/context/exe/variableinstance/NullInstance.hbm.xml (revision 75353)
- @@ -1,8 +1,7 @@
- <?xml version="1.0"?>
- -<!DOCTYPE hibernate-mapping PUBLIC
- - "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- +"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping auto-import="false" default-access="field">
- <subclass name="org.jbpm.context.exe.variableinstance.NullInstance"
- Index: src/main/resources/org/jbpm/context/exe/variableinstance/DateInstance.hbm.xml
- ===================================================================
- --- src/main/resources/org/jbpm/context/exe/variableinstance/DateInstance.hbm.xml (revision 65983)
- +++ src/main/resources/org/jbpm/context/exe/variableinstance/DateInstance.hbm.xml (revision 75353)
- @@ -1,8 +1,7 @@
- <?xml version="1.0"?>
- -<!DOCTYPE hibernate-mapping PUBLIC
- - "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- +"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping auto-import="false" default-access="field">
- <subclass name="org.jbpm.context.exe.variableinstance.DateInstance"
- Index: src/main/resources/org/jbpm/context/exe/variableinstance/LongInstance.hbm.xml
- ===================================================================
- --- src/main/resources/org/jbpm/context/exe/variableinstance/LongInstance.hbm.xml (revision 65983)
- +++ src/main/resources/org/jbpm/context/exe/variableinstance/LongInstance.hbm.xml (revision 75353)
- @@ -1,8 +1,7 @@
- <?xml version="1.0"?>
- -<!DOCTYPE hibernate-mapping PUBLIC
- - "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- +"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping auto-import="false" default-access="field">
- <subclass name="org.jbpm.context.exe.variableinstance.LongInstance"
- Index: src/main/resources/org/jbpm/context/exe/variableinstance/HibernateLongInstance.hbm.xml
- ===================================================================
- --- src/main/resources/org/jbpm/context/exe/variableinstance/HibernateLongInstance.hbm.xml (revision 65983)
- +++ src/main/resources/org/jbpm/context/exe/variableinstance/HibernateLongInstance.hbm.xml (revision 75353)
- @@ -1,8 +1,7 @@
- <?xml version="1.0"?>
- -<!DOCTYPE hibernate-mapping PUBLIC
- - "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- +"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping auto-import="false" default-access="field">
- <subclass name="org.jbpm.context.exe.variableinstance.HibernateLongInstance"
- Index: src/main/resources/org/jbpm/context/exe/variableinstance/ByteArrayInstance.hbm.xml
- ===================================================================
- --- src/main/resources/org/jbpm/context/exe/variableinstance/ByteArrayInstance.hbm.xml (revision 65983)
- +++ src/main/resources/org/jbpm/context/exe/variableinstance/ByteArrayInstance.hbm.xml (revision 75353)
- @@ -1,8 +1,7 @@
- <?xml version="1.0"?>
- -<!DOCTYPE hibernate-mapping PUBLIC
- - "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- +"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping auto-import="false" default-access="field">
- <subclass name="org.jbpm.context.exe.variableinstance.ByteArrayInstance"
- Index: src/main/resources/org/jbpm/context/exe/variableinstance/JcrNodeInstance.hbm.xml
- ===================================================================
- --- src/main/resources/org/jbpm/context/exe/variableinstance/JcrNodeInstance.hbm.xml (revision 65983)
- +++ src/main/resources/org/jbpm/context/exe/variableinstance/JcrNodeInstance.hbm.xml (revision 75353)
- @@ -1,8 +1,7 @@
- <?xml version="1.0"?>
- -<!DOCTYPE hibernate-mapping PUBLIC
- - "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- +"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping auto-import="false" default-access="field">
- <subclass name="org.jbpm.context.exe.variableinstance.JcrNodeInstance"
- Index: src/main/resources/org/jbpm/context/exe/ContextInstance.hbm.xml
- ===================================================================
- --- src/main/resources/org/jbpm/context/exe/ContextInstance.hbm.xml (revision 65983)
- +++ src/main/resources/org/jbpm/context/exe/ContextInstance.hbm.xml (revision 75353)
- @@ -1,8 +1,7 @@
- <?xml version="1.0"?>
- -<!DOCTYPE hibernate-mapping PUBLIC
- - "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- +"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping auto-import="false" default-access="field">
- Index: src/main/resources/org/jbpm/context/exe/VariableInstance.hbm.xml
- ===================================================================
- --- src/main/resources/org/jbpm/context/exe/VariableInstance.hbm.xml (revision 65983)
- +++ src/main/resources/org/jbpm/context/exe/VariableInstance.hbm.xml (revision 75353)
- @@ -1,8 +1,7 @@
- <?xml version="1.0"?>
- -<!DOCTYPE hibernate-mapping PUBLIC
- - "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- - "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- +"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
- <hibernate-mapping auto-import="false" default-access="field">
- <class name="org.jbpm.context.exe.VariableInstance"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement