001 package net.sourceforge.mp3dings.export;
002
003 /* Mp3dings - manage mp3 meta-information
004 * Copyright (C) 2003 Moritz Ringler
005 * $Id: DatabaseExporter.java 143 2008-05-14 07:18:25Z ringler $
006 *
007 * This program is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU General Public License
009 * as published by the Free Software Foundation; either version 2
010 * of the License, or (at your option) any later version.
011 *
012 * This program is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
015 * GNU General Public License for more details.
016 *
017 * You should have received a copy of the GNU General Public License
018 * along with this program; if not, write to the Free Software
019 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
020 */
021
022 import java.awt.Component;
023 import java.io.IOException;
024 import java.sql.PreparedStatement;
025 import java.sql.SQLException;
026 import java.util.Iterator;
027 import java.util.Properties;
028 import java.util.SortedSet;
029 import java.util.TreeSet;
030 import java.util.logging.Logger;
031 import de.mospace.lang.ClassLoaderProvider;
032 import net.sourceforge.mp3dings.Field;
033 import net.sourceforge.mp3dings.Globals;
034
035 /** Exports data to a JDBC database.
036 * @author Moritz Ringler
037 * @version $Revision: 143 $ ($Date: 2008-05-14 09:18:25 +0200 (Mi, 14 Mai 2008) $)
038 */
039 public class DatabaseExporter extends DatabaseConnection implements Exporter{
040 private static final Logger logger = Logger.getLogger(DatabaseExporter.class.getPackage().getName());
041 private final SortedSet fields = new TreeSet();
042 private final PreparedStatement insert;
043
044 /** Establishes a new database connection that can export data from mp3dings
045 * to the database. A suitable configuration can be created interactively
046 * with the {@link #editConfig editConfig} method.
047
048 * @param config the jdbc configuration
049 * @param clp a classloader provider that manages the dynamic class path
050 * for loading the JDBC driver, may be <code>null</code>
051
052 * @throws ExportException if a required property is missing in
053 * <code>config</code>, or if the JDBC driver cannot be loaded
054 * @throws SQLException if an SQL/JDBC error occurs
055 */
056 public DatabaseExporter(Properties config, ClassLoaderProvider clp) throws
057 ExportException, SQLException {
058
059 super(config, clp);
060
061 /* read the field-to-column mapping */
062 Iterator it = config.keySet().iterator();
063 while(it.hasNext()){
064 String key = it.next().toString();
065 if(key.startsWith(P_FIELD_PREFIX)){
066 Field f = Field.forName(key.substring(P_FIELD_PREFIX.length()));
067 if(f != null){
068 fields.add(f);
069 }
070 }
071 }
072
073 /* prepare the insert statement */
074 StringBuffer sbA = new StringBuffer();
075 sbA.append("INSERT INTO ");
076 sbA.append(config.getProperty(P_TABLE));
077 sbA.append(" (");
078
079 StringBuffer sbB = new StringBuffer();
080 sbB.append(") VALUES(");
081
082 it = fields.iterator();
083 boolean comma = false;
084 while(it.hasNext()){
085 Object field = it.next();
086 String dbcolumn = config.getProperty(P_FIELD_PREFIX + field.toString());
087 if(dbcolumn != null && dbcolumn.length() != 0){
088 if(comma){
089 sbA.append(", ");
090 sbB.append(", ");
091 }
092 sbA.append(dbcolumn);
093 sbB.append('?');
094 comma = true;
095 } else {
096 fields.remove(field);
097 }
098 }
099 sbA.append(sbB);
100 sbA.append(")");
101 insert = getConnection().prepareStatement(sbA.toString());
102 }
103
104 /** Displays a wizard to interactively create or modify a JDBC
105 * configuration that can be used to establish a database export
106 * connection.
107 * @param parent the GUI component to use as a dialog owner
108 * @param config the previous configuration if any, may be <code>null</code>
109 * @param availableFields the fields that are available in the mp3dings table
110 * that will exchange data with the database
111 * @param clp a classloader provider that manages the dynamic class path
112 * for loading the JDBC driver, may be <code>null</code>
113 *
114 * @see net.sourceforge.mp3dings.Mp3dingsTableModel#getFields
115 */
116 public static Properties editConfig(Component parent, Properties config,
117 Field[] availableFields, ClassLoaderProvider clp) throws SQLException{
118 return DatabaseConnection.editConfig(parent, config, availableFields, clp, false);
119 }
120
121 /** Tries to load a previously saved database export configuration.
122 * @return a previously stored database export configuration or
123 * <code>null</code> if no such configuration exists
124 *
125 * @throws IOException if the JDBC configuration cannot be read from
126 * the properties file whose location was stored in the preferences
127 */
128 public static Properties loadConfig() throws IOException{
129 return DatabaseConnection.loadConfig(PREF_EXPORT);
130 }
131
132 /** Inserts the data passed as the second argument into the
133 * database table to which we are connected.
134 * @param data <code>data[i][j]</code> is the value for
135 * <code>keys[j]</code> in the <code>i</code>th record
136 * @return the number of records that were successfully exported
137 * @see #getKeys()
138 */
139 public int export(Object[] keys, Object[][] data)
140 throws ExportException{
141 int rows = -1;
142 try{
143 for(int i=0; i<data.length; i++){
144 insert.clearParameters();
145 for(int j=0; j<data[i].length; j++){
146 Object val = (data[i][j] instanceof de.mospace.lang.FullTextString)
147 ? data[i][j].toString()
148 : data[i][j];
149 insert.setObject(j+1, val);
150 }
151 //javax.swing.JOptionPane.showMessageDialog(null, insert);
152 rows = insert.executeUpdate();
153 }
154 getConnection().commit();
155 } catch (SQLException ex){
156 try{
157 getConnection().rollback();
158 } catch (SQLException ex2){
159 logger.severe("Cannot roll back failed SQL transaction.");
160 logger.severe(ex2.toString());
161 logger.severe("Original SQL error was");
162 logger.severe(ex.toString());
163 }
164 throw new ExportException(ex);
165 }
166 return rows;
167 }
168
169 /** Gets the keys to use when passing data to this exporter.
170 * @return an array of {@link net.sourceforge.mp3dings.Field Field} objects
171 */
172 public Object[] getKeys(){
173 return fields.toArray();
174 }
175
176 /** Returns <code>false</code>. */
177 public boolean getFileFallback(){
178 return false;
179 }
180
181 /** Does nothing.
182 * @param enc ignored
183 */
184 public boolean setEncoding(String enc){
185 return true;
186 }
187
188 /** Returns a localized name for this exporter. */
189 public String getName(){
190 return Globals.getString("EXPORT_DB_EXPORTER_NAME");
191 }
192 }