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.security.Principal;
20  import java.util.ArrayList;
21  import java.util.Collection;
22  import java.util.HashMap;
23  import java.util.Iterator;
24  import java.util.Map;
25  import java.util.Set;
26  import java.util.prefs.Preferences;
27  
28  import javax.security.auth.Subject;
29  
30  import javolution.xml.XMLBinding;
31  
32  import org.apache.jetspeed.capabilities.Capabilities;
33  import org.apache.jetspeed.capabilities.Capability;
34  import org.apache.jetspeed.capabilities.Client;
35  import org.apache.jetspeed.capabilities.MediaType;
36  import org.apache.jetspeed.capabilities.MimeType;
37  import org.apache.jetspeed.components.ComponentManager;
38  import org.apache.jetspeed.profiler.Profiler;
39  import org.apache.jetspeed.profiler.ProfilerException;
40  import org.apache.jetspeed.profiler.rules.PrincipalRule;
41  import org.apache.jetspeed.profiler.rules.ProfilingRule;
42  import org.apache.jetspeed.profiler.rules.RuleCriterion;
43  import org.apache.jetspeed.security.BasePrincipal;
44  import org.apache.jetspeed.security.Group;
45  import org.apache.jetspeed.security.GroupManager;
46  import org.apache.jetspeed.security.PasswordCredential;
47  import org.apache.jetspeed.security.PermissionManager;
48  import org.apache.jetspeed.security.PortalResourcePermission;
49  import org.apache.jetspeed.security.Role;
50  import org.apache.jetspeed.security.RoleManager;
51  import org.apache.jetspeed.security.User;
52  import org.apache.jetspeed.security.UserManager;
53  import org.apache.jetspeed.security.om.InternalPermission;
54  import org.apache.jetspeed.security.om.InternalPrincipal;
55  import org.apache.jetspeed.security.spi.PasswordCredentialProvider;
56  import org.apache.jetspeed.serializer.objects.JSCapabilities;
57  import org.apache.jetspeed.serializer.objects.JSCapability;
58  import org.apache.jetspeed.serializer.objects.JSClient;
59  import org.apache.jetspeed.serializer.objects.JSClientCapabilities;
60  import org.apache.jetspeed.serializer.objects.JSClientMimeTypes;
61  import org.apache.jetspeed.serializer.objects.JSClients;
62  import org.apache.jetspeed.serializer.objects.JSGroup;
63  import org.apache.jetspeed.serializer.objects.JSGroups;
64  import org.apache.jetspeed.serializer.objects.JSMediaType;
65  import org.apache.jetspeed.serializer.objects.JSMediaTypes;
66  import org.apache.jetspeed.serializer.objects.JSMimeType;
67  import org.apache.jetspeed.serializer.objects.JSMimeTypes;
68  import org.apache.jetspeed.serializer.objects.JSNVPElements;
69  import org.apache.jetspeed.serializer.objects.JSPWAttributes;
70  import org.apache.jetspeed.serializer.objects.JSPermission;
71  import org.apache.jetspeed.serializer.objects.JSPermissions;
72  import org.apache.jetspeed.serializer.objects.JSPrincipalRule;
73  import org.apache.jetspeed.serializer.objects.JSPrincipalRules;
74  import org.apache.jetspeed.serializer.objects.JSProfilingRule;
75  import org.apache.jetspeed.serializer.objects.JSProfilingRules;
76  import org.apache.jetspeed.serializer.objects.JSRole;
77  import org.apache.jetspeed.serializer.objects.JSRoles;
78  import org.apache.jetspeed.serializer.objects.JSRuleCriterion;
79  import org.apache.jetspeed.serializer.objects.JSRuleCriterions;
80  import org.apache.jetspeed.serializer.objects.JSSeedData;
81  import org.apache.jetspeed.serializer.objects.JSSnapshot;
82  import org.apache.jetspeed.serializer.objects.JSUser;
83  import org.apache.jetspeed.serializer.objects.JSUserAttributes;
84  import org.apache.jetspeed.serializer.objects.JSUserGroups;
85  import org.apache.jetspeed.serializer.objects.JSUserRoles;
86  import org.apache.jetspeed.serializer.objects.JSUserUsers;
87  import org.apache.jetspeed.serializer.objects.JSUsers;
88  
89  /***
90   * Jetspeed Serializer
91   * <p>
92   * The Serializer is capable of reading and writing the current content of the
93   * Jetspeed environment to and from XML files. The component can be used from a
94   * standalone java application for seeding a new database or from a running
95   * portal as an administrative backup/restore function.
96   * <p>
97   * The XML file needs to indicate whether passwords used in credentials
98   * are plain text or whether they are encoded. The import algoritm can determine -
99   * prior to reading users - which encode/decode scheme was used and if <none> or
100  * <implements PasswordEncodingService> then we store plain passwords (Note that
101  * that alone requires the resulting XML to be encoded!!!!!)
102  * 
103  * @author <a href="mailto:hajo@bluesunrise.com">Hajo Birthelmer</a>
104  * @version $Id: $
105  */
106 public class JetspeedSerializerImpl extends JetspeedSerializerBase implements JetspeedSerializer
107 {
108 
109  
110     private HashMap roleMap = new HashMap();
111 
112     private HashMap groupMap = new HashMap();
113 
114     private HashMap userMap = new HashMap();
115 
116     private HashMap mimeMap = new HashMap();
117     private HashMap mimeMapInt = new HashMap();
118 
119     private HashMap mediaMap = new HashMap();
120 
121     private HashMap capabilityMap = new HashMap();
122     private HashMap capabilityMapInt = new HashMap();
123 
124     private HashMap clientMap = new HashMap();
125 
126     private HashMap permissionMap = new HashMap();
127 
128     private HashMap rulesMap = new HashMap();
129 
130     int refCouter = 0;
131 
132  
133     private static String ENCODING_STRING = "JETSPEED 2.1 - 2006";
134     private static String JETSPEED = "JETSPEED";
135     
136     
137     protected Class getSerializerDataClass()
138     {
139     	return JSSeedData.class;
140     }    
141 
142     protected String getSerializerDataTag()
143     {
144     	return TAG_SNAPSHOT;
145     }    
146     
147     public JetspeedSerializerImpl()
148     {
149     	super();
150     }
151 
152     /***
153      * hand over existing component manager
154      * 
155      * @param cm
156      */
157     public JetspeedSerializerImpl(ComponentManager cm)
158     {
159     	super(cm);
160     }
161 
162     /***
163      * This constructor takes the application root, the search path for the boot
164      * component configuration files and the search path for the application
165      * component configuration files.
166      * <p>
167      * For example: new JetspeedSerializerImpl("./", "assembly/boot/*.xml",
168      * "assembly/*.xml") will establish the current directory as the root,
169      * process all xml files in the assembly/boot directory before processing
170      * all xml files in the assembly directory itself.
171      * 
172      * @param appRoot
173      *            working directory
174      * @param bootConfig
175      *            boot (primary) file or files (wildcards are allowed)
176      * @param appConfig
177      *            application (secondary) file or files (wildcards are allowed)
178      */
179     public JetspeedSerializerImpl(String appRoot, String[] bootConfig,
180             String[] appConfig) throws SerializerException
181     {
182     	super(appRoot,bootConfig,appConfig);
183     }
184 
185      /***
186      * reset instruction flags to default settings (all true)
187      * 
188      */
189     protected void resetSettings()
190     {
191         setSetting(JetspeedSerializer.KEY_PROCESS_USERS, true);
192         setSetting(JetspeedSerializer.KEY_PROCESS_CAPABILITIES, true);
193         setSetting(JetspeedSerializer.KEY_PROCESS_PROFILER, true);
194         setSetting(JetspeedSerializer.KEY_PROCESS_PERMISSIONS, true);
195         setSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING, true);
196         setSetting(JetspeedSerializer.KEY_BACKUP_BEFORE_PROCESS, true);
197     }
198 
199  
200     /***
201      * On import, get the basic SnapShot data
202      * 
203      */
204     protected void getSnapshotData()
205     {
206         logMe("date created : " + getSnapshot().getDateCreated());
207         logMe("software Version : " + getSnapshot().getSavedVersion());
208         logMe("software SUbVersion : " + getSnapshot().getSavedSubversion());
209     }
210 
211   
212     
213     private void recreateCapabilities (Capabilities caps) throws SerializerException
214     {
215     	logMe("recreateCapabilities - processing");
216     	JSCapabilities capabilities = ((JSSeedData)getSnapshot()).getCapabilities();
217     	if ((capabilities != null) && (capabilities.size() > 0))
218     	{
219     		Iterator _it = capabilities.iterator();
220     		while (_it.hasNext())
221     		{
222     			JSCapability _c = (JSCapability)_it.next();
223 // create a new Capability
224     			try
225     			{
226     				Capability capability = caps.createCapability(_c.getName());
227 					/*** THE KEY_OVERWRITE_EXISTING test is not required for capabilites, since they carry no other information than the name
228 					 *  Used here for consistency, though
229 					 */   				
230     				if ((this.getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) || (capability.getCapabilityId() == 0))
231     				{
232     					caps.storeCapability(capability);
233     				}
234     				this.capabilityMap.put(_c.getName(), capability);
235     			}
236     			catch (Exception e)
237     			{
238     				throw new SerializerException(
239     			            SerializerException.CREATE_OBJECT_FAILED
240     			            	.create("org.apache.jetspeed.capabilities.Capabilities",e.getLocalizedMessage()));
241  			}
242     		}
243     	}
244     	else
245     		logMe("NO CAPABILITES?????");
246     	logMe("recreateCapabilities - done");
247     }
248     private void recreateMimeTypes (Capabilities caps) throws SerializerException
249     {
250     	logMe("recreateMimeTypes - processing");
251     	JSMimeTypes mimeTypes = ((JSSeedData)getSnapshot()).getMimeTypes();
252     	if ((mimeTypes != null) && (mimeTypes.size() > 0))
253     	{
254     		Iterator _it = mimeTypes.iterator();
255     		while (_it.hasNext())
256     		{
257     			JSMimeType _c = (JSMimeType)_it.next();
258 // create a new Mime Type
259     			try
260     			{
261     				MimeType mimeType = caps.createMimeType(_c.getName());
262 					/*** THE KEY_OVERWRITE_EXISTING test is not required for mime types, since they carry no other information than the name
263 					 *  Used here for consistency, though
264 					 */   				
265     				if ((this.getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) || (mimeType.getMimetypeId() == 0))
266     				{
267     					caps.storeMimeType(mimeType);
268     				}
269     				this.mimeMap.put(_c.getName(), mimeType);
270 
271     			}
272     			catch (Exception e)
273     			{
274     				throw new SerializerException(
275     			            SerializerException.CREATE_OBJECT_FAILED
276     			                    .create("org.apache.jetspeed.capabilities.MimeType",e.getLocalizedMessage()));
277     			}
278     		}
279     	}
280     	else
281     		logMe("NO MIME TYPES?????");
282     	logMe("recreateMimeTypes - done");
283     }
284 
285     private void recreateMediaTypes (Capabilities caps) throws SerializerException
286     {
287     	 String _line;
288     	 
289     	logMe("recreateMediaTypes - processing");
290     	JSMediaTypes mediaTypes = ((JSSeedData)getSnapshot()).getMediaTypes();
291     	if ((mediaTypes != null) && (mediaTypes.size() > 0))
292     	{
293     		Iterator _it = mediaTypes.iterator();
294     		while (_it.hasNext())
295     		{
296     			JSMediaType _c = (JSMediaType)_it.next();
297 // create a new Media
298     			try
299     			{
300     				MediaType mediaType = caps.createMediaType(_c.getName());
301 					/*** THE KEY_OVERWRITE_EXISTING test IS required for media types, since they carry no other information than the name
302 					 *  Used here for consistency, though
303 					 */   				
304     				if ((this.getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) || (mediaType.getMediatypeId() == 0))
305     				{
306 //    					 set object fields               
307     			        mediaType.setCharacterSet(_c.getCharacterSet());
308     			        mediaType.setTitle(_c.getTitle());
309     			        mediaType.setDescription(_c.getDescription());
310     			       
311     			        try
312     			        {
313     			        	_line = _c.getMimeTypesString().toString();
314     			        	ArrayList list = this.getTokens(_line);
315     			        	if ((list != null) && (list.size()>0))
316     			        	{
317     			        		Iterator _it1 = list.iterator();
318 	        			        int added = 0;
319 	        			        while (_it1.hasNext())
320 	        			        {
321 	        			        	MimeType _mt = caps.createMimeType((String)_it1.next());
322 	        			        	if (_mt != null)
323 	        			        		mediaType.addMimetype(_mt);
324 	        			        	added++;
325 	        			        }
326     			        	}
327     			        }
328     			        catch (Exception e1)
329     			        {
330     			        	e1.printStackTrace();
331     			        }
332     			        try
333     			        {
334     			        	_line  = _c.getCapabilitiesString().toString();
335     			        	ArrayList list = this.getTokens(_line);
336     			        	if ((list != null) && (list.size()>0))
337     			        	{
338 	    			        	Iterator _it1 = list.iterator();
339 	    			        	if ((list != null) && (list.size()>0))
340 	    			        	{
341 		        			        int added = 0;
342 		        			        while (_it1.hasNext())
343 		        			        {
344 		        			        	Capability _ct = caps.createCapability((String)_it1.next());
345 		        			        	if (_ct != null)
346 		        			        		mediaType.addCapability(_ct);
347 		        			        	added++;
348 		        			        }
349 	    			        	}
350     			        	}
351     			        }
352     			        catch (Exception e1)
353     			        {
354     			        	e1.printStackTrace();
355     			        }
356     					caps.storeMediaType(mediaType);
357     				}
358     				this.mediaMap.put(_c.getName(), mediaType);
359     			}
360     			catch (Exception e)
361     			{
362     				throw new SerializerException(
363     			            SerializerException.CREATE_OBJECT_FAILED
364     			                    .create("org.apache.jetspeed.capabilities.MediaType",e.getLocalizedMessage()));
365     			}
366     		}
367     	}
368     	else
369     		logMe("NO MEDIA TYPES?????");
370     	logMe("recreateMediaTypes - done");
371     }
372  
373     
374     private void recreateClients (Capabilities caps) throws SerializerException
375     {
376     	 String _line;
377     	 
378     	logMe("recreateClients - processing");
379     	JSClients clients = ((JSSeedData)getSnapshot()).getClients();
380     	if ((clients != null) && (clients.size() > 0))
381     	{
382     		Iterator _it = clients.iterator();
383     		while (_it.hasNext())
384     		{
385     			JSClient _c = (JSClient)_it.next();
386 // create a new Media
387     			try
388     			{
389     				Client client = caps.createClient(_c.getName());
390 					/*** THE KEY_OVERWRITE_EXISTING test IS required for media types, since they carry no other information than the name
391 					 *  Used here for consistency, though
392 					 */   				
393     				if ((this.getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) || (client.getClientId() == 0))
394     				{
395 //    					 set object fields               
396     			        client.setUserAgentPattern(_c.getUserAgentPattern());
397     			        client.setManufacturer(_c.getManufacturer());
398     			        client.setModel(_c.getModel());
399     			        client.setEvalOrder(_c.getEvalOrder());
400     			        String myPrefMimeType = _c.getPreferredMimeTypeID();
401     			        client.setVersion(_c.getVersion());
402     			        try
403     			        {
404     			        	_line = _c.getMimeTypesString().toString();
405     			        	ArrayList list = this.getTokens(_line);
406     			        	if ((list != null) && (list.size()>0))
407     			        	{
408     			        		Iterator _it1 = list.iterator();
409 	        			        int added = 0;
410 	        			        while (_it1.hasNext())
411 	        			        {
412 	        			        	MimeType _mt = caps.createMimeType((String)_it1.next());
413 	        			        	if (_mt != null)
414 	        			        	{
415 	        			        		client.getMimetypes().add(_mt);
416 	        			        		if (_mt.getMimetypeId() == 0)
417 	        			        		{
418 	        			        			caps.storeMimeType(_mt);
419 	        			        		}
420 	        			        		if (myPrefMimeType.equalsIgnoreCase(_mt.getName()))
421 	        			        				client.setPreferredMimeTypeId(_mt.getMimetypeId());	
422 	        			        			
423 	        			        	}
424 	        			        	added++;
425 	        			        }
426     			        	}
427     			        }
428     			        catch (Exception e1)
429     			        {
430     			        	e1.printStackTrace();
431     			        }
432     			        try
433     			        {
434     			        	_line  = _c.getCapabilitiesString().toString();
435     			        	ArrayList list = this.getTokens(_line);
436     			        	if ((list != null) && (list.size()>0))
437     			        	{
438 	    			        	Iterator _it1 = list.iterator();
439 	    			        	if ((list != null) && (list.size()>0))
440 	    			        	{
441 		        			        int added = 0;
442 		        			        while (_it1.hasNext())
443 		        			        {
444 		        			        	Capability _ct = caps.createCapability((String)_it1.next());
445 		        			        	if (_ct != null)
446 		        			        		client.getCapabilities().add(_ct);
447 		        			        	added++;
448 		        			        }
449 	    			        	}
450     			        	}
451     			        }
452     			        catch (Exception e1)
453     			        {
454     			        	e1.printStackTrace();
455     			        }
456     					caps.storeClient(client);
457     				}
458     				this.clientMap.put(_c.getName(), client);
459     			}
460     			catch (Exception e)
461     			{
462     				throw new SerializerException(
463     			            SerializerException.CREATE_OBJECT_FAILED
464     			                    .create("org.apache.jetspeed.capabilities.Client",e.getLocalizedMessage()));
465     			}
466     		}
467     	}
468     	else
469     		logMe("NO MEDIA TYPES?????");
470     	logMe("recreateClients - done");
471     }
472 
473     
474     private void importCapabilitiesInfrastructure() throws SerializerException
475     {
476     	logMe("importCapabilitiesInfrastructure - processing");
477         Capabilities caps = (Capabilities) getCM()
478         .getComponent("org.apache.jetspeed.capabilities.Capabilities");
479         if (caps == null)
480         	throw new SerializerException(
481             SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
482                     .create("org.apache.jetspeed.capabilities.Capabilities"));
483         
484         recreateCapabilities(caps);
485         recreateMimeTypes(caps);
486         recreateMediaTypes(caps);
487         recreateClients(caps);
488         
489         
490     	logMe("importCapabilitiesInfrastructure - processing done");
491     }
492 
493 
494     /***
495      * import the groups, roles and finally the users to the current environment
496      * 
497      * @throws SerializerException
498      */
499     private void recreateRolesGroupsUsers() throws SerializerException
500     {
501     	logMe("recreateRolesGroupsUsers");
502         GroupManager groupManager = (GroupManager) getCM()
503                 .getComponent("org.apache.jetspeed.security.GroupManager");
504         if (groupManager == null)
505             throw new SerializerException(
506                     SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
507                             .create("org.apache.jetspeed.security.GroupManager"));
508         RoleManager roleManager = (RoleManager) getCM()
509         .getComponent("org.apache.jetspeed.security.RoleManager");
510         if (roleManager == null)
511             throw new SerializerException(
512                     SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
513                             .create("org.apache.jetspeed.security.RoleManager"));
514         UserManager userManager = (UserManager) getCM()
515         .getComponent("org.apache.jetspeed.security.UserManager");
516         if (userManager == null)
517         	throw new SerializerException(
518             SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
519                     .create("org.apache.jetspeed.security.UserManager"));
520 
521         
522         
523         
524         JSGroups groups = null;
525         JSRoles roles = null;
526         Iterator _it = null;
527         groups = ((JSSeedData)getSnapshot()).getGroups();
528         if (groups != null)
529         {
530          _it = groups.iterator();
531         while (_it.hasNext())
532         {
533         	String name = ((JSGroup)_it.next()).getName();
534 
535 	        try
536 	        {
537 	        	if (!(groupManager.groupExists(name)))
538 	        		groupManager.addGroup(name);
539 	        	Group group = groupManager.getGroup(name);
540 	        	this.groupMap.put(name, group.getPrincipal());
541 	        } catch (Exception e)
542 	        {
543 	            throw new SerializerException(
544 	                    SerializerException.CREATE_OBJECT_FAILED
545 	                            .create(new String[]
546 	                            { "Group", e.getMessage()}));
547 	        }
548         }
549         }
550     	logMe("recreateGroups - done");
551     	logMe("processing roles");
552 
553         roles = ((JSSeedData)getSnapshot()).getRoles();
554         if (roles!= null)
555         {      
556         _it = roles.iterator();
557         
558         while (_it.hasNext())
559         {
560         	String name = ((JSRole)_it.next()).getName();
561 
562 	        try
563 	        {
564 	        	if (!(roleManager.roleExists(name)))
565 	        		roleManager.addRole(name);
566 	        	Role role = roleManager.getRole(name);
567 	        	this.roleMap.put(name, role.getPrincipal());
568 	        } catch (Exception e)
569 	        {
570 	            throw new SerializerException(
571 	                    SerializerException.CREATE_OBJECT_FAILED
572 	                            .create(new String[]
573 	                            { "Role", e.getMessage()}));
574 	        }
575         }
576         }
577         logMe("recreateRoles - done");
578     	logMe("processing users");
579 
580     	/*** determine whether passwords can be reconstructed or not */
581     	int passwordEncoding = compareCurrentSecurityProvider((JSSeedData)getSnapshot());
582         JSUsers users = null;
583         users = ((JSSeedData)getSnapshot()).getUsers();
584         if(users!=null)
585         {_it = users.iterator();
586         while (_it.hasNext())
587         {
588         	
589         	JSUser jsuser = (JSUser)_it.next();
590 
591 	        try
592 	        {
593 	        	User user = null;
594 	        	if (userManager.userExists(jsuser.getName()))
595 	        	{
596 	        		user = userManager.getUser(jsuser.getName());
597 	        	}
598 				if ((this.getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) || (user == null))
599 				{
600 					if (user == null) //create new one
601 					{
602     					String password = recreatePassword(jsuser.getPassword());
603     			    	logMe("add User "+ jsuser.getName() + " with password " + password);
604    			    		userManager.importUser(jsuser.getName(), password,(passwordEncoding == PASSTHRU_REQUIRED));
605     			    	logMe("add User done ");
606 						user = userManager.getUser(jsuser.getName());
607 					}
608 					try
609 					{
610 						userManager.setPasswordEnabled(jsuser.getName(), jsuser.getPwEnabled());						
611 						userManager.setPasswordUpdateRequired(jsuser.getName(), jsuser.getPwRequiredUpdate());
612 						java.sql.Date d = jsuser.getPwExpirationDate();
613 						if (d != null)
614 							userManager.setPasswordExpiration(jsuser.getName(), d);						
615 					}
616 					catch (Exception e)
617 					{
618 						// most likely caused by protected users (like "guest")
619 						logMe("setting userinfo for "+ jsuser.getName() + " failed because of " + e.getLocalizedMessage());
620 					}
621 					
622 				//credentials
623 			        Subject subject = user.getSubject();
624 
625 					ArrayList listTemp = jsuser.getPrivateCredentials();
626 					if ((listTemp != null) && (listTemp.size()>0))
627 					{
628 						Iterator _itTemp = listTemp.iterator();
629 						while (_itTemp.hasNext())
630 						{
631 							subject.getPrivateCredentials().add(_itTemp.next());
632 						}
633 					}
634 					listTemp = jsuser.getPublicCredentials();
635 					if ((listTemp != null) && (listTemp.size()>0))
636 					{
637 						Iterator _itTemp = listTemp.iterator();
638 						while (_itTemp.hasNext())
639 						{
640 							subject.getPublicCredentials().add(_itTemp.next());
641 						}
642 					}
643 					JSUserGroups jsUserGroups = jsuser.getGroupString();
644 					if (jsUserGroups != null)
645 						listTemp = this.getTokens(jsUserGroups.toString());
646 					else
647 						listTemp = null;
648 					if ((listTemp != null) && (listTemp.size()>0))
649 					{
650 						Iterator _itTemp = listTemp.iterator();
651 						while (_itTemp.hasNext())
652 						{
653 							groupManager.addUserToGroup(jsuser.getName(), (String)_itTemp.next());
654 						}
655 					}
656 					JSUserRoles jsUserRoles = jsuser.getRoleString();
657 					if (jsUserRoles != null)
658 						listTemp = this.getTokens(jsUserRoles.toString());
659 					else
660 						listTemp = null;
661 					if ((listTemp != null) && (listTemp.size()>0))
662 					{
663 						Iterator _itTemp = listTemp.iterator();
664 						while (_itTemp.hasNext())
665 						{
666 							roleManager.addRoleToUser(jsuser.getName(), (String)_itTemp.next());
667 						}
668 					}
669     				JSUserAttributes attributes = jsuser.getUserInfo();
670 					if (attributes != null)
671 					{
672 		                Preferences userAttributes = user.getUserAttributes();
673 						HashMap map = attributes.getMyMap();
674 						if (map != null)
675 						{
676 							Iterator _itTemp = map.keySet().iterator();
677 							while (_itTemp.hasNext())
678 							{
679 						         String userAttrName = (String)_itTemp.next();
680 //						         if ( userAttributes.get(userAttrName, "").equals("") 
681 						         String userAttrValue = (String)map.get(userAttrName);
682 						         userAttributes.put(userAttrName, userAttrValue);
683 				            }
684 						}
685 						
686 					}
687     				
688 					JSNVPElements jsNVP = jsuser.getPreferences();
689 					if ((jsNVP != null) && (jsNVP.getMyMap() != null))
690 					{
691     					Preferences preferences = user.getPreferences();	
692 						Iterator _itTemp = jsNVP.getMyMap().keySet().iterator();
693 						while (_itTemp.hasNext())
694 						{
695 							String prefKey = (String)_itTemp.next();
696 							String prefValue = (String)(jsNVP.getMyMap().get(prefKey));
697 							preferences.put(prefKey,prefValue);
698 						}
699 					}
700 		        	
701 		        	this.userMap.put(jsuser.getName(), getUserPrincipal(user));
702 
703 				}    					
704 	        } catch (Exception e)
705 	        {
706 	            e.printStackTrace();
707                 throw new SerializerException(
708 	                    SerializerException.CREATE_OBJECT_FAILED
709 	                            .create(new String[]
710 	                            { "User", e.getMessage()}));
711 	        }
712         }
713         }
714     	logMe("recreateUsers - done");
715     	return;
716     }
717     
718     /***
719      * called only after users have been established
720      * @throws SerializerException
721      */
722     private void recreateUserPrincipalRules() throws SerializerException
723     {
724     	logMe("recreateUserPrincipalRules - started");
725     	
726         Profiler pm = (Profiler) getCM()
727         .getComponent("org.apache.jetspeed.profiler.Profiler");
728         if (pm == null)
729 
730         	throw new SerializerException(
731             SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
732                     .create("org.apache.jetspeed.profiler.Profiler"));
733         UserManager userManager = (UserManager) getCM()
734         .getComponent("org.apache.jetspeed.security.UserManager");
735         if (userManager == null)
736         	throw new SerializerException(
737             SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
738                     .create("org.apache.jetspeed.security.UserManager"));
739 
740         // get Rules for each user
741 
742         Iterator _itUsers = ((JSSeedData)getSnapshot()).getUsers().iterator();
743         while (_itUsers.hasNext())
744         {
745             JSUser _user = (JSUser) _itUsers.next();
746             JSPrincipalRules jsRules = _user.getRules();
747             try
748             {
749 	            User user = userManager.getUser(_user.getName());
750 	            Principal principal = getUserPrincipal(user);
751 	            if (jsRules != null)
752 	            {
753 	            	Iterator _itRoles = jsRules.iterator();
754 	                while (_itRoles.hasNext())
755 	                {
756 	                	JSPrincipalRule pr = (JSPrincipalRule) _itRoles.next();
757 	                	ProfilingRule pRule = pm.getRule(pr.getRule());
758 	                	
759 	                	try
760 	                	{
761 	                		PrincipalRule p1 = pm.createPrincipalRule();
762 	                		p1.setLocatorName(pr.getLocator());
763 	                		p1.setProfilingRule(pRule);
764 	                		p1.setPrincipalName(principal.getName());
765 	                		pm.storePrincipalRule(p1);
766 	                	}
767 	                	catch (Exception eRole)
768 	                	{
769 	                		eRole.printStackTrace();
770 	                	}
771 	                }
772 	            }
773             }
774         	catch (Exception eUser)
775         	{
776         		eUser.printStackTrace();
777         	}
778         }
779     	logMe("recreateUserPrincipalRules - done");
780 
781     }
782     /***
783      * recreates all permissions from the current snapshot
784      * 
785      * @throws SerializerException
786      */
787     private void recreatePermissions() throws SerializerException
788     {
789     	logMe("recreatePermissions - started");
790         PermissionManager pm = (PermissionManager) getCM()
791                 .getComponent("org.apache.jetspeed.security.PermissionManager");
792         if (pm == null)
793             throw new SerializerException(
794                     SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
795                             .create("org.apache.jetspeed.security.PermissionManager"));
796 
797         Iterator list = null;
798         JSPermissions permissions = ((JSSeedData)getSnapshot()).getPermissions();
799  
800         if (permissions != null)
801         {
802            list =  permissions.iterator();
803             while (list.hasNext())
804             {
805                 JSPermission _js = (JSPermission)list.next();
806                 PortalResourcePermission perm = _js.getPermissionForType();
807                 if ((perm != null) && (perm instanceof PortalResourcePermission))
808                 {
809                 	try
810                     {
811                         pm.addPermission(perm);
812                         ArrayList listTemp = null;
813     					JSUserGroups jsUserGroups = _js.getGroupString();
814     					if (jsUserGroups != null)
815     						listTemp = this.getTokens(jsUserGroups.toString());
816     					else
817     						listTemp = null;
818     					if ((listTemp != null) && (listTemp.size()>0))
819     					{
820     						Iterator _itTemp = listTemp.iterator();
821     						while (_itTemp.hasNext())
822     						{
823     							Principal p = (Principal)this.groupMap.get((String)_itTemp.next());
824     							if (p != null)
825     								pm.grantPermission(p, perm);
826     						}
827     					}
828     					JSUserRoles jsUserRoles = _js.getRoleString();
829     					if (jsUserRoles != null)
830     						listTemp = this.getTokens(jsUserRoles.toString());
831     					else
832     						listTemp = null;
833     					if ((listTemp != null) && (listTemp.size()>0))
834     					{
835     						Iterator _itTemp = listTemp.iterator();
836     						while (_itTemp.hasNext())
837     						{
838        							Principal p = (Principal)this.roleMap.get((String)_itTemp.next());
839     							if (p != null)
840     								pm.grantPermission(p, perm);
841     						}
842     					}
843     					JSUserUsers jsUserUsers = _js.getUserString();
844     					if (jsUserUsers != null)
845     						listTemp = this.getTokens(jsUserUsers.toString());
846     					else
847     						listTemp = null;
848     					if ((listTemp != null) && (listTemp.size()>0))
849     					{
850     						Iterator _itTemp = listTemp.iterator();
851     						while (_itTemp.hasNext())
852     						{
853        							Principal p = (Principal)this.userMap.get((String)_itTemp.next());
854     							if (p != null)
855     								pm.grantPermission(p, perm);
856     						}
857     					}
858     
859     	            } 
860     	           	catch (Exception e)
861     	            {
862     	                throw new SerializerException(
863     	                        SerializerException.CREATE_SERIALIZED_OBJECT_FAILED
864     	                                .create(new String[]
865     	                                { "Permissions", e.getMessage()}));
866     	            }
867                 }
868             }
869         }
870     	logMe("recreatePermissions - done");
871     }
872 
873     private Principal getUserPrincipal(User user)
874     {
875         Subject subject = user.getSubject();
876         // get the user principal
877         Set principals = subject.getPrincipals();
878         Iterator list = principals.iterator();
879         while (list.hasNext())
880         {
881             BasePrincipal principal = (BasePrincipal) list.next();
882             String path = principal.getFullPath();
883             if (path.startsWith("/user/"))
884             return principal;
885         }
886         return null;
887 
888     }
889     
890     private void importProfiler()
891     {
892         System.out.println("importProfiler - processing");
893         try
894         {
895         	recreateProfilingRules();
896         }
897         catch (Exception e)
898         {
899         	e.printStackTrace();
900         }  
901     }
902 
903     private void importUserGroupRoles()
904     {
905         System.out.println("importUserGroupRoles - processing");
906         try
907         {
908             recreateRolesGroupsUsers();
909         }
910         catch (Exception e)
911         {
912             e.printStackTrace();
913         }  
914     }
915 
916     private void importUserPrincipals()
917     {
918         System.out.println("importUserPrincipals - processing");
919         try
920         {
921             recreateUserPrincipalRules();
922         }
923         catch (Exception e)
924         {
925             e.printStackTrace();
926         }  
927     }
928     
929 
930     /***
931      * The workhorse for importing data
932      * 
933      * @param binding
934      *            established XML binding
935      * @return
936      * @throws SerializerException
937      */
938     protected void processImport() throws SerializerException
939     {
940         this.logMe("*********reinstalling data*********");
941         
942         // TODO: HJB Make sure to clean lookup tables before next run
943 
944         if (this.getSetting(JetspeedSerializer.KEY_PROCESS_CAPABILITIES))
945         {
946             logMe("creating clients, mediatypes and mimetypes");
947             importCapabilitiesInfrastructure();
948         }        
949         /***
950          * the order is important, since profiling rules are referenced by the user 
951          * 
952          */        
953         if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PROFILER))
954         {
955             logMe("collecting permissions, profiling rules and users/proups etc. etc.");
956             importProfiler();
957         } 
958         if (this.getSetting(JetspeedSerializer.KEY_PROCESS_USERS))
959         {
960             logMe("creating users/roles/groups");
961             this.importUserGroupRoles();
962         }
963         if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PROFILER) || this.getSetting(JetspeedSerializer.KEY_PROCESS_USERS))
964         {
965             logMe("collecting user principals");
966             this.importUserPrincipals();
967         } 
968         
969         if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PERMISSIONS))        
970         {
971             logMe("permissions, rules etc. skipped ");
972             recreatePermissions();            
973         }        
974     }
975 
976     /***
977      * The workhorse for exporting data
978      * 
979      * @param binding
980      *            established XML binding
981      * @return
982      * @throws SerializerException
983      */
984     protected void processExport(String name, XMLBinding binding)
985             throws SerializerException
986     {
987         this.logMe("*********collecting data*********");
988         /*** first create the snapshot file */
989 
990        setSnapshot(new JSSeedData(name));
991 
992         setSnapshotData();
993 
994         if (this.getSetting(JetspeedSerializer.KEY_PROCESS_CAPABILITIES))
995         {
996             logMe("collecting clients, mediatypes and mimetypes");
997             exportCapabilitiesInfrastructure();
998         } else
999             logMe("capabilities skipped");
1000 
1001         if (this.getSetting(JetspeedSerializer.KEY_PROCESS_USERS))
1002         {
1003             logMe("collecting users");
1004             exportUsers();
1005         } else
1006             logMe("users skipped");
1007 
1008         if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PROFILER))
1009         {
1010             logMe("collecting profiling rules");
1011             this.getProfilingRules();
1012         } else
1013             logMe(" profiling rules skipped");
1014 
1015         if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PERMISSIONS))
1016         {
1017             logMe("collecting permissions");
1018             this.getPermissions();
1019         } else
1020             logMe(" permissions skipped");
1021         
1022     }
1023 
1024     /***
1025      * Setup the binding for the different classes, mapping each extracted class
1026      * to a unique tag name in the XML
1027      * 
1028      * @param binding
1029      */
1030     protected void setupAliases(XMLBinding binding)
1031     {
1032         binding.setAlias(JSRole.class, "Role");
1033         binding.setAlias(JSRoles.class, "Roles");
1034         binding.setAlias(JSGroup.class, "Group");
1035         binding.setAlias(JSGroups.class, "Groups");
1036         binding.setAlias(JSUser.class, "User");
1037         binding.setAlias(JSUsers.class, "Users");
1038         binding.setAlias(JSNVPElements.class, "preferences");
1039         binding.setAlias(JSUserAttributes.class, "userinfo");
1040         binding.setAlias(JSSnapshot.class, "snapshot");
1041         binding.setAlias(JSUserRoles.class, "roles");
1042         binding.setAlias(JSUserGroups.class, "groups");
1043         binding.setAlias(JSClient.class, "Client");
1044         binding.setAlias(JSClients.class, "Clients");
1045         binding.setAlias(JSClientCapabilities.class, "capabilities");
1046         binding.setAlias(JSClientMimeTypes.class, "mimeTypes");
1047         binding.setAlias(JSMimeTypes.class, "MimeTypes");
1048         binding.setAlias(JSMimeType.class, "MimeType");
1049         binding.setAlias(JSCapabilities.class, "Capabilities");
1050         binding.setAlias(JSCapability.class, "Capability");
1051         binding.setAlias(JSMediaTypes.class, "MediaTypes");
1052         binding.setAlias(JSMediaType.class, "MediaType");
1053         binding.setAlias(JSUserUsers.class, "users");
1054 
1055         binding.setAlias(JSPermissions.class, "Permissions");
1056         binding.setAlias(JSPermission.class, "Permission");
1057         binding.setAlias(JSProfilingRules.class, "ProfilingRules");
1058         binding.setAlias(JSProfilingRule.class, "ProfilingRule");
1059         binding.setAlias(JSRuleCriterions.class, "Criteria");
1060         binding.setAlias(JSRuleCriterion.class, "Criterion");
1061 
1062         binding.setAlias(JSPrincipalRule.class, "Rule");
1063         binding.setAlias(JSPrincipalRules.class, "Rules");
1064 
1065         binding.setAlias(String.class, "String");
1066         binding.setAlias(Integer.class, "int");
1067         
1068         binding.setAlias(JSPWAttributes.class,"credentials");
1069 
1070         binding.setClassAttribute(null);
1071 
1072     }
1073 
1074     /***
1075      * simple lookup for principal object from a map
1076      * @param map
1077      * @param _fullPath
1078      * @return
1079      */
1080 
1081     private Object getObjectBehindPrinicpal(Map map, BasePrincipal _principal)
1082     {
1083         return getObjectBehindPath(map, _principal.getFullPath());
1084     }
1085 
1086 
1087 
1088 	/***
1089 	 * create a serializable wrapper for role 
1090 	 * 
1091 	 * @param role
1092 	 * @return
1093 	 */
1094     private JSRole createJSRole(Role role)
1095     {
1096         JSRole _role = new JSRole();
1097         _role.setName(role.getPrincipal().getName());
1098         return _role;
1099     }
1100 
1101 	/***
1102 	 * export roles 
1103 	 * 
1104 	 * @return
1105 	 */
1106     private void exportRoles() throws SerializerException
1107     {
1108         RoleManager roleManager = (RoleManager) getCM()
1109                 .getComponent("org.apache.jetspeed.security.RoleManager");
1110         if (roleManager == null)
1111             throw new SerializerException(
1112                     SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
1113                             .create("org.apache.jetspeed.security.RoleManager"));
1114 
1115         Iterator list = null;
1116         try
1117         {
1118             list = roleManager.getRoles("");
1119         } catch (Exception e)
1120         {
1121             throw new SerializerException(
1122                     SerializerException.GET_EXISTING_OBJECTS
1123                             .create(new String[]
1124                             { "Role", e.getMessage()}));
1125         }
1126         while (list.hasNext())
1127         {
1128             try
1129             {
1130                 Role role = (Role) list.next();
1131                 JSRole _tempRole = (JSRole) getObjectBehindPrinicpal(roleMap,
1132                         (BasePrincipal) (role.getPrincipal()));
1133                 if (_tempRole == null)
1134                 {
1135                     _tempRole = createJSRole(role);
1136                     roleMap.put(_tempRole.getName(), _tempRole);
1137                     ((JSSeedData)getSnapshot()).getRoles().add(_tempRole);
1138                 }
1139 
1140             } catch (Exception e)
1141             {
1142                 throw new SerializerException(
1143                         SerializerException.CREATE_SERIALIZED_OBJECT_FAILED
1144                                 .create(new String[]
1145                                 { "Role", e.getMessage()}));
1146             }
1147         }
1148         return;
1149     }
1150 
1151     /*** Groups -------------------------- */
1152     /***
1153      * create a wrapper JSGroup object
1154      */
1155     private JSGroup createJSGroup(Group group)
1156     {
1157         JSGroup _group = new JSGroup();
1158         _group.setName(group.getPrincipal().getName());
1159         return _group;
1160     }
1161 
1162     /***
1163      * extract the groups from the current environment
1164      * 
1165      * @throws SerializerException
1166      */
1167     private void exportGroups() throws SerializerException
1168     {
1169         GroupManager groupManager = (GroupManager) getCM()
1170                 .getComponent("org.apache.jetspeed.security.GroupManager");
1171         if (groupManager == null)
1172             throw new SerializerException(
1173                     SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
1174                             .create("org.apache.jetspeed.security.GroupManager"));
1175         Iterator list = null;
1176         try
1177         {
1178             list = groupManager.getGroups("");
1179         } catch (Exception e)
1180         {
1181             throw new SerializerException(
1182                     SerializerException.GET_EXISTING_OBJECTS
1183                             .create(new String[]
1184                             { "Group", e.getMessage()}));
1185         }
1186         while (list.hasNext())
1187         {
1188 
1189             try
1190             {
1191                 Group group = (Group) list.next();
1192                 JSGroup _tempGroup = (JSGroup) getObjectBehindPrinicpal(
1193                         groupMap, (BasePrincipal) (group.getPrincipal()));
1194                 if (_tempGroup == null)
1195                 {
1196                     _tempGroup = createJSGroup(group);
1197                     groupMap.put(_tempGroup.getName(), _tempGroup);
1198                     ((JSSeedData)getSnapshot()).getGroups().add(_tempGroup);
1199                 }
1200 
1201             } catch (Exception e)
1202             {
1203                 throw new SerializerException(
1204                         SerializerException.CREATE_SERIALIZED_OBJECT_FAILED
1205                                 .create(new String[]
1206                                 { "Group", e.getMessage()}));
1207             }
1208         }
1209         return;
1210     }
1211 
1212     /***
1213      * Add the credentials to the JSUser object.
1214      * <p>
1215      * If the credential provided is a PasswordCredential, userid and password
1216      * are extracted and set explcitely
1217      * 
1218      * @param isPublic
1219      *            public or private credential
1220      * @param newUser
1221      *            the JS user object reference
1222      * @param credential
1223      *            the credential object
1224      */
1225 
1226     private void addJSUserCredentials(boolean isPublic, JSUser newUser,
1227             Object credential)
1228     {
1229         if (credential == null) return;
1230         if (credential instanceof PasswordCredential)
1231         {
1232             PasswordCredential pw = (PasswordCredential) credential;
1233             newUser.setUserCredential(pw.getUserName(), pw.getPassword(),pw.getExpirationDate(),pw.isEnabled(), pw.isExpired(), pw.isUpdateRequired());
1234             return;
1235         } else if (isPublic)
1236             newUser.addPublicCredential(credential);
1237         else
1238             newUser.addPrivateCredential(credential);
1239     }
1240 
1241     /***
1242      * create a new JSUser object
1243      * 
1244      * @param user
1245      * @return a new JSUser object
1246      */
1247     private JSUser createJSUser(User user)
1248     {
1249         JSUser _newUser = new JSUser();
1250 
1251         Subject subject = user.getSubject();
1252         // get the user principal
1253         Set principals = subject.getPrincipals();
1254         Iterator list = principals.iterator();
1255         while (list.hasNext())
1256         {
1257             BasePrincipal principal = (BasePrincipal) list.next();
1258             String path = principal.getFullPath();
1259             if (path.startsWith("/role/"))
1260             {
1261                 JSRole _tempRole = (JSRole) this.getObjectBehindPath(roleMap,
1262                         principal.getName());
1263                 if (_tempRole != null)
1264                 {
1265                     _newUser.addRole(_tempRole);
1266                 }
1267 
1268             } else
1269             {
1270                 if (path.startsWith("/group/"))
1271                 {
1272                     JSGroup _tempGroup = (JSGroup) this.getObjectBehindPath(
1273                             groupMap, principal.getName());
1274                     if (_tempGroup != null)
1275                     {
1276                         _newUser.addGroup(_tempGroup);
1277                     }
1278 
1279                 } else if (path.startsWith("/user/"))
1280                     _newUser.setPrincipal(principal);
1281 
1282             }
1283 
1284         }
1285         // System.out.println("User Public Credentials");
1286         Set credentials = subject.getPublicCredentials();
1287         list = credentials.iterator();
1288         while (list.hasNext())
1289         {
1290             Object credential = list.next();
1291             addJSUserCredentials(true, _newUser, credential);
1292         }
1293         // System.out.println("User Private Credentials");
1294         credentials = subject.getPrivateCredentials();
1295         list = credentials.iterator();
1296         while (list.hasNext())
1297         {
1298             Object credential = list.next();
1299             addJSUserCredentials(false, _newUser, credential);
1300         }
1301 
1302         Preferences preferences = user.getPreferences();
1303         _newUser.setPreferences(preferences);
1304         preferences = user.getUserAttributes();
1305         _newUser.setUserInfo(preferences);
1306         //TODO: HJB, fix preferences...userinfo doesn't return values in prefs_property_value (in fact preferences.keys() is []
1307         return _newUser;
1308     }
1309 
1310 
1311     /***
1312      * Collect all the roles, groups and users from the current environment.
1313      * Include the current SecurityProvider to understand, whether the password
1314      * collected can be used upon import
1315      * 
1316      * @throws SerializerException
1317      */
1318 
1319     private void exportUsers() throws SerializerException
1320     {
1321         /*** set the security provider info in the snapshot file */
1322         ((JSSeedData)getSnapshot()).setEncryption(getEncryptionString());
1323         /*** get the roles */
1324         exportRoles();
1325         /*** get the groups */
1326         exportGroups();
1327 
1328         /*** users */
1329         UserManager userManager = (UserManager) getCM()
1330                 .getComponent("org.apache.jetspeed.security.UserManager");
1331         if (userManager == null)
1332             throw new SerializerException(
1333                     SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
1334                             .create("org.apache.jetspeed.security.UserManager"));
1335         Iterator list = null;
1336         try
1337         {
1338             list = userManager.getUsers("");
1339         } catch (Exception e)
1340         {
1341             throw new SerializerException(
1342                     SerializerException.GET_EXISTING_OBJECTS
1343                             .create(new String[]
1344                             { "User", e.getMessage()}));
1345         }
1346         while (list.hasNext())
1347         {
1348 
1349             try
1350             {
1351                 User _user = (User) list.next();
1352                 JSUser _tempUser = createJSUser(_user);
1353                 userMap.put(_tempUser.getName(), _tempUser);
1354                 ((JSSeedData)getSnapshot()).getUsers().add(_tempUser);
1355             } catch (Exception e)
1356             {
1357                 throw new SerializerException(
1358                         SerializerException.CREATE_SERIALIZED_OBJECT_FAILED
1359                                 .create(new String[]
1360                                 { "User", e.getMessage()}));
1361             }
1362 
1363         }
1364         return;
1365 
1366     }
1367 
1368     /***
1369      * extract the capabilities and save in snapshot file
1370      * 
1371      * @param caps
1372      *            capability-container
1373      * @throws SerializerException
1374      */
1375     private void exportCapabilites(Capabilities caps)
1376             throws SerializerException
1377     {
1378 
1379         Iterator list = caps.getCapabilities();
1380 
1381         while (list.hasNext())
1382         {
1383             try
1384             {
1385                 Capability _cp = (Capability) list.next();
1386                 JSCapability _jsC = new JSCapability();
1387                 _jsC.setName(_cp.getName());
1388                 this.capabilityMap.put(_jsC.getName(), _jsC);
1389                 this.capabilityMapInt.put(new Integer(_cp.getCapabilityId()), _jsC);
1390                 ((JSSeedData)getSnapshot()).getCapabilities().add(_jsC);
1391             } catch (Exception e)
1392             {
1393                 throw new SerializerException(
1394                         SerializerException.CREATE_SERIALIZED_OBJECT_FAILED
1395                                 .create(new String[]
1396                                 { "C", e.getMessage()}));
1397             }
1398         }
1399         return;
1400 
1401     }
1402 
1403     /***
1404      * exstract the mime types anmd save in snapshot file
1405      * 
1406      * @param caps
1407      *            capability container
1408      * @throws SerializerException
1409      */
1410     private void exportMimeTypes(Capabilities caps) throws SerializerException
1411     {
1412 
1413         Iterator list = caps.getMimeTypes();
1414 
1415         while (list.hasNext())
1416         {
1417             try
1418             {
1419                 MimeType _mt = (MimeType) list.next();
1420                 JSMimeType _jsM = new JSMimeType();
1421                 _jsM.setName(_mt.getName());
1422                 this.mimeMap.put(_jsM.getName(), _jsM);
1423                 this.mimeMapInt.put(new Integer(_mt.getMimetypeId()), _jsM);
1424 
1425                 ((JSSeedData)getSnapshot()).getMimeTypes().add(_jsM);
1426             } catch (Exception e)
1427             {
1428                 throw new SerializerException(
1429                         SerializerException.CREATE_SERIALIZED_OBJECT_FAILED
1430                                 .create(new String[]
1431                                 { "MimeType", e.getMessage()}));
1432             }
1433         }
1434         return;
1435 
1436     }
1437 
1438     /***
1439      * create a JS CLient
1440      * 
1441      * @param c
1442      *            the existing Client object
1443      * @return
1444      * @throws SerializerException
1445      */
1446 
1447     private JSClient createJSClient(Client c) throws SerializerException
1448     {
1449         try
1450         {
1451             JSClient jsC = new JSClient(c);
1452             // find the mimeTypes
1453             Iterator _itM = c.getMimetypes().iterator();
1454             while (_itM.hasNext())
1455             {
1456                 MimeType _m = (MimeType) _itM.next();
1457                 JSMimeType _mt = (JSMimeType) mimeMap.get(_m.getName());
1458                 if (_mt != null) jsC.getMimeTypes().add(_mt);
1459             }
1460             
1461     		Integer id = new Integer(c.getPreferredMimeTypeId());
1462     		JSMimeType _mt = (JSMimeType) mimeMapInt.get(id);
1463     		if (_mt != null)
1464     			jsC.setPreferredMimeTypeID(_mt.getName());
1465     		else
1466     			jsC.setPreferredMimeTypeID("???");
1467 
1468             // find the capabilities
1469             Iterator _itC = c.getCapabilities().iterator();
1470             while (_itC.hasNext())
1471             {
1472                 Capability _c = (Capability) _itC.next();
1473                 JSCapability _ct = (JSCapability) capabilityMap.get(_c
1474                         .getName());
1475                 if (_ct != null) jsC.getCapabilities().add(_ct);
1476             }
1477 
1478             return jsC;
1479         } catch (Exception e)
1480         {
1481             throw new SerializerException(
1482                     SerializerException.CREATE_SERIALIZED_OBJECT_FAILED
1483                             .create(new String[]
1484                             { "Client", e.getMessage()}));
1485         }
1486 
1487     }
1488 
1489     /***
1490      * extract the current clients and save in the snapshot file
1491      * 
1492      * @param list
1493      * @param caps
1494      * @return
1495      * @throws SerializerException
1496      */
1497     private void exportClients(Capabilities caps) throws SerializerException
1498     {
1499 
1500         /*** first the the mime types */
1501         exportMimeTypes(caps);
1502 
1503         /*** second get the capabilities */
1504         this.exportCapabilites(caps);
1505 
1506         /*** now get the clients */
1507         Iterator _it = caps.getClients();
1508         while (_it.hasNext())
1509         {
1510             Client c = (Client) _it.next();
1511             JSClient jsC = createJSClient(c);
1512             if (jsC == null)
1513                 throw new SerializerException(
1514                         SerializerException.CREATE_SERIALIZED_OBJECT_FAILED
1515                                 .create(new String[]
1516                                 { "Client", "createClient returned NULL"}));
1517             this.clientMap.put(jsC.getName(), jsC);
1518             ((JSSeedData)getSnapshot()).getClients().add(jsC);
1519         }
1520         return;
1521     }
1522 
1523     /***
1524      * extract the media types and save in snapshot file
1525      * 
1526      * @param caps
1527      *            capabilit container
1528      * @throws SerializerException
1529      */
1530     private void exportMediaTypes(Capabilities caps) throws SerializerException
1531     {
1532         Iterator list = caps.getMediaTypes();
1533 
1534         while (list.hasNext())
1535         {
1536             try
1537             {
1538                 MediaType _mt = (MediaType) list.next();
1539                 JSMediaType _jsM = new JSMediaType(_mt);
1540                 // find the mimeTypes
1541                 Iterator _itM = _mt.getMimetypes().iterator();
1542                 while (_itM.hasNext())
1543                 {
1544                     MimeType _m = (MimeType) _itM.next();
1545                     JSMimeType _mttype = (JSMimeType) mimeMap.get(_m.getName());
1546                     if (_mttype != null) _jsM.getMimeTypes().add(_mttype);
1547                 }
1548                 // find the capabilities
1549                 Iterator _itC = _mt.getCapabilities().iterator();
1550                 while (_itC.hasNext())
1551                 {
1552                     Capability _c = (Capability) _itC.next();
1553                     JSCapability _ct = (JSCapability) capabilityMap.get(_c
1554                             .getName());
1555                     if (_ct != null) _jsM.getCapabilities().add(_ct);
1556                 }
1557                 this.mediaMap.put(_jsM.getName(), _jsM);
1558                 ((JSSeedData)getSnapshot()).getMediaTypes().add(_jsM);
1559             } catch (Exception e)
1560             {
1561                 // do whatever
1562                 throw new SerializerException(
1563                         SerializerException.CREATE_SERIALIZED_OBJECT_FAILED
1564                                 .create(new String[]
1565                                 { "MediaType", e.getMessage()}));
1566             }
1567         }
1568         return;
1569     }
1570 
1571     /***
1572      * Extracts all capability related objects (clients, mimetypes and
1573      * mediatypes) and their relationships
1574      * 
1575      * @return
1576      */
1577 
1578     private void exportCapabilitiesInfrastructure() throws SerializerException
1579     {
1580         Capabilities caps = (Capabilities) getCM()
1581                 .getComponent("org.apache.jetspeed.capabilities.Capabilities");
1582         if (caps == null)
1583             throw new SerializerException(
1584                     SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
1585                             .create("org.apache.jetspeed.capabilities.Capabilities"));
1586 
1587         /***
1588          * get the clients (which in turn will get the mime types and
1589          * capailities)
1590          */
1591 
1592         exportClients(caps);
1593         // get the mediatTypes, too
1594 
1595         exportMediaTypes(caps);
1596 
1597     }
1598 
1599     /***
1600      * extract all permissions from the current environment
1601      * 
1602      * @throws SerializerException
1603      */
1604     private void getPermissions() throws SerializerException
1605     {
1606         Object o = null;
1607         PermissionManager pm = (PermissionManager) getCM()
1608                 .getComponent("org.apache.jetspeed.security.PermissionManager");
1609         if (pm == null)
1610             throw new SerializerException(
1611                     SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
1612                             .create("org.apache.jetspeed.security.PermissionManager"));
1613 
1614         Iterator list = null;
1615         try
1616         {
1617             list = pm.getPermissions().iterator();
1618         } catch (Exception e)
1619         {
1620             throw new SerializerException(
1621                     SerializerException.GET_EXISTING_OBJECTS
1622                             .create(new String[]
1623                             { "Permissions", e.getMessage()}));
1624         }
1625 
1626         while (list.hasNext())
1627         {
1628             try
1629             {
1630                 JSPermission _js = new JSPermission();
1631 
1632                 InternalPermission p = (InternalPermission) list.next();
1633                 _js.setResource(p.getName());
1634                 _js.setActions(p.getActions());
1635                 _js.setId(p.getPermissionId());
1636                 _js.setType(_js.getTypeForClass(p.getClassname()));
1637 
1638                 Iterator list2 = p.getPrincipals().iterator();
1639                 while (list2.hasNext())
1640                 {
1641                     o = list2.next();
1642                     InternalPrincipal principal = (InternalPrincipal) o;
1643                     String path = principal.getFullPath();
1644                     if (path.startsWith("/role/"))
1645                     {
1646                         JSRole _tempRole = (JSRole) this.getObjectBehindPath(
1647                                 roleMap, removeFromString(path, "/role/"));
1648                         if (_tempRole != null)
1649                         {
1650                             _js.addRole(_tempRole);
1651                         }
1652 
1653                     } else
1654                     {
1655                         if (path.startsWith("/group/"))
1656                         {
1657                             JSGroup _tempGroup = (JSGroup) this
1658                                     .getObjectBehindPath(groupMap,
1659                                             removeFromString(path, "/group/"));
1660                             if (_tempGroup != null)
1661                             {
1662                                 _js.addGroup(_tempGroup);
1663                             }
1664 
1665                         } else
1666                         {
1667                             if (path.startsWith("/user/"))
1668                             {
1669                                 JSUser _tempUser = (JSUser) this
1670                                         .getObjectBehindPath(
1671                                                 userMap,
1672                                                 removeFromString(path, "/user/"));
1673                                 if (_tempUser != null)
1674                                 {
1675                                     _js.addUser(_tempUser);
1676                                 }
1677 
1678                             }
1679 
1680                         }
1681 
1682                     }
1683                 }
1684                 this.permissionMap.put(_js.getType(), _js);
1685                 ((JSSeedData)getSnapshot()).getPermissions().add(_js);
1686 
1687             } catch (Exception e)
1688             {
1689                 throw new SerializerException(
1690                         SerializerException.CREATE_SERIALIZED_OBJECT_FAILED
1691                                 .create(new String[]
1692                                 { "Permissions", e.getMessage()}));
1693             }
1694         }
1695         return;
1696 
1697     }
1698 
1699     /***
1700      * Create the Profiling Rule Wrapper
1701      * 
1702      * @param p
1703      * @return
1704      */
1705     private JSProfilingRule createProfilingRule(ProfilingRule p, boolean standard)
1706     {
1707         JSProfilingRule rule = new JSProfilingRule();
1708         
1709         
1710         
1711         rule.setStandardRule(standard);
1712         rule.setDescription(p.getTitle());
1713         rule.setId(p.getId());
1714 
1715         Collection col = p.getRuleCriteria();
1716         Iterator keys = col.iterator();
1717         while (keys.hasNext())
1718         {
1719             RuleCriterion rc = (RuleCriterion) keys.next();
1720             rule.getCriterions().add(new JSRuleCriterion(rc));
1721         }
1722         return rule;
1723 
1724     }
1725 
1726     /***
1727      * read the permissions and then the profiling rules.
1728      * <p>
1729      * after that update the cross reference with the users
1730      * 
1731      * @throws SerializerException
1732      */
1733     private void getProfilingRules() throws SerializerException
1734     {
1735         Profiler pm = (Profiler) getCM()
1736                 .getComponent("org.apache.jetspeed.profiler.Profiler");
1737         if (pm == null)
1738 
1739             throw new SerializerException(
1740                     SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
1741                             .create("org.apache.jetspeed.profiler.Profiler"));
1742         Class standardRuleClass = null;
1743         try
1744         {
1745         	ProfilingRule tempStandardRule = pm.createProfilingRule(true);
1746         	standardRuleClass = tempStandardRule.getClass();
1747         }
1748         catch (Exception e)
1749         {
1750         	throw new SerializerException(
1751                 SerializerException.CREATE_OBJECT_FAILED
1752                         .create(new String[]
1753                         { "Standard Rule", e.getMessage()}));
1754         }
1755         
1756         Iterator list = null;
1757         try
1758         {
1759             list = pm.getRules().iterator();
1760         } catch (Exception e)
1761         {
1762             throw new SerializerException(
1763                     SerializerException.GET_EXISTING_OBJECTS
1764                             .create(new String[]
1765                             { "ProfilingRules", e.getMessage()}));
1766         }
1767         while (list.hasNext())
1768         {
1769             try
1770             {
1771                 ProfilingRule p = (ProfilingRule) list.next();
1772                 if (!(this.rulesMap.containsKey(p.getId())))
1773                 {
1774                     JSProfilingRule rule = createProfilingRule(p, (standardRuleClass == p.getClass()));
1775                     rulesMap.put(rule.getId(), rule);
1776                     ((JSSeedData)getSnapshot()).getRules().add(rule);
1777 
1778                 }
1779             } catch (Exception e)
1780             {
1781                 throw new SerializerException(
1782                         SerializerException.CREATE_SERIALIZED_OBJECT_FAILED
1783                                 .create(new String[]
1784                                 { "ProfilingRules", e.getMessage()}));
1785             }
1786         }
1787 
1788         // determine the defualt rule
1789         ProfilingRule defaultRule = pm.getDefaultRule();
1790         if (defaultRule != null)
1791         	((JSSeedData)getSnapshot()).setDefaultRule(defaultRule.getId());
1792 
1793         // get Rules for each user
1794 
1795         Iterator _itUsers = this.userMap.values().iterator();
1796         while (_itUsers.hasNext())
1797         {
1798             JSUser _user = (JSUser) _itUsers.next();
1799             Principal principal = _user.getPrincipal();
1800             if (principal != null)
1801             {
1802                 Collection col = pm.getRulesForPrincipal(principal);
1803                 Iterator _itCol = col.iterator();
1804                 while (_itCol.hasNext())
1805                 {
1806                     PrincipalRule p1 = (PrincipalRule) _itCol.next();
1807                     JSPrincipalRule pr = new JSPrincipalRule(p1
1808                             .getLocatorName(), p1.getProfilingRule().getId());
1809                     _user.getRules().add(pr);
1810                 }
1811             }
1812         }
1813 
1814         return;
1815 
1816     }
1817 
1818     /***
1819      * Establish whether incoming passwords are "clear" text or whether they are
1820      * to be decoded. That however depends on whether the passwords were encoded
1821      * with the current active provider or not.
1822      * 
1823      * @return
1824      */
1825     protected int compareCurrentSecurityProvider(JSSeedData file)
1826     {
1827         String _fileEncryption = file.getEncryption();
1828         if ((_fileEncryption == null) || (_fileEncryption.length() == 0))
1829             return NO_DECODING; // passwords are in clear text
1830         
1831         if (_fileEncryption.equals(getEncryptionString()))
1832         	return PASSTHRU_REQUIRED;
1833         else
1834         	return NO_DECODING;
1835     }
1836 
1837     private String getEncryptionString()
1838     {
1839         PasswordCredentialProvider provider = (PasswordCredentialProvider) getCM()
1840         .getComponent("org.apache.jetspeed.security.spi.PasswordCredentialProvider");
1841 		if (provider == null)
1842 		{
1843 		    System.err
1844 		            .println("Error!!! PasswordCredentialProvider not available");
1845 		    return ENCODING_STRING;
1846 		}
1847 		try
1848 		{
1849 			PasswordCredential credential = provider.create(JETSPEED,ENCODING_STRING);
1850 			if ((credential != null) && (credential.getPassword() != null))
1851 				return new String(credential.getPassword());
1852 			else
1853 			    return ENCODING_STRING;
1854 		}
1855 		catch (Exception e)
1856 		{
1857 			e.printStackTrace();
1858 			return ENCODING_STRING;
1859 		}
1860     }
1861     
1862     /***
1863      * ++++++++++++++++++++++++++++++HELPERS
1864      * +++++++++++++++++++++++++++++++++++++++++++++
1865      */
1866 
1867   
1868 
1869 
1870     /***
1871      * recreate a rule criterion object from the deserialized wrapper
1872      * @param profiler established profile manager
1873      * @param jsr deserialized object
1874      * @return new RuleCriterion with content set to deserialized wrapepr
1875      * @throws SerializerException
1876      */
1877 	protected RuleCriterion recreateRuleCriterion(Profiler profiler, JSRuleCriterion jsr, ProfilingRule rule)
1878 		throws SerializerException, ClassNotFoundException
1879 	
1880 	{
1881 		try
1882 		{
1883 	
1884 	    	RuleCriterion c = profiler.createRuleCriterion();
1885 	    	if (c == null)
1886 	    		throw new SerializerException(
1887 	    				SerializerException.CREATE_OBJECT_FAILED
1888 	    					.create("org.apache.jetspeed.profiler.rules.RuleCriterion","returned null"));
1889 	    	c.setFallbackOrder(jsr.getFallBackOrder());
1890 	    	c.setFallbackType(jsr.getFallBackType());
1891 	    	c.setName(jsr.getName());
1892 	    	c.setType(jsr.getType());
1893 	    	c.setValue(jsr.getValue());
1894 	    	c.setRuleId(rule.getId());
1895 	    	return c;
1896 		}
1897 		catch (Exception e)
1898 		{
1899 			SerializerException.CREATE_OBJECT_FAILED
1900 			.create("org.apache.jetspeed.profiler.rules.RuleCriterion",e.getLocalizedMessage());
1901 			return null;
1902 		}
1903 	}
1904     	
1905 	   /***
1906      * recreate a profiling rule object from the deserialized wrapper and store it
1907      * @param profiler established profile manager
1908      * @param jsp deserialized object
1909      * @
1910      * @throws SerializerException, ClassNotFoundException, ProfilerException
1911      */
1912 	   protected ProfilingRule recreateRule(Profiler profiler, ProfilingRule existingRule, JSProfilingRule jsp) throws SerializerException, ClassNotFoundException, ProfilerException
1913 	   {
1914 		   ProfilingRule rule = null;
1915 		   boolean existing = false;
1916 		   
1917 		   if (existingRule == null)
1918 		   {
1919 			   rule = profiler.getRule(jsp.getId());
1920 			   if (jsp.isStandardRule())
1921 			  	   rule = profiler.createProfilingRule(true);   
1922 			   else
1923 			  	   rule = profiler.createProfilingRule(false); 
1924 			   rule.setId(jsp.getId());
1925 		   }
1926 		   else
1927 		   {
1928 			   rule = existingRule;
1929 			   existing = true;
1930 		   }
1931 			   
1932 		   rule.setTitle(jsp.getDescription());
1933 		   
1934 		   JSRuleCriterions col = jsp.getCriterions();
1935 			   
1936 		   Iterator _it = col.iterator();
1937 		   while (_it.hasNext())
1938 		   {
1939 				   RuleCriterion c = recreateRuleCriterion(profiler, (JSRuleCriterion) _it.next(),rule);
1940 				   if (c != null)
1941 				   {
1942 					   Collection cHelp = rule.getRuleCriteria();
1943 					   if ((existing) && (cHelp.contains(c)))
1944 						   cHelp.remove(c); //remove existing duplicate
1945 					   cHelp.add(c); // add the current version back in
1946 				   }
1947 		   }
1948 		   return rule;
1949 
1950 	   }  	
1951 	
1952     	
1953     	
1954 	   private void recreateProfilingRules () throws SerializerException
1955 	    {
1956 	    	logMe("recreateProfilingRules - processing");
1957 	        Profiler pm = (Profiler) getCM()
1958             .getComponent("org.apache.jetspeed.profiler.Profiler");
1959 	        if (pm == null)
1960 	        	throw new SerializerException(
1961 	        			SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST
1962                         	.create("org.apache.jetspeed.profiler.Profiler"));
1963 	    	JSProfilingRules rules = ((JSSeedData)getSnapshot()).getRules();
1964 	    	if ((rules != null) && (rules.size() > 0))
1965 	    	{
1966 	    		Iterator _it = rules.iterator();
1967 	    		while (_it.hasNext())
1968 	    		{
1969 	    			JSProfilingRule _c = (JSProfilingRule)_it.next();
1970 
1971 	    			try
1972 	    			{
1973 	    				ProfilingRule rule = null;
1974 	    				   
1975 	    				   rule = pm.getRule(_c.getId());
1976 	    				   if ((rule == null) || (this.getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)))
1977 	    				   {
1978 	    					   rule = recreateRule(pm,rule, _c);
1979 	    					   pm.storeProfilingRule(rule);
1980 	    				   }
1981 	    			}
1982 	    			catch (Exception e)
1983 	    			{
1984 	    				throw new SerializerException(
1985 	    			            SerializerException.CREATE_OBJECT_FAILED
1986 	    			            	.create("org.apache.jetspeed.capabilities.Capabilities",e.getLocalizedMessage()));
1987 	 			}
1988 	    		}
1989 	    		/*** reset the default profiling rule */
1990 	    		String defaultRuleID = ((JSSeedData)getSnapshot()).getDefaultRule();
1991 	    		if (defaultRuleID != null)
1992 	    		{
1993 	    			ProfilingRule defaultRule = pm.getRule(defaultRuleID);
1994 	    			if (defaultRule != null)
1995 	    				pm.setDefaultRule(defaultRuleID);
1996 	    		}
1997 	    	}
1998 	    	else
1999 	    		logMe("NO PROFILING RULES?????");
2000 	    	logMe("recreateProfilingRules - done");
2001 	    }	
2002 
2003 
2004 
2005 }