001 package org.apache.torque.util;
002
003 import java.util.Comparator;
004
005 import static org.apache.commons.lang.StringUtils.*;
006
007 import org.kuali.db.jdbc.Transaction;
008
009 /**
010 *
011 *
012 */
013 public class TransactionComparator<T> implements Comparator<Transaction> {
014
015 String suffix = ".sql";
016 String constraints = "-constraints";
017 String artifactId;
018
019 public TransactionComparator() {
020 this(null);
021 }
022
023 public TransactionComparator(String artifactId) {
024 super();
025 this.artifactId = artifactId;
026 }
027
028 @Override
029 public int compare(Transaction one, Transaction two) {
030 String loc1 = one.getResourceLocation();
031 String loc2 = two.getResourceLocation();
032 // If loc1 is ks-embedded-db.sql, loc1 goes before loc2
033 if (isSchemaSQL(loc1)) {
034 return -1;
035 }
036 // If loc2 is ks-embedded-db.sql, loc1 goes after loc2
037 if (isSchemaSQL(loc2)) {
038 return 1;
039 }
040 // If loc1 is ks-embedded-db-constraints.sql, loc1 goes after loc2
041 if (isSchemaConstraintsSQL(loc1)) {
042 return 1;
043 }
044 // If loc2 is ks-embedded-db-constraints.sql, loc1 goes before loc2
045 if (isSchemaConstraintsSQL(loc2)) {
046 return -1;
047 }
048 // They are both empty, it is a tie
049 if (isEmpty(loc1) && isEmpty(loc2)) {
050 return 0;
051 }
052 // Loc2 is empty but loc1 is not, loc1 goes after loc2
053 if (isEmpty(loc1) && !isEmpty(loc2)) {
054 return 1;
055 }
056 // Loc1 is empty but loc2 is not, loc1 goes before loc2
057 if (!isEmpty(loc1) && isEmpty(loc2)) {
058 return -1;
059 }
060 // Fall through to the normal string compare
061 return loc1.compareTo(loc2);
062 }
063
064 protected boolean isSchemaSQL(String location) {
065 if (isEmpty(location)) {
066 return false;
067 } else {
068 return location.endsWith(getArtifactId() + getSuffix());
069 }
070 }
071
072 protected boolean isSchemaConstraintsSQL(String location) {
073 return location.endsWith(getArtifactId() + getConstraints() + getSuffix());
074 }
075
076 public String getArtifactId() {
077 return artifactId;
078 }
079
080 public void setArtifactId(String schema) {
081 this.artifactId = schema;
082 }
083
084 public String getSuffix() {
085 return suffix;
086 }
087
088 public void setSuffix(String suffix) {
089 this.suffix = suffix;
090 }
091
092 public String getConstraints() {
093 return constraints;
094 }
095
096 public void setConstraints(String constraints) {
097 this.constraints = constraints;
098 }
099
100 }