You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@syncope.apache.org by il...@apache.org on 2012/10/25 18:17:54 UTC

svn commit: r1402206 [1/2] - in /incubator/syncope/trunk: ./ build-tools/src/main/resources/org/apache/syncope/ client/src/main/java/org/apache/syncope/client/mod/ client/src/main/java/org/apache/syncope/client/to/ client/src/main/java/org/apache/synco...

Author: ilgrosso
Date: Thu Oct 25 16:17:52 2012
New Revision: 1402206

URL: http://svn.apache.org/viewvc?rev=1402206&view=rev
Log:
[SYNCOPE-225] All features implemented in core, now it's time to update the admin console

Added:
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeRoleCheck.java
      - copied, changed from r1401988, incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeUserCheck.java
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeRoleValidator.java
      - copied, changed from r1401988, incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeUserValidator.java
Modified:
    incubator/syncope/trunk/   (props changed)
    incubator/syncope/trunk/build-tools/src/main/resources/org/apache/syncope/pmd.xml
    incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/mod/RoleMod.java
    incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/to/RoleTO.java
    incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/util/AttributableOperations.java
    incubator/syncope/trunk/client/src/main/java/org/apache/syncope/types/EntityViolationType.java
    incubator/syncope/trunk/core/pom.xml
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/beans/role/SyncopeRole.java
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/dao/RoleDAO.java
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/RoleDAOImpl.java
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/policy/PasswordPolicyEnforcer.java
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/controller/AuthenticationController.java
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/controller/RoleController.java
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/data/RoleDataBinder.java
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/EncodePasswordCLI.java
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/PasswordEncoder.java
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/SyncopeAuthenticationProvider.java
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/SyncopeUserDetailsService.java
    incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/util/EntitlementUtil.java
    incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/dao/RoleTest.java
    incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/dao/UserTest.java
    incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/relationships/RoleTest.java
    incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/rest/AuthenticationTestITCase.java
    incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/rest/RoleTestITCase.java
    incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/rest/UserTestITCase.java
    incubator/syncope/trunk/core/src/test/resources/content.xml

Propchange: incubator/syncope/trunk/
------------------------------------------------------------------------------
  Merged /incubator/syncope/branches/1_0_X:r1400926-1402200

Modified: incubator/syncope/trunk/build-tools/src/main/resources/org/apache/syncope/pmd.xml
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/build-tools/src/main/resources/org/apache/syncope/pmd.xml?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/build-tools/src/main/resources/org/apache/syncope/pmd.xml (original)
+++ incubator/syncope/trunk/build-tools/src/main/resources/org/apache/syncope/pmd.xml Thu Oct 25 16:17:52 2012
@@ -32,7 +32,9 @@ under the License.
   <rule ref="rulesets/unusedcode.xml"/>
   <rule ref="rulesets/design.xml"/>
   <rule ref="rulesets/imports.xml"/>
-  <rule ref="rulesets/strings.xml"/>
+  <rule ref="rulesets/strings.xml">
+    <exclude name="AvoidDuplicateLiterals"/>
+  </rule>
   <rule ref="rulesets/codesize.xml"/>
   <rule ref="rulesets/javabeans.xml">
     <exclude name="BeanMembersShouldSerialize"/>
@@ -40,6 +42,7 @@ under the License.
   <rule ref="rulesets/coupling.xml"/>
   <rule ref="rulesets/controversial.xml">
     <exclude name="NullAssignment"/>
+    <exclude name="DataflowAnomalyAnalysis"/>
   </rule>
   <rule ref="rulesets/strictexception.xml"/>
   <rule ref="rulesets/typeresolution.xml"/>

Modified: incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/mod/RoleMod.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/mod/RoleMod.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/mod/RoleMod.java (original)
+++ incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/mod/RoleMod.java Thu Oct 25 16:17:52 2012
@@ -18,7 +18,6 @@
  */
 package org.apache.syncope.client.mod;
 
-import java.util.ArrayList;
 import java.util.List;
 import org.codehaus.jackson.annotate.JsonIgnore;
 
@@ -28,6 +27,12 @@ public class RoleMod extends AbstractAtt
 
     private String name;
 
+    private ReferenceMod userOwner;
+
+    private ReferenceMod roleOwner;
+
+    private Boolean inheritOwner;
+
     private Boolean inheritAttributes;
 
     private Boolean inheritDerivedAttributes;
@@ -44,10 +49,36 @@ public class RoleMod extends AbstractAtt
 
     private ReferenceMod accountPolicy;
 
-    public RoleMod() {
-        super();
+    public String getName() {
+        return name;
+    }
+
+    public void setName(final String name) {
+        this.name = name;
+    }
+
+    public ReferenceMod getUserOwner() {
+        return userOwner;
+    }
+
+    public void setUserOwner(ReferenceMod userOwner) {
+        this.userOwner = userOwner;
+    }
+
+    public ReferenceMod getRoleOwner() {
+        return roleOwner;
+    }
+
+    public void setRoleOwner(ReferenceMod roleOwner) {
+        this.roleOwner = roleOwner;
+    }
+
+    public Boolean getInheritOwner() {
+        return inheritOwner;
+    }
 
-        entitlements = new ArrayList<String>();
+    public void setInheritOwner(Boolean inheritOwner) {
+        this.inheritOwner = inheritOwner;
     }
 
     public Boolean getInheritAttributes() {
@@ -74,31 +105,12 @@ public class RoleMod extends AbstractAtt
         this.inheritVirtualAttributes = inheritVirtualAttributes;
     }
 
-    public String getName() {
-        return name;
-    }
-
-    public void setName(final String name) {
-        this.name = name;
-    }
-
-    public boolean addEntitlement(final String entitlement) {
-        return entitlements.add(entitlement);
-    }
-
-    public boolean removeEntitlement(final String entitlement) {
-        return entitlements.remove(entitlement);
-    }
-
     public List<String> getEntitlements() {
         return entitlements;
     }
 
     public void setEntitlements(final List<String> entitlements) {
-        this.entitlements.clear();
-        if (entitlements != null && !entitlements.isEmpty()) {
-            this.entitlements.addAll(entitlements);
-        }
+        this.entitlements = entitlements;
     }
 
     public ReferenceMod getPasswordPolicy() {

Modified: incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/to/RoleTO.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/to/RoleTO.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/to/RoleTO.java (original)
+++ incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/to/RoleTO.java Thu Oct 25 16:17:52 2012
@@ -22,7 +22,7 @@ import java.util.ArrayList;
 import java.util.List;
 import org.codehaus.jackson.annotate.JsonIgnoreProperties;
 
-@JsonIgnoreProperties( { "displayName", "empty" })
+@JsonIgnoreProperties({"displayName", "empty"})
 public class RoleTO extends AbstractAttributableTO {
 
     private static final long serialVersionUID = -7785920258290147542L;
@@ -31,6 +31,12 @@ public class RoleTO extends AbstractAttr
 
     private long parent;
 
+    private Long userOwner;
+
+    private Long roleOwner;
+
+    private boolean inheritOwner;
+
     private boolean inheritAttributes;
 
     private boolean inheritDerivedAttributes;
@@ -67,6 +73,30 @@ public class RoleTO extends AbstractAttr
         this.parent = parent;
     }
 
+    public Long getUserOwner() {
+        return userOwner;
+    }
+
+    public void setUserOwner(final Long userOwner) {
+        this.userOwner = userOwner;
+    }
+
+    public Long getRoleOwner() {
+        return roleOwner;
+    }
+
+    public void setRoleOwner(final Long roleOwner) {
+        this.roleOwner = roleOwner;
+    }
+
+    public boolean isInheritOwner() {
+        return inheritOwner;
+    }
+
+    public void setInheritOwner(final boolean inheritOwner) {
+        this.inheritOwner = inheritOwner;
+    }
+
     public boolean isInheritAttributes() {
         return inheritAttributes;
     }

Modified: incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/util/AttributableOperations.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/util/AttributableOperations.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/util/AttributableOperations.java (original)
+++ incubator/syncope/trunk/client/src/main/java/org/apache/syncope/client/util/AttributableOperations.java Thu Oct 25 16:17:52 2012
@@ -306,7 +306,9 @@ public final class AttributableOperation
         // 4. entitlements
         Set<String> updatedEnts = new HashSet<String>(updated.getEntitlements());
         Set<String> originalEnts = new HashSet<String>(original.getEntitlements());
-        if (!updatedEnts.equals(originalEnts)) {
+        if (updatedEnts.equals(originalEnts)) {
+            result.setEntitlements(null);
+        } else {
             result.setEntitlements(updated.getEntitlements());
         }
 

Modified: incubator/syncope/trunk/client/src/main/java/org/apache/syncope/types/EntityViolationType.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/client/src/main/java/org/apache/syncope/types/EntityViolationType.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/client/src/main/java/org/apache/syncope/types/EntityViolationType.java (original)
+++ incubator/syncope/trunk/client/src/main/java/org/apache/syncope/types/EntityViolationType.java Thu Oct 25 16:17:52 2012
@@ -21,34 +21,34 @@ package org.apache.syncope.types;
 public enum EntityViolationType {
 
     Standard(""),
+    InvalidAccountPolicy("org.apache.syncope.core.validation.accountpolicy"),
+    InvalidEntitlementName("org.apache.syncope.core.validation.entitlement.name"),
+    InvalidMSchema("org.apache.syncope.core.validation.attrvalue.mSchema"),
+    InvalidMDerSchema("org.apache.syncope.core.validation.attrvalue.mDerSchema"),
+    InvalidMVirSchema("org.apache.syncope.core.validation.attrvalue.mVirSchema"),
+    InvalidNotification("org.apache.syncope.core.validation.notification"),
+    InvalidPassword("org.apache.syncope.core.validation.syncopeuser.password"),
+    InvalidPasswordPolicy("org.apache.syncope.core.validation.passwordpolicy"),
+    InvalidPolicy("org.apache.syncope.core.validation.policy"),
+    InvalidPropagationTask("org.apache.syncope.core.validation.propagationtask"),
+    InvalidRSchema("org.apache.syncope.core.validation.attrvalue.rSchema"),
+    InvalidRDerSchema("org.apache.syncope.core.validation.attrvalue.rDerSchema"),
+    InvalidRVirSchema("org.apache.syncope.core.validation.attrvalue.rVirSchema"),
+    InvalidReport("org.apache.syncope.core.validation.report"),
+    InvalidResource("org.apache.syncope.core.validation.externalresource"),
+    InvalidRoleOwner("org.apache.syncope.core.validation.syncoperole.owner"),
+    InvalidSchemaTypeSpecification("org.apache.syncope.core.validation.attrvalue.schemaTypeSpecification"),
+    InvalidSchedTask("org.apache.syncope.core.validation.schedtask"),
+    InvalidSyncTask("org.apache.syncope.core.validation.synctask"),
+    InvalidSchemaMapping("org.apache.syncope.core.validation.mapping"),
+    InvalidSyncPolicy("org.apache.syncope.core.validation.syncpolicy"),
+    InvalidUSchema("org.apache.syncope.core.validation.attrvalue.uSchema"),
+    InvalidUDerSchema("org.apache.syncope.core.validation.attrvalue.derSchema"),
+    InvalidUVirSchema("org.apache.syncope.core.validation.attrvalue.uVirSchema"),
+    InvalidUsername("org.apache.syncope.core.validation.syncopeuser.username"),
+    InvalidValueList("org.apache.syncope.core.validation.attr.valueList"),
     MultivalueAndUniqueConstraint("org.apache.syncope.core.validation.schema.multivalueAndUniqueConstraint"),
-    MoreThanOneNonNull("org.apache.syncope.core.validation.attrvalue.moreThanOneNonNull"),
-    InvalidUSchema("org.apache.syncope.core.validation.attrvalue.invalidUSchema"),
-    InvalidUDerSchema("org.apache.syncope.core.validation.attrvalue.invalidUDerSchema"),
-    InvalidUVirSchema("org.apache.syncope.core.validation.attrvalue.invalidUVirSchema"),
-    InvalidRSchema("org.apache.syncope.core.validation.attrvalue.invalidRSchema"),
-    InvalidRDerSchema("org.apache.syncope.core.validation.attrvalue.invalidRDerSchema"),
-    InvalidRVirSchema("org.apache.syncope.core.validation.attrvalue.invalidRVirSchema"),
-    InvalidMSchema("org.apache.syncope.core.validation.attrvalue.invalidMSchema"),
-    InvalidMDerSchema("org.apache.syncope.core.validation.attrvalue.invalidMDerSchema"),
-    InvalidMVirSchema("org.apache.syncope.core.validation.attrvalue.invalidMVirSchema"),
-    InvalidSchemaTypeSpecification("org.apache.syncope.core.validation.attrvalue.invalidSchemaTypeSpecification"),
-    InvalidValueList("org.apache.syncope.core.validation.attr.invalidValueList"),
-    InvalidEntitlementName("org.apache.syncope.core.validation.entitlement.invalidName"),
-    InvalidPropagationTask("org.apache.syncope.core.validation.propagationtask.invalid"),
-    InvalidResource("org.apache.syncope.core.validation.externalresource.invalid"),
-    InvalidSchedTask("org.apache.syncope.core.validation.schedtask.invalid"),
-    InvalidSyncTask("org.apache.syncope.core.validation.synctask.invalid"),
-    InvalidPassword("org.apache.syncope.core.validation.password.invalid"),
-    InvalidUsername("org.apache.syncope.core.validation.username.invalid"),
-    // not throwable using rest interface because the TO is typed
-    InvalidPolicy("org.apache.syncope.core.validation.policy.invalid"),
-    InvalidPasswordPolicy("org.apache.syncope.core.validation.policy.invalid"),
-    InvalidAccountPolicy("org.apache.syncope.core.validation.policy.invalid"),
-    InvalidSyncPolicy("org.apache.syncope.core.validation.policy.invalid"),
-    InvalidNotification("org.apache.syncope.core.validation.notification.invalid"),
-    InvalidReport("org.apache.syncope.core.validation.report.invalid"),
-    InvalidSchemaMapping("org.apache.syncope.core.validation.mapping.invalid");
+    MoreThanOneNonNull("org.apache.syncope.core.validation.attrvalue.moreThanOneNonNull");
 
     private String message;
 

Modified: incubator/syncope/trunk/core/pom.xml
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/pom.xml?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/pom.xml (original)
+++ incubator/syncope/trunk/core/pom.xml Thu Oct 25 16:17:52 2012
@@ -417,43 +417,6 @@ under the License.
 
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
-        <artifactId>maven-surefire-plugin</artifactId>
-        <inherited>true</inherited>
-        <configuration>
-          <skip>true</skip>
-        </configuration>
-        <executions>
-          <execution>
-            <id>test-phase-execution</id>
-            <phase>test</phase>
-            <goals>
-              <goal>test</goal>
-            </goals>
-            <configuration>
-              <skip>false</skip>
-              <excludes>
-                <exclude>**/relationships/**Test.java</exclude>
-              </excludes>
-            </configuration>
-          </execution>
-          <execution>
-            <id>relationship-test-execution</id>
-            <phase>test</phase>
-            <goals>
-              <goal>test</goal>
-            </goals>
-            <configuration>
-              <skip>false</skip>
-              <includes>
-                <include>**/relationships/**Test.java</include>
-              </includes>
-            </configuration>
-          </execution>
-        </executions>
-      </plugin>
-
-      <plugin>
-        <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-failsafe-plugin</artifactId>
         <inherited>true</inherited>
         <executions>
@@ -718,7 +681,6 @@ under the License.
       <id>dev</id>
       <properties>
         <waitForCheck>true</waitForCheck>
-        <sureExcludes>**</sureExcludes>
         <javaagent />
       </properties>
       <build>
@@ -732,44 +694,6 @@ under the License.
             <configuration>
               <skip>true</skip>
             </configuration>
-            <executions>
-              <execution>
-                <id>test-phase-execution</id>
-                <phase>test</phase>
-                <goals>
-                  <goal>test</goal>
-                </goals>
-                <configuration>
-                  <skip>false</skip>
-                  <includes>
-                    <include>**/dao/**Test.java</include>
-                    <include>**/security/**Test.java</include>
-                  </includes>
-                  <excludes>
-                    <exclude>**/relationships/**Test.java</exclude>
-                    <exclude>${sureExcludes}</exclude>
-                  </excludes>
-                </configuration>
-              </execution>
-              <execution>
-                <id>relationship-test-execution</id>
-                <phase>test</phase>
-                <goals>
-                  <goal>test</goal>
-                </goals>
-                <configuration>
-                  <skip>false</skip>
-                  <includes>
-                    <include>**/relationships/**Test.java</include>
-                  </includes>
-                  <excludes>
-                    <exclude>**/dao/**Test.java</exclude>
-                    <exclude>**/security/**Test.java</exclude>
-                    <exclude>${sureExcludes}</exclude>
-                  </excludes>
-                </configuration>
-              </execution>
-            </executions>
           </plugin>
 
           <plugin>

Modified: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/beans/role/SyncopeRole.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/beans/role/SyncopeRole.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/beans/role/SyncopeRole.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/beans/role/SyncopeRole.java Thu Oct 25 16:17:52 2012
@@ -53,11 +53,14 @@ import org.apache.syncope.core.persisten
 import org.apache.syncope.core.persistence.beans.Entitlement;
 import org.apache.syncope.core.persistence.beans.ExternalResource;
 import org.apache.syncope.core.persistence.beans.PasswordPolicy;
+import org.apache.syncope.core.persistence.beans.user.SyncopeUser;
+import org.apache.syncope.core.persistence.validation.entity.SyncopeRoleCheck;
 
 @Entity
 @Table(uniqueConstraints =
 @UniqueConstraint(columnNames = {"name", "parent_id"}))
 @Cacheable
+@SyncopeRoleCheck
 public class SyncopeRole extends AbstractAttributable {
 
     private static final long serialVersionUID = -5281258853142421875L;
@@ -71,6 +74,12 @@ public class SyncopeRole extends Abstrac
     @ManyToOne(optional = true)
     private SyncopeRole parent;
 
+    @ManyToOne(optional = true)
+    private SyncopeUser userOwner;
+
+    @ManyToOne(optional = true)
+    private SyncopeRole roleOwner;
+
     @ManyToMany(fetch = FetchType.EAGER)
     @JoinTable(joinColumns =
     @JoinColumn(name = "role_id"),
@@ -93,6 +102,11 @@ public class SyncopeRole extends Abstrac
     @Basic(optional = true)
     @Min(0)
     @Max(1)
+    private Integer inheritOwner;
+
+    @Basic(optional = true)
+    @Min(0)
+    @Max(1)
     private Integer inheritAttributes;
 
     @Basic(optional = true)
@@ -139,6 +153,7 @@ public class SyncopeRole extends Abstrac
         attributes = new ArrayList<RAttr>();
         derivedAttributes = new ArrayList<RDerAttr>();
         virtualAttributes = new ArrayList<RVirAttr>();
+        inheritOwner = getBooleanAsInteger(false);
         inheritAttributes = getBooleanAsInteger(false);
         inheritDerivedAttributes = getBooleanAsInteger(false);
         inheritVirtualAttributes = getBooleanAsInteger(false);
@@ -173,6 +188,30 @@ public class SyncopeRole extends Abstrac
         this.parent = parent;
     }
 
+    public boolean isInheritOwner() {
+        return isBooleanAsInteger(inheritOwner);
+    }
+
+    public void setInheritOwner(final boolean inheritOwner) {
+        this.inheritOwner = getBooleanAsInteger(inheritOwner);
+    }
+
+    public SyncopeUser getUserOwner() {
+        return userOwner;
+    }
+
+    public void setUserOwner(final SyncopeUser userOwner) {
+        this.userOwner = userOwner;
+    }
+
+    public SyncopeRole getRoleOwner() {
+        return roleOwner;
+    }
+
+    public void setRoleOwner(final SyncopeRole roleOwner) {
+        this.roleOwner = roleOwner;
+    }
+
     public boolean addEntitlement(final Entitlement entitlement) {
         return entitlements.add(entitlement);
     }

Modified: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/dao/RoleDAO.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/dao/RoleDAO.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/dao/RoleDAO.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/dao/RoleDAO.java Thu Oct 25 16:17:52 2012
@@ -23,6 +23,7 @@ import org.apache.syncope.core.persisten
 import org.apache.syncope.core.persistence.beans.ExternalResource;
 import org.apache.syncope.core.persistence.beans.membership.Membership;
 import org.apache.syncope.core.persistence.beans.role.SyncopeRole;
+import org.apache.syncope.core.persistence.beans.user.SyncopeUser;
 import org.apache.syncope.core.persistence.validation.entity.InvalidEntityException;
 
 public interface RoleDAO extends DAO {
@@ -33,13 +34,15 @@ public interface RoleDAO extends DAO {
 
     SyncopeRole find(String name, Long parent);
 
+    List<SyncopeRole> findOwned(SyncopeUser owner);
+
     List<SyncopeRole> findByEntitlement(final Entitlement entitlement);
 
     List<SyncopeRole> findByResource(ExternalResource resource);
 
     List<SyncopeRole> findAncestors(SyncopeRole role);
 
-    List<SyncopeRole> findChildren(Long roleId);
+    List<SyncopeRole> findChildren(SyncopeRole role);
 
     List<SyncopeRole> findDescendants(SyncopeRole role);
 

Modified: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/RoleDAOImpl.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/RoleDAOImpl.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/RoleDAOImpl.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/RoleDAOImpl.java Thu Oct 25 16:17:52 2012
@@ -27,6 +27,7 @@ import org.apache.syncope.core.persisten
 import org.apache.syncope.core.persistence.beans.ExternalResource;
 import org.apache.syncope.core.persistence.beans.membership.Membership;
 import org.apache.syncope.core.persistence.beans.role.SyncopeRole;
+import org.apache.syncope.core.persistence.beans.user.SyncopeUser;
 import org.apache.syncope.core.persistence.dao.EntitlementDAO;
 import org.apache.syncope.core.persistence.dao.RoleDAO;
 import org.apache.syncope.core.persistence.dao.UserDAO;
@@ -85,6 +86,40 @@ public class RoleDAOImpl extends Abstrac
                 : result.get(0);
     }
 
+    private void findSameOwnerDescendants(final List<SyncopeRole> result, final SyncopeRole role) {
+        List<SyncopeRole> children = findChildren(role);
+        if (children != null) {
+            for (SyncopeRole child : children) {
+                if ((child.getUserOwner() == null && child.getRoleOwner() == null && child.isInheritOwner())
+                        || (child.getUserOwner() != null && child.getUserOwner().equals(role.getUserOwner()))
+                        || (child.getRoleOwner() != null && child.getRoleOwner().equals(role.getRoleOwner()))) {
+
+                    findDescendants(result, child);
+                }
+            }
+        }
+        result.add(role);
+    }
+
+    @Override
+    public List<SyncopeRole> findOwned(final SyncopeUser owner) {
+        StringBuilder queryString = new StringBuilder("SELECT e FROM ").append(SyncopeRole.class.getSimpleName()).
+                append(" e WHERE e.userOwner=:owner ");
+        for (Long roleId : owner.getRoleIds()) {
+            queryString.append("OR e.roleOwner.id=").append(roleId).append(' ');
+        }
+
+        Query query = entityManager.createQuery(queryString.toString());
+        query.setParameter("owner", owner);
+
+        List<SyncopeRole> result = new ArrayList<SyncopeRole>();
+        for (SyncopeRole role : (List<SyncopeRole>) query.getResultList()) {
+            findSameOwnerDescendants(result, role);
+        }
+
+        return result;
+    }
+
     @Override
     public List<SyncopeRole> findByEntitlement(final Entitlement entitlement) {
         Query query = entityManager.createQuery("SELECT e FROM " + SyncopeRole.class.getSimpleName() + " e "
@@ -118,14 +153,14 @@ public class RoleDAOImpl extends Abstrac
     }
 
     @Override
-    public List<SyncopeRole> findChildren(final Long roleId) {
-        Query query = entityManager.createQuery("SELECT r FROM SyncopeRole r WHERE " + "r.parent.id=:roleId");
-        query.setParameter("roleId", roleId);
+    public List<SyncopeRole> findChildren(final SyncopeRole role) {
+        Query query = entityManager.createQuery("SELECT r FROM SyncopeRole r WHERE " + "r.parent=:role");
+        query.setParameter("role", role);
         return query.getResultList();
     }
 
     private void findDescendants(final List<SyncopeRole> result, final SyncopeRole role) {
-        List<SyncopeRole> children = findChildren(role.getId());
+        List<SyncopeRole> children = findChildren(role);
         if (children != null) {
             for (SyncopeRole child : children) {
                 findDescendants(result, child);
@@ -192,6 +227,8 @@ public class RoleDAOImpl extends Abstrac
             roleToBeDeleted.getEntitlements().clear();
 
             roleToBeDeleted.setParent(null);
+            roleToBeDeleted.setUserOwner(null);
+            roleToBeDeleted.setRoleOwner(null);
             entityManager.remove(roleToBeDeleted);
 
             entitlementDAO.delete(EntitlementUtil.getEntitlementNameFromRoleId(roleToBeDeleted.getId()));

Copied: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeRoleCheck.java (from r1401988, incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeUserCheck.java)
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeRoleCheck.java?p2=incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeRoleCheck.java&p1=incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeUserCheck.java&r1=1401988&r2=1402206&rev=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeUserCheck.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeRoleCheck.java Thu Oct 25 16:17:52 2012
@@ -26,13 +26,13 @@ import java.lang.annotation.Target;
 import javax.validation.Constraint;
 import javax.validation.Payload;
 
-@Target( { ElementType.TYPE })
+@Target({ElementType.TYPE})
 @Retention(RetentionPolicy.RUNTIME)
-@Constraint(validatedBy = SyncopeUserValidator.class)
+@Constraint(validatedBy = SyncopeRoleValidator.class)
 @Documented
-public @interface SyncopeUserCheck {
+public @interface SyncopeRoleCheck {
 
-    String message() default "{org.apache.syncope.core.validation.syncopeuser}";
+    String message() default "{org.apache.syncope.core.validation.syncoperole}";
 
     Class<?>[] groups() default {};
 

Copied: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeRoleValidator.java (from r1401988, incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeUserValidator.java)
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeRoleValidator.java?p2=incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeRoleValidator.java&p1=incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeUserValidator.java&r1=1401988&r2=1402206&rev=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeUserValidator.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/persistence/validation/entity/SyncopeRoleValidator.java Thu Oct 25 16:17:52 2012
@@ -18,171 +18,31 @@
  */
 package org.apache.syncope.core.persistence.validation.entity;
 
-import java.util.ArrayList;
-import java.util.List;
 import javax.validation.ConstraintValidator;
 import javax.validation.ConstraintValidatorContext;
-import org.apache.syncope.core.persistence.beans.AccountPolicy;
-import org.apache.syncope.core.persistence.beans.ExternalResource;
-import org.apache.syncope.core.persistence.beans.PasswordPolicy;
-import org.apache.syncope.core.persistence.beans.Policy;
 import org.apache.syncope.core.persistence.beans.role.SyncopeRole;
-import org.apache.syncope.core.persistence.beans.user.SyncopeUser;
-import org.apache.syncope.core.persistence.dao.PolicyDAO;
-import org.apache.syncope.core.policy.AccountPolicyEnforcer;
-import org.apache.syncope.core.policy.PasswordPolicyEnforcer;
-import org.apache.syncope.core.policy.PolicyEvaluator;
-import org.apache.syncope.types.AccountPolicySpec;
 import org.apache.syncope.types.EntityViolationType;
-import org.apache.syncope.types.PasswordPolicySpec;
-import org.springframework.beans.factory.annotation.Autowired;
 
-public class SyncopeUserValidator extends AbstractValidator implements
-        ConstraintValidator<SyncopeUserCheck, SyncopeUser> {
-
-    @Autowired
-    private PolicyDAO policyDAO;
-
-    @Autowired
-    private PolicyEvaluator evaluator;
-
-    @Autowired
-    private PasswordPolicyEnforcer ppEnforcer;
-
-    @Autowired
-    private AccountPolicyEnforcer apEnforcer;
+public class SyncopeRoleValidator extends AbstractValidator implements
+        ConstraintValidator<SyncopeRoleCheck, SyncopeRole> {
 
     @Override
-    public void initialize(final SyncopeUserCheck constraintAnnotation) {
+    public void initialize(final SyncopeRoleCheck constraintAnnotation) {
     }
 
     @Override
-    public boolean isValid(final SyncopeUser object, final ConstraintValidatorContext context) {
+    public boolean isValid(final SyncopeRole object, final ConstraintValidatorContext context) {
         context.disableDefaultConstraintViolation();
 
-        // ------------------------------
-        // Verify password policies
-        // ------------------------------
-        LOG.debug("Password Policy enforcement");
-
-        if (object.getClearPassword() != null) {
-            try {
-                int maxPPSpecHistory = 0;
-                for (Policy policy : getPasswordPolicies(object)) {
-                    // evaluate policy
-                    final PasswordPolicySpec ppSpec = evaluator.evaluate(policy, object);
-                    // enforce policy
-                    ppEnforcer.enforce(ppSpec, policy.getType(), object.getClearPassword());
-
-                    if (ppSpec.getHistoryLength() > maxPPSpecHistory) {
-                        maxPPSpecHistory = ppSpec.getHistoryLength();
-                    }
-                }
-
-                // update user's password history with encrypted password
-                if (maxPPSpecHistory > 0 && object.getPassword() != null) {
-                    object.getPasswordHistory().add(object.getPassword());
-                }
-                // keep only the last maxPPSpecHistory items in user's password history
-                if (maxPPSpecHistory < object.getPasswordHistory().size()) {
-                    for (int i = 0; i < object.getPasswordHistory().size() - maxPPSpecHistory; i++) {
-                        object.getPasswordHistory().remove(i);
-                    }
-                }
-            } catch (Exception e) {
-                LOG.debug("Invalid password");
-
-                context.buildConstraintViolationWithTemplate(e.getMessage()).addNode(
-                        EntityViolationType.InvalidPassword.toString()).addConstraintViolation();
-
-                return false;
-            } finally {
-                // password has been validated, let's remove its clear version
-                object.removeClearPassword();
-            }
-        }
-        // ------------------------------
-
-        // ------------------------------
-        // Verify account policies
-        // ------------------------------
-        LOG.debug("Account Policy enforcement");
-
-        try {
-            // missing username
-            for (Policy policy : getAccountPolicies(object)) {
-                // evaluate policy
-                final AccountPolicySpec accountPolicy = evaluator.evaluate(policy, object);
-
-                // enforce policy
-                apEnforcer.enforce(accountPolicy, policy.getType(), object);
-            }
-        } catch (Exception e) {
-            LOG.debug("Invalid username");
-
-            context.buildConstraintViolationWithTemplate(e.getMessage()).addNode(
-                    EntityViolationType.InvalidUsername.toString()).addConstraintViolation();
-
-            return false;
-        }
-        // ------------------------------
-
-        return true;
-    }
-
-    private List<PasswordPolicy> getPasswordPolicies(final SyncopeUser user) {
-        final List<PasswordPolicy> policies = new ArrayList<PasswordPolicy>();
+        boolean isValid = true;
 
-        // Add global policy
-        PasswordPolicy policy = policyDAO.getGlobalPasswordPolicy();
-        if (policy != null) {
-            policies.add(policy);
-        }
-
-        // add resource policies
-        for (ExternalResource resource : user.getResources()) {
-            policy = resource.getPasswordPolicy();
-            if (policy != null) {
-                policies.add(policy);
-            }
-        }
-
-        // add role policies
-        for (SyncopeRole role : user.getRoles()) {
-            policy = role.getPasswordPolicy();
-            if (policy != null) {
-                policies.add(policy);
-            }
-        }
-
-        return policies;
-    }
-
-    private List<AccountPolicy> getAccountPolicies(final SyncopeUser user) {
-        final List<AccountPolicy> policies = new ArrayList<AccountPolicy>();
-
-        // Add global policy
-        AccountPolicy policy = policyDAO.getGlobalAccountPolicy();
-        if (policy != null) {
-            policies.add(policy);
-        }
-
-        // add resource policies
-        for (ExternalResource resource : user.getResources()) {
-            policy = resource.getAccountPolicy();
-            if (policy != null) {
-                policies.add(policy);
-            }
-        }
+        if (object.getUserOwner() != null && object.getRoleOwner() != null) {
+            isValid = false;
 
-        // add role policies
-        for (SyncopeRole role : user.getRoles()) {
-            policy = role.getAccountPolicy();
-            if (policy != null) {
-                policies.add(policy);
-            }
+            context.buildConstraintViolationWithTemplate("A role must either be owned by an user or a role, not both").
+                    addNode(EntityViolationType.InvalidRoleOwner.toString()).addConstraintViolation();
         }
 
-        return policies;
+        return isValid;
     }
 }

Modified: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/policy/PasswordPolicyEnforcer.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/policy/PasswordPolicyEnforcer.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/policy/PasswordPolicyEnforcer.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/policy/PasswordPolicyEnforcer.java Thu Oct 25 16:17:52 2012
@@ -147,47 +147,47 @@ public class PasswordPolicyEnforcer exte
         }
     }
 
-    private boolean checkForDigit(String str) {
-        return PolicyPattern.DIGIT.matcher((CharSequence) str).matches();
+    private boolean checkForDigit(final String str) {
+        return PolicyPattern.DIGIT.matcher(str).matches();
     }
 
-    private boolean checkForLowercase(String str) {
-        return PolicyPattern.ALPHA_LOWERCASE.matcher((CharSequence) str).matches();
+    private boolean checkForLowercase(final String str) {
+        return PolicyPattern.ALPHA_LOWERCASE.matcher(str).matches();
     }
 
-    private boolean checkForUppercase(String str) {
-        return PolicyPattern.ALPHA_UPPERCASE.matcher((CharSequence) str).matches();
+    private boolean checkForUppercase(final String str) {
+        return PolicyPattern.ALPHA_UPPERCASE.matcher(str).matches();
     }
 
-    private boolean checkForFirstDigit(String str) {
-        return PolicyPattern.FIRST_DIGIT.matcher((CharSequence) str).matches();
+    private boolean checkForFirstDigit(final String str) {
+        return PolicyPattern.FIRST_DIGIT.matcher(str).matches();
     }
 
-    private boolean checkForLastDigit(String str) {
-        return PolicyPattern.LAST_DIGIT.matcher((CharSequence) str).matches();
+    private boolean checkForLastDigit(final String str) {
+        return PolicyPattern.LAST_DIGIT.matcher(str).matches();
     }
 
-    private boolean checkForAlphanumeric(String str) {
+    private boolean checkForAlphanumeric(final String str) {
         return PolicyPattern.ALPHANUMERIC.matcher(str).matches();
     }
 
-    private boolean checkForFirstAlphanumeric(String str) {
+    private boolean checkForFirstAlphanumeric(final String str) {
         return PolicyPattern.FIRST_ALPHANUMERIC.matcher(str).matches();
     }
 
-    private boolean checkForLastAlphanumeric(String str) {
+    private boolean checkForLastAlphanumeric(final String str) {
         return PolicyPattern.LAST_ALPHANUMERIC.matcher(str).matches();
     }
 
-    private boolean checkForNonAlphanumeric(String str) {
+    private boolean checkForNonAlphanumeric(final String str) {
         return PolicyPattern.NON_ALPHANUMERIC.matcher(str).matches();
     }
 
-    private boolean checkForFirstNonAlphanumeric(String str) {
+    private boolean checkForFirstNonAlphanumeric(final String str) {
         return PolicyPattern.FIRST_NON_ALPHANUMERIC.matcher(str).matches();
     }
 
-    private boolean checkForLastNonAlphanumeric(String str) {
+    private boolean checkForLastNonAlphanumeric(final String str) {
         return PolicyPattern.LAST_NON_ALPHANUMERIC.matcher(str).matches();
     }
 }

Modified: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/controller/AuthenticationController.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/controller/AuthenticationController.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/controller/AuthenticationController.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/controller/AuthenticationController.java Thu Oct 25 16:17:52 2012
@@ -21,10 +21,6 @@ package org.apache.syncope.core.rest.con
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Set;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
 import org.apache.syncope.core.audit.AuditManager;
 import org.apache.syncope.core.persistence.beans.Entitlement;
 import org.apache.syncope.core.persistence.dao.EntitlementDAO;
@@ -32,6 +28,10 @@ import org.apache.syncope.core.util.Enti
 import org.apache.syncope.types.AuditElements.AuthenticationSubCategory;
 import org.apache.syncope.types.AuditElements.Category;
 import org.apache.syncope.types.AuditElements.Result;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
 
 @Controller
 @RequestMapping("/auth")

Modified: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/controller/RoleController.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/controller/RoleController.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/controller/RoleController.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/controller/RoleController.java Thu Oct 25 16:17:52 2012
@@ -60,66 +60,51 @@ public class RoleController extends Abst
     private UserDAO userDAO;
 
     @Autowired
-    private RoleDataBinder roleDataBinder;
+    private RoleDataBinder dataBinder;
 
-    @PreAuthorize("hasRole('ROLE_CREATE')")
-    @RequestMapping(method = RequestMethod.POST, value = "/create")
-    public RoleTO create(final HttpServletResponse response, @RequestBody final RoleTO roleTO)
-            throws SyncopeClientCompositeErrorException, UnauthorizedRoleException {
+    @PreAuthorize("hasRole('ROLE_READ')")
+    @RequestMapping(method = RequestMethod.GET, value = "/read/{roleId}")
+    @Transactional(readOnly = true)
+    public RoleTO read(@PathVariable("roleId") final Long roleId)
+            throws NotFoundException, UnauthorizedRoleException {
 
-        LOG.debug("Role create called with parameters {}", roleTO);
+        SyncopeRole role = dataBinder.getSyncopeRole(roleId);
 
         Set<Long> allowedRoleIds = EntitlementUtil.getRoleIds(EntitlementUtil.getOwnedEntitlementNames());
-        if (roleTO.getParent() != 0 && !allowedRoleIds.contains(roleTO.getParent())) {
-            throw new UnauthorizedRoleException(roleTO.getParent());
+        if (!allowedRoleIds.contains(role.getId())) {
+            throw new UnauthorizedRoleException(role.getId());
         }
 
-        SyncopeRole role = roleDAO.save(roleDataBinder.create(roleTO));
-
-        auditManager.audit(Category.role, RoleSubCategory.create, Result.success,
-                "Successfully created role: " + role.getId());
+        auditManager.audit(Category.role, RoleSubCategory.read, Result.success,
+                "Successfully read role: " + role.getId());
 
-        response.setStatus(HttpServletResponse.SC_CREATED);
-        return roleDataBinder.getRoleTO(role);
+        return dataBinder.getRoleTO(role);
     }
 
-    @PreAuthorize("hasRole('ROLE_DELETE')")
-    @RequestMapping(method = RequestMethod.GET, value = "/delete/{roleId}")
-    public RoleTO delete(@PathVariable("roleId") final Long roleId) throws NotFoundException, UnauthorizedRoleException {
+    @PreAuthorize("isAuthenticated()")
+    @RequestMapping(method = RequestMethod.GET, value = "/selfRead/{roleId}")
+    @Transactional(readOnly = true)
+    public RoleTO selfRead(@PathVariable("roleId") final Long roleId)
+            throws NotFoundException, UnauthorizedRoleException {
 
-        SyncopeRole role = roleDAO.find(roleId);
-        if (role == null) {
-            throw new NotFoundException("Role " + roleId);
+        SyncopeRole role = dataBinder.getSyncopeRole(roleId);
+
+        SyncopeUser authUser = userDAO.find(SecurityContextHolder.getContext().getAuthentication().getName());
+        if (authUser == null) {
+            throw new NotFoundException("Authenticated user "
+                    + SecurityContextHolder.getContext().getAuthentication().getName());
         }
-        
-        RoleTO roleToDelete = roleDataBinder.getRoleTO(role);
 
         Set<Long> allowedRoleIds = EntitlementUtil.getRoleIds(EntitlementUtil.getOwnedEntitlementNames());
+        allowedRoleIds.addAll(authUser.getRoleIds());
         if (!allowedRoleIds.contains(role.getId())) {
             throw new UnauthorizedRoleException(role.getId());
         }
 
-        auditManager.audit(Category.role, RoleSubCategory.delete, Result.success,
-                "Successfully deleted role: " + role.getId());
-
-        roleDAO.delete(roleId);
-        
-        return roleToDelete;
-    }
-
-    @RequestMapping(method = RequestMethod.GET, value = "/list")
-    @Transactional(readOnly = true)
-    public List<RoleTO> list() {
-        List<SyncopeRole> roles = roleDAO.findAll();
-        List<RoleTO> roleTOs = new ArrayList<RoleTO>();
-        for (SyncopeRole role : roles) {
-            roleTOs.add(roleDataBinder.getRoleTO(role));
-        }
-
-        auditManager.audit(Category.role, RoleSubCategory.list, Result.success,
-                "Successfully listed all roles: " + roleTOs.size());
+        auditManager.audit(Category.role, RoleSubCategory.selfRead, Result.success,
+                "Successfully read own role: " + role.getId());
 
-        return roleTOs;
+        return dataBinder.getRoleTO(role);
     }
 
     @PreAuthorize("hasRole('ROLE_READ')")
@@ -128,10 +113,7 @@ public class RoleController extends Abst
     public RoleTO parent(@PathVariable("roleId") final Long roleId)
             throws NotFoundException, UnauthorizedRoleException {
 
-        SyncopeRole role = roleDAO.find(roleId);
-        if (role == null) {
-            throw new NotFoundException("Role " + roleId);
-        }
+        SyncopeRole role = dataBinder.getSyncopeRole(roleId);
 
         Set<Long> allowedRoleIds = EntitlementUtil.getRoleIds(EntitlementUtil.getOwnedEntitlementNames());
         if (role.getParent() != null && !allowedRoleIds.contains(role.getParent().getId())) {
@@ -140,7 +122,7 @@ public class RoleController extends Abst
 
         RoleTO result = role.getParent() == null
                 ? null
-                : roleDataBinder.getRoleTO(role.getParent());
+                : dataBinder.getRoleTO(role.getParent());
 
         auditManager.audit(Category.role, RoleSubCategory.parent, Result.success,
                 result == null
@@ -153,95 +135,99 @@ public class RoleController extends Abst
     @PreAuthorize("hasRole('ROLE_READ')")
     @RequestMapping(method = RequestMethod.GET, value = "/children/{roleId}")
     @Transactional(readOnly = true)
-    public List<RoleTO> children(@PathVariable("roleId") final Long roleId) {
+    public List<RoleTO> children(@PathVariable("roleId") final Long roleId) throws NotFoundException {
+        SyncopeRole role = dataBinder.getSyncopeRole(roleId);
+
         Set<Long> allowedRoleIds = EntitlementUtil.getRoleIds(EntitlementUtil.getOwnedEntitlementNames());
 
-        List<SyncopeRole> roles = roleDAO.findChildren(roleId);
-        List<RoleTO> roleTOs = new ArrayList<RoleTO>(roles.size());
-        for (SyncopeRole role : roles) {
-            if (allowedRoleIds.contains(role.getId())) {
-                roleTOs.add(roleDataBinder.getRoleTO(role));
+        List<SyncopeRole> children = roleDAO.findChildren(role);
+        List<RoleTO> childrenTOs = new ArrayList<RoleTO>(children.size());
+        for (SyncopeRole child : children) {
+            if (allowedRoleIds.contains(child.getId())) {
+                childrenTOs.add(dataBinder.getRoleTO(child));
             }
         }
 
         auditManager.audit(Category.role, RoleSubCategory.children, Result.success,
-                "Found " + roleTOs.size() + " children of role " + roleId);
+                "Found " + childrenTOs.size() + " children of role " + roleId);
 
-        return roleTOs;
+        return childrenTOs;
     }
 
-    @PreAuthorize("hasRole('ROLE_READ')")
-    @RequestMapping(method = RequestMethod.GET, value = "/read/{roleId}")
+    @RequestMapping(method = RequestMethod.GET, value = "/list")
     @Transactional(readOnly = true)
-    public RoleTO read(@PathVariable("roleId") final Long roleId)
-            throws NotFoundException, UnauthorizedRoleException {
-
-        SyncopeRole role = roleDAO.find(roleId);
-        if (role == null) {
-            throw new NotFoundException("Role " + roleId);
-        }
-
-        Set<Long> allowedRoleIds = EntitlementUtil.getRoleIds(EntitlementUtil.getOwnedEntitlementNames());
-        if (!allowedRoleIds.contains(role.getId())) {
-            throw new UnauthorizedRoleException(role.getId());
+    public List<RoleTO> list() {
+        List<SyncopeRole> roles = roleDAO.findAll();
+        List<RoleTO> roleTOs = new ArrayList<RoleTO>(roles.size());
+        for (SyncopeRole role : roles) {
+            roleTOs.add(dataBinder.getRoleTO(role));
         }
 
-        auditManager.audit(Category.role, RoleSubCategory.read, Result.success,
-                "Successfully read role: " + role.getId());
+        auditManager.audit(Category.role, RoleSubCategory.list, Result.success,
+                "Successfully listed all roles: " + roleTOs.size());
 
-        return roleDataBinder.getRoleTO(role);
+        return roleTOs;
     }
 
-    @PreAuthorize("isAuthenticated()")
-    @RequestMapping(method = RequestMethod.GET, value = "/selfRead/{roleId}")
-    @Transactional(readOnly = true)
-    public RoleTO selfRead(@PathVariable("roleId") final Long roleId)
-            throws NotFoundException, UnauthorizedRoleException {
+    @PreAuthorize("hasRole('ROLE_CREATE')")
+    @RequestMapping(method = RequestMethod.POST, value = "/create")
+    public RoleTO create(final HttpServletResponse response, @RequestBody final RoleTO roleTO)
+            throws SyncopeClientCompositeErrorException, UnauthorizedRoleException {
 
-        SyncopeRole role = roleDAO.find(roleId);
-        if (role == null) {
-            throw new NotFoundException("Role " + roleId);
-        }
-        SyncopeUser authUser = userDAO.find(SecurityContextHolder.getContext().getAuthentication().getName());
-        if (authUser == null) {
-            throw new NotFoundException("Authenticated user "
-                    + SecurityContextHolder.getContext().getAuthentication().getName());
-        }
+        LOG.debug("Role create called with parameters {}", roleTO);
 
         Set<Long> allowedRoleIds = EntitlementUtil.getRoleIds(EntitlementUtil.getOwnedEntitlementNames());
-        allowedRoleIds.addAll(authUser.getRoleIds());
-        if (!allowedRoleIds.contains(role.getId())) {
-            throw new UnauthorizedRoleException(role.getId());
+        if (roleTO.getParent() != 0 && !allowedRoleIds.contains(roleTO.getParent())) {
+            throw new UnauthorizedRoleException(roleTO.getParent());
         }
 
-        auditManager.audit(Category.role, RoleSubCategory.selfRead, Result.success,
-                "Successfully read own role: " + role.getId());
+        SyncopeRole role = roleDAO.save(dataBinder.create(roleTO));
+
+        auditManager.audit(Category.role, RoleSubCategory.create, Result.success,
+                "Successfully created role: " + role.getId());
 
-        return roleDataBinder.getRoleTO(role);
+        response.setStatus(HttpServletResponse.SC_CREATED);
+        return dataBinder.getRoleTO(role);
     }
 
     @PreAuthorize("hasRole('ROLE_UPDATE')")
     @RequestMapping(method = RequestMethod.POST, value = "/update")
     public RoleTO update(@RequestBody final RoleMod roleMod) throws NotFoundException, UnauthorizedRoleException {
-
         LOG.debug("Role update called with parameter {}", roleMod);
 
-        SyncopeRole role = roleDAO.find(roleMod.getId());
-        if (role == null) {
-            throw new NotFoundException("Role " + String.valueOf(roleMod.getId()));
-        }
+        SyncopeRole role = dataBinder.getSyncopeRole(roleMod.getId());
 
         Set<Long> allowedRoleIds = EntitlementUtil.getRoleIds(EntitlementUtil.getOwnedEntitlementNames());
         if (!allowedRoleIds.contains(role.getId())) {
             throw new UnauthorizedRoleException(role.getId());
         }
 
-        roleDataBinder.update(role, roleMod);
+        dataBinder.update(role, roleMod);
         role = roleDAO.save(role);
 
         auditManager.audit(Category.role, RoleSubCategory.update, Result.success,
                 "Successfully updated role: " + role.getId());
 
-        return roleDataBinder.getRoleTO(role);
+        return dataBinder.getRoleTO(role);
+    }
+
+    @PreAuthorize("hasRole('ROLE_DELETE')")
+    @RequestMapping(method = RequestMethod.GET, value = "/delete/{roleId}")
+    public RoleTO delete(@PathVariable("roleId") final Long roleId) throws NotFoundException, UnauthorizedRoleException {
+        SyncopeRole role = dataBinder.getSyncopeRole(roleId);
+
+        RoleTO roleToDelete = dataBinder.getRoleTO(role);
+
+        Set<Long> allowedRoleIds = EntitlementUtil.getRoleIds(EntitlementUtil.getOwnedEntitlementNames());
+        if (!allowedRoleIds.contains(role.getId())) {
+            throw new UnauthorizedRoleException(role.getId());
+        }
+
+        auditManager.audit(Category.role, RoleSubCategory.delete, Result.success,
+                "Successfully deleted role: " + role.getId());
+
+        roleDAO.delete(roleId);
+
+        return roleToDelete;
     }
 }

Modified: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/data/RoleDataBinder.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/data/RoleDataBinder.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/data/RoleDataBinder.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/rest/data/RoleDataBinder.java Thu Oct 25 16:17:52 2012
@@ -19,10 +19,6 @@
 package org.apache.syncope.core.rest.data;
 
 import java.util.List;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.apache.syncope.core.util.AttributableUtil;
-import org.springframework.http.HttpStatus;
-import org.springframework.stereotype.Component;
 import org.apache.syncope.client.mod.RoleMod;
 import org.apache.syncope.client.to.RoleTO;
 import org.apache.syncope.client.validation.SyncopeClientCompositeErrorException;
@@ -34,10 +30,16 @@ import org.apache.syncope.core.persisten
 import org.apache.syncope.core.persistence.beans.role.RDerAttr;
 import org.apache.syncope.core.persistence.beans.role.RVirAttr;
 import org.apache.syncope.core.persistence.beans.role.SyncopeRole;
+import org.apache.syncope.core.persistence.beans.user.SyncopeUser;
 import org.apache.syncope.core.persistence.dao.EntitlementDAO;
 import org.apache.syncope.core.propagation.PropagationByResource;
+import org.apache.syncope.core.util.AttributableUtil;
+import org.apache.syncope.core.util.NotFoundException;
 import org.apache.syncope.types.AttributableType;
 import org.apache.syncope.types.SyncopeClientExceptionType;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Component;
 
 @Component
 public class RoleDataBinder extends AbstractAttributableDataBinder {
@@ -45,9 +47,20 @@ public class RoleDataBinder extends Abst
     @Autowired
     private EntitlementDAO entitlementDAO;
 
-    public SyncopeRole create(final RoleTO roleTO) throws SyncopeClientCompositeErrorException {
+    public SyncopeRole getSyncopeRole(final Long roleId) throws NotFoundException {
+        SyncopeRole role = roleDAO.find(roleId);
+        if (role == null) {
+            throw new NotFoundException("Role " + roleId);
+        }
+
+        return role;
+    }
 
+    public SyncopeRole create(final RoleTO roleTO) throws SyncopeClientCompositeErrorException {
         SyncopeRole role = new SyncopeRole();
+
+        role.setInheritOwner(roleTO.isInheritOwner());
+
         role.setInheritAttributes(roleTO.isInheritAttributes());
         role.setInheritDerivedAttributes(roleTO.isInheritDerivedAttributes());
         role.setInheritVirtualAttributes(roleTO.isInheritVirtualAttributes());
@@ -101,98 +114,128 @@ public class RoleDataBinder extends Abst
             }
         }
 
-        role.setPasswordPolicy(roleTO.getPasswordPolicy() != null
-                ? (PasswordPolicy) policyDAO.find(roleTO.getPasswordPolicy())
-                : null);
-
-        role.setAccountPolicy(roleTO.getAccountPolicy() != null
-                ? (AccountPolicy) policyDAO.find(roleTO.getAccountPolicy())
-                : null);
+        // owner
+        if (roleTO.getUserOwner() != null) {
+            SyncopeUser owner = userDAO.find(roleTO.getUserOwner());
+            if (owner == null) {
+                LOG.warn("Ignoring invalid user specified as owner: {}", roleTO.getUserOwner());
+            } else {
+                role.setUserOwner(owner);
+            }
+        }
+        if (roleTO.getRoleOwner() != null) {
+            SyncopeRole owner = roleDAO.find(roleTO.getRoleOwner());
+            if (owner == null) {
+                LOG.warn("Ignoring invalid role specified as owner: {}", roleTO.getRoleOwner());
+            } else {
+                role.setRoleOwner(owner);
+            }
+        }
+
+        // policies
+        if (roleTO.getPasswordPolicy() != null) {
+            role.setPasswordPolicy((PasswordPolicy) policyDAO.find(roleTO.getPasswordPolicy()));
+        }
+        if (roleTO.getAccountPolicy() != null) {
+            role.setAccountPolicy((AccountPolicy) policyDAO.find(roleTO.getAccountPolicy()));
+        }
 
         return role;
     }
 
-    public PropagationByResource update(SyncopeRole role, RoleMod roleMod) throws SyncopeClientCompositeErrorException {
+    public PropagationByResource update(final SyncopeRole role, final RoleMod roleMod)
+            throws SyncopeClientCompositeErrorException {
 
         SyncopeClientCompositeErrorException scce = new SyncopeClientCompositeErrorException(HttpStatus.BAD_REQUEST);
 
         // name
         SyncopeClientException invalidRoles = new SyncopeClientException(SyncopeClientExceptionType.InvalidRoles);
         if (roleMod.getName() != null) {
-            SyncopeRole otherRole = roleDAO.find(roleMod.getName(), role.getParent() != null
-                    ? role.getParent().getId()
-                    : 0L);
-
-            if (otherRole != null) {
-                LOG.error("Another role exists with the same name " + "and the same parent role: " + otherRole);
+            SyncopeRole otherRole = roleDAO.find(roleMod.getName(),
+                    role.getParent() == null ? null : role.getParent().getId());
+            if (otherRole == null || role.equals(otherRole)) {
+                role.setName(roleMod.getName());
+            } else {
+                LOG.error("Another role exists with the same name and the same parent role: " + otherRole);
 
                 invalidRoles.addElement(roleMod.getName());
                 scce.addException(invalidRoles);
-            } else {
-                role.setName(roleMod.getName());
             }
         }
 
-        // inherited attributes
+        if (roleMod.getInheritOwner() != null) {
+            role.setInheritOwner(roleMod.getInheritOwner());
+        }
+
         if (roleMod.getInheritAttributes() != null) {
             role.setInheritAttributes(roleMod.getInheritAttributes());
         }
-
-        // inherited derived attributes
         if (roleMod.getInheritDerivedAttributes() != null) {
             role.setInheritDerivedAttributes(roleMod.getInheritDerivedAttributes());
         }
-
-        // inherited virtual attributes
         if (roleMod.getInheritVirtualAttributes() != null) {
             role.setInheritVirtualAttributes(roleMod.getInheritVirtualAttributes());
         }
 
-        // inherited password Policy
         if (roleMod.getInheritPasswordPolicy() != null) {
             role.setInheritPasswordPolicy(roleMod.getInheritPasswordPolicy());
         }
-
-        // inherited account Policy
         if (roleMod.getInheritAccountPolicy() != null) {
             role.setInheritAccountPolicy(roleMod.getInheritAccountPolicy());
         }
 
         // entitlements
-        role.getEntitlements().clear();
-        Entitlement entitlement;
-        for (String entitlementName : roleMod.getEntitlements()) {
-            entitlement = entitlementDAO.find(entitlementName);
-            if (entitlement == null) {
-                LOG.warn("Ignoring invalid entitlement {}", entitlementName);
-            } else {
-                role.addEntitlement(entitlement);
+        if (roleMod.getEntitlements() != null) {
+            role.getEntitlements().clear();
+            for (String entitlementName : roleMod.getEntitlements()) {
+                Entitlement entitlement = entitlementDAO.find(entitlementName);
+                if (entitlement == null) {
+                    LOG.warn("Ignoring invalid entitlement {}", entitlementName);
+                } else {
+                    role.addEntitlement(entitlement);
+                }
             }
         }
 
+        // policies
         if (roleMod.getPasswordPolicy() != null) {
-            role.setPasswordPolicy(roleMod.getPasswordPolicy().getId() != null
-                    ? (PasswordPolicy) policyDAO.find(roleMod.getPasswordPolicy().getId())
-                    : null);
+            role.setPasswordPolicy(roleMod.getPasswordPolicy().getId() == null
+                    ? null
+                    : (PasswordPolicy) policyDAO.find(roleMod.getPasswordPolicy().getId()));
         }
-
         if (roleMod.getAccountPolicy() != null) {
-            role.setAccountPolicy(roleMod.getAccountPolicy().getId() != null
-                    ? (AccountPolicy) policyDAO.find(roleMod.getAccountPolicy().getId())
-                    : null);
+            role.setAccountPolicy(roleMod.getAccountPolicy().getId() == null
+                    ? null
+                    : (AccountPolicy) policyDAO.find(roleMod.getAccountPolicy().getId()));
+        }
+
+        // owner
+        if (roleMod.getUserOwner() != null) {
+            role.setUserOwner(roleMod.getUserOwner().getId() == null
+                    ? null
+                    : userDAO.find(roleMod.getUserOwner().getId()));
+        }
+        if (roleMod.getRoleOwner() != null) {
+            role.setRoleOwner(roleMod.getRoleOwner().getId() == null
+                    ? null
+                    : roleDAO.find(roleMod.getRoleOwner().getId()));
         }
 
         // attributes, derived attributes, virtual attributes and resources
         return fill(role, roleMod, AttributableUtil.getInstance(AttributableType.ROLE), scce);
     }
 
-    public RoleTO getRoleTO(SyncopeRole role) {
+    public RoleTO getRoleTO(final SyncopeRole role) {
         RoleTO roleTO = new RoleTO();
         roleTO.setId(role.getId());
         roleTO.setName(role.getName());
+
+        roleTO.setInheritOwner(role.isInheritOwner());
+
         roleTO.setInheritAttributes(role.isInheritAttributes());
         roleTO.setInheritDerivedAttributes(role.isInheritDerivedAttributes());
         roleTO.setInheritVirtualAttributes(role.isInheritVirtualAttributes());
+
         roleTO.setInheritPasswordPolicy(role.isInheritPasswordPolicy());
         roleTO.setInheritAccountPolicy(role.isInheritAccountPolicy());
 
@@ -219,13 +262,12 @@ public class RoleDataBinder extends Abst
             roleTO.addEntitlement(entitlement.getName());
         }
 
-        roleTO.setPasswordPolicy(role.getPasswordPolicy() != null
-                ? role.getPasswordPolicy().getId()
-                : null);
-
-        roleTO.setAccountPolicy(role.getAccountPolicy() != null
-                ? role.getAccountPolicy().getId()
-                : null);
+        roleTO.setPasswordPolicy(role.getPasswordPolicy() == null
+                ? null
+                : role.getPasswordPolicy().getId());
+        roleTO.setAccountPolicy(role.getAccountPolicy() == null
+                ? null
+                : role.getAccountPolicy().getId());
 
         return roleTO;
     }

Modified: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/EncodePasswordCLI.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/EncodePasswordCLI.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/EncodePasswordCLI.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/EncodePasswordCLI.java Thu Oct 25 16:17:52 2012
@@ -22,25 +22,22 @@ import java.util.Arrays;
 import org.apache.syncope.types.CipherAlgorithm;
 
 /**
- * Command line version of encoder to encode the admin password
+ * Command line version of encoder to encode the admin password.
  */
-public class EncodePasswordCLI {
+public final class EncodePasswordCLI {
 
-    /**
-     * @param args
-     */
-    public static void main(String[] args)
+    public static void main(final String[] args)
             throws Exception {
 
         if (args.length != 2) {
             usage();
-            System.exit(0);
+            System.exit(1);
         }
 
         if (CipherAlgorithm.valueOf(args[1]).getAlgorithm().isEmpty()) {
-            System.out.println("Unsupported algorithm " + args[1]);
+            System.err.println("Unsupported algorithm " + args[1]);
             usage();
-            System.exit(0);
+            System.exit(2);
         }
 
         System.out.println("Encoding password '" + args[0] + "' with " + args[1]);
@@ -51,4 +48,7 @@ public class EncodePasswordCLI {
         System.out.println("Usage: EncodePassword <password> <algorithm>");
         System.out.println("Supported algorithms:" + Arrays.toString(CipherAlgorithm.values()));
     }
+
+    private EncodePasswordCLI() {
+    }
 }

Modified: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/PasswordEncoder.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/PasswordEncoder.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/PasswordEncoder.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/PasswordEncoder.java Thu Oct 25 16:17:52 2012
@@ -34,17 +34,9 @@ import org.slf4j.LoggerFactory;
 import org.springframework.security.crypto.bcrypt.BCrypt;
 import org.springframework.security.crypto.codec.Base64;
 
-/**
- * TODO: Description of the class.
- *
- * @author bl
- *
- * @since
- *
- */
-public class PasswordEncoder {
+public final class PasswordEncoder {
 
-    protected static final Logger LOG = LoggerFactory.getLogger(PasswordEncoder.class);
+    private static final Logger LOG = LoggerFactory.getLogger(PasswordEncoder.class);
 
     private static SecretKeySpec keySpec;
 
@@ -64,7 +56,6 @@ public class PasswordEncoder {
 
         if (password != null) {
             if (cipherAlgorithm == null || cipherAlgorithm == CipherAlgorithm.AES) {
-
                 final byte[] cleartext = password.getBytes("UTF8");
 
                 final Cipher cipher = Cipher.getInstance(CipherAlgorithm.AES.getAlgorithm());
@@ -83,7 +74,8 @@ public class PasswordEncoder {
         return encodedPassword;
     }
 
-    public static boolean verifyPassword(String password, CipherAlgorithm cipherAlgorithm, String digestedPassword) {
+    public static boolean verifyPassword(final String password, final CipherAlgorithm cipherAlgorithm,
+            final String digestedPassword) {
 
         boolean res = false;
 
@@ -111,7 +103,7 @@ public class PasswordEncoder {
         return res;
     }
 
-    private static StandardStringDigester getDigester(CipherAlgorithm cipherAlgorithm) {
+    private static StandardStringDigester getDigester(final CipherAlgorithm cipherAlgorithm) {
         StandardStringDigester digester = new StandardStringDigester();
 
         if (cipherAlgorithm.getAlgorithm().startsWith("S-")) {
@@ -124,10 +116,15 @@ public class PasswordEncoder {
             digester.setAlgorithm(cipherAlgorithm.getAlgorithm());
             digester.setIterations(1);
             digester.setSaltSizeBytes(0);
-
         }
 
         digester.setStringOutputType("hexadecimal");
         return digester;
     }
+
+    /**
+     * Private default constructor, for static-only classes.
+     */
+    private PasswordEncoder() {
+    }
 }

Modified: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/SyncopeAuthenticationProvider.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/SyncopeAuthenticationProvider.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/SyncopeAuthenticationProvider.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/SyncopeAuthenticationProvider.java Thu Oct 25 16:17:52 2012
@@ -148,15 +148,14 @@ public class SyncopeAuthenticationProvid
             auditManager.audit(Category.authentication, AuthenticationSubCategory.login, Result.success,
                     "Successfully authenticated, with roles: " + token.getAuthorities());
 
-            LOG.debug("User {} successfully authenticated, with roles {}", authentication.getPrincipal(), token.
-                    getAuthorities());
+            LOG.debug("User {} successfully authenticated, with roles {}",
+                    authentication.getPrincipal(), token.getAuthorities());
 
             if (user != null) {
                 user.setLastLoginDate(new Date());
                 user.setFailedLogins(0);
                 userDAO.save(user);
             }
-
         } else {
             if (user != null) {
                 user.setFailedLogins(user.getFailedLogins() + 1);

Modified: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/SyncopeUserDetailsService.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/SyncopeUserDetailsService.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/SyncopeUserDetailsService.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/security/SyncopeUserDetailsService.java Thu Oct 25 16:17:52 2012
@@ -19,6 +19,7 @@
 package org.apache.syncope.core.security;
 
 import java.util.HashSet;
+import java.util.List;
 import java.util.Set;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Configurable;
@@ -34,6 +35,7 @@ import org.apache.syncope.core.persisten
 import org.apache.syncope.core.persistence.dao.EntitlementDAO;
 import org.apache.syncope.core.persistence.dao.RoleDAO;
 import org.apache.syncope.core.persistence.dao.UserDAO;
+import org.apache.syncope.core.util.EntitlementUtil;
 
 @Configurable
 public class SyncopeUserDetailsService implements UserDetailsService {
@@ -59,8 +61,7 @@ public class SyncopeUserDetailsService i
 
     @Override
     public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException, DataAccessException {
-
-        Set<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
+        final Set<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
         if (adminUser.equals(username)) {
             for (Entitlement entitlement : entitlementDAO.findAll()) {
                 authorities.add(new SimpleGrantedAuthority(entitlement.getName()));
@@ -72,8 +73,8 @@ public class SyncopeUserDetailsService i
                 throw new UsernameNotFoundException("Could not find any user with id " + username);
             }
 
-            // Give entitlements based on roles owned by user, and their ancestors
-            Set<SyncopeRole> roles = new HashSet<SyncopeRole>(user.getRoles());
+            // Give entitlements based on roles assigned to user (and their ancestors)
+            final Set<SyncopeRole> roles = new HashSet<SyncopeRole>(user.getRoles());
             for (SyncopeRole role : user.getRoles()) {
                 roles.addAll(roleDAO.findAncestors(role));
             }
@@ -82,6 +83,19 @@ public class SyncopeUserDetailsService i
                     authorities.add(new SimpleGrantedAuthority(entitlement.getName()));
                 }
             }
+            // Give role operational entitlements for owned roles
+            List<SyncopeRole> ownedRoles = roleDAO.findOwned(user);
+            if (!ownedRoles.isEmpty()) {
+                authorities.add(new SimpleGrantedAuthority("ROLE_CREATE"));
+                authorities.add(new SimpleGrantedAuthority("ROLE_READ"));
+                authorities.add(new SimpleGrantedAuthority("ROLE_UPDATE"));
+                authorities.add(new SimpleGrantedAuthority("ROLE_DELETE"));
+
+                for (SyncopeRole role : ownedRoles) {
+                    authorities.add(new SimpleGrantedAuthority(EntitlementUtil.
+                            getEntitlementNameFromRoleId(role.getId())));
+                }
+            }
         }
 
         return new User(username, "<PASSWORD_PLACEHOLDER>", true, true, true, true, authorities);

Modified: incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/util/EntitlementUtil.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/util/EntitlementUtil.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/util/EntitlementUtil.java (original)
+++ incubator/syncope/trunk/core/src/main/java/org/apache/syncope/core/util/EntitlementUtil.java Thu Oct 25 16:17:52 2012
@@ -22,18 +22,21 @@ import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 import java.util.regex.Pattern;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.context.SecurityContext;
-import org.springframework.security.core.context.SecurityContextHolder;
 import org.apache.syncope.core.persistence.beans.Entitlement;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.context.SecurityContext;
+import org.springframework.security.core.context.SecurityContextHolder;
 
-public class EntitlementUtil {
+/**
+ * Utility class for manipulating entitlements.
+ */
+public final class EntitlementUtil {
 
     private static final Pattern ROLE_ENTITLEMENT_NAME_PATTERN = Pattern.compile("^ROLE_([\\d])+");
-    private static final Logger LOG = LoggerFactory.getLogger(EntitlementUtil.class);
 
+    private static final Logger LOG = LoggerFactory.getLogger(EntitlementUtil.class);
 
     public static Set<String> getOwnedEntitlementNames() {
         final Set<String> result = new HashSet<String>();
@@ -93,4 +96,10 @@ public class EntitlementUtil {
         }
         return getRoleIds(names);
     }
+
+    /**
+     * Private default constructor, for static-only classes.
+     */
+    private EntitlementUtil() {
+    }
 }

Modified: incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/dao/RoleTest.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/dao/RoleTest.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/dao/RoleTest.java (original)
+++ incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/dao/RoleTest.java Thu Oct 25 16:17:52 2012
@@ -46,7 +46,7 @@ public class RoleTest extends AbstractTe
 
     @Test
     public void findChildren() {
-        assertEquals(3, roleDAO.findChildren(4L).size());
+        assertEquals(3, roleDAO.findChildren(roleDAO.find(4L)).size());
     }
 
     @Test

Modified: incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/dao/UserTest.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/dao/UserTest.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/dao/UserTest.java (original)
+++ incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/dao/UserTest.java Thu Oct 25 16:17:52 2012
@@ -18,6 +18,8 @@
  */
 package org.apache.syncope.core.persistence.dao;
 
+import static org.junit.Assert.*;
+
 import java.util.Date;
 import java.util.List;
 import java.util.Set;
@@ -30,7 +32,6 @@ import org.apache.syncope.core.util.Enti
 import org.apache.syncope.core.util.IncompatiblePolicyException;
 import org.apache.syncope.core.util.PasswordGenerator;
 import org.apache.syncope.types.CipherAlgorithm;
-import static org.junit.Assert.*;
 import org.junit.Test;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.transaction.annotation.Transactional;
@@ -201,7 +202,6 @@ public class UserTest extends AbstractTe
         String password = "";
         try {
             password = passwordGenerator.generateUserPassword(user);
-            System.out.println("PASSWORD GENERATA: " + password);
         } catch (IncompatiblePolicyException ex) {
             fail(ex.getMessage());
         }

Modified: incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/relationships/RoleTest.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/relationships/RoleTest.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/relationships/RoleTest.java (original)
+++ incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/persistence/relationships/RoleTest.java Thu Oct 25 16:17:52 2012
@@ -19,8 +19,9 @@
 package org.apache.syncope.core.persistence.relationships;
 
 import static org.junit.Assert.*;
-import org.junit.Test;
 
+import java.util.List;
+import org.junit.Test;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.transaction.annotation.Transactional;
 import org.apache.syncope.core.persistence.beans.role.RAttr;
@@ -35,7 +36,9 @@ import org.apache.syncope.core.persisten
 import org.apache.syncope.core.AbstractTest;
 import org.apache.syncope.core.persistence.beans.PasswordPolicy;
 import org.apache.syncope.core.persistence.beans.role.SyncopeRole;
+import org.apache.syncope.core.persistence.beans.user.SyncopeUser;
 import org.apache.syncope.core.persistence.dao.PolicyDAO;
+import org.apache.syncope.core.persistence.validation.entity.InvalidEntityException;
 
 @Transactional
 public class RoleTest extends AbstractTest {
@@ -61,12 +64,52 @@ public class RoleTest extends AbstractTe
     @Autowired
     private PolicyDAO policyDAO;
 
-    public void createWithPasswordPolicy() {
-        final String ROLE_NAME = "roleWithPasswordPolicy";
+    @Test(expected = InvalidEntityException.class)
+    public void saveWithTwoOwners() {
+        SyncopeRole root = roleDAO.find("root", null);
+        assertNotNull("did not find expected role", root);
+
+        SyncopeUser user = userDAO.find(1L);
+        assertNotNull("did not find expected user", user);
+
+        SyncopeRole role = new SyncopeRole();
+        role.setName("error");
+        role.setUserOwner(user);
+        role.setRoleOwner(root);
 
+        roleDAO.save(role);
+    }
+
+    @Test
+    public void findByOwner() {
+        SyncopeRole role = roleDAO.find(6L);
+        assertNotNull("did not find expected role", role);
+
+        SyncopeUser user = userDAO.find(5L);
+        assertNotNull("did not find expected user", user);
+
+        assertEquals(user, role.getUserOwner());
+
+        SyncopeRole child1 = roleDAO.find(7L);
+        assertNotNull(child1);
+        assertEquals(role, child1.getParent());
+
+        SyncopeRole child2 = roleDAO.find(10L);
+        assertNotNull(child2);
+        assertEquals(role, child2.getParent());
+
+        List<SyncopeRole> ownedRoles = roleDAO.findOwned(user);
+        assertFalse(ownedRoles.isEmpty());
+        assertEquals(2, ownedRoles.size());
+        assertTrue(ownedRoles.contains(role));
+        assertTrue(ownedRoles.contains(child1));
+        assertFalse(ownedRoles.contains(child2));
+    }
+
+    public void createWithPasswordPolicy() {
         PasswordPolicy policy = (PasswordPolicy) policyDAO.find(4L);
         SyncopeRole role = new SyncopeRole();
-        role.setName(ROLE_NAME);
+        role.setName("roleWithPasswordPolicy");
         role.setPasswordPolicy(policy);
 
         SyncopeRole actual = roleDAO.save(role);

Modified: incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/rest/AuthenticationTestITCase.java
URL: http://svn.apache.org/viewvc/incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/rest/AuthenticationTestITCase.java?rev=1402206&r1=1402205&r2=1402206&view=diff
==============================================================================
--- incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/rest/AuthenticationTestITCase.java (original)
+++ incubator/syncope/trunk/core/src/test/java/org/apache/syncope/core/rest/AuthenticationTestITCase.java Thu Oct 25 16:17:52 2012
@@ -24,7 +24,6 @@ import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
-import org.apache.syncope.client.http.PreemptiveAuthHttpRequestFactory;
 import org.junit.Test;
 import org.springframework.http.HttpStatus;
 import org.springframework.web.client.HttpClientErrorException;