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