This project has retired. For details please refer to its Attic page.
DefaultRoleManager xref
View Javadoc

1   package org.apache.archiva.redback.role;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   * http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import org.apache.archiva.redback.rbac.RBACManager;
23  import org.apache.archiva.redback.rbac.RbacManagerException;
24  import org.apache.archiva.redback.rbac.Role;
25  import org.apache.archiva.redback.rbac.UserAssignment;
26  import org.apache.archiva.redback.role.model.ModelApplication;
27  import org.apache.archiva.redback.role.model.ModelRole;
28  import org.apache.archiva.redback.role.model.ModelTemplate;
29  import org.apache.archiva.redback.role.model.RedbackRoleModel;
30  import org.apache.archiva.redback.role.model.io.stax.RedbackRoleModelStaxReader;
31  import org.apache.archiva.redback.role.processor.RoleModelProcessor;
32  import org.apache.commons.io.IOUtils;
33  import org.apache.commons.lang.SystemUtils;
34  import org.apache.archiva.redback.rbac.Resource;
35  import org.apache.archiva.redback.role.template.RoleTemplateProcessor;
36  import org.apache.archiva.redback.role.util.RoleModelUtils;
37  import org.apache.archiva.redback.role.validator.RoleModelValidator;
38  import org.apache.commons.lang.time.StopWatch;
39  import org.slf4j.Logger;
40  import org.slf4j.LoggerFactory;
41  import org.springframework.stereotype.Service;
42  
43  import javax.annotation.PostConstruct;
44  import javax.inject.Inject;
45  import javax.inject.Named;
46  import javax.xml.stream.XMLStreamException;
47  import java.io.IOException;
48  import java.io.InputStreamReader;
49  import java.net.MalformedURLException;
50  import java.net.URL;
51  import java.util.Arrays;
52  import java.util.Enumeration;
53  import java.util.HashMap;
54  import java.util.List;
55  import java.util.Map;
56  
57  /**
58   * RoleProfileManager:
59   *
60   * @author: Jesse McConnell <jesse@codehaus.org>
61   */
62  @Service("roleManager")
63  public class DefaultRoleManager
64      implements RoleManager
65  {
66      private Logger log = LoggerFactory.getLogger( DefaultRoleManager.class );
67  
68      /**
69       * the blessed model that has been validated as complete
70       */
71      private RedbackRoleModel blessedModel;
72  
73      /**
74       * the merged model that can be validated as complete
75       */
76      private RedbackRoleModel unblessedModel;
77  
78      /**
79       * a map of the resources, and the model that they loaded
80       */
81      private Map<String, ModelApplication> knownResources = new HashMap<String, ModelApplication>();
82  
83      @Inject
84      @Named(value = "roleModelValidator")
85      private RoleModelValidator modelValidator;
86  
87      @Inject
88      @Named(value = "roleModelProcessor")
89      private RoleModelProcessor modelProcessor;
90  
91      @Inject
92      @Named(value = "roleTemplateProcessor")
93      private RoleTemplateProcessor templateProcessor;
94  
95      @Inject
96      @Named(value = "rbacManager#default")
97      private RBACManager rbacManager;
98  
99  
100     public void loadRoleModel( URL resource )
101         throws RoleManagerException
102     {
103         RedbackRoleModelStaxReader reader = new RedbackRoleModelStaxReader();
104 
105         InputStreamReader inputStreamReader = null;
106 
107         try
108         {
109 
110             inputStreamReader = new InputStreamReader( resource.openStream() );
111 
112             RedbackRoleModel roleModel = reader.read( inputStreamReader );
113 
114             for ( ModelApplication app : roleModel.getApplications() )
115             {
116                 if ( !knownResources.containsKey( app.getId() ) )
117                 {
118                     log.info( "loading {}", app.getId() );
119                     loadApplication( app );
120                 }
121             }
122         }
123         catch ( MalformedURLException e )
124         {
125             throw new RoleManagerException( "error locating redback profile", e );
126         }
127         catch ( IOException e )
128         {
129             throw new RoleManagerException( "error reading redback profile", e );
130         }
131         catch ( XMLStreamException e )
132         {
133             throw new RoleManagerException( "error parsing redback profile", e );
134         }
135         finally
136         {
137             IOUtils.closeQuietly( inputStreamReader );
138         }
139     }
140 
141     public void loadRoleModel( RedbackRoleModel roleModel )
142         throws RoleManagerException
143     {
144         for ( ModelApplication app : roleModel.getApplications() )
145         {
146             if ( !knownResources.containsKey( app.getId() ) )
147             {
148                 loadApplication( app );
149             }
150         }
151 
152     }
153 
154     public void loadApplication( ModelApplication app )
155         throws RoleManagerException
156     {
157         if ( unblessedModel == null )
158         {
159             unblessedModel = new RedbackRoleModel();
160         }
161 
162         unblessedModel.addApplication( app );
163 
164         if ( modelValidator.validate( unblessedModel ) )
165         {
166             blessedModel = unblessedModel;
167         }
168         else
169         {
170             StringBuilder stringBuilder = new StringBuilder( "Role Model Validation Errors:" );
171 
172             for ( String error : modelValidator.getValidationErrors() )
173             {
174                 stringBuilder.append( error ).append( SystemUtils.LINE_SEPARATOR );
175             }
176 
177             log.error( stringBuilder.toString() );
178 
179             throw new RoleManagerException(
180                 "Role Model Validation Error " + SystemUtils.LINE_SEPARATOR + stringBuilder.toString() );
181         }
182 
183         modelProcessor.process( blessedModel );
184 
185         knownResources.put( app.getId(), app );
186     }
187 
188     /**
189      * create a role for the given roleName using the resource passed in for
190      * resolving the ${resource} expression
191      */
192     public void createTemplatedRole( String templateId, String resource )
193         throws RoleManagerException
194     {
195         templateProcessor.create( blessedModel, templateId, resource );
196     }
197 
198     /**
199      * remove the role corresponding to the role using the resource passed in for resolving the
200      * ${resource} expression
201      */
202     public void removeTemplatedRole( String templateId, String resource )
203         throws RoleManagerException
204     {
205         ModelTemplate template = RoleModelUtils.getModelTemplate( blessedModel, templateId );
206 
207         String roleName = template.getNamePrefix() + template.getDelimiter() + resource;
208 
209         try
210         {
211             Role role = rbacManager.getRole( roleName );
212 
213             for ( UserAssignment assignment : rbacManager.getUserAssignmentsForRoles(
214                 Arrays.asList( role.getName() ) ) )
215             {
216                 assignment.removeRoleName( role );
217                 rbacManager.saveUserAssignment( assignment );
218             }
219 
220         }
221         catch ( RbacManagerException e )
222         {
223             throw new RoleManagerException( "unable to remove role", e );
224         }
225 
226         templateProcessor.remove( blessedModel, templateId, resource );
227     }
228 
229     /**
230      * update the role from templateId from oldResource to newResource
231      * <p/>
232      * NOTE: this requires removal and creation of the role since the jdo store does not tolerate renaming
233      * because of the use of the name as an identifier
234      */
235     public void updateRole( String templateId, String oldResource, String newResource )
236         throws RoleManagerException
237     {
238         // make the new role
239         templateProcessor.create( blessedModel, templateId, newResource );
240 
241         ModelTemplate template = RoleModelUtils.getModelTemplate( blessedModel, templateId );
242 
243         String oldRoleName = template.getNamePrefix() + template.getDelimiter() + oldResource;
244         String newRoleName = template.getNamePrefix() + template.getDelimiter() + newResource;
245 
246         try
247         {
248             Role role = rbacManager.getRole( oldRoleName );
249 
250             // remove the user assignments
251             for ( UserAssignment assignment : rbacManager.getUserAssignmentsForRoles(
252                 Arrays.asList( role.getName() ) ) )
253             {
254                 assignment.removeRoleName( oldRoleName );
255                 assignment.addRoleName( newRoleName );
256                 rbacManager.saveUserAssignment( assignment );
257             }
258         }
259         catch ( RbacManagerException e )
260         {
261             throw new RoleManagerException( "unable to update role", e );
262         }
263 
264         templateProcessor.remove( blessedModel, templateId, oldResource );
265     }
266 
267     public void assignRole( String roleId, String principal )
268         throws RoleManagerException
269     {
270         ModelRole modelRole = RoleModelUtils.getModelRole( blessedModel, roleId );
271 
272         if ( modelRole == null )
273         {
274             throw new RoleManagerException( "Unable to assign role: " + roleId + " does not exist." );
275         }
276 
277         try
278         {
279             UserAssignment userAssignment;
280 
281             if ( rbacManager.userAssignmentExists( principal ) )
282             {
283                 userAssignment = rbacManager.getUserAssignment( principal );
284             }
285             else
286             {
287                 userAssignment = rbacManager.createUserAssignment( principal );
288             }
289 
290             userAssignment.addRoleName( modelRole.getName() );
291             rbacManager.saveUserAssignment( userAssignment );
292         }
293         catch ( RbacManagerException e )
294         {
295             throw new RoleManagerException( "Unable to assign role: unable to manage user assignment", e );
296         }
297     }
298 
299     public void assignRoleByName( String roleName, String principal )
300         throws RoleManagerException
301     {
302         try
303         {
304             UserAssignment userAssignment;
305 
306             if ( rbacManager.userAssignmentExists( principal ) )
307             {
308                 userAssignment = rbacManager.getUserAssignment( principal );
309             }
310             else
311             {
312                 userAssignment = rbacManager.createUserAssignment( principal );
313             }
314 
315             if ( !rbacManager.roleExists( roleName ) )
316             {
317                 throw new RoleManagerException( "Unable to assign role: " + roleName + " does not exist." );
318             }
319 
320             userAssignment.addRoleName( roleName );
321             rbacManager.saveUserAssignment( userAssignment );
322         }
323         catch ( RbacManagerException e )
324         {
325             throw new RoleManagerException( "Unable to assign role: unable to manage user assignment", e );
326         }
327     }
328 
329     public void assignTemplatedRole( String templateId, String resource, String principal )
330         throws RoleManagerException
331     {
332         ModelTemplate modelTemplate = RoleModelUtils.getModelTemplate( blessedModel, templateId );
333 
334         if ( modelTemplate == null )
335         {
336             throw new RoleManagerException( "Unable to assign role: " + templateId + " does not exist." );
337         }
338         try
339         {
340             if ( !rbacManager.resourceExists( resource ) )
341             {
342                 Resource newResource = rbacManager.createResource( resource );
343                 rbacManager.saveResource( newResource );
344             }
345 
346             UserAssignment userAssignment;
347 
348             if ( rbacManager.userAssignmentExists( principal ) )
349             {
350                 userAssignment = rbacManager.getUserAssignment( principal );
351             }
352             else
353             {
354                 userAssignment = rbacManager.createUserAssignment( principal );
355             }
356 
357             userAssignment.addRoleName( modelTemplate.getNamePrefix() + modelTemplate.getDelimiter() + resource );
358             rbacManager.saveUserAssignment( userAssignment );
359         }
360         catch ( RbacManagerException e )
361         {
362             throw new RoleManagerException( "Unable to assign role: unable to manage user assignment", e );
363         }
364     }
365 
366     public void unassignRole( String roleId, String principal )
367         throws RoleManagerException
368     {
369         ModelRole modelRole = RoleModelUtils.getModelRole( blessedModel, roleId );
370 
371         if ( modelRole == null )
372         {
373             throw new RoleManagerException( "Unable to assign role: " + roleId + " does not exist." );
374         }
375 
376         try
377         {
378             UserAssignment userAssignment;
379 
380             if ( rbacManager.userAssignmentExists( principal ) )
381             {
382                 userAssignment = rbacManager.getUserAssignment( principal );
383             }
384             else
385             {
386                 throw new RoleManagerException(
387                     "UserAssignment for principal " + principal + "does not exist, can't unassign role." );
388             }
389 
390             userAssignment.removeRoleName( modelRole.getName() );
391             rbacManager.saveUserAssignment( userAssignment );
392         }
393         catch ( RbacManagerException e )
394         {
395             throw new RoleManagerException( "Unable to unassign role: unable to manage user assignment", e );
396         }
397     }
398 
399     public void unassignRoleByName( String roleName, String principal )
400         throws RoleManagerException
401     {
402         try
403         {
404             UserAssignment userAssignment;
405 
406             if ( rbacManager.userAssignmentExists( principal ) )
407             {
408                 userAssignment = rbacManager.getUserAssignment( principal );
409             }
410             else
411             {
412                 throw new RoleManagerException(
413                     "UserAssignment for principal " + principal + "does not exist, can't unassign role." );
414             }
415 
416             if ( !rbacManager.roleExists( roleName ) )
417             {
418                 throw new RoleManagerException( "Unable to unassign role: " + roleName + " does not exist." );
419             }
420 
421             userAssignment.removeRoleName( roleName );
422             rbacManager.saveUserAssignment( userAssignment );
423         }
424         catch ( RbacManagerException e )
425         {
426             throw new RoleManagerException( "Unable to unassign role: unable to manage user assignment", e );
427         }
428     }
429 
430     public boolean roleExists( String roleId )
431         throws RoleManagerException
432     {
433         ModelRole modelRole = RoleModelUtils.getModelRole( blessedModel, roleId );
434 
435         if ( modelRole == null )
436         {
437             return false;
438         }
439         else
440         {
441             try
442             {
443                 if ( rbacManager.roleExists( modelRole.getName() ) )
444                 {
445                     return true;
446                 }
447                 else
448                 {
449                     // perhaps try and reload the model here?
450                     throw new RoleManagerException( "breakdown in role management, role '" + modelRole.getName()
451                                                         + "' exists in configuration but was not created in underlying store" );
452                 }
453             }
454             catch ( RbacManagerException e )
455             {
456                 throw new RoleManagerException( e.getMessage(), e );
457             }
458         }
459     }
460 
461     public boolean templatedRoleExists( String templateId, String resource )
462         throws RoleManagerException
463     {
464         ModelTemplate modelTemplate = RoleModelUtils.getModelTemplate( blessedModel, templateId );
465 
466         // template not existing is valid to check, it will throw exception on trying to create
467         if ( modelTemplate == null )
468         {
469             return false;
470         }
471         else
472         {
473             try
474             {
475                 if ( rbacManager.roleExists( modelTemplate.getNamePrefix() + modelTemplate.getDelimiter() + resource ) )
476                 {
477                     return true;
478                 }
479                 else
480                 {
481                     return false;
482                 }
483             }
484             catch ( RbacManagerException e )
485             {
486                 throw new RoleManagerException( e.getMessage(), e );
487             }
488         }
489     }
490 
491     @PostConstruct
492     public void initialize()
493     {
494 
495         knownResources = new HashMap<String, ModelApplication>();
496         this.unblessedModel = new RedbackRoleModel();
497         StopWatch stopWatch = new StopWatch();
498         stopWatch.start();
499 
500         try
501         {
502             URL baseResource = RoleManager.class.getResource( "/META-INF/redback/redback-core.xml" );
503 
504             if ( baseResource == null )
505             {
506                 throw new RuntimeException( "unable to initialize role manager, missing redback-core.xml" );
507             }
508 
509             loadRoleModel( baseResource );
510 
511             Enumeration<URL> enumerator =
512                 RoleManager.class.getClassLoader().getResources( "META-INF/redback/redback.xml" );
513 
514             while ( enumerator.hasMoreElements() )
515             {
516                 URL redbackResource = enumerator.nextElement();
517 
518                 loadRoleModel( redbackResource );
519             }
520         }
521         catch ( RoleManagerException e )
522         {
523             throw new RuntimeException( "unable to initialize RoleManager", e );
524         }
525         catch ( IOException e )
526         {
527             throw new RuntimeException( "unable to initialize RoleManager, problem with redback.xml loading", e );
528         }
529 
530         stopWatch.stop();
531         log.info( "DefaultRoleManager initialize time {}", stopWatch.getTime() );
532     }
533 
534     public RedbackRoleModel getModel()
535     {
536         return blessedModel;
537     }
538 
539     public void verifyTemplatedRole( String templateId, String resource )
540         throws RoleManagerException
541     {
542         // create also serves as update
543         templateProcessor.create( blessedModel, templateId, resource );
544     }
545 
546     public RedbackRoleModel getBlessedModel()
547     {
548         return blessedModel;
549     }
550 
551     public void setBlessedModel( RedbackRoleModel blessedModel )
552     {
553         this.blessedModel = blessedModel;
554     }
555 
556     public RedbackRoleModel getUnblessedModel()
557     {
558         return unblessedModel;
559     }
560 
561     public void setUnblessedModel( RedbackRoleModel unblessedModel )
562     {
563         this.unblessedModel = unblessedModel;
564     }
565 
566     public Map<String, ModelApplication> getKnownResources()
567     {
568         return knownResources;
569     }
570 
571     public void setKnownResources( Map<String, ModelApplication> knownResources )
572     {
573         this.knownResources = knownResources;
574     }
575 
576     public RoleModelValidator getModelValidator()
577     {
578         return modelValidator;
579     }
580 
581     public void setModelValidator( RoleModelValidator modelValidator )
582     {
583         this.modelValidator = modelValidator;
584     }
585 
586     public RoleModelProcessor getModelProcessor()
587     {
588         return modelProcessor;
589     }
590 
591     public void setModelProcessor( RoleModelProcessor modelProcessor )
592     {
593         this.modelProcessor = modelProcessor;
594     }
595 
596     public RoleTemplateProcessor getTemplateProcessor()
597     {
598         return templateProcessor;
599     }
600 
601     public void setTemplateProcessor( RoleTemplateProcessor templateProcessor )
602     {
603         this.templateProcessor = templateProcessor;
604     }
605 
606     public RBACManager getRbacManager()
607     {
608         return rbacManager;
609     }
610 
611     public void setRbacManager( RBACManager rbacManager )
612     {
613         this.rbacManager = rbacManager;
614     }
615 }