syncope-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ilgro...@apache.org
Subject svn commit: r1415070 [4/7] - in /syncope/branches/DEV_ROLE_PROVISIONING: ./ archetype/ archetype/src/main/resources/archetype-resources/console/ build-tools/ client/ client/src/main/java/org/apache/syncope/client/search/ client/src/main/java/org/apache...
Date Thu, 29 Nov 2012 07:46:24 GMT
Modified: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/RoleDAO.java
URL: http://svn.apache.org/viewvc/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/RoleDAO.java?rev=1415070&r1=1415069&r2=1415070&view=diff
==============================================================================
--- syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/RoleDAO.java (original)
+++ syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/RoleDAO.java Thu Nov 29 07:46:03 2012
@@ -24,9 +24,11 @@ import org.apache.syncope.core.persisten
 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.beans.user.UAttrValue;
 import org.apache.syncope.core.persistence.validation.entity.InvalidEntityException;
+import org.apache.syncope.core.rest.controller.InvalidSearchConditionException;
 
-public interface RoleDAO extends DAO {
+public interface RoleDAO extends AttributableDAO {
 
     SyncopeRole find(Long id);
 
@@ -38,14 +40,20 @@ public interface RoleDAO extends DAO {
 
     List<SyncopeRole> findByEntitlement(final Entitlement entitlement);
 
-    List<SyncopeRole> findByResource(ExternalResource resource);
-
     List<SyncopeRole> findAncestors(SyncopeRole role);
 
     List<SyncopeRole> findChildren(SyncopeRole role);
 
     List<SyncopeRole> findDescendants(SyncopeRole role);
 
+    List<SyncopeRole> findByDerAttrValue(String schemaName, String value) throws InvalidSearchConditionException;
+
+    List<SyncopeRole> findByAttrValue(String schemaName, UAttrValue attrValue);
+
+    SyncopeRole findByAttrUniqueValue(String schemaName, UAttrValue attrUniqueValue);
+
+    List<SyncopeRole> findByResource(ExternalResource resource);
+
     List<SyncopeRole> findAll();
 
     List<Membership> findMemberships(SyncopeRole role);

Modified: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/UserDAO.java
URL: http://svn.apache.org/viewvc/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/UserDAO.java?rev=1415070&r1=1415069&r2=1415070&view=diff
==============================================================================
--- syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/UserDAO.java (original)
+++ syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/UserDAO.java Thu Nov 29 07:46:03 2012
@@ -26,7 +26,7 @@ import org.apache.syncope.core.persisten
 import org.apache.syncope.core.persistence.validation.entity.InvalidEntityException;
 import org.apache.syncope.core.rest.controller.InvalidSearchConditionException;
 
-public interface UserDAO extends DAO {
+public interface UserDAO extends AttributableDAO {
 
     SyncopeUser find(Long id);
 

Added: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/AbstractAttributableDAOImpl.java
URL: http://svn.apache.org/viewvc/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/AbstractAttributableDAOImpl.java?rev=1415070&view=auto
==============================================================================
--- syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/AbstractAttributableDAOImpl.java (added)
+++ syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/AbstractAttributableDAOImpl.java Thu Nov 29 07:46:03 2012
@@ -0,0 +1,341 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.syncope.core.persistence.dao.impl;
+
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.regex.Pattern;
+import javax.persistence.Query;
+import javax.persistence.TemporalType;
+import org.apache.commons.jexl2.parser.Parser;
+import org.apache.commons.jexl2.parser.ParserConstants;
+import org.apache.commons.jexl2.parser.Token;
+import org.apache.syncope.core.persistence.beans.AbstractAttrValue;
+import org.apache.syncope.core.persistence.beans.AbstractAttributable;
+import org.apache.syncope.core.persistence.beans.AbstractDerSchema;
+import org.apache.syncope.core.persistence.beans.AbstractSchema;
+import org.apache.syncope.core.persistence.beans.ExternalResource;
+import org.apache.syncope.core.persistence.dao.AttributableDAO;
+import org.apache.syncope.core.persistence.dao.DerSchemaDAO;
+import org.apache.syncope.core.persistence.dao.SchemaDAO;
+import org.apache.syncope.core.rest.controller.InvalidSearchConditionException;
+import org.apache.syncope.core.util.AttributableUtil;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.util.StringUtils;
+
+public abstract class AbstractAttributableDAOImpl extends AbstractDAOImpl implements AttributableDAO {
+
+    @Autowired
+    protected SchemaDAO schemaDAO;
+
+    @Autowired
+    protected DerSchemaDAO derSchemaDAO;
+
+    /**
+     * Split an attribute value recurring on provided literals/tokens.
+     *
+     * @param attrValue value to be split
+     * @param literals literals/tokens
+     * @return
+     */
+    private List<String> split(final String attrValue, final List<String> literals) {
+        final List<String> attrValues = new ArrayList<String>();
+
+        if (literals.isEmpty()) {
+            attrValues.add(attrValue);
+        } else {
+            for (String token : attrValue.split(Pattern.quote(literals.get(0)))) {
+                attrValues.addAll(split(token, literals.subList(1, literals.size())));
+            }
+        }
+
+        return attrValues;
+    }
+
+    /**
+     * Generate one where clause for each different attribute schema into the derived schema expression provided.
+     *
+     * @param expression derived schema expression
+     * @param value derived attribute value
+     * @return where clauses to use to build the query
+     * @throws InvalidSearchConditionException in case of errors retrieving identifiers
+     */
+    private Set<String> getWhereClause(final String expression, final String value, final AttributableUtil attrUtil)
+            throws InvalidSearchConditionException {
+
+        final Parser parser = new Parser(new StringReader(expression));
+
+        // Schema names
+        final List<String> identifiers = new ArrayList<String>();
+
+        // Literals
+        final List<String> literals = new ArrayList<String>();
+
+        // Get schema names and literals
+        Token token;
+        while ((token = parser.getNextToken()) != null && StringUtils.hasText(token.toString())) {
+
+            if (token.kind == ParserConstants.STRING_LITERAL) {
+                literals.add(token.toString().substring(1, token.toString().length() - 1));
+            }
+
+            if (token.kind == ParserConstants.IDENTIFIER) {
+                identifiers.add(token.toString());
+            }
+        }
+
+        // Sort literals in order to process later literals included into others
+        Collections.sort(literals, new Comparator<String>() {
+
+            @Override
+            public int compare(String t, String t1) {
+                if (t == null && t1 == null) {
+                    return 0;
+                } else if (t != null && t1 == null) {
+                    return -1;
+                } else if (t == null && t1 != null) {
+                    return 1;
+                } else if (t.length() == t1.length()) {
+                    return 0;
+                } else if (t.length() > t1.length()) {
+                    return -1;
+                } else {
+                    return 1;
+                }
+            }
+        });
+
+        // Split value on provided literals
+        final List<String> attrValues = split(value, literals);
+
+        if (attrValues.size() != identifiers.size()) {
+            LOG.error("Ambiguous jexl expression resolution.");
+            throw new InvalidSearchConditionException("literals and values have different size");
+        }
+
+        // clauses to be used with INTERSECTed queries
+        final Set<String> clauses = new HashSet<String>();
+
+        // builder to build the clauses
+        final StringBuilder bld = new StringBuilder();
+
+        // Contains used identifiers in order to avoid replications
+        final Set<String> used = new HashSet<String>();
+
+        // Create several clauses: one for eanch identifiers
+        for (int i = 0; i < identifiers.size(); i++) {
+            if (!used.contains(identifiers.get(i))) {
+
+                // verify schema existence and get schema type
+                AbstractSchema schema = schemaDAO.find(identifiers.get(i), attrUtil.schemaClass());
+                if (schema == null) {
+                    LOG.error("Invalid schema name '{}'", identifiers.get(i));
+                    throw new InvalidSearchConditionException("Invalid schema name " + identifiers.get(i));
+                }
+
+                // clear builder
+                bld.delete(0, bld.length());
+
+                bld.append("(");
+
+                // set schema name
+                bld.append("s.name = '").append(identifiers.get(i)).append("'");
+
+                bld.append(" AND ");
+
+                bld.append("s.name = a.schema_name").append(" AND ");
+
+                bld.append("a.id = v.attribute_id");
+
+                bld.append(" AND ");
+
+                // use a value clause different for eanch different schema type
+                switch (schema.getType()) {
+                    case Boolean:
+                        bld.append("v.booleanValue = '").append(attrValues.get(i)).append("'");
+                        break;
+                    case Long:
+                        bld.append("v.longValue = ").append(attrValues.get(i));
+                        break;
+                    case Double:
+                        bld.append("v.doubleValue = ").append(attrValues.get(i));
+                        break;
+                    case Date:
+                        bld.append("v.dateValue = '").append(attrValues.get(i)).append("'");
+                        break;
+                    default:
+                        bld.append("v.stringValue = '").append(attrValues.get(i)).append("'");
+                }
+
+                bld.append(")");
+
+                used.add(identifiers.get(i));
+
+                clauses.add(bld.toString());
+            }
+        }
+
+        LOG.debug("Generated where clauses {}", clauses);
+
+        return clauses;
+    }
+
+    protected abstract <T extends AbstractAttributable> T find(final Long id);
+
+    @Override
+    public <T extends AbstractAttributable> List<T> findByAttrValue(final String schemaName,
+            final AbstractAttrValue attrValue, final AttributableUtil attrUtil) {
+
+        AbstractSchema schema = schemaDAO.find(schemaName, attrUtil.schemaClass());
+        if (schema == null) {
+            LOG.error("Invalid schema name '{}'", schemaName);
+            return Collections.EMPTY_LIST;
+        }
+
+        final String entityName = schema.isUniqueConstraint()
+                ? attrUtil.attrUniqueValueClass().getName()
+                : attrUtil.attrValueClass().getName();
+
+        Query query = entityManager.createQuery("SELECT e FROM " + entityName + " e"
+                + " WHERE e.attribute.schema.name = :schemaName " + " AND (e.stringValue IS NOT NULL"
+                + " AND e.stringValue = :stringValue)" + " OR (e.booleanValue IS NOT NULL"
+                + " AND e.booleanValue = :booleanValue)" + " OR (e.dateValue IS NOT NULL"
+                + " AND e.dateValue = :dateValue)" + " OR (e.longValue IS NOT NULL" + " AND e.longValue = :longValue)"
+                + " OR (e.doubleValue IS NOT NULL" + " AND e.doubleValue = :doubleValue)");
+
+        query.setParameter("schemaName", schemaName);
+        query.setParameter("stringValue", attrValue.getStringValue());
+        query.setParameter("booleanValue", attrValue.getBooleanValue() == null
+                ? null
+                : attrValue.getBooleanAsInteger(attrValue.getBooleanValue()));
+        if (attrValue.getDateValue() == null) {
+            query.setParameter("dateValue", null);
+        } else {
+            query.setParameter("dateValue", attrValue.getDateValue(), TemporalType.TIMESTAMP);
+        }
+        query.setParameter("longValue", attrValue.getLongValue());
+        query.setParameter("doubleValue", attrValue.getDoubleValue());
+
+        List<T> result = new ArrayList<T>();
+        for (AbstractAttrValue value : (List<AbstractAttrValue>) query.getResultList()) {
+            T subject = value.getAttribute().getOwner();
+            if (!result.contains(subject)) {
+                result.add(subject);
+            }
+        }
+
+        return result;
+    }
+
+    @Override
+    public <T extends AbstractAttributable> AbstractAttributable findByAttrUniqueValue(final String schemaName,
+            final AbstractAttrValue attrUniqueValue, final AttributableUtil attrUtil) {
+
+        AbstractSchema schema = schemaDAO.find(schemaName, attrUtil.schemaClass());
+        if (schema == null) {
+            LOG.error("Invalid schema name '{}'", schemaName);
+            return null;
+        }
+        if (!schema.isUniqueConstraint()) {
+            LOG.error("This schema has not unique constraint: '{}'", schemaName);
+            return null;
+        }
+
+        List<T> result = findByAttrValue(schemaName, attrUniqueValue, attrUtil);
+        return result.isEmpty()
+                ? null
+                : result.iterator().next();
+    }
+
+    /**
+     * Find users / roles by derived attribute value. This method could fail if one or more string literals contained
+     * into the derived attribute value provided derive from identifier (schema name) replacement. When you are going to
+     * specify a derived attribute expression you must be quite sure that string literals used to build the expression
+     * cannot be found into the attribute values used to replace attribute schema names used as identifiers.
+     *
+     * @param schemaName derived schema name
+     * @param value derived attribute value
+     * @return list of users / roles
+     * @throws InvalidSearchConditionException in case of errors retrieving schema names used to buid the derived schema
+     * expression.
+     */
+    @Override
+    public <T extends AbstractAttributable> List<T> findByDerAttrValue(final String schemaName, final String value,
+            final AttributableUtil attrUtil)
+            throws InvalidSearchConditionException {
+
+        AbstractDerSchema schema = derSchemaDAO.find(schemaName, attrUtil.derSchemaClass());
+        if (schema == null) {
+            LOG.error("Invalid schema name '{}'", schemaName);
+            return Collections.EMPTY_LIST;
+        }
+
+        // query string
+        final StringBuilder querystring = new StringBuilder();
+
+        boolean subquery = false;
+        for (String clause : getWhereClause(schema.getExpression(), value, attrUtil)) {
+            if (querystring.length() > 0) {
+                subquery = true;
+                querystring.append(" AND a.owner_id IN ( ");
+            }
+
+            querystring.append("SELECT a.owner_id ").
+                    append("FROM ").append(attrUtil.attrClass().getSimpleName()).append(" a, ").
+                    append(attrUtil.attrValueClass().getSimpleName()).append(" v, ").
+                    append(attrUtil.schemaClass().getSimpleName()).append(" s ").
+                    append("WHERE ").append(clause);
+
+            if (subquery) {
+                querystring.append(')');
+            }
+        }
+
+        LOG.debug("Execute query {}", querystring);
+
+        final Query query = entityManager.createNativeQuery(querystring.toString());
+
+        final List<T> result = new ArrayList<T>();
+
+        for (Object userId : query.getResultList()) {
+            T subject = find(Long.parseLong(userId.toString()));
+            if (!result.contains(subject)) {
+                result.add(subject);
+            }
+        }
+
+        return result;
+    }
+
+    @Override
+    public <T extends AbstractAttributable> List<T> findByResource(final ExternalResource resource,
+            final Class<T> reference) {
+
+        Query query = entityManager.createQuery("SELECT e FROM " + reference.getSimpleName() + " e "
+                + "WHERE :resource MEMBER OF e.resources");
+        query.setParameter("resource", resource);
+
+        return query.getResultList();
+    }
+}

Propchange: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/AbstractAttributableDAOImpl.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/AbstractAttributableDAOImpl.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/AbstractAttributableDAOImpl.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Copied: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/AttributableSearchDAOImpl.java (from r1410294, incubator/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/UserSearchDAOImpl.java)
URL: http://svn.apache.org/viewvc/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/AttributableSearchDAOImpl.java?p2=syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/AttributableSearchDAOImpl.java&p1=incubator/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/UserSearchDAOImpl.java&r1=1410294&r2=1415070&rev=1415070&view=diff
==============================================================================
--- incubator/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/UserSearchDAOImpl.java (original)
+++ syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/AttributableSearchDAOImpl.java Thu Nov 29 07:46:03 2012
@@ -28,26 +28,28 @@ import java.util.Set;
 import javax.persistence.Query;
 import javax.persistence.TemporalType;
 import javax.validation.ValidationException;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Repository;
+import org.apache.syncope.client.search.AttributableCond;
 import org.apache.syncope.client.search.AttributeCond;
-import org.apache.syncope.client.search.SyncopeUserCond;
 import org.apache.syncope.client.search.MembershipCond;
 import org.apache.syncope.client.search.NodeCond;
 import org.apache.syncope.client.search.ResourceCond;
-import org.apache.syncope.core.persistence.beans.user.SyncopeUser;
-import org.apache.syncope.core.persistence.beans.user.UAttrValue;
-import org.apache.syncope.core.persistence.beans.user.USchema;
+import org.apache.syncope.core.persistence.beans.AbstractAttrValue;
+import org.apache.syncope.core.persistence.beans.AbstractAttributable;
+import org.apache.syncope.core.persistence.beans.AbstractSchema;
+import org.apache.syncope.core.persistence.dao.AttributableSearchDAO;
 import org.apache.syncope.core.persistence.dao.RoleDAO;
 import org.apache.syncope.core.persistence.dao.SchemaDAO;
 import org.apache.syncope.core.persistence.dao.UserDAO;
-import org.apache.syncope.core.persistence.dao.UserSearchDAO;
+import org.apache.syncope.core.util.AttributableUtil;
+import org.apache.syncope.types.AttributableType;
 import org.apache.syncope.types.SchemaType;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
 
 @Repository
-public class UserSearchDAOImpl extends AbstractDAOImpl implements UserSearchDAO {
+public class AttributableSearchDAOImpl extends AbstractDAOImpl implements AttributableSearchDAO {
 
-    static final private String EMPTY_ATTR_QUERY = "SELECT user_id FROM user_search_attr WHERE 1=2";
+    static final private String EMPTY_ATTR_QUERY = "SELECT subject_id FROM user_search_attr WHERE 1=2";
 
     @Autowired
     private UserDAO userDAO;
@@ -58,20 +60,18 @@ public class UserSearchDAOImpl extends A
     @Autowired
     private SchemaDAO schemaDAO;
 
-    public UserSearchDAOImpl() {
-        super();
-    }
-
-    private String getAdminRolesFilter(final Set<Long> adminRoles) {
+    private String getAdminRolesFilter(final Set<Long> adminRoles, final AttributableUtil attrUtil) {
         final StringBuilder adminRolesFilter = new StringBuilder();
 
-        adminRolesFilter.append("SELECT syncopeUser_id AS user_id ").append("FROM Membership M1 ").
-                append("WHERE syncopeRole_id IN (");
-
-        adminRolesFilter.append("SELECT syncopeRole_id ").append("FROM Membership M2 ").
-                append("WHERE M2.syncopeUser_id=M1.syncopeUser_id ").append("AND syncopeRole_id NOT IN (");
+        if (attrUtil.getType() == AttributableType.USER) {
+            adminRolesFilter.append("SELECT syncopeUser_id AS subject_id FROM Membership M1 WHERE syncopeRole_id IN (").
+                    append("SELECT syncopeRole_id FROM Membership M2 WHERE M2.syncopeUser_id=M1.syncopeUser_id ").
+                    append("AND syncopeRole_id NOT IN (");
+        }
 
-        adminRolesFilter.append("SELECT id AS syncopeRole_id FROM SyncopeRole");
+        adminRolesFilter.append("SELECT id AS ").
+                append(attrUtil.getType() == AttributableType.USER ? "syncopeRole" : "subject").
+                append("_id FROM SyncopeRole");
 
         boolean firstRole = true;
 
@@ -80,32 +80,34 @@ public class UserSearchDAOImpl extends A
                 adminRolesFilter.append(" WHERE");
                 firstRole = false;
             } else {
-                adminRolesFilter.append(" OR");
+                adminRolesFilter.append(attrUtil.getType() == AttributableType.USER ? " OR" : " AND");
             }
-            adminRolesFilter.append(" id=").append(adminRoleId);
+            adminRolesFilter.append(attrUtil.getType() == AttributableType.USER
+                    ? " id=" : " id <>").append(adminRoleId);
         }
 
-        adminRolesFilter.append("))");
+        if (attrUtil.getType() == AttributableType.USER) {
+            adminRolesFilter.append("))");
+        }
 
         return adminRolesFilter.toString();
     }
 
     @Override
-    public int count(final Set<Long> adminRoles, final NodeCond searchCondition) {
-
+    public int count(final Set<Long> adminRoles, final NodeCond searchCondition, final AttributableUtil attrUtil) {
         List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());
 
         // 1. get the query string from the search condition
-        StringBuilder queryString = getQuery(searchCondition, parameters);
+        StringBuilder queryString = getQuery(searchCondition, parameters, attrUtil);
 
         // 2. take into account administrative roles
-        queryString.insert(0, "SELECT u.user_id FROM (");
-        queryString.append(") u WHERE user_id NOT IN (");
-        queryString.append(getAdminRolesFilter(adminRoles)).append(")");
+        queryString.insert(0, "SELECT u.subject_id FROM (");
+        queryString.append(") u WHERE subject_id NOT IN (");
+        queryString.append(getAdminRolesFilter(adminRoles, attrUtil)).append(")");
 
         // 3. prepare the COUNT query
-        queryString.insert(0, "SELECT COUNT(user_id) FROM (");
-        queryString.append(") count_user_id");
+        queryString.insert(0, "SELECT COUNT(subject_id) FROM (");
+        queryString.append(") count_subject_id");
 
         Query countQuery = entityManager.createNativeQuery(queryString.toString());
         fillWithParameters(countQuery, parameters);
@@ -119,27 +121,29 @@ public class UserSearchDAOImpl extends A
     }
 
     @Override
-    public List<SyncopeUser> search(final Set<Long> adminRoles, final NodeCond searchCondition) {
-        return search(adminRoles, searchCondition, -1, -1);
+    public <T extends AbstractAttributable> List<T> search(final Set<Long> adminRoles, final NodeCond searchCondition,
+            final AttributableUtil attrUtil) {
+
+        return search(adminRoles, searchCondition, -1, -1, attrUtil);
     }
 
     @Override
-    public List<SyncopeUser> search(
-            final Set<Long> adminRoles, final NodeCond searchCondition, final int page, final int itemsPerPage) {
+    public <T extends AbstractAttributable> List<T> search(final Set<Long> adminRoles, final NodeCond searchCondition,
+            final int page, final int itemsPerPage, final AttributableUtil attrUtil) {
 
-        List<SyncopeUser> result = Collections.emptyList();
+        List<T> result = Collections.EMPTY_LIST;
 
         if (adminRoles != null && (!adminRoles.isEmpty() || roleDAO.findAll().isEmpty())) {
             LOG.debug("Search condition:\n{}", searchCondition);
 
-            if (!searchCondition.checkValidity()) {
-                LOG.error("Invalid search condition:\n{}", searchCondition);
-            } else {
+            if (searchCondition.checkValidity()) {
                 try {
-                    result = doSearch(adminRoles, searchCondition, page, itemsPerPage);
+                    result = doSearch(adminRoles, searchCondition, page, itemsPerPage, attrUtil);
                 } catch (Exception e) {
-                    LOG.error("While searching users", e);
+                    LOG.error("While searching for {}", attrUtil.getType(), e);
                 }
+            } else {
+                LOG.error("Invalid search condition:\n{}", searchCondition);
             }
         }
 
@@ -147,16 +151,17 @@ public class UserSearchDAOImpl extends A
     }
 
     @Override
-    public boolean matches(final SyncopeUser user, final NodeCond searchCondition) {
+    public <T extends AbstractAttributable> boolean matches(final T user, final NodeCond searchCondition,
+            final AttributableUtil attrUtil) {
 
         List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());
 
         // 1. get the query string from the search condition
-        StringBuilder queryString = getQuery(searchCondition, parameters);
+        StringBuilder queryString = getQuery(searchCondition, parameters, attrUtil);
 
         // 2. take into account the passed user
-        queryString.insert(0, "SELECT u.user_id FROM (");
-        queryString.append(") u WHERE user_id=?").append(setParameter(parameters, user.getId()));
+        queryString.insert(0, "SELECT u.subject_id FROM (");
+        queryString.append(") u WHERE subject_id=?").append(setParameter(parameters, user.getId()));
 
         // 3. prepare the search query
         Query query = entityManager.createNativeQuery(queryString.toString());
@@ -165,13 +170,12 @@ public class UserSearchDAOImpl extends A
         fillWithParameters(query, parameters);
 
         // 5. executes query
-        List<SyncopeUser> result = query.getResultList();
+        List<T> result = query.getResultList();
 
         return !result.isEmpty();
     }
 
     private int setParameter(final List<Object> parameters, final Object parameter) {
-
         int key;
         synchronized (parameters) {
             parameters.add(parameter);
@@ -182,7 +186,6 @@ public class UserSearchDAOImpl extends A
     }
 
     private void fillWithParameters(final Query query, final List<Object> parameters) {
-
         for (int i = 0; i < parameters.size(); i++) {
             if (parameters.get(i) instanceof Date) {
                 query.setParameter(i + 1, (Date) parameters.get(i), TemporalType.TIMESTAMP);
@@ -196,31 +199,29 @@ public class UserSearchDAOImpl extends A
         }
     }
 
-    private List<SyncopeUser> doSearch(
-            final Set<Long> adminRoles, final NodeCond nodeCond, final int page, final int itemsPerPage) {
+    private <T extends AbstractAttributable> List<T> doSearch(final Set<Long> adminRoles, final NodeCond nodeCond,
+            final int page, final int itemsPerPage, final AttributableUtil attrUtil) {
 
         List<Object> parameters = Collections.synchronizedList(new ArrayList<Object>());
 
         // 1. get the query string from the search condition
-        final StringBuilder queryString = getQuery(nodeCond, parameters);
+        final StringBuilder queryString = getQuery(nodeCond, parameters, attrUtil);
 
         // 2. take into account administrative roles
         if (queryString.charAt(0) == '(') {
-            queryString.insert(0, "SELECT u.user_id FROM ");
-            queryString.append(" u WHERE user_id NOT IN (");
+            queryString.insert(0, "SELECT u.subject_id FROM ");
+            queryString.append(" u WHERE subject_id NOT IN (");
         } else {
-            queryString.insert(0, "SELECT u.user_id FROM (");
-            queryString.append(") u WHERE user_id NOT IN (");
+            queryString.insert(0, "SELECT u.subject_id FROM (");
+            queryString.append(") u WHERE subject_id NOT IN (");
         }
-        queryString.append(getAdminRolesFilter(adminRoles)).append(")");
+        queryString.append(getAdminRolesFilter(adminRoles, attrUtil)).append(")");
 
         // 3. prepare the search query
         final Query query = entityManager.createNativeQuery(queryString.toString());
 
         // page starts from 1, while setFirtResult() starts from 0
-        query.setFirstResult(itemsPerPage * (page <= 0
-                ? 0
-                : page - 1));
+        query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1));
 
         if (itemsPerPage >= 0) {
             query.setMaxResults(itemsPerPage);
@@ -232,36 +233,39 @@ public class UserSearchDAOImpl extends A
         LOG.debug("Native query\n{}\nwith parameters\n{}", queryString.toString(), parameters);
 
         // 5. Prepare the result (avoiding duplicates - set)
-        final Set<Number> userIds = new HashSet<Number>();
+        final Set<Number> subjectIds = new HashSet<Number>();
         final List resultList = query.getResultList();
 
         //fix for HHH-5902 - bug hibernate
         if (resultList != null) {
             for (Object userId : resultList) {
                 if (userId instanceof Object[]) {
-                    userIds.add((Number) ((Object[]) userId)[0]);
+                    subjectIds.add((Number) ((Object[]) userId)[0]);
                 } else {
-                    userIds.add((Number) userId);
+                    subjectIds.add((Number) userId);
                 }
             }
         }
 
-        final List<SyncopeUser> result = new ArrayList<SyncopeUser>(userIds.size());
+        final List<T> result = new ArrayList<T>(subjectIds.size());
 
-        SyncopeUser user;
-        for (Object userId : userIds) {
-            user = userDAO.find(((Number) userId).longValue());
-            if (user == null) {
-                LOG.error("Could not find user with id {}, " + "even though returned by the native query", userId);
+        for (Object subjectId : subjectIds) {
+            T subject = attrUtil.getType() == AttributableType.USER
+                    ? (T) userDAO.find(((Number) subjectId).longValue())
+                    : (T) roleDAO.find(((Number) subjectId).longValue());
+            if (subject == null) {
+                LOG.error("Could not find {} with id {}, even though returned by the native query",
+                        attrUtil.getType(), subjectId);
             } else {
-                result.add(user);
+                result.add(subject);
             }
         }
 
         return result;
     }
 
-    private StringBuilder getQuery(final NodeCond nodeCond, final List<Object> parameters) {
+    private StringBuilder getQuery(final NodeCond nodeCond, final List<Object> parameters,
+            final AttributableUtil attrUtil) {
 
         StringBuilder query = new StringBuilder();
 
@@ -269,32 +273,37 @@ public class UserSearchDAOImpl extends A
 
             case LEAF:
             case NOT_LEAF:
-                if (nodeCond.getMembershipCond() != null) {
+                if (nodeCond.getMembershipCond() != null && AttributableType.USER == attrUtil.getType()) {
                     query.append(getQuery(nodeCond.getMembershipCond(), nodeCond.getType() == NodeCond.Type.NOT_LEAF,
-                            parameters));
+                            parameters, attrUtil));
                 }
                 if (nodeCond.getResourceCond() != null) {
                     query.append(getQuery(nodeCond.getResourceCond(), nodeCond.getType() == NodeCond.Type.NOT_LEAF,
-                            parameters));
+                            parameters, attrUtil));
                 }
                 if (nodeCond.getAttributeCond() != null) {
                     query.append(getQuery(nodeCond.getAttributeCond(), nodeCond.getType() == NodeCond.Type.NOT_LEAF,
-                            parameters));
+                            parameters, attrUtil));
                 }
-                if (nodeCond.getSyncopeUserCond() != null) {
-                    query.append(getQuery(nodeCond.getSyncopeUserCond(), nodeCond.getType() == NodeCond.Type.NOT_LEAF,
-                            parameters));
+                if (nodeCond.getAttributableCond() != null) {
+                    query.append(getQuery(nodeCond.getAttributableCond(), nodeCond.getType() == NodeCond.Type.NOT_LEAF,
+                            parameters, attrUtil));
                 }
                 break;
 
             case AND:
-                query.append(getQuery(nodeCond.getLeftNodeCond(), parameters)).append(" AND user_id IN ( ").append(
-                        getQuery(nodeCond.getRightNodeCond(), parameters).append(")"));
+                query.append(getQuery(nodeCond.getLeftNodeCond(), parameters, attrUtil)).
+                        append(" AND subject_id IN ( ").
+                        append(getQuery(nodeCond.getRightNodeCond(), parameters, attrUtil).
+                        append(")"));
                 break;
 
             case OR:
-                query.append("(").append(getQuery(nodeCond.getLeftNodeCond(), parameters)).append(" UNION ").append(
-                        getQuery(nodeCond.getRightNodeCond(), parameters).append(")"));
+                query.append("(").
+                        append(getQuery(nodeCond.getLeftNodeCond(), parameters, attrUtil)).
+                        append(" UNION ").
+                        append(getQuery(nodeCond.getRightNodeCond(), parameters, attrUtil).
+                        append(")"));
                 break;
 
             default:
@@ -303,17 +312,20 @@ public class UserSearchDAOImpl extends A
         return query;
     }
 
-    private String getQuery(final MembershipCond cond, final boolean not, final List<Object> parameters) {
+    private String getQuery(final MembershipCond cond, final boolean not, final List<Object> parameters,
+            final AttributableUtil attrUtil) {
 
-        StringBuilder query = new StringBuilder("SELECT DISTINCT user_id FROM user_search WHERE ");
+        StringBuilder query = new StringBuilder("SELECT DISTINCT subject_id FROM ").
+                append(attrUtil.searchView()).append(" WHERE ");
 
         if (not) {
-            query.append("user_id NOT IN (");
+            query.append("subject_id NOT IN (");
         } else {
-            query.append("user_id IN (");
+            query.append("subject_id IN (");
         }
 
-        query.append("SELECT DISTINCT user_id ").append("FROM user_search_membership WHERE ");
+        query.append("SELECT DISTINCT subject_id ").append("FROM ").
+                append(attrUtil.searchView()).append("_membership WHERE ");
 
         if (cond.getRoleId() != null) {
             query.append("role_id=?").append(setParameter(parameters, cond.getRoleId()));
@@ -326,17 +338,20 @@ public class UserSearchDAOImpl extends A
         return query.toString();
     }
 
-    private String getQuery(final ResourceCond cond, final boolean not, final List<Object> parameters) {
+    private String getQuery(final ResourceCond cond, final boolean not, final List<Object> parameters,
+            final AttributableUtil attrUtil) {
 
-        final StringBuilder query = new StringBuilder("SELECT DISTINCT user_id FROM user_search WHERE ");
+        final StringBuilder query = new StringBuilder("SELECT DISTINCT subject_id FROM ").
+                append(attrUtil.searchView()).append(" WHERE ");
 
         if (not) {
-            query.append("user_id NOT IN (");
+            query.append("subject_id NOT IN (");
         } else {
-            query.append("user_id IN (");
+            query.append("subject_id IN (");
         }
 
-        query.append("SELECT DISTINCT user_id ").append("FROM user_search_resource WHERE ");
+        query.append("SELECT DISTINCT subject_id ").append("FROM ").
+                append(attrUtil.searchView()).append("_resource WHERE ");
 
         query.append("resource_name=?").append(setParameter(parameters, cond.getResourceName()));
 
@@ -345,10 +360,10 @@ public class UserSearchDAOImpl extends A
         return query.toString();
     }
 
-    private void fillAttributeQuery(final StringBuilder query, final UAttrValue attrValue, final USchema schema,
-            final AttributeCond cond, final boolean not, final List<Object> parameters) {
+    private void fillAttributeQuery(final StringBuilder query, final AbstractAttrValue attrValue,
+            final AbstractSchema schema, final AttributeCond cond, final boolean not, final List<Object> parameters) {
 
-        String column = (cond instanceof SyncopeUserCond)
+        String column = (cond instanceof AttributableCond)
                 ? cond.getSchema()
                 : "' AND " + getFieldName(schema.getType());
 
@@ -377,7 +392,7 @@ public class UserSearchDAOImpl extends A
                     query.append(" LIKE '").append(cond.getExpression()).append("'");
 
                 } else {
-                    if (!(cond instanceof SyncopeUserCond)) {
+                    if (!(cond instanceof AttributableCond)) {
                         query.append("' AND");
                     }
                     query.append(" 1=2");
@@ -471,15 +486,16 @@ public class UserSearchDAOImpl extends A
         return result;
     }
 
-    private String getQuery(final AttributeCond cond, final boolean not, final List<Object> parameters) {
+    private String getQuery(final AttributeCond cond, final boolean not, final List<Object> parameters,
+            AttributableUtil attrUtil) {
 
-        USchema schema = schemaDAO.find(cond.getSchema(), USchema.class);
+        AbstractSchema schema = schemaDAO.find(cond.getSchema(), attrUtil.schemaClass());
         if (schema == null) {
             LOG.warn("Ignoring invalid schema '{}'", cond.getSchema());
             return EMPTY_ATTR_QUERY;
         }
 
-        UAttrValue attrValue = new UAttrValue();
+        AbstractAttrValue attrValue = attrUtil.newAttrValue();
         try {
             if (cond.getType() != AttributeCond.Type.LIKE && cond.getType() != AttributeCond.Type.ISNULL
                     && cond.getType() != AttributeCond.Type.ISNOTNULL) {
@@ -491,21 +507,21 @@ public class UserSearchDAOImpl extends A
             return EMPTY_ATTR_QUERY;
         }
 
-        StringBuilder query = new StringBuilder("SELECT DISTINCT user_id FROM user_search_attr WHERE ").append(
-                "schema_name='").append(schema.getName());
+        StringBuilder query = new StringBuilder("SELECT DISTINCT subject_id FROM ").
+                append(attrUtil.searchView()).append("_attr WHERE ").append("schema_name='").append(schema.getName());
         fillAttributeQuery(query, attrValue, schema, cond, not, parameters);
 
         return query.toString();
     }
 
-    private String getQuery(final SyncopeUserCond cond, final boolean not, final List<Object> parameters) {
-
-        Field syncopeUserClassField = null;
-        // loop over SyncopeUser class and all superclasses searching for field
-        for (Class<?> i = SyncopeUser.class; syncopeUserClassField == null && i != Object.class;) {
+    private String getQuery(final AttributableCond cond, final boolean not, final List<Object> parameters,
+            final AttributableUtil attrUtil) {
 
+        Field attributableClassField = null;
+        // loop over attributable class and all superclasses searching for field
+        for (Class i = attrUtil.attributableClass(); attributableClassField == null && i != Object.class;) {
             try {
-                syncopeUserClassField = i.getDeclaredField(cond.getSchema());
+                attributableClassField = i.getDeclaredField(cond.getSchema());
             } catch (Exception ignore) {
                 // ignore exception
                 LOG.debug("Field '{}' not found on class '{}'", new String[]{cond.getSchema(), i.getSimpleName()},
@@ -514,21 +530,20 @@ public class UserSearchDAOImpl extends A
                 i = i.getSuperclass();
             }
         }
-        if (syncopeUserClassField == null) {
+        if (attributableClassField == null) {
             LOG.warn("Ignoring invalid schema '{}'", cond.getSchema());
             return EMPTY_ATTR_QUERY;
         }
 
-        USchema schema = new USchema();
-        schema.setName(syncopeUserClassField.getName());
+        AbstractSchema schema = attrUtil.newSchema();
+        schema.setName(attributableClassField.getName());
         for (SchemaType type : SchemaType.values()) {
-            if (syncopeUserClassField.getType().getName().equals(type.getClassName())) {
-
+            if (attributableClassField.getType().getName().equals(type.getClassName())) {
                 schema.setType(type);
             }
         }
 
-        UAttrValue attrValue = new UAttrValue();
+        AbstractAttrValue attrValue = attrUtil.newAttrValue();
         try {
             if (cond.getType() != AttributeCond.Type.LIKE && cond.getType() != AttributeCond.Type.ISNULL
                     && cond.getType() != AttributeCond.Type.ISNOTNULL) {
@@ -540,7 +555,8 @@ public class UserSearchDAOImpl extends A
             return EMPTY_ATTR_QUERY;
         }
 
-        final StringBuilder query = new StringBuilder("SELECT DISTINCT user_id FROM user_search WHERE ");
+        final StringBuilder query = new StringBuilder("SELECT DISTINCT subject_id FROM ").
+                append(attrUtil.searchView()).append(" WHERE ");
 
         fillAttributeQuery(query, attrValue, schema, cond, not, parameters);
 

Modified: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/RoleDAOImpl.java
URL: http://svn.apache.org/viewvc/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/RoleDAOImpl.java?rev=1415070&r1=1415069&r2=1415070&view=diff
==============================================================================
--- syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/RoleDAOImpl.java (original)
+++ syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/RoleDAOImpl.java Thu Nov 29 07:46:03 2012
@@ -28,24 +28,24 @@ import org.apache.syncope.core.persisten
 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.beans.user.UAttrValue;
 import org.apache.syncope.core.persistence.dao.EntitlementDAO;
 import org.apache.syncope.core.persistence.dao.RoleDAO;
-import org.apache.syncope.core.persistence.dao.TaskDAO;
 import org.apache.syncope.core.persistence.dao.UserDAO;
+import org.apache.syncope.core.rest.controller.InvalidSearchConditionException;
+import org.apache.syncope.core.util.AttributableUtil;
 import org.apache.syncope.core.util.EntitlementUtil;
+import org.apache.syncope.types.AttributableType;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Repository;
 
 @Repository
-public class RoleDAOImpl extends AbstractDAOImpl implements RoleDAO {
+public class RoleDAOImpl extends AbstractAttributableDAOImpl implements RoleDAO {
 
     @Autowired
     private UserDAO userDAO;
 
     @Autowired
-    private TaskDAO taskDAO;
-
-    @Autowired
     private EntitlementDAO entitlementDAO;
 
     @Override
@@ -133,15 +133,6 @@ public class RoleDAOImpl extends Abstrac
         return query.getResultList();
     }
 
-    @Override
-    public List<SyncopeRole> findByResource(final ExternalResource resource) {
-        Query query = entityManager.createQuery("SELECT e FROM " + SyncopeRole.class.getSimpleName() + " e "
-                + "WHERE :resource MEMBER OF e.resources");
-        query.setParameter("resource", resource);
-
-        return query.getResultList();
-    }
-
     private void findAncestors(final List<SyncopeRole> result, final SyncopeRole role) {
         if (role.getParent() != null && !result.contains(role.getParent())) {
             result.add(role.getParent());
@@ -181,6 +172,29 @@ public class RoleDAOImpl extends Abstrac
     }
 
     @Override
+    public List<SyncopeRole> findByDerAttrValue(final String schemaName, final String value)
+            throws InvalidSearchConditionException {
+
+        return findByDerAttrValue(schemaName, value, AttributableUtil.getInstance(AttributableType.ROLE));
+    }
+
+    @Override
+    public List<SyncopeRole> findByAttrValue(final String schemaName, final UAttrValue attrValue) {
+        return findByAttrValue(schemaName, attrValue, AttributableUtil.getInstance(AttributableType.ROLE));
+    }
+
+    @Override
+    public SyncopeRole findByAttrUniqueValue(final String schemaName, final UAttrValue attrUniqueValue) {
+        return (SyncopeRole) findByAttrUniqueValue(schemaName, attrUniqueValue,
+                AttributableUtil.getInstance(AttributableType.ROLE));
+    }
+
+    @Override
+    public List<SyncopeRole> findByResource(final ExternalResource resource) {
+        return findByResource(resource, SyncopeRole.class);
+    }
+
+    @Override
     public List<SyncopeRole> findAll() {
         Query query = entityManager.createQuery("SELECT e FROM SyncopeRole e");
         return query.getResultList();

Modified: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/UserDAOImpl.java
URL: http://svn.apache.org/viewvc/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/UserDAOImpl.java?rev=1415070&r1=1415069&r2=1415070&view=diff
==============================================================================
--- syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/UserDAOImpl.java (original)
+++ syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/persistence/dao/impl/UserDAOImpl.java Thu Nov 29 07:46:03 2012
@@ -18,55 +18,31 @@
  */
 package org.apache.syncope.core.persistence.dao.impl;
 
-import java.io.StringReader;
 import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
-import java.util.regex.Pattern;
 import javax.persistence.NoResultException;
 import javax.persistence.Query;
-import javax.persistence.TemporalType;
 import javax.persistence.TypedQuery;
-import org.apache.commons.jexl2.parser.Parser;
-import org.apache.commons.jexl2.parser.ParserConstants;
-import org.apache.commons.jexl2.parser.Token;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Repository;
-import org.springframework.util.StringUtils;
-import org.apache.syncope.core.persistence.beans.AbstractAttrValue;
 import org.apache.syncope.core.persistence.beans.AbstractVirAttr;
 import org.apache.syncope.core.persistence.beans.ExternalResource;
 import org.apache.syncope.core.persistence.beans.membership.Membership;
 import org.apache.syncope.core.persistence.beans.user.SyncopeUser;
-import org.apache.syncope.core.persistence.beans.user.UAttrUniqueValue;
 import org.apache.syncope.core.persistence.beans.user.UAttrValue;
-import org.apache.syncope.core.persistence.beans.user.UDerSchema;
-import org.apache.syncope.core.persistence.beans.user.USchema;
-import org.apache.syncope.core.persistence.dao.DerSchemaDAO;
 import org.apache.syncope.core.persistence.dao.RoleDAO;
-import org.apache.syncope.core.persistence.dao.SchemaDAO;
-import org.apache.syncope.core.persistence.dao.TaskDAO;
 import org.apache.syncope.core.persistence.dao.UserDAO;
 import org.apache.syncope.core.rest.controller.InvalidSearchConditionException;
+import org.apache.syncope.core.util.AttributableUtil;
+import org.apache.syncope.types.AttributableType;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
 
 @Repository
-public class UserDAOImpl extends AbstractDAOImpl implements UserDAO {
-
-    @Autowired
-    private SchemaDAO schemaDAO;
-
-    @Autowired
-    private DerSchemaDAO derSchemaDAO;
+public class UserDAOImpl extends AbstractAttributableDAOImpl implements UserDAO {
 
     @Autowired
     private RoleDAO roleDAO;
 
-    @Autowired
-    private TaskDAO taskDAO;
-
     @Override
     public SyncopeUser find(final Long id) {
         TypedQuery<SyncopeUser> query = entityManager.createQuery("SELECT e FROM " + SyncopeUser.class.getSimpleName()
@@ -106,135 +82,27 @@ public class UserDAOImpl extends Abstrac
         return query.getSingleResult();
     }
 
-    /**
-     * Find users by derived attribute value. This method could fail if one or more string literals contained into the
-     * derived attribute value provided derive from identifier (schema name) replacement. When you are going to specify
-     * a derived attribute expression you must be quite sure that string literals used to build the expression cannot be
-     * found into the attribute values used to replace attribute schema names used as identifiers.
-     *
-     * @param schemaName derived schema name.
-     * @param value derived attribute value.
-     * @return list of users.
-     * @throws InvalidSearchConditionException in case of errors retrieving schema names used to buid the derived schema
-     * expression.
-     */
     @Override
     public List<SyncopeUser> findByDerAttrValue(final String schemaName, final String value)
             throws InvalidSearchConditionException {
 
-        UDerSchema schema = derSchemaDAO.find(schemaName, UDerSchema.class);
-        if (schema == null) {
-            LOG.error("Invalid schema name '{}'", schemaName);
-            return Collections.emptyList();
-        }
-
-        // query string
-        final StringBuilder querystring = new StringBuilder();
-
-        boolean subquery = false;
-        for (String clause : getWhereClause(schema.getExpression(), value)) {
-            if (querystring.length() > 0) {
-                subquery = true;
-                querystring.append(" AND a.owner_id IN ( ");
-            }
-
-            querystring.append("SELECT a.owner_id ").append("FROM UAttr a, UAttrValue v, USchema s ").append("WHERE ")
-                    .append(clause);
-
-            if (subquery) {
-                querystring.append(')');
-            }
-        }
-
-        LOG.debug("Execute query {}", querystring);
-
-        final Query query = entityManager.createNativeQuery(querystring.toString());
-
-        final List<SyncopeUser> result = new ArrayList<SyncopeUser>();
-
-        SyncopeUser user;
-        for (Object userId : query.getResultList()) {
-            user = find(Long.parseLong(userId.toString()));
-            if (!result.contains(user)) {
-                result.add(user);
-            }
-        }
-
-        return result;
+        return findByDerAttrValue(schemaName, value, AttributableUtil.getInstance(AttributableType.USER));
     }
 
     @Override
     public List<SyncopeUser> findByAttrValue(final String schemaName, final UAttrValue attrValue) {
-
-        USchema schema = schemaDAO.find(schemaName, USchema.class);
-        if (schema == null) {
-            LOG.error("Invalid schema name '{}'", schemaName);
-            return Collections.emptyList();
-        }
-
-        final String entityName = schema.isUniqueConstraint()
-                ? UAttrUniqueValue.class.getName()
-                : UAttrValue.class.getName();
-
-        Query query = entityManager.createQuery("SELECT e FROM " + entityName + " e"
-                + " WHERE e.attribute.schema.name = :schemaName " + " AND (e.stringValue IS NOT NULL"
-                + " AND e.stringValue = :stringValue)" + " OR (e.booleanValue IS NOT NULL"
-                + " AND e.booleanValue = :booleanValue)" + " OR (e.dateValue IS NOT NULL"
-                + " AND e.dateValue = :dateValue)" + " OR (e.longValue IS NOT NULL" + " AND e.longValue = :longValue)"
-                + " OR (e.doubleValue IS NOT NULL" + " AND e.doubleValue = :doubleValue)");
-
-        query.setParameter("schemaName", schemaName);
-        query.setParameter("stringValue", attrValue.getStringValue());
-        query.setParameter("booleanValue", attrValue.getBooleanValue() == null
-                ? null
-                : attrValue.getBooleanAsInteger(attrValue.getBooleanValue()));
-        if (attrValue.getDateValue() != null) {
-            query.setParameter("dateValue", attrValue.getDateValue(), TemporalType.TIMESTAMP);
-        } else {
-            query.setParameter("dateValue", null);
-        }
-        query.setParameter("longValue", attrValue.getLongValue());
-        query.setParameter("doubleValue", attrValue.getDoubleValue());
-
-        List<SyncopeUser> result = new ArrayList<SyncopeUser>();
-        SyncopeUser user;
-        for (AbstractAttrValue value : (List<AbstractAttrValue>) query.getResultList()) {
-
-            user = (SyncopeUser) value.getAttribute().getOwner();
-            if (!result.contains(user)) {
-                result.add(user);
-            }
-        }
-
-        return result;
+        return findByAttrValue(schemaName, attrValue, AttributableUtil.getInstance(AttributableType.USER));
     }
 
     @Override
     public SyncopeUser findByAttrUniqueValue(final String schemaName, final UAttrValue attrUniqueValue) {
-
-        USchema schema = schemaDAO.find(schemaName, USchema.class);
-        if (schema == null) {
-            LOG.error("Invalid schema name '{}'", schemaName);
-            return null;
-        }
-        if (!schema.isUniqueConstraint()) {
-            LOG.error("This schema has not unique constraint: '{}'", schemaName);
-            return null;
-        }
-
-        List<SyncopeUser> result = findByAttrValue(schemaName, attrUniqueValue);
-        return result.isEmpty()
-                ? null
-                : result.iterator().next();
+        return (SyncopeUser) findByAttrUniqueValue(schemaName, attrUniqueValue,
+                AttributableUtil.getInstance(AttributableType.USER));
     }
 
     @Override
     public List<SyncopeUser> findByResource(final ExternalResource resource) {
-        Query query = entityManager.createQuery("SELECT e FROM " + SyncopeUser.class.getSimpleName() + " e "
-                + "WHERE :resource MEMBER OF e.resources");
-        query.setParameter("resource", resource);
-
-        return query.getResultList();
+        return findByResource(resource, SyncopeUser.class);
     }
 
     private StringBuilder getFindAllQuery(final Set<Long> adminRoles) {
@@ -274,7 +142,6 @@ public class UserDAOImpl extends Abstrac
 
     @Override
     public final List<SyncopeUser> findAll(final Set<Long> adminRoles, final int page, final int itemsPerPage) {
-
         final Query query = entityManager.createNativeQuery(getFindAllQuery(adminRoles).toString());
 
         query.setFirstResult(itemsPerPage * (page <= 0
@@ -363,157 +230,4 @@ public class UserDAOImpl extends Abstrac
 
         entityManager.remove(user);
     }
-
-    /**
-     * Generate one where clause for each different attribute schema into the derived schema expression provided.
-     *
-     * @param expression derived schema expression.
-     * @param value derived attribute value.
-     * @return where clauses to use to build the query.
-     * @throws InvalidSearchConditionException in case of errors retrieving identifiers.
-     */
-    private Set<String> getWhereClause(final String expression, final String value)
-            throws InvalidSearchConditionException {
-        final Parser parser = new Parser(new StringReader(expression));
-
-        // Schema names
-        final List<String> identifiers = new ArrayList<String>();
-
-        // Literals
-        final List<String> literals = new ArrayList<String>();
-
-        // Get schema names and literals
-        Token token;
-        while ((token = parser.getNextToken()) != null && StringUtils.hasText(token.toString())) {
-
-            if (token.kind == ParserConstants.STRING_LITERAL) {
-                literals.add(token.toString().substring(1, token.toString().length() - 1));
-            }
-
-            if (token.kind == ParserConstants.IDENTIFIER) {
-                identifiers.add(token.toString());
-            }
-        }
-
-        // Sort literals in order to process later literals included into others
-        Collections.sort(literals, new Comparator<String>() {
-
-            @Override
-            public int compare(String t, String t1) {
-                if (t == null && t1 == null) {
-                    return 0;
-                } else if (t != null && t1 == null) {
-                    return -1;
-                } else if (t == null && t1 != null) {
-                    return 1;
-                } else if (t.length() == t1.length()) {
-                    return 0;
-                } else if (t.length() > t1.length()) {
-                    return -1;
-                } else {
-                    return 1;
-                }
-            }
-        });
-
-        // Split value on provided literals
-        final List<String> attrValues = split(value, literals);
-
-        if (attrValues.size() != identifiers.size()) {
-            LOG.error("Ambiguous jexl expression resolution.");
-            throw new InvalidSearchConditionException("literals and values have different size");
-        }
-
-        // clauses to be used with INTERSECTed queries
-        final Set<String> clauses = new HashSet<String>();
-
-        // builder to build the clauses
-        final StringBuilder bld = new StringBuilder();
-
-        // Contains used identifiers in order to avoid replications
-        final Set<String> used = new HashSet<String>();
-
-        USchema schema;
-
-        // Create several clauses: one for eanch identifiers
-        for (int i = 0; i < identifiers.size(); i++) {
-            if (!used.contains(identifiers.get(i))) {
-
-                // verify schema existence and get schema type
-                schema = schemaDAO.find(identifiers.get(i), USchema.class);
-                if (schema == null) {
-                    LOG.error("Invalid schema name '{}'", identifiers.get(i));
-                    throw new InvalidSearchConditionException("Invalid schema name " + identifiers.get(i));
-                }
-
-                // clear builder
-                bld.delete(0, bld.length());
-
-                bld.append("(");
-
-                // set schema name
-                bld.append("s.name = '").append(identifiers.get(i)).append("'");
-
-                bld.append(" AND ");
-
-                bld.append("s.name = a.schema_name").append(" AND ");
-
-                bld.append("a.id = v.attribute_id");
-
-                bld.append(" AND ");
-
-                // use a value clause different for eanch different schema type
-                switch (schema.getType()) {
-                    case Boolean:
-                        bld.append("v.booleanValue = '").append(attrValues.get(i)).append("'");
-                        break;
-                    case Long:
-                        bld.append("v.longValue = ").append(attrValues.get(i));
-                        break;
-                    case Double:
-                        bld.append("v.doubleValue = ").append(attrValues.get(i));
-                        break;
-                    case Date:
-                        bld.append("v.dateValue = '").append(attrValues.get(i)).append("'");
-                        break;
-                    default:
-                        bld.append("v.stringValue = '").append(attrValues.get(i)).append("'");
-                }
-
-                bld.append(")");
-
-                used.add(identifiers.get(i));
-
-                clauses.add(bld.toString());
-            }
-        }
-
-        LOG.debug("Generated where clauses {}", clauses);
-
-        return clauses;
-    }
-
-    /**
-     * Split an attribute value recurring on provided literals/tokens.
-     *
-     * @param attrValue value to be split.
-     * @param literals literals/tokens.
-     * @return
-     */
-    private List<String> split(final String attrValue, final List<String> literals) {
-
-        final List<String> attrValues = new ArrayList<String>();
-
-        if (literals.isEmpty()) {
-            attrValues.add(attrValue);
-        } else {
-
-            for (String token : attrValue.split(Pattern.quote(literals.get(0)))) {
-
-                attrValues.addAll(split(token, literals.subList(1, literals.size())));
-            }
-        }
-
-        return attrValues;
-    }
 }

Modified: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/report/UserReportlet.java
URL: http://svn.apache.org/viewvc/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/report/UserReportlet.java?rev=1415070&r1=1415069&r2=1415070&view=diff
==============================================================================
--- syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/report/UserReportlet.java (original)
+++ syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/report/UserReportlet.java Thu Nov 29 07:46:03 2012
@@ -22,7 +22,6 @@ import java.util.Collection;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.apache.syncope.client.report.UserReportletConf;
 import org.apache.syncope.client.report.UserReportletConf.Feature;
 import org.apache.syncope.client.to.AbstractAttributableTO;
@@ -31,13 +30,16 @@ import org.apache.syncope.client.to.Memb
 import org.apache.syncope.client.to.UserTO;
 import org.apache.syncope.core.persistence.beans.membership.Membership;
 import org.apache.syncope.core.persistence.beans.user.SyncopeUser;
+import org.apache.syncope.core.persistence.dao.AttributableSearchDAO;
 import org.apache.syncope.core.persistence.dao.EntitlementDAO;
 import org.apache.syncope.core.persistence.dao.UserDAO;
-import org.apache.syncope.core.persistence.dao.UserSearchDAO;
+import static org.apache.syncope.core.report.ReportXMLConst.*;
 import org.apache.syncope.core.rest.data.RoleDataBinder;
 import org.apache.syncope.core.rest.data.UserDataBinder;
-import static org.apache.syncope.core.report.ReportXMLConst.*;
+import org.apache.syncope.core.util.AttributableUtil;
 import org.apache.syncope.core.util.EntitlementUtil;
+import org.apache.syncope.types.AttributableType;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.SAXException;
 import org.xml.sax.helpers.AttributesImpl;
@@ -45,7 +47,7 @@ import org.xml.sax.helpers.AttributesImp
 @ReportletConfClass(UserReportletConf.class)
 public class UserReportlet extends AbstractReportlet<UserReportletConf> {
 
-    private final static int PAGE_SIZE = 10;
+    private static final int PAGE_SIZE = 10;
 
     @Autowired
     private EntitlementDAO entitlementDAO;
@@ -54,7 +56,7 @@ public class UserReportlet extends Abstr
     private UserDAO userDAO;
 
     @Autowired
-    private UserSearchDAO searchDAO;
+    private AttributableSearchDAO searchDAO;
 
     @Autowired
     private UserDataBinder userDataBinder;
@@ -63,11 +65,17 @@ public class UserReportlet extends Abstr
     private RoleDataBinder roleDataBinder;
 
     private List<SyncopeUser> getPagedUsers(final int page) {
-        Set<Long> adminRoleIds = EntitlementUtil.getRoleIds(entitlementDAO.findAll());
+        final Set<Long> adminRoleIds = EntitlementUtil.getRoleIds(entitlementDAO.findAll());
 
-        return conf.getMatchingCond() == null
-                ? userDAO.findAll(adminRoleIds, page, PAGE_SIZE)
-                : searchDAO.search(adminRoleIds, conf.getMatchingCond(), page, PAGE_SIZE);
+        final List<SyncopeUser> result;
+        if (conf.getMatchingCond() == null) {
+            result = userDAO.findAll(adminRoleIds, page, PAGE_SIZE);
+        } else {
+            result = searchDAO.search(adminRoleIds, conf.getMatchingCond(), page, PAGE_SIZE,
+                    AttributableUtil.getInstance(AttributableType.USER));
+        }
+
+        return result;
     }
 
     private int count() {
@@ -75,7 +83,8 @@ public class UserReportlet extends Abstr
 
         return conf.getMatchingCond() == null
                 ? userDAO.count(adminRoleIds)
-                : searchDAO.count(adminRoleIds, conf.getMatchingCond());
+                : searchDAO.count(adminRoleIds, conf.getMatchingCond(),
+                AttributableUtil.getInstance(AttributableType.USER));
     }
 
     private void doExtractResources(final ContentHandler handler, final AbstractAttributableTO attributableTO)
@@ -122,8 +131,8 @@ public class UserReportlet extends Abstr
                         handler.endElement("", "", "value");
                     }
                 } else {
-                    LOG.debug("{} not found for {}[{}]", new Object[] { attrName,
-                            attributableTO.getClass().getSimpleName(), attributableTO.getId() });
+                    LOG.debug("{} not found for {}[{}]", new Object[]{attrName,
+                                attributableTO.getClass().getSimpleName(), attributableTO.getId()});
                 }
 
                 handler.endElement("", "", "attribute");
@@ -148,8 +157,8 @@ public class UserReportlet extends Abstr
                         handler.endElement("", "", "value");
                     }
                 } else {
-                    LOG.debug("{} not found for {}[{}]", new Object[] { attrName,
-                            attributableTO.getClass().getSimpleName(), attributableTO.getId() });
+                    LOG.debug("{} not found for {}[{}]", new Object[]{attrName,
+                                attributableTO.getClass().getSimpleName(), attributableTO.getId()});
                 }
 
                 handler.endElement("", "", "derivedAttribute");
@@ -174,8 +183,8 @@ public class UserReportlet extends Abstr
                         handler.endElement("", "", "value");
                     }
                 } else {
-                    LOG.debug("{} not found for {}[{}]", new Object[] { attrName,
-                            attributableTO.getClass().getSimpleName(), attributableTO.getId() });
+                    LOG.debug("{} not found for {}[{}]", new Object[]{attrName,
+                                attributableTO.getClass().getSimpleName(), attributableTO.getId()});
                 }
 
                 handler.endElement("", "", "virtualAttribute");
@@ -302,7 +311,6 @@ public class UserReportlet extends Abstr
 
     @Override
     protected void doExtract(final ContentHandler handler) throws SAXException, ReportException {
-
         for (int i = 1; i <= (count() / PAGE_SIZE) + 1; i++) {
             doExtract(handler, getPagedUsers(i));
         }

Modified: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/controller/RoleController.java
URL: http://svn.apache.org/viewvc/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/controller/RoleController.java?rev=1415070&r1=1415069&r2=1415070&view=diff
==============================================================================
--- syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/controller/RoleController.java (original)
+++ syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/controller/RoleController.java Thu Nov 29 07:46:03 2012
@@ -24,12 +24,14 @@ import java.util.List;
 import java.util.Set;
 import javax.servlet.http.HttpServletResponse;
 import org.apache.syncope.client.mod.RoleMod;
+import org.apache.syncope.client.search.NodeCond;
 import org.apache.syncope.client.to.PropagationTO;
 import org.apache.syncope.client.to.RoleTO;
 import org.apache.syncope.core.audit.AuditManager;
 import org.apache.syncope.core.persistence.beans.PropagationTask;
 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.AttributableSearchDAO;
 import org.apache.syncope.core.persistence.dao.RoleDAO;
 import org.apache.syncope.core.persistence.dao.UserDAO;
 import org.apache.syncope.core.propagation.DefaultPropagationHandler;
@@ -37,12 +39,15 @@ import org.apache.syncope.core.propagati
 import org.apache.syncope.core.propagation.PropagationManager;
 import org.apache.syncope.core.propagation.PropagationTaskExecutor;
 import org.apache.syncope.core.rest.data.RoleDataBinder;
+import org.apache.syncope.core.util.AttributableUtil;
 import org.apache.syncope.core.util.ConnObjectUtil;
 import org.apache.syncope.core.util.EntitlementUtil;
 import org.apache.syncope.core.util.NotFoundException;
 import org.apache.syncope.core.workflow.WorkflowException;
 import org.apache.syncope.core.workflow.WorkflowResult;
 import org.apache.syncope.core.workflow.role.RoleWorkflowAdapter;
+import org.apache.syncope.types.AttributableType;
+import org.apache.syncope.types.AuditElements;
 import org.apache.syncope.types.AuditElements.Category;
 import org.apache.syncope.types.AuditElements.Result;
 import org.apache.syncope.types.AuditElements.RoleSubCategory;
@@ -59,6 +64,7 @@ import org.springframework.web.bind.anno
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
 
 @Controller
 @RequestMapping("/role")
@@ -74,6 +80,9 @@ public class RoleController extends Abst
     private UserDAO userDAO;
 
     @Autowired
+    private AttributableSearchDAO searchDAO;
+
+    @Autowired
     private RoleDataBinder dataBinder;
 
     @Autowired
@@ -191,6 +200,77 @@ public class RoleController extends Abst
         return childrenTOs;
     }
 
+    @PreAuthorize("hasRole('ROLE_READ')")
+    @RequestMapping(method = RequestMethod.POST, value = "/search")
+    @Transactional(readOnly = true, rollbackFor = {Throwable.class})
+    public List<RoleTO> search(@RequestBody final NodeCond searchCondition)
+            throws InvalidSearchConditionException {
+
+        LOG.debug("Role search called with condition {}", searchCondition);
+
+        if (!searchCondition.checkValidity()) {
+            LOG.error("Invalid search condition: {}", searchCondition);
+            throw new InvalidSearchConditionException();
+        }
+
+        List<SyncopeRole> matchingRoles = searchDAO.search(EntitlementUtil.getRoleIds(EntitlementUtil.
+                getOwnedEntitlementNames()), searchCondition, AttributableUtil.getInstance(AttributableType.ROLE));
+        List<RoleTO> result = new ArrayList<RoleTO>(matchingRoles.size());
+        for (SyncopeRole role : matchingRoles) {
+            result.add(dataBinder.getRoleTO(role));
+        }
+
+        auditManager.audit(Category.role, AuditElements.RoleSubCategory.read, Result.success,
+                "Successfully searched for roles: " + result.size());
+
+        return result;
+    }
+
+    @PreAuthorize("hasRole('ROLE_READ')")
+    @RequestMapping(method = RequestMethod.POST, value = "/search/{page}/{size}")
+    @Transactional(readOnly = true, rollbackFor = {Throwable.class})
+    public List<RoleTO> search(@RequestBody final NodeCond searchCondition, @PathVariable("page") final int page,
+            @PathVariable("size") final int size)
+            throws InvalidSearchConditionException {
+
+        LOG.debug("Role search called with condition {}", searchCondition);
+
+        if (!searchCondition.checkValidity()) {
+            LOG.error("Invalid search condition: {}", searchCondition);
+            throw new InvalidSearchConditionException();
+        }
+
+        final List<SyncopeRole> matchingRoles = searchDAO.search(EntitlementUtil.getRoleIds(EntitlementUtil.
+                getOwnedEntitlementNames()), searchCondition, page, size,
+                AttributableUtil.getInstance(AttributableType.ROLE));
+
+        final List<RoleTO> result = new ArrayList<RoleTO>(matchingRoles.size());
+        for (SyncopeRole role : matchingRoles) {
+            result.add(dataBinder.getRoleTO(role));
+        }
+
+        auditManager.audit(Category.role, AuditElements.RoleSubCategory.read, Result.success,
+                "Successfully searched for roles (page=" + page + ", size=" + size + "): " + result.size());
+
+        return result;
+    }
+
+    @PreAuthorize("hasRole('ROLE_READ')")
+    @RequestMapping(method = RequestMethod.POST, value = "/search/count")
+    @Transactional(readOnly = true, rollbackFor = {Throwable.class})
+    public ModelAndView searchCount(@RequestBody final NodeCond searchCondition)
+            throws InvalidSearchConditionException {
+
+        if (!searchCondition.checkValidity()) {
+            LOG.error("Invalid search condition: {}", searchCondition);
+            throw new InvalidSearchConditionException();
+        }
+
+        final Set<Long> adminRoleIds = EntitlementUtil.getRoleIds(EntitlementUtil.getOwnedEntitlementNames());
+        return new ModelAndView().addObject(searchDAO.count(adminRoleIds, searchCondition,
+                AttributableUtil.getInstance(AttributableType.ROLE)));
+    }
+
     @RequestMapping(method = RequestMethod.GET, value = "/list")
     @Transactional(readOnly = true)
     public List<RoleTO> list() {

Modified: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/controller/UserController.java
URL: http://svn.apache.org/viewvc/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/controller/UserController.java?rev=1415070&r1=1415069&r2=1415070&view=diff
==============================================================================
--- syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/controller/UserController.java (original)
+++ syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/controller/UserController.java Thu Nov 29 07:46:03 2012
@@ -36,19 +36,21 @@ import org.apache.syncope.core.audit.Aud
 import org.apache.syncope.core.notification.NotificationManager;
 import org.apache.syncope.core.persistence.beans.PropagationTask;
 import org.apache.syncope.core.persistence.beans.user.SyncopeUser;
+import org.apache.syncope.core.persistence.dao.AttributableSearchDAO;
 import org.apache.syncope.core.persistence.dao.UserDAO;
-import org.apache.syncope.core.persistence.dao.UserSearchDAO;
 import org.apache.syncope.core.propagation.DefaultPropagationHandler;
 import org.apache.syncope.core.propagation.PropagationException;
 import org.apache.syncope.core.propagation.PropagationManager;
 import org.apache.syncope.core.propagation.PropagationTaskExecutor;
 import org.apache.syncope.core.rest.data.UserDataBinder;
+import org.apache.syncope.core.util.AttributableUtil;
 import org.apache.syncope.core.util.ConnObjectUtil;
 import org.apache.syncope.core.util.EntitlementUtil;
 import org.apache.syncope.core.util.NotFoundException;
 import org.apache.syncope.core.workflow.WorkflowException;
 import org.apache.syncope.core.workflow.WorkflowResult;
 import org.apache.syncope.core.workflow.user.UserWorkflowAdapter;
+import org.apache.syncope.types.AttributableType;
 import org.apache.syncope.types.AuditElements.Category;
 import org.apache.syncope.types.AuditElements.Result;
 import org.apache.syncope.types.AuditElements.UserSubCategory;
@@ -88,7 +90,7 @@ public class UserController {
     private UserDAO userDAO;
 
     @Autowired
-    private UserSearchDAO searchDAO;
+    private AttributableSearchDAO searchDAO;
 
     @Autowired
     private UserDataBinder dataBinder;
@@ -144,9 +146,9 @@ public class UserController {
             throw new InvalidSearchConditionException();
         }
 
-        Set<Long> adminRoleIds = EntitlementUtil.getRoleIds(EntitlementUtil.getOwnedEntitlementNames());
-
-        return new ModelAndView().addObject(searchDAO.count(adminRoleIds, searchCondition));
+        final Set<Long> adminRoleIds = EntitlementUtil.getRoleIds(EntitlementUtil.getOwnedEntitlementNames());
+        return new ModelAndView().addObject(searchDAO.count(adminRoleIds, searchCondition,
+                AttributableUtil.getInstance(AttributableType.USER)));
     }
 
     @PreAuthorize("hasRole('USER_LIST')")
@@ -200,7 +202,7 @@ public class UserController {
         return result;
     }
 
-    @PreAuthorize("hasRole('USER_READ')")
+    @PreAuthorize("#username == authentication.name or hasRole('USER_READ')")
     @RequestMapping(method = RequestMethod.GET, value = "/readByUsername/{username}")
     @Transactional(readOnly = true, rollbackFor = {Throwable.class})
     public UserTO read(@PathVariable final String username)
@@ -214,6 +216,18 @@ public class UserController {
         return result;
     }
 
+    @PreAuthorize("isAuthenticated()")
+    @RequestMapping(method = RequestMethod.GET, value = "/read/self")
+    @Transactional(readOnly = true)
+    public UserTO read() throws NotFoundException {
+        UserTO userTO = dataBinder.getAuthenticatedUserTO();
+
+        auditManager.audit(Category.user, UserSubCategory.read, Result.success,
+                "Successfully read own data: " + userTO.getUsername());
+
+        return userTO;
+    }
+
     @PreAuthorize("hasRole('USER_READ')")
     @RequestMapping(method = RequestMethod.POST, value = "/search")
     @Transactional(readOnly = true, rollbackFor = {Throwable.class})
@@ -228,7 +242,7 @@ public class UserController {
         }
 
         List<SyncopeUser> matchingUsers = searchDAO.search(EntitlementUtil.getRoleIds(EntitlementUtil.
-                getOwnedEntitlementNames()), searchCondition);
+                getOwnedEntitlementNames()), searchCondition, AttributableUtil.getInstance(AttributableType.USER));
         List<UserTO> result = new ArrayList<UserTO>(matchingUsers.size());
         for (SyncopeUser user : matchingUsers) {
             result.add(dataBinder.getUserTO(user));
@@ -255,7 +269,8 @@ public class UserController {
         }
 
         final List<SyncopeUser> matchingUsers = searchDAO.search(EntitlementUtil.getRoleIds(EntitlementUtil.
-                getOwnedEntitlementNames()), searchCondition, page, size);
+                getOwnedEntitlementNames()), searchCondition, page, size,
+                AttributableUtil.getInstance(AttributableType.USER));
 
         final List<UserTO> result = new ArrayList<UserTO>(matchingUsers.size());
         for (SyncopeUser user : matchingUsers) {

Modified: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/controller/UserRequestController.java
URL: http://svn.apache.org/viewvc/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/controller/UserRequestController.java?rev=1415070&r1=1415069&r2=1415070&view=diff
==============================================================================
--- syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/controller/UserRequestController.java (original)
+++ syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/controller/UserRequestController.java Thu Nov 29 07:46:03 2012
@@ -67,21 +67,8 @@ public class UserRequestController {
     @Autowired
     private UserRequestDataBinder dataBinder;
 
-    @PreAuthorize("isAuthenticated()")
-    @RequestMapping(method = RequestMethod.GET, value = "/read/self")
-    @Transactional(readOnly = true)
-    public UserTO read() throws NotFoundException {
-
-        UserTO userTO = dataBinder.getAuthUserTO();
-
-        auditManager.audit(Category.userRequest, UserRequestSubCategory.read, Result.success,
-                "Successfully read self data");
-
-        return userTO;
-    }
-
     private Boolean isCreateAllowedByConf() {
-        SyncopeConf createRequestAllowed = confDAO.find("createRequest.allowed", "false");
+        final SyncopeConf createRequestAllowed = confDAO.find("createRequest.allowed", "false");
 
         return Boolean.valueOf(createRequestAllowed.getValue());
     }
@@ -89,7 +76,6 @@ public class UserRequestController {
     @RequestMapping(method = RequestMethod.GET, value = "/create/allowed")
     @Transactional(readOnly = true)
     public ModelAndView isCreateAllowed() {
-
         auditManager.audit(Category.userRequest, UserRequestSubCategory.isCreateAllowed, Result.success,
                 "Successfully checked whether self create is allowed");
 
@@ -98,7 +84,6 @@ public class UserRequestController {
 
     @RequestMapping(method = RequestMethod.POST, value = "/create")
     public UserRequestTO create(@RequestBody final UserTO userTO) throws UnauthorizedRoleException {
-
         if (!isCreateAllowedByConf()) {
             LOG.error("Create requests are not allowed");
 
@@ -146,6 +131,29 @@ public class UserRequestController {
         return dataBinder.getUserRequestTO(request);
     }
 
+    @PreAuthorize("isAuthenticated()")
+    @RequestMapping(method = RequestMethod.GET, value = "/delete/{userId}")
+    public UserRequestTO delete(@PathVariable("userId") final Long userId) throws NotFoundException,
+            UnauthorizedRoleException {
+
+        LOG.debug("Request user delete called with {}", userId);
+
+        try {
+            dataBinder.testDelete(userId);
+        } catch (RollbackException e) {
+            LOG.debug("Testing delete - ignore exception");
+        }
+
+        UserRequest request = new UserRequest();
+        request.setUserId(userId);
+        request = userRequestDAO.save(request);
+
+        auditManager.audit(Category.userRequest, UserRequestSubCategory.delete, Result.success,
+                "Successfully deleted user request for user" + userId);
+
+        return dataBinder.getUserRequestTO(request);
+    }
+
     @PreAuthorize("hasRole('USER_REQUEST_LIST')")
     @RequestMapping(method = RequestMethod.GET, value = "/list")
     @Transactional(readOnly = true)
@@ -166,7 +174,6 @@ public class UserRequestController {
     @RequestMapping(method = RequestMethod.GET, value = "/read/{requestId}")
     @Transactional(readOnly = true)
     public UserRequestTO read(@PathVariable("requestId") final Long requestId) throws NotFoundException {
-
         UserRequest request = userRequestDAO.find(requestId);
         if (request == null) {
             throw new NotFoundException("User request " + requestId);
@@ -178,44 +185,21 @@ public class UserRequestController {
         return dataBinder.getUserRequestTO(request);
     }
 
-    @PreAuthorize("isAuthenticated()")
-    @RequestMapping(method = RequestMethod.GET, value = "/delete/{requestId}")
-    public UserRequestTO delete(@PathVariable("requestId") final Long userId) throws NotFoundException, UnauthorizedRoleException {
-
-        LOG.debug("Request user delete called with {}", userId);
-
-        try {
-            dataBinder.testDelete(userId);
-        } catch (RollbackException e) {
-            LOG.debug("Testing delete - ignore exception");
-        }
-
-        UserRequest request = new UserRequest();
-        request.setUserId(userId);
-        request = userRequestDAO.save(request);
-
-        auditManager.audit(Category.userRequest, UserRequestSubCategory.delete, Result.success,
-                "Successfully deleted user request for user" + userId);
-
-        return dataBinder.getUserRequestTO(request);
-    }
-
     @PreAuthorize("hasRole('USER_REQUEST_DELETE')")
     @RequestMapping(method = RequestMethod.GET, value = "/deleteRequest/{requestId}")
     public UserRequestTO deleteRequest(@PathVariable("requestId") final Long requestId) throws NotFoundException {
-
         UserRequest request = userRequestDAO.find(requestId);
         if (request == null) {
             throw new NotFoundException("User request " + requestId);
         }
-        
+
         UserRequestTO requestToDelete = dataBinder.getUserRequestTO(request);
 
         auditManager.audit(Category.userRequest, UserRequestSubCategory.delete, Result.success,
                 "Successfully deleted user request for user" + request.getUserId());
 
         userRequestDAO.delete(requestId);
-        
+
         return requestToDelete;
     }
 }

Modified: syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/data/ResourceDataBinder.java
URL: http://svn.apache.org/viewvc/syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/data/ResourceDataBinder.java?rev=1415070&r1=1415069&r2=1415070&view=diff
==============================================================================
--- syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/data/ResourceDataBinder.java (original)
+++ syncope/branches/DEV_ROLE_PROVISIONING/core/src/main/java/org/apache/syncope/core/rest/data/ResourceDataBinder.java Thu Nov 29 07:46:03 2012
@@ -137,8 +137,11 @@ public class ResourceDataBinder {
 
         resource.setConnectorConfigurationProperties(new HashSet<ConnConfProperty>(resourceTO.getConnConfProperties()));
 
-        if (resourceTO.getSyncToken() == null) {
-            resource.setSerializedSyncToken(null);
+        if (resourceTO.getUsyncToken() == null) {
+            resource.setUserializedSyncToken(null);
+        }
+        if (resourceTO.getRsyncToken() == null) {
+            resource.setRserializedSyncToken(null);
         }
 
         resource.setActionsClassName(resourceTO.getActionsClassName());
@@ -240,7 +243,9 @@ public class ResourceDataBinder {
                 ? null : resource.getSyncPolicy().getId());
 
         resourceTO.setConnectorConfigurationProperties(resource.getConfiguration());
-        resourceTO.setSyncToken(resource.getSerializedSyncToken());
+
+        resourceTO.setUsyncToken(resource.getUserializedSyncToken());
+        resourceTO.setRsyncToken(resource.getRserializedSyncToken());
 
         resourceTO.setActionsClassName(resource.getActionsClassName());
 



Mime
View raw message