View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    * 
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   * 
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.jetspeed.serializer;
18  
19  import java.io.File;
20  import java.io.FilenameFilter;
21  import java.util.ArrayList;
22  import java.util.HashMap;
23  import java.util.Map;
24  import java.util.StringTokenizer;
25  
26  import org.apache.commons.configuration.PropertiesConfiguration;
27  import org.apache.jetspeed.components.jndi.SpringJNDIStarter;
28  import org.apache.log4j.Level;
29  import org.apache.log4j.Logger;
30  /***
31   * Jetspeed Serializer Application
32   * 
33   * invoke with mandatory 
34   * <p>-E filename or -I filename to denote the export or the import file</p>
35   * <p>-I filename | directory, if a directory will process all XML files of pattern "*seed.xml"</p>
36   * 
37   * invoke with (optional) parameters as
38   * <p>-p propertyFilename : overwrite the default filename defined in System.getProperty JetSpeed.Serializer.Configuration</p> 
39   * <p>-a ApplicationPath : overwrite the default ./ or ApplicationPath property in properties file)</p>
40   * <p>-b bootPath : directory to Spring boot files,   overwrite the default assembly/boot/ or bootPath  property in properties file)</p>  
41   * <p>-c configPath : directory to Spring config files,   overwrite the default assembly/ or configPath property in properties file)</p>
42   * 
43   * <p>-O optionstring : overwrite defrault "ALL,REPLACE"</p>
44   * <p>optionstring: 
45   *      ALL - extract/import all (with exception of PREFERENCES)
46   *      USER - extract/import users
47   *      CAPABILITIES - extract/import capabilities
48   *      PROFILE = extract/import profile settings (for export requires USER) 
49   *      PREFS = extract/import  portlet preferences (ignored if any of the above is set)
50   *      
51   *      NOOVERWRITE = don't overwrite existing file (for export)
52   *      BACKUP = backup before process
53   * </p>
54   * <p>
55   * -dc driverClass, for example com.mysql.jdbc.Driver
56   * </p>
57   * <p>
58   * -ds url, ruls according to the driver used, URL needs to point to the correct
59   * database
60   * </p>
61   * <p>
62   * -du user, user with create/drop etc. rights on the database
63   * </p>
64   * <p>
65   * -dp password
66   * </p>
67   * 
68   * <p>
69   * -l log4j-level, ERROR (default), WARN, INFO 
70   * </p>
71   * 
72   * @author <a href="mailto:hajo@bluesunrise.com">Hajo Birthelmer</a>
73   * @version $Id: $
74   */
75  public class JetspeedSerializerApplication
76  {
77      public static final String JNDI_DS_NAME = "jetspeed";    
78      
79      public static void main(String[] args)
80      {
81          String propertyFileName = null;
82          
83          String fileName = null; // XML filename - mandatory on command line        
84          String applicationPath = null; // configuration.getProperties("applicationPath");
85          String bootConfigFiles = null; // configuration.getProperties("bootConfigFiles");
86          String configFiles = null; // configuration.getProperties("configFiles");
87  
88          String name = null;
89          
90          String options = null;
91          
92          PropertiesConfiguration configuration = null;
93          
94          String defaultIndent = null;
95  
96      	String driverClass = null; // jdbc driver
97      	String url = null; // jdbc url to database
98      	String user = null; // user
99      	String password = null; // password
100 
101         String logLevel = null;
102         
103         boolean doImport = false;
104         boolean doExport = false;
105  
106         if (args == null)
107             throw new IllegalArgumentException("Either import or export have to be defined (-I or -E follwoed by the filename");
108 
109         
110         // Parse all the command-line arguments
111         for (int n = 0; n < args.length; n++)
112         {
113             if (args[n].equals("-p"))
114                 propertyFileName = args[++n];
115             else if (args[n].equals("-a"))
116                 applicationPath = args[++n];
117             else if (args[n].equals("-b"))
118                 bootConfigFiles = args[++n];
119             else if (args[n].equals("-c"))
120                 configFiles = args[++n];
121             else if (args[n].equals("-E"))
122             {
123                 doExport = true;
124                 fileName = args[++n];
125             } 
126             else if (args[n].equals("-I"))
127             {
128                 doImport = true;
129                 fileName = args[++n];
130             } 
131             else if (args[n].equals("-N"))
132             {
133                 name = args[++n];
134             }
135             else if (args[n].equals("-l"))
136                 logLevel = args[++n];
137             else if (args[n].equals("-O"))
138                 options = args[++n];
139             else if (args[n].equals("-dc"))
140                 driverClass = args[++n];
141             else if (args[n].equals("-ds"))
142                 url = args[++n];
143             else if (args[n].equals("-du"))
144             {
145                 if (((n + 1) >= args.length) || args[n + 1].startsWith("-d"))
146                 {
147                     user = "";
148                 } else
149                 {
150                     user = args[++n];
151                 }
152             } 
153             else if (args[n].equals("-dp"))
154             {
155                 if (((n + 1) >= args.length) || args[n + 1].startsWith("-d"))
156                 {
157                     password = "";
158                 } else
159                 {
160                     password = args[++n];
161                 }
162             } 
163             else
164             {
165                 throw new IllegalArgumentException("Unknown argument: "
166                         + args[n]);
167             }
168         }
169         
170         /*** The only required argument is the filename for either export or import*/
171         if ((!doImport) && (!doExport))
172           throw new IllegalArgumentException("Either import or export have to be defined (-I or -E follwoed by the filename");
173 
174         /*** But not both*/
175         if ((doImport) && (doExport))
176             throw new IllegalArgumentException("Only one - either import or export - can be requested");
177 
178         if (name == null) name = fileName;
179         
180         /*** get system property definition */
181         if (propertyFileName == null)
182             propertyFileName = System.getProperty(
183                 "org.apache.jetspeed.xml.importer.configuration",
184                 null);
185  
186         if (propertyFileName != null)
187         {    
188             try
189             {
190                 configuration = new PropertiesConfiguration(propertyFileName);
191             }
192             catch (Exception e)
193             {
194                 e.printStackTrace();
195                 System.exit(1);
196             }
197             if (configuration != null)
198             {
199                 /*** only read what was not defined on the command line */
200             
201                 if (applicationPath == null) 
202                     applicationPath = configuration.getString("applicationPath");
203                 if (bootConfigFiles == null)  
204                     bootConfigFiles = configuration.getString("bootConfigFiles");
205                 if (configFiles == null) 
206                     configFiles = configuration.getString("configFiles");
207                 if (options == null) 
208                     options = configuration.getString("options");
209                 if (defaultIndent == null) 
210                     defaultIndent = configuration.getString("defaultIndent");
211 
212         		if (driverClass == null)
213     				driverClass = configuration.getString("driverClass");
214     			if (url == null)
215     				url = configuration.getString("url");
216     			if (user == null)
217     				user = configuration.getString("user");
218     			if (password == null)
219     				password = configuration.getString("password");
220     			if (logLevel == null)
221     				logLevel = configuration.getString("loglevel");
222     				
223     	
224             }
225         }
226 
227         // if we still miss some settings, use hardoced defaults
228         if (applicationPath == null) 
229             applicationPath = "./";
230         if (bootConfigFiles == null) 
231             bootConfigFiles = "assembly/boot/";
232         if (configFiles == null) 
233             configFiles = "assembly/";
234 		if (logLevel == null) 
235             logLevel = "ERROR";
236       
237 
238         bootConfigFiles = bootConfigFiles + "*.xml";
239         configFiles = configFiles + "*.xml";
240      
241         // ok - we are ready to rumble....
242         
243         /*** create the instruction map */
244         
245         Map settings = null;
246         int processHelper = 1; // default process SEED
247         if (options != null)
248         {
249             settings = new HashMap();
250             settings.put(JetspeedSerializer.KEY_PROCESS_USERS, Boolean.FALSE);
251             settings.put(JetspeedSerializer.KEY_PROCESS_CAPABILITIES, Boolean.FALSE);
252             settings.put(JetspeedSerializer.KEY_PROCESS_PROFILER, Boolean.FALSE);
253             settings.put(JetspeedSerializer.KEY_PROCESS_USER_PREFERENCES, Boolean.FALSE);
254             settings.put(JetspeedSerializer.KEY_OVERWRITE_EXISTING, Boolean.TRUE);
255             settings.put(JetspeedSerializer.KEY_BACKUP_BEFORE_PROCESS, Boolean.FALSE);            
256             String[] optionSet = getTokens(options);
257             
258             processHelper = 0;
259             
260             for (int i = 0; i < optionSet.length; i++)
261             {
262                 String o = optionSet[i];
263                 if (o.equalsIgnoreCase("all"))
264                 {
265                     settings.put(JetspeedSerializer.KEY_PROCESS_USERS, Boolean.TRUE);
266                     settings.put(JetspeedSerializer.KEY_PROCESS_CAPABILITIES, Boolean.TRUE);
267                     settings.put(JetspeedSerializer.KEY_PROCESS_PROFILER, Boolean.TRUE);
268                     settings.put(JetspeedSerializer.KEY_PROCESS_USER_PREFERENCES, Boolean.FALSE);
269                     processHelper = 1;
270                 }
271                 else
272                 if (o.equalsIgnoreCase("user"))
273                 {
274                     settings.put(JetspeedSerializer.KEY_PROCESS_USERS, Boolean.TRUE);
275                     processHelper = 1;
276                 }
277                 else 
278                     if (o.equalsIgnoreCase("PREFS"))
279                     {
280                         settings.put(JetspeedSerializer.KEY_PROCESS_USER_PREFERENCES, Boolean.TRUE);
281                 		processHelper = 2;
282                     }
283                     else 
284                         if (o.equalsIgnoreCase("CAPABILITIES"))
285                         {
286                             settings.put(JetspeedSerializer.KEY_PROCESS_CAPABILITIES, Boolean.TRUE);
287                             processHelper = 1;
288                         }
289                         else 
290                             if (o.equalsIgnoreCase("PROFILE"))
291                             {
292                                 settings.put(JetspeedSerializer.KEY_PROCESS_PROFILER, Boolean.TRUE);
293                                 processHelper = 1;
294                             }
295                             else 
296                                 if (o.equalsIgnoreCase("NOOVERWRITE"))
297                                     settings.put(JetspeedSerializer.KEY_OVERWRITE_EXISTING, Boolean.FALSE);
298                                 else 
299                                     if (o.equalsIgnoreCase("BACKUP"))
300                                         settings.put(JetspeedSerializer.KEY_BACKUP_BEFORE_PROCESS, Boolean.TRUE);
301                 
302             }
303             
304         }
305         JetspeedSerializer serializer = null;
306 
307 		if (driverClass == null)
308 			driverClass = System.getProperty(
309 					"org.apache.jetspeed.database.driverClass",
310 					"com.mysql.jdbc.Driver");
311 		if (url == null)
312 			url = System.getProperty("org.apache.jetspeed.database.url",
313 					"jdbc:mysql://localhost/j2test");
314 		if (user == null)
315 			user = System.getProperty("org.apache.jetspeed.database.user",
316 					"user");
317 		if (password == null)
318 			password = System.getProperty(
319 					"org.apache.jetspeed.database.password", "password");
320 
321 		if (driverClass == null)
322 			throw new IllegalArgumentException(
323 					"Can't proceed without a valid driver");
324 		if (url == null)
325 			throw new IllegalArgumentException(
326 					"Can't proceed without a valid url to the target database");
327 		if (user == null)
328 			throw new IllegalArgumentException(
329 					"Can't proceed without a valid database user");
330 
331         
332         
333         HashMap context = new HashMap();
334  
335 		context.put(SpringJNDIStarter.DATASOURCE_DRIVER, driverClass);
336 		context.put(SpringJNDIStarter.DATASOURCE_URL, url);
337 		context.put(SpringJNDIStarter.DATASOURCE_USERNAME, user);
338 		context.put(SpringJNDIStarter.DATASOURCE_PASSWORD, password);
339         
340 		Logger  logger = Logger.getLogger("org.springframework");
341 		Level level = logger.getLevel();
342 		if (logLevel.equalsIgnoreCase("INFO"))
343 			logger.setLevel(Level.INFO);
344 		else
345 			if (logLevel.equalsIgnoreCase("WARN"))
346 				logger.setLevel(Level.WARN);
347 			else
348 				logger.setLevel(Level.ERROR);
349 				
350 /***
351  * set the application root
352  */
353         System.out.println("APP ROOT is " + applicationPath);
354 		System.setProperty("applicationRoot",applicationPath);
355 		System.setProperty("portal.name","jetspped");
356         SpringJNDIStarter starter = new SpringJNDIStarter(context,applicationPath,getTokens(bootConfigFiles),getTokens(configFiles));
357         
358         System.out.println("starter framework created " + starter);
359         
360         
361         try
362         {
363             starter.setUp();
364         }
365         catch (Exception e)
366         {
367             e.printStackTrace();
368             System.exit(1);
369         }
370         System.out.println("starter framework established " + starter);
371         String[] importList = null;
372 
373         if (doImport)
374         	importList = parseFiles(fileName);
375     	
376         if ((doImport) && (importList != null) && (importList.length > 0))
377         {
378 			for (int i = 0; i < importList.length; i++)
379 			{
380 				try
381 			    {
382 			        System.out.println("processing import  " + importList[i]);
383 			        if (processHelper == 2)
384 			        {
385 			        	serializer = new JetspeedSerializerSecondaryImpl(starter.getComponentManager());
386 			        }
387 			        else
388 			        	serializer = new JetspeedSerializerImpl(starter.getComponentManager());
389 			        serializer.importData(importList[i], settings);
390 			        System.out.println("processing import  " + importList[i] + " done");
391 			        
392 			    } 
393 			    catch (Exception e)
394 			    {
395 			        System.err.println("Failed to process XML import for " + importList[i] + ":" + e);
396 			        e.printStackTrace();
397 			    }
398 			    finally
399 			    {
400 			        if (serializer != null)
401 			            serializer.closeUp();
402 			    }
403 			 }
404         }
405         if (doExport)
406         {
407         	try
408 	        {
409 		        System.out.println("processing export to  " + fileName);
410 		        if (processHelper == 2)
411 		        {
412 		        	serializer = new JetspeedSerializerSecondaryImpl(starter.getComponentManager());
413 		        }
414 		        else
415 		        	serializer = new JetspeedSerializerImpl(starter.getComponentManager());
416 
417 		        serializer.exportData(name, fileName, settings);
418 	        } 
419 	        catch (Exception e)
420 	        {
421 	            System.err.println("Failed to process XML export of " + fileName + ": " + e);
422 	            e.printStackTrace();
423 	        }
424 	        finally
425 	        {
426 	            if (serializer != null)
427 	                serializer.closeUp();
428  	        }
429 
430         }
431         try
432         {
433            starter.tearDown();
434            logger.setLevel(level);;
435         }
436         catch (Exception e1)
437         {
438             System.out.println("starter framework teardown caused exception "  + e1.getLocalizedMessage());
439             e1.printStackTrace();
440             
441         }            
442         System.out.println("DONE performing " + (doExport?"export":"import")+ " with " + fileName);
443     }
444     
445         
446        
447 	/***
448 	 * process provided filename or directory name
449 	 * 
450 	 * @return one or more files to be processed
451 	 */
452 	static private String[] parseFiles(String schemaDirectory)
453 	{
454 		String[] fileList = null;
455 		try
456 		{
457 			File dir = new File(schemaDirectory);
458 			if (!(dir.exists()))
459             {
460 				return fileList;
461             }
462 			if (!(dir.isDirectory()))
463 			{
464 				fileList = new String[1];
465 				fileList[0] = schemaDirectory;
466 				return fileList;
467 			}
468 			// 	Handling a directory
469 			File[] files = dir.listFiles(
470 				    new FilenameFilter() {
471 				        public boolean accept(File dir, String name) 
472 				        			{String n = name.toLowerCase();
473 	   								return n.endsWith("seed.xml");
474 				        }
475 				    });
476 			if (files == null)
477 				return fileList;
478 
479 			fileList = new String[files.length];
480 			for (int i = 0; i < files.length; i++)
481             {
482 				fileList[i] = files[i].getAbsolutePath();
483             }
484 			return fileList;
485 		} 
486         catch (Exception e)
487 		{
488 			e.printStackTrace(); 
489 			throw new IllegalArgumentException(
490 					"Processing the schema-directory " + schemaDirectory
491 							+ " caused exception "
492 							+ e.getLocalizedMessage());
493 		}
494 
495 		
496 	}
497 
498     
499         private static  String[] getTokens(String _line)
500         {
501             if ((_line == null) || (_line.length() == 0))
502                 return null;
503             
504             StringTokenizer st = new StringTokenizer(_line, ",");
505             ArrayList list = new ArrayList();
506 
507             while (st.hasMoreTokens())
508                 list.add(st.nextToken());
509             String[] s = new String[list.size()];
510             for (int i=0; i<list.size(); i++)
511                 s[i] = (String)list.get(i);
512             return s;
513         }
514 
515         
516 }