View Javadoc

1   /* ===================================================================
2    * Copyright 2002-06 SRI International.
3    * Released under the MOZILLA PUBLIC LICENSE Version 1.1
4    * which can be obtained at http://www.mozilla.org/MPL/MPL-1.1.html
5    * This software is distributed on an "AS IS"
6    * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
7    * See the License for the specific language governing rights and
8    * limitations under the License.
9    * =================================================================== */
10  package com.sri.emo.commandline;
11  
12  import java.io.BufferedInputStream;
13  import java.io.File;
14  import java.io.FileInputStream;
15  import java.io.InputStream;
16  import java.io.InputStreamReader;
17  import java.io.LineNumberReader;
18  import java.util.Vector;
19  
20  import org.apache.log4j.Logger;
21  
22  import com.jcorporate.expresso.core.ExpressoSchema;
23  import com.jcorporate.expresso.core.db.DBConnection;
24  import com.jcorporate.expresso.core.db.DBConnectionPool;
25  import com.jcorporate.expresso.core.db.DBException;
26  import com.jcorporate.expresso.core.dbobj.Schema;
27  import com.jcorporate.expresso.core.dbobj.SchemaFactory;
28  import com.jcorporate.expresso.kernel.ConsoleInstallLog;
29  import com.jcorporate.expresso.services.test.SchemaCreator;
30  import com.jcorporate.expresso.services.test.SchemaDeleter;
31  import com.jcorporate.expresso.services.test.TestSystemInitializer;
32  import com.sri.emo.EmoSchema;
33  
34  /***
35   * Allows import of a file of sql statements to be dropped into a database.
36   * @author Michael Rimov
37   * @todo If this turns out to be useful, add --no-drop arg to skip the
38   * drop/create steps.
39   */
40  public class Import extends AbstractEmoUtility {
41  	
42  	/***
43  	 * Logger.
44  	 */
45  	private static final Logger log = Logger.getLogger(Import.class);
46  
47  	/***
48  	 * 
49  	 * @param args
50  	 * @throws Exception 
51  	 */
52  	public static void main(String[] args) throws Exception {
53  		// TODO Auto-generated method stub
54      	if (!AbstractEmoUtility.checkArgs(args)) {
55      		usage();
56      		System.exit(-1);
57      	}
58      	
59      	//Default import context is 'import'
60      	setupExpresso("import");
61      	
62      	boolean skipPrompt = false;
63      	if (args.length > 1 && args[0].equalsIgnoreCase("--force")) {
64      		skipPrompt = true;    		    		
65      	} 
66      	
67     	
68      	
69      	if (!skipPrompt) {
70      		System.out.println("*********************************************");
71      		System.out.println("Warning, the import will destroy all data");
72      		System.out.println("On the database context labelled: " + TestSystemInitializer.getTestContext());    		
73      		System.out.println("*********************************************");
74      		//The fork that is running in ANT doesn't seem to
75      		//print this line if print() is used even if
76      		//System.out.flush() is called afterwards :(
77      		System.out.println("Are you sure you want to continue? Y/[N]");
78      		char oneChar = (char)System.in.read();
79      		if (!(oneChar == 'Y' || oneChar == 'y')) {
80      			System.out.println("Import aborted");
81      			System.exit(0);
82      		}    		
83      	}
84      	
85      	createFreshSchemas();
86      	
87      	String inputFile = getInputFile(args);
88      	
89      	System.out.println("Importing file " + inputFile);
90      	File f= new File(inputFile);
91      	if (!f.exists()) {
92      		throw new IllegalArgumentException("Could not find file " + inputFile);
93      	}
94      	
95      	InputStream is = new BufferedInputStream(new FileInputStream(f));
96      	
97      	LineNumberReader reader = new LineNumberReader(new InputStreamReader(is));
98      	
99      	DBConnection connection = DBConnectionPool.getInstance(TestSystemInitializer.getTestContext()).getConnection("Database import");
100     	int totalRecords = 0;
101     	int totalErrors = 0;
102     	int currentLine = 0;
103     	try {
104     		String oneStatement = reader.readLine();
105     		while (oneStatement != null) {
106         		currentLine = reader.getLineNumber();
107     			try {
108     				if (log.isDebugEnabled()) {
109     					log.debug("Executing insert " + oneStatement);
110     				}
111     				connection.execute(oneStatement);
112     				totalRecords++;
113     				if (log.isDebugEnabled()) {
114     					log.debug("Total Records Imported = " + totalRecords);
115     				}
116     			} catch (DBException ex) {
117     				log.error("Error executing statement from file " + inputFile + " line " + currentLine, ex);
118     				totalErrors++;
119     			}
120 
121     			oneStatement = reader.readLine();    			
122     		}
123     	} finally {
124     		connection.release();
125     		DBConnectionPool.getInstance(TestSystemInitializer.getTestContext()).disconnectAll();
126     		is.close();
127     	}
128 		
129     	if (totalErrors == 0) {
130     		System.out.println("Successfully imported " + totalRecords + " into database.");
131     	} else {
132     		System.out.println("Import Errors.");
133     		System.out.println("Import failed with " + totalErrors + " errors");
134     		System.out.println(totalRecords + " were successfully imported");    		
135     	}
136     	
137         System.exit(0);    	
138 	}
139 
140 	private static void createFreshSchemas() throws Exception {
141 		SchemaDeleter deleter = new SchemaDeleter();
142 		deleter.setDataContext(TestSystemInitializer.getTestContext());
143 		
144 		SchemaFactory schemaFactory = SchemaFactory.getInstance();
145 		Schema emo = schemaFactory.getSchema(EmoSchema.class.getName());
146 		//TODO: which is necessary -- set db context here or in deleter or both?
147 		//Better safe than sorry.
148 		Schema expresso = schemaFactory.getSchema(ExpressoSchema.class.getName());
149 		emo.setDataContext(TestSystemInitializer.getTestContext());
150 		expresso.setDataContext(TestSystemInitializer.getTestContext());
151 		
152 		
153 		log.info("Dropping any existing exprseso or emo schema on the existing database");
154 		Vector toDelete = new Vector();
155 		toDelete.add(emo);
156 		toDelete.add(expresso);
157 		SchemaDeleter.setSchemas(toDelete);
158 		SchemaDeleter.deleteSchemas(TestSystemInitializer.getTestContext());
159 		
160 		log.info("Schemas dropped.  Creating fresh ones");
161 		
162 		
163 		SchemaCreator.ensureSchemaExists(expresso, new ConsoleInstallLog());
164 		SchemaCreator.ensureSchemaExists(emo, new ConsoleInstallLog());
165 		log.info("Fresh schemas created.");
166 	}
167 
168 	private static String getInputFile(String[] args) {
169 		for (int i =0; i < args.length; i++) {
170 			String commandParam = args[i];
171 			if (! (commandParam.startsWith("-") || commandParam.startsWith("--")) ) {
172 				return commandParam;
173 			}
174 		}
175 		
176 		usage();
177 		throw new IllegalArgumentException("Could nto find file name in command line");
178 	}
179 
180 	private static void usage() {
181 		System.out.println("Usage:  ");
182 		System.out.println("\t [--force] <import filename>");		
183 	}
184 
185 }