001    package org.apache.ojb.broker.util.dbhandling;
002    
003    /* Copyright 2004-2005 The Apache Software Foundation
004     *
005     * Licensed under the Apache License, Version 2.0 (the "License");
006     * you may not use this file except in compliance with the License.
007     * You may obtain a copy of the License at
008     *
009     *     http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    
018    import java.io.IOException;
019    import java.util.ArrayList;
020    import java.util.Iterator;
021    import java.util.StringTokenizer;
022    
023    import org.apache.ojb.broker.PBKey;
024    import org.apache.ojb.broker.PersistenceBrokerFactory;
025    import org.apache.ojb.broker.util.ClassHelper;
026    import org.apache.ojb.broker.metadata.ConnectionRepository;
027    import org.apache.ojb.broker.metadata.MetadataManager;
028    import org.apache.tools.ant.*;
029    import org.apache.tools.ant.types.FileSet;
030    
031    /**
032     * Ant task for performing basic db setup functions.
033     * 
034     * @author Thomas Dudziak
035     */
036    public class DBHandlingTask extends Task
037    {
038        /** The name of the known db handlings */
039        private static final String HANDLING_TORQUE = "torque";
040        /** The commands */
041        private static final String COMMAND_CREATE  = "create";
042        private static final String COMMAND_INIT    = "init";
043        
044        /** The name of the db handling to use */
045        private String _handling = HANDLING_TORQUE;
046        /** The path to the properties file */
047        private String _propertiesFile = null;
048        /** The alias of the jdbc connection to use (empty = default connection) */
049        private String _jcdAlias = null;
050        /** The working directory */
051        private String _workDir = null;
052        /** The input files */
053        private ArrayList _fileSets = new ArrayList();
054        /** The commands to perform */
055        private String _commands = "";
056        
057        /**
058         * Sets the name of the handling to use.
059         * 
060         * @param name The short name of the handling
061         */
062        public void setHandling(String name)
063        {
064            _handling = (name == null ? HANDLING_TORQUE : name.toLowerCase());
065        }
066    
067        /**
068         * Returns the name of the handling that is used.
069         * 
070         * @return The short name of the handling
071         */
072        public String getHandling()
073        {
074            return _handling;
075        }
076    
077        /**
078         * Sets the properties file (OJB.properties).
079         * 
080         * @param path The path to the properties file
081         */
082        public void setPropertiesFile(String path)
083        {
084            _propertiesFile = path;
085        }
086    
087        /**
088         * Returns the properties file.
089         * 
090         * @return The path to the properties file
091         */
092        public String getPropertiesFile()
093        {
094            return _propertiesFile;
095        }
096    
097        /**
098         * Sets the alias of the jdbc connection to use.
099         * 
100         * @param alias The alias of the connection
101         */
102        public void setJcdAlias(String alias)
103        {
104            _jcdAlias = alias;
105        }
106    
107        /**
108         * Returns the alias of the jdbc connection.
109         * 
110         * @return The alias
111         */
112        public String getJcdAlias()
113        {
114            return _jcdAlias;
115        }
116    
117        /**
118         * Sets the working directory. If none is given, then the system's temporary directory is used.
119         * 
120         * @param dir The working directory
121         */
122        public void setWorkDir(String dir)
123        {
124            _workDir = dir;
125        }
126    
127        /**
128         * Returns the working directory.
129         * 
130         * @return The working directory
131         */
132        public String getWorkDir()
133        {
134            return _workDir;
135        }
136    
137        /**
138         * Adds a fileset.
139         * 
140         * @param fileset The additional input files
141         */
142        public void addFileset(FileSet fileset)
143        {
144            _fileSets.add(fileset);
145        }
146    
147        /**
148         * Sets the list of commands to perform.
149         * 
150         * @param listOfCommands The comma-separated list of commands
151         */
152        public void setCommands(String listOfCommands)
153        {
154            _commands = listOfCommands;
155        }
156    
157        /**
158         * Returns the list of commands.
159         * 
160         * @return The comma-separated list of commands
161         */
162        public String getCommands()
163        {
164            return _commands;
165        }
166    
167        /* (non-Javadoc)
168         * @see org.apache.tools.ant.Task#execute()
169         */
170        public void execute() throws BuildException
171        {
172            if ((_commands == null) || (_commands.length() == 0))
173            {
174                return;
175            }
176    
177            DBHandling handling = createDBHandling();
178    
179            try
180            {
181                if ((_workDir != null) && (_workDir.length() > 0))
182                {
183                    handling.setWorkDir(_workDir);
184                    System.setProperty("user.dir", _workDir);
185                }
186                for (Iterator it = _fileSets.iterator(); it.hasNext();)
187                {
188                    addIncludes(handling, (FileSet)it.next());
189                }
190    
191                if ((_propertiesFile != null) && (_propertiesFile.length() > 0))
192                {
193                    System.setProperty("OJB.properties", _propertiesFile);
194                }
195    
196                ConnectionRepository connRep = MetadataManager.getInstance().connectionRepository();
197                PBKey                pbKey   = null;
198    
199                if ((_jcdAlias == null) || (_jcdAlias.length() == 0))
200                {
201                    pbKey = PersistenceBrokerFactory.getDefaultKey();
202                }
203                else
204                {
205                    pbKey = connRep.getStandardPBKeyForJcdAlias(_jcdAlias);
206                    if (pbKey == null)
207                    {
208                        throw new BuildException("Undefined jcdAlias "+_jcdAlias);
209                    }
210                }
211                handling.setConnection(connRep.getDescriptor(pbKey));
212    
213                String command;
214    
215                for (StringTokenizer tokenizer = new StringTokenizer(_commands, ","); tokenizer.hasMoreTokens();)
216                {
217                    command = tokenizer.nextToken().toLowerCase().trim();
218                    if (COMMAND_CREATE.equals(command))
219                    {
220                        handling.createDB();
221                    }
222                    else if (COMMAND_INIT.equals(command))
223                    {
224                        handling.initDB();
225                    }
226                    else
227                    {
228                        throw new BuildException("Unknown command "+command);
229                    }
230                }
231            }
232            catch (Exception ex)
233            {
234                throw new BuildException(ex);
235            }
236        }
237    
238        /**
239         * Creates a db handling object.
240         * 
241         * @return The db handling object
242         * @throws BuildException If the handling is invalid
243         */
244        private DBHandling createDBHandling() throws BuildException
245        {
246            if ((_handling == null) || (_handling.length() == 0))
247            {
248                throw new BuildException("No handling specified");
249            }
250            try
251            {
252                String className     = "org.apache.ojb.broker.platforms."+
253                                                       Character.toTitleCase(_handling.charAt(0))+_handling.substring(1)+
254                                                       "DBHandling";
255                Class  handlingClass = ClassHelper.getClass(className);
256    
257                return (DBHandling)handlingClass.newInstance();
258            }
259            catch (Exception ex)
260            {
261                throw new BuildException("Invalid handling '"+_handling+"' specified");
262            }
263        }
264    
265        /**
266         * Adds the includes of the fileset to the handling.
267         * 
268         * @param handling The handling
269         * @param fileSet  The fileset
270         */
271        private void addIncludes(DBHandling handling, FileSet fileSet) throws BuildException
272        {
273            DirectoryScanner scanner  = fileSet.getDirectoryScanner(getProject());
274            String[]         files    = scanner.getIncludedFiles();
275            StringBuffer     includes = new StringBuffer();
276    
277            for (int idx = 0; idx < files.length; idx++)
278            {
279                if (idx > 0)
280                {
281                    includes.append(",");
282                }
283                includes.append(files[idx]);
284            }
285            try
286            {
287                handling.addDBDefinitionFiles(fileSet.getDir(getProject()).getAbsolutePath(), includes.toString());
288            }
289            catch (IOException ex)
290            {
291                throw new BuildException(ex);
292            }
293        }
294    }