001    package biz.hammurapi.sql;
002    
003    import java.sql.Connection;
004    import java.sql.SQLException;
005    import java.text.MessageFormat;
006    
007    /**
008     * Generates identities using SQLProcessor nextPK method
009     * @author Pavel Vlasov
010     *
011     */
012    public class TableIdentityGenerator implements IdentityGenerator {
013            
014            /**
015             * Default constructor with "{0}" pattern
016             */
017            public TableIdentityGenerator(String primaryKeysTable) {
018                    this(primaryKeysTable, "{0}");
019            }
020            
021            private int mode; // 0 - passthrough 1 - invariant 2 - format
022            private MessageFormat mf;
023            private String keyName;
024            private String primaryKeysTable;
025            private Object[] args=new Object[] {null};
026            
027            /**
028             * Constructor
029             * @param primaryKeysTable - Table which hold primary keys. See SQLProcessor documentation.
030             * @param pattern - Key name pattern. {0} stands for table name.
031             */
032            public TableIdentityGenerator(String primaryKeysTable, String pattern) {
033                    if ("{0}".equals(pattern)) {
034                            mode=0;
035                    } else if (pattern.indexOf("{0}")==-1) {
036                            mode=1;
037                            this.keyName=pattern;
038                    } else {
039                            mode=2;
040                            mf=new MessageFormat(pattern);
041                    }
042                    this.primaryKeysTable=primaryKeysTable;
043            }
044    
045            public int generate(Connection con, String name) throws SQLException {
046                    String ename;
047                    switch (mode) {
048                    case 0: 
049                            ename=name;
050                            break;
051                    case 1:
052                            ename=keyName;
053                            break;
054                    case 2:
055                            synchronized (mf) {
056                                    args[0]=name;
057                                    ename=mf.format(args, new StringBuffer(), null).toString();
058                            }
059                    default:
060                            throw new IllegalStateException("Invalid mode: "+mode);
061                    }
062                    
063                    return new SQLProcessor(con, null).nextPK(primaryKeysTable, ename);
064            }
065    
066    }