Example usage for org.hibernate Query setParameterList

List of usage examples for org.hibernate Query setParameterList

Introduction

In this page you can find the example usage for org.hibernate Query setParameterList.

Prototype

Query<R> setParameterList(int position, Object[] values);

Source Link

Usage

From source file:io.github.jonestimd.finance.dao.hibernate.AccountDaoImpl.java

License:Open Source License

public void removeAccountsFromCompanies(final Collection<Company> companies) {
    Query query = getSession().getNamedQuery("account.removeFromCompany");
    query.setParameterList("companies", companies);
    query.executeUpdate();//from w  w  w  .j  a  v  a2  s. c  om
}

From source file:io.github.jonestimd.finance.dao.hibernate.TransactionDetailDaoImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<TransactionDetail> findSecuritySalesWithoutLots(String namePrefix, Date saleDate) {
    Query query = getSession().getNamedQuery(TransactionDetail.SECURITY_SALES_WITHOUT_LOTS);
    query.setParameter("securityName", namePrefix + "%");
    query.setParameter("saleDate", saleDate);
    query.setParameterList("actions", Arrays.asList(SELL.code(), SHARES_OUT.code()));
    return query.list();
}

From source file:io.github.jonestimd.finance.dao.hibernate.TransactionDetailDaoImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<TransactionDetail> findPurchasesWithRemainingShares(Account account, Asset security,
        Date purchaseDate) {/*  www.ja v a  2 s  .  c o  m*/
    Query query = getSession().getNamedQuery(TransactionDetail.UNSOLD_SECURITY_SHARES_BY_DATE);
    query.setParameter("account", account);
    query.setParameter("security", security);
    query.setParameter("purchaseDate", purchaseDate);
    query.setParameterList("actions", Arrays.asList(BUY.code(), SHARES_IN.code(), REINVEST.code()));
    return query.list();
}

From source file:it.cilea.osd.common.dao.impl.GenericDaoHibernateImpl.java

License:Open Source License

/**
 * We support only named query without named parameter OR with only named
 * parameter named like par&lt;idx&gt;
 * //from  w ww  . j a v a2s . c om
 * @param method
 * @param querySuffixes
 * @param queryArgs
 * @return
 */
private Query buildQuery(Method method, String[] querySuffixes, Object[] queryArgs) {
    StringBuffer sb = new StringBuffer();
    sb.append(type.getSimpleName()).append('.').append(method.getName());
    if (querySuffixes != null) {
        for (int i = 0; i < querySuffixes.length; i++) {
            sb.append('.').append(querySuffixes[i]);
        }
    }
    String queryName = new String(sb);
    Query namedQuery = getSession().getNamedQuery(queryName);
    String[] namedParameters = namedQuery.getNamedParameters();

    if (namedParameters.length > 0) {
        for (int i = 0; i < namedParameters.length; i++) {
            Object arg = queryArgs[i];
            if (arg instanceof Collection) {

                namedQuery.setParameterList("par" + i, (Collection) arg);
            } else {

                namedQuery.setParameter("par" + i, arg);
            }
        }
    } else if (queryArgs != null) {
        for (int i = 0; i < queryArgs.length; i++) {
            Object arg = queryArgs[i];
            namedQuery.setParameter(i, arg);
        }
    }
    return namedQuery;
}

From source file:it.eng.spagobi.analiticalmodel.document.dao.BIObjectDAOHibImpl.java

License:Mozilla Public License

/**
 * Loads visible objects of the user roles
 * @param folderID/*from w  ww .  j a  v a  2 s  .  c  o m*/
 * @param profile the profile of the user
 * @return
 * @throws EMFUserError
 */
public List loadBIObjects(Integer folderID, IEngUserProfile profile, boolean isPersonalFolder)
        throws EMFUserError {
    logger.debug("IN");
    Session aSession = null;
    Transaction tx = null;
    List realResult = new ArrayList();
    try {
        aSession = getSession();
        tx = aSession.beginTransaction();
        StringBuffer buffer = new StringBuffer();
        Collection roles = null;

        if (!isPersonalFolder) {

            try {
                if (profile != null)
                    roles = ((UserProfile) profile).getRolesForUse();
            } catch (Exception e) {
                logger.error("Error while recovering user profile", e);
            }

            if (folderID != null && roles != null && roles.size() > 0) {
                buffer.append("select o from SbiObjects o, SbiObjFunc sof, SbiFunctions f,  SbiFuncRole fr "
                        + "where sof.id.sbiFunctions.functId = f.functId and o.biobjId = sof.id.sbiObjects.biobjId  "
                        + " and fr.id.role.extRoleId IN (select extRoleId from SbiExtRoles e  where  e.name in (:ROLES)) "
                        + " and fr.id.function.functId = f.functId " + " and f.functId = :FOLDER_ID  ");

                if (profile.isAbleToExecuteAction(SpagoBIConstants.DOCUMENT_MANAGEMENT_ADMIN)) {
                    //                  buffer.append(" and ( fr.id.state.valueId = o.state OR o.stateCode = 'SUSP') " ); 

                    buffer.append(" and (" + "(fr.id.state.valueCd = '"
                            + SpagoBIConstants.PERMISSION_ON_FOLDER_TO_DEVELOP + "' AND o.state.valueCd = '"
                            + SpagoBIConstants.DOC_STATE_DEV + "') OR" + "(fr.id.state.valueCd = '"
                            + SpagoBIConstants.PERMISSION_ON_FOLDER_TO_TEST + "' AND o.state.valueCd = '"
                            + SpagoBIConstants.DOC_STATE_TEST + "') OR " + "(fr.id.state.valueCd = '"
                            + SpagoBIConstants.PERMISSION_ON_FOLDER_TO_EXECUTE + "' AND o.state.valueCd = '"
                            + SpagoBIConstants.DOC_STATE_REL + "') OR " + "o.stateCode = '"
                            + SpagoBIConstants.DOC_STATE_SUSP + "'" + ") ");
                } else {
                    buffer.append(" and (" + "(fr.id.state.valueCd = '"
                            + SpagoBIConstants.PERMISSION_ON_FOLDER_TO_DEVELOP + "' AND o.state.valueCd = '"
                            + SpagoBIConstants.DOC_STATE_DEV + "') OR" + "(fr.id.state.valueCd = '"
                            + SpagoBIConstants.PERMISSION_ON_FOLDER_TO_TEST + "' AND o.state.valueCd = '"
                            + SpagoBIConstants.DOC_STATE_TEST + "') OR " + "(fr.id.state.valueCd = '"
                            + SpagoBIConstants.PERMISSION_ON_FOLDER_TO_EXECUTE + "' AND o.state.valueCd = '"
                            + SpagoBIConstants.DOC_STATE_REL + "')" + ") ");
                }

                if (!profile.isAbleToExecuteAction(SpagoBIConstants.DOCUMENT_MANAGEMENT_ADMIN)
                        && !profile.isAbleToExecuteAction(SpagoBIConstants.DOCUMENT_MANAGEMENT_DEV)) {
                    buffer.append(" and o.visible = 1"); //only visible objetcs (1 means true)
                }
                buffer.append(" order by o.name");
            } else {
                buffer.append("select objects from SbiObjects as objects ");
            }
        } else {
            if (folderID != null) {
                buffer.append("select o from SbiObjects o, SbiObjFunc sof, SbiFunctions f "
                        + "where sof.id.sbiFunctions.functId = f.functId and o.biobjId = sof.id.sbiObjects.biobjId  "
                        + " and f.functId = :FOLDER_ID  ");

                if (!profile.isAbleToExecuteAction(SpagoBIConstants.DOCUMENT_MANAGEMENT_ADMIN)
                        && !profile.isAbleToExecuteAction(SpagoBIConstants.DOCUMENT_MANAGEMENT_DEV)) {
                    buffer.append(" and o.visible = 1"); //only visible objetcs (1 means true)
                }
                buffer.append(" order by o.name");
            }
        }

        String hql = buffer.toString();
        Query query = aSession.createQuery(hql);

        if (!isPersonalFolder) {
            if (folderID != null && roles != null && roles.size() > 0) {
                query.setInteger("FOLDER_ID", folderID.intValue());
                query.setParameterList("ROLES", roles);
            }
        } else {
            if (folderID != null) {
                query.setInteger("FOLDER_ID", folderID.intValue());
            }
        }

        List hibList = query.list();
        Iterator it = hibList.iterator();
        while (it.hasNext()) {
            SbiObjects object = (SbiObjects) it.next();
            realResult.add(toBIObject(object));
        }
        tx.commit();
    } catch (HibernateException he) {
        logger.error(he);
        if (tx != null)
            tx.rollback();
        throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
    } catch (Exception e) {
        logger.error(e);
        if (tx != null)
            tx.rollback();
        throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
    } finally {
        if (aSession != null) {
            if (aSession.isOpen())
                aSession.close();
        }
    }
    logger.debug("OUT");
    return realResult;
}

From source file:it.eng.spagobi.analiticalmodel.document.dao.BIObjectDAOHibImpl.java

License:Mozilla Public License

/**
 * Search objects with the features specified
 * @param valueFilter  the value of the filter for the research
 * @param typeFilter   the type of the filter (the operator: equals, starts...)
 * @param columnFilter the column on which the filter is applied
 * @param nodeFilter   the node (folder id) on which the filter is applied
 * @param profile      the profile of the user
 * @return//from w  w w . ja v  a2  s  . co  m
 * @throws EMFUserError
 */
public List searchBIObjects(String valueFilter, String typeFilter, String columnFilter, String scope,
        Integer nodeFilter, IEngUserProfile profile) throws EMFUserError {
    logger.debug("IN");
    Session aSession = null;
    Transaction tx = null;
    List realResult = new ArrayList();
    try {
        aSession = getSession();
        tx = aSession.beginTransaction();

        Collection roles = null;
        try {
            RequestContainer reqCont = RequestContainer.getRequestContainer();
            roles = ((UserProfile) profile).getRolesForUse();
            logger.debug("Profile roles: " + roles);

        } catch (Exception e) {
            logger.error("Error while recovering user profile", e);
            throw new EMFUserError(EMFErrorSeverity.ERROR, 1084);
        }

        StringBuffer bufferSelect = new StringBuffer();
        StringBuffer bufferFrom = new StringBuffer();
        StringBuffer bufferWhere = new StringBuffer();
        StringBuffer bufferOrder = new StringBuffer();

        //definition of the the search query 
        if (roles != null && roles.size() > 0) {
            bufferSelect.append(" select distinct o ");
            /*bufferSelect.append(" select distinct o.biobjId, o.sbiEngines, o.descr, o.label, o.path, o.relName, o.state, "+
                " o.stateCode, o.objectTypeCode, o.objectType, o.schedFl, "+
                " o.execMode, o.stateConsideration, o.execModeCode, o.stateConsiderationCode, o.name, o.visible, o.uuid, " +
                " o.extendedDescription, o.objectve, o.language, o.creationDate, o.creationUser, "+
                " o.keywords, o.refreshSeconds, o.profiledVisibility ");*/
            bufferFrom
                    .append(" from SbiObjects as o, SbiObjFunc as sof, SbiFunctions as f,  SbiFuncRole as fr ");
            bufferWhere.append(
                    " where sof.id.sbiFunctions.functId = f.functId and o.biobjId = sof.id.sbiObjects.biobjId and "
                            + " ((fr.id.role.extRoleId IN (select extRoleId from SbiExtRoles e  where  e.name in (:ROLES)) "
                            + " and fr.id.function.functId = f.functId and (" + "(fr.id.state.valueCd = '"
                            + SpagoBIConstants.PERMISSION_ON_FOLDER_TO_DEVELOP + "' AND o.state.valueCd = '"
                            + SpagoBIConstants.DOC_STATE_DEV + "') OR" + "(fr.id.state.valueCd = '"
                            + SpagoBIConstants.PERMISSION_ON_FOLDER_TO_TEST + "' AND o.state.valueCd = '"
                            + SpagoBIConstants.DOC_STATE_TEST + "') OR " + "(fr.id.state.valueCd = '"
                            + SpagoBIConstants.PERMISSION_ON_FOLDER_TO_EXECUTE + "' AND o.state.valueCd = '"
                            + SpagoBIConstants.DOC_STATE_REL + "') "
                            + ") ) OR  f.path like :PERSONAL_FOLDER_PREFIX )");

        }
        String operCondition = "";
        String likeStart = "";
        String likeEnd = "";
        if (valueFilter != null && !valueFilter.equals("") && typeFilter != null && !typeFilter.equals("")
                && columnFilter != null && !columnFilter.equals("")) {
            //defines correct logical operator
            if (typeFilter.equalsIgnoreCase(START_WITH)) {
                operCondition = " like :VALUE_FILTER";
                likeStart = "";
                likeEnd = "%";
            } else if (typeFilter.equalsIgnoreCase(END_WITH)) {
                operCondition = " like :VALUE_FILTER";
                likeStart = "%";
                likeEnd = "";
            } else if (EQUALS_TO.equalsIgnoreCase(typeFilter)) {
                operCondition = " = :VALUE_FILTER";
            } else if (NOT_EQUALS_TO.equalsIgnoreCase(typeFilter)) {
                operCondition = " != :VALUE_FILTER";
            } else if (GREATER_THAN.equalsIgnoreCase(typeFilter)) {
                operCondition = " > :VALUE_FILTER";
            } else if (LESS_THAN.equalsIgnoreCase(typeFilter)) {
                operCondition = " < :VALUE_FILTER";
            } else if (CONTAINS.equalsIgnoreCase(typeFilter)) {
                operCondition = " like :VALUE_FILTER";
                likeStart = "%";
                likeEnd = "%";
            } else if (EQUALS_OR_LESS_THAN.equalsIgnoreCase(typeFilter)) {
                operCondition = " <= :VALUE_FILTER";
            } else if (EQUALS_OR_GREATER_THAN.equalsIgnoreCase(typeFilter)) {
                operCondition = " >= :VALUE_FILTER";
                /*
                }else if (NOT_ENDS_WITH.equalsIgnoreCase( typeFilter )) {
                operCondition =  "NOT LIKE %:VALUE_FILTER";
                } else if (NOT_CONTAINS.equalsIgnoreCase( typeFilter )) {
                operCondition =  "NOT LIKE %:VALUE_FILTER%";
                } else if (IS_NULL.equalsIgnoreCase( typeFilter )) {
                operCondition =  "IS NULL";
                } else if (NOT_NULL.equalsIgnoreCase( typeFilter )) {
                operCondition =  "IS NOT NULL";*/
            } else {
                logger.error("The query Operator " + typeFilter + " is invalid.");
                throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
            }

            if (columnFilter.equalsIgnoreCase(COLUMN_LABEL)) {
                bufferWhere.append(" and o.label " + operCondition);
            }
            if (columnFilter.equalsIgnoreCase(COLUMN_NAME)) {
                bufferWhere.append(" and o.name " + operCondition);
            }
            if (columnFilter.equalsIgnoreCase(COLUMN_ENGINE)) {
                bufferFrom.append(", SbiEngines e ");
                bufferWhere.append(" and e.engineId = o.sbiEngines and e.name " + operCondition);
            }

            if (columnFilter.equalsIgnoreCase(COLUMN_STATE)) {
                bufferFrom.append(", SbiDomains d ");
                bufferWhere.append(" and d.valueId = o.state and d.valueCd " + operCondition);
            }

            if (columnFilter.equalsIgnoreCase(COLUMN_TYPE)) {
                bufferFrom.append(", SbiDomains d ");
                bufferWhere.append(" and d.valueId = o.objectType and d.valueCd " + operCondition);
            }

            if (columnFilter != null && columnFilter.equalsIgnoreCase(COLUMN_DATE)) {
                bufferWhere.append(" and convert(o.creationDate, DATE) " + operCondition);
            }

        }

        if (scope != null && scope.equals(SCOPE_NODE) && nodeFilter != null && !nodeFilter.equals("")) {
            bufferWhere.append(" and (f.functId = :FOLDER_ID or f.parentFunct = :FOLDER_ID) ");
        }

        bufferOrder.append(" order by o.name");

        String hql = bufferSelect.toString() + bufferFrom.toString() + bufferWhere.toString()
                + bufferOrder.toString();

        logger.debug("query hql: " + hql);

        Query query = aSession.createQuery(hql);

        query.setParameter("PERSONAL_FOLDER_PREFIX",
                "/" + ((UserProfile) profile).getUserId().toString() + "%");

        //setting query parameters
        query.setParameterList("ROLES", roles);
        logger.debug("Parameter value ROLES: " + roles);

        if (valueFilter != null) {
            if (!likeStart.equals("") || !likeEnd.equals("")) {
                query.setParameter("VALUE_FILTER", likeStart + valueFilter + likeEnd);
                logger.debug("Parameter value VALUE_FILTER: " + likeStart + valueFilter + likeEnd);
            } else {
                query.setParameter("VALUE_FILTER", valueFilter);
                logger.debug("Parameter value VALUE_FILTER: " + valueFilter);
            }
        }

        if (scope != null && scope.equals("node") && nodeFilter != null && !nodeFilter.equals("")) {
            query.setParameter("FOLDER_ID", nodeFilter);
            logger.debug("Parameter value FOLDER_ID: " + nodeFilter);
        }
        //executes query
        List hibList = query.list();
        Iterator it = hibList.iterator();
        while (it.hasNext()) {
            SbiObjects object = (SbiObjects) it.next();
            realResult.add(toBIObject(object));
        }
        tx.commit();
    } catch (HibernateException he) {
        logger.error(he);
        if (tx != null)
            tx.rollback();
        throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
    } catch (Exception e) {
        logger.error(e.getStackTrace());
        if (tx != null)
            tx.rollback();
        throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
    } finally {
        if (aSession != null) {
            if (aSession.isOpen())
                aSession.close();
        }
    }
    logger.debug("OUT");
    return realResult;
}

From source file:it.eng.spagobi.analiticalmodel.functionalitytree.dao.LowFunctionalityDAOHibImpl.java

License:Mozilla Public License

/**
 * Load all functionalities associated the user roles. 
 * /*from  w  ww.  j  a  v  a  2  s.  c o m*/
 * @param onlyFirstLevel limits functionalities to first level
 * @param recoverBIObjects the recover bi objects
 * 
 * @return the list
 * 
 * @throws EMFUserError the EMF user error
 * 
 * @see it.eng.spagobi.analiticalmodel.functionalitytree.dao.ILowFunctionalityDAO#loadAllLowFunctionalities(boolean)
 */
public List loadUserFunctionalities(Integer parentId, boolean recoverBIObjects, IEngUserProfile profile)
        throws EMFUserError {
    logger.debug("IN");
    Session aSession = null;
    Transaction tx = null;
    List realResult = new ArrayList();
    try {
        aSession = getSession();
        tx = aSession.beginTransaction();
        String username = null;
        Collection roles = null;
        try {
            RequestContainer reqCont = RequestContainer.getRequestContainer();
            if (reqCont != null) {
                username = (String) ((UserProfile) profile).getUserId();
                roles = ((UserProfile) profile).getRolesForUse();

            }
        } catch (Exception e) {
            logger.error("Error while recovering user profile", e);
        }
        boolean onlyFirstLevel = (parentId == null) ? true : false;

        Query hibQuery = null;

        //getting correct root parent id (if the function must return only functionality of first level)
        Integer tmpParentId = null;
        List lstParentId = null;
        if (onlyFirstLevel) {
            hibQuery = aSession.createQuery(
                    " from SbiFunctions s where s.parentFunct.functId is null and s.functTypeCd  = 'LOW_FUNCT'");
            //tmpParentId = (Integer)hibQuery.uniqueResult();
            lstParentId = hibQuery.list();
            tmpParentId = (lstParentId == null || lstParentId.size() == 0) ? new Integer("-1")
                    : ((SbiFunctions) lstParentId.get(0)).getFunctId();
        } else
            tmpParentId = parentId;

        //getting functionalities
        if (username == null || roles == null) {
            hibQuery = aSession.createQuery(
                    " from SbiFunctions s where s.functTypeCd = 'LOW_FUNCT' order by s.parentFunct.functId, s.prog");
        } else if (onlyFirstLevel) {

            hibQuery = aSession.createQuery(
                    " from SbiFunctions s where ((s.functTypeCd = 'LOW_FUNCT' and s.parentFunct.functId = ?) or s.path like ? ) "
                            + " order by s.parentFunct.functId, s.prog");
            hibQuery.setInteger(0, tmpParentId.intValue());
            hibQuery.setString(1, "/" + username);
        } else {
            hibQuery = aSession.createQuery(
                    " from SbiFunctions s where (s.functTypeCd = 'LOW_FUNCT' and s.parentFunct.functId = ?  ) "
                            + " order by s.parentFunct.functId, s.prog");
            hibQuery.setInteger(0, tmpParentId.intValue());
        }
        List hibList = hibQuery.list();

        //getting correct ext_role_id
        String hql = " from SbiExtRoles as extRole where extRole.name in (:roles)  ";
        hibQuery = aSession.createQuery(hql);

        int originalSize = roles.size();
        int MAX_PARAMIN_SIZE = 1000;
        List rolesIds = null;
        if (originalSize >= MAX_PARAMIN_SIZE) {
            int start = 0;
            List tmpRoles = new ArrayList(roles);
            do {
                List subList = tmpRoles.subList(start, Math.min(start + MAX_PARAMIN_SIZE, originalSize));

                hibQuery.setParameterList("roles", subList);
                List rolesIdsTmp = hibQuery.list();

                if (rolesIds == null) {
                    rolesIds = rolesIdsTmp;
                } else {
                    rolesIds.addAll(rolesIdsTmp);
                }

                start += MAX_PARAMIN_SIZE;
            } while (start < originalSize);
        } else {
            hibQuery.setParameterList("roles", roles);
            rolesIds = hibQuery.list();
        }

        Iterator it = hibList.iterator();
        //maintains functionalities that have the same user's role
        while (it.hasNext()) {
            SbiFunctions tmpFunc = (SbiFunctions) it.next();
            if (tmpFunc.getFunctTypeCd().equalsIgnoreCase("USER_FUNCT")) {
                realResult.add(toLowFunctionality(tmpFunc, recoverBIObjects));
            } else {
                Object[] tmpRole = tmpFunc.getSbiFuncRoles().toArray();
                for (int j = 0; j < rolesIds.size(); j++) {
                    Integer principalRole = ((SbiExtRoles) rolesIds.get(j)).getExtRoleId();
                    for (int i = 0; i < tmpRole.length; i++) {
                        SbiFuncRole role = (SbiFuncRole) tmpRole[i];
                        Integer localRoleId = ((SbiFuncRoleId) role.getId()).getRole().getExtRoleId();
                        if (localRoleId != null && localRoleId.compareTo(principalRole) == 0) {
                            if (!existFunction(realResult, tmpFunc)) {
                                realResult.add(toLowFunctionality(tmpFunc, recoverBIObjects));
                                break;
                            }
                        }
                    }
                }
            }
        }
        tx.commit();
    } catch (HibernateException he) {
        logger.error("HibernateException", he);

        if (tx != null)
            tx.rollback();

        throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

    } finally {
        if (aSession != null) {
            if (aSession.isOpen())
                aSession.close();
        }
    }
    logger.debug("OUT");
    return realResult;
}

From source file:it.eng.spagobi.analiticalmodel.functionalitytree.dao.LowFunctionalityDAOHibImpl.java

License:Mozilla Public License

/**
 * Load all functionalities associated the user roles. 
 * /*from w  w w  . j a va2 s . co  m*/
 * @param onlyFirstLevel limits functionalities to first level
 * @param recoverBIObjects the recover bi objects
 * 
 * @return the list
 * 
 * @throws EMFUserError the EMF user error
 * 
 * @see it.eng.spagobi.analiticalmodel.functionalitytree.dao.ILowFunctionalityDAO#loadAllLowFunctionalities(boolean)
 */
public List loadUserFunctionalitiesFiltered(Integer parentId, boolean recoverBIObjects, IEngUserProfile profile,
        String permission) throws EMFUserError {
    logger.debug("IN");
    Session aSession = null;
    Transaction tx = null;
    List realResult = new ArrayList();
    try {
        aSession = getSession();
        tx = aSession.beginTransaction();
        String username = (String) ((UserProfile) profile).getUserId();
        Collection roles;
        try {
            roles = ((UserProfile) profile).getRolesForUse();
        } catch (EMFInternalError e) {
            throw new SpagoBIRuntimeException("Error while retrieving user roles", e);
        }
        boolean isFirstLevel = (parentId == null) ? true : false;

        Query hibQuery = null;

        //getting correct root parent id (if the function must return only functionality of first level)
        Integer tmpParentId = null;
        List lstParentId = null;
        if (isFirstLevel) {
            hibQuery = aSession.createQuery(
                    " from SbiFunctions s where s.parentFunct.functId is null and s.functTypeCd  = 'LOW_FUNCT'");
            lstParentId = hibQuery.list();
            tmpParentId = (lstParentId == null || lstParentId.size() == 0) ? new Integer("-1")
                    : ((SbiFunctions) lstParentId.get(0)).getFunctId();
        } else {
            tmpParentId = parentId;
        }

        //getting functionalities
        if (isFirstLevel) {
            hibQuery = aSession.createQuery("select distinct sfr.id.function from SbiFuncRole sfr where "
                    + "sfr.id.function.functTypeCd = 'LOW_FUNCT' and sfr.id.function.parentFunct.functId = ?  "
                    + "and sfr.stateCd = ? and sfr.id.role.name in (:roles) ");
            // CANNOT order by in SQL query: see https://spagobi.eng.it/jira/browse/SPAGOBI-942
            //+ "order by sfr.id.function.parentFunct.functId, sfr.id.function.prog");
            hibQuery.setInteger(0, tmpParentId.intValue());
            hibQuery.setString(1, permission);
            hibQuery.setParameterList("roles", roles);
            Query hibQueryPersonalFolder = aSession
                    .createQuery("select f from SbiFunctions f where f.path like ? ");
            hibQueryPersonalFolder.setString(0, "/" + username);
            List hibListPersF = hibQueryPersonalFolder.list();
            Iterator it = hibListPersF.iterator();
            while (it.hasNext()) {
                SbiFunctions tmpFunc = (SbiFunctions) it.next();
                realResult.add(toLowFunctionality(tmpFunc, recoverBIObjects));
            }
        } else {
            hibQuery = aSession.createQuery("select distinct sfr.id.function from SbiFuncRole sfr where "
                    + "sfr.id.function.functTypeCd = 'LOW_FUNCT' and sfr.id.function.parentFunct.functId = ? "
                    + "and sfr.stateCd = ? and sfr.id.role.name in (:roles) ");
            // CANNOT order by in SQL query: see https://spagobi.eng.it/jira/browse/SPAGOBI-942
            //+ "order by sfr.id.function.parentFunct.functId, sfr.id.function.prog");
            hibQuery.setInteger(0, tmpParentId.intValue());
            hibQuery.setString(1, permission);
            hibQuery.setParameterList("roles", roles);
        }
        List<SbiFunctions> hibList = (List<SbiFunctions>) hibQuery.list();

        // MUST order using a comparator, see https://spagobi.eng.it/jira/browse/SPAGOBI-942
        Collections.sort(hibList, new Comparator<SbiFunctions>() {

            public int compare(SbiFunctions funct1, SbiFunctions funct2) {
                SbiFunctions parent1 = funct1.getParentFunct();
                SbiFunctions parent2 = funct2.getParentFunct();

                if (parent1 == null) {
                    return 1;
                }
                if (parent2 == null) {
                    return -1;
                }
                Integer parentId1 = parent1.getFunctId();
                Integer parentId2 = parent2.getFunctId();

                if (parentId1 > parentId2)
                    return 1;
                else if (parentId1 < parentId2)
                    return -1;
                else {
                    Integer progId1 = funct1.getProg();
                    Integer progId2 = funct2.getProg();

                    if (progId1 > progId2)
                        return 1;
                    else if (progId1 < progId2)
                        return -1;
                    else
                        return 0;

                }
            }
        });

        Iterator it = hibList.iterator();
        while (it.hasNext()) {
            SbiFunctions tmpFunc = (SbiFunctions) it.next();
            realResult.add(toLowFunctionality(tmpFunc, recoverBIObjects));
        }
    } catch (HibernateException he) {
        logger.error("HibernateException", he);

        if (tx != null)
            tx.rollback();

        throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

    } finally {
        if (aSession != null) {
            if (aSession.isOpen())
                aSession.close();
        }
    }
    logger.debug("OUT");
    return realResult;
}

From source file:it.eng.spagobi.commons.dao.UserFunctionalityDAO.java

License:Mozilla Public License

public String[] readUserFunctionality(String[] roles) throws Exception {
    logger.debug("IN");
    if (roles == null || roles.length == 0) {
        logger.warn("The array of roles is empty...");
        return new String[0];
    }//from w  ww .j  a v  a 2 s .c om
    ArrayList toReturn = new ArrayList();
    Session aSession = null;
    Transaction tx = null;
    try {
        aSession = getSession();
        tx = aSession.beginTransaction();

        List roleTypes = new ArrayList();

        for (int i = 0; i < roles.length; i++) {
            String hql = "from SbiExtRoles ser where ser.name=?";
            Query query = aSession.createQuery(hql);
            query.setParameter(0, roles[i]);
            logger.debug("Read role of=" + roles[i]);
            SbiExtRoles spaobiRole = (SbiExtRoles) query.uniqueResult();
            if (spaobiRole != null) {
                String roleTypeCode = spaobiRole.getRoleType().getValueCd();
                if (!roleTypes.contains(roleTypeCode))
                    roleTypes.add(roleTypeCode);
            } else {
                logger.warn("The role " + roles[i] + "doesn't exist in SBI_EXT_ROLES");
            }
        }
        logger.debug("Role type=" + roleTypes);
        if (roleTypes.size() == 0)
            logger.warn("No role types found for the user...!!!!!");

        // String hql =
        // "from SbiRolesUserFunctionality suf where suf.userFunctionality.domainCd = 'USER_FUNCTIONALITY'"
        // +
        // " and suf.roleType.valueCd in ("+strRoles+")";
        // String hql =
        // "Select distinct suf.name from SbiUserFunctionality suf where suf.roleType.valueCd in ("+strRoles+") and suf.roleType.domainCd='ROLE_TYPE'";
        String hql = "Select distinct suf.name from SbiUserFunctionality suf left join suf.roleType rt "
                + "where rt.valueCd IN (:ROLE_TYPES) " + "and rt.domainCd='ROLE_TYPE'";
        Query query = aSession.createQuery(hql);
        query.setParameterList("ROLE_TYPES", roleTypes);
        List userFuncList = query.list();
        Iterator iter = userFuncList.iterator();
        while (iter.hasNext()) {
            String tmp = (String) iter.next();
            toReturn.add(tmp);
            logger.debug("Add Functionality=" + tmp);
        }
        tx.commit();
    } catch (HibernateException he) {
        logger.error("HibernateException during query", he);

        if (tx != null)
            tx.rollback();

        throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

    } finally {
        if (aSession != null) {
            if (aSession.isOpen())
                aSession.close();
        }
        logger.debug("OUT");
    }
    String[] ris = new String[toReturn.size()];
    toReturn.toArray(ris);
    return ris;

}

From source file:it.eng.spagobi.events.dao.EventLogDAOHibImpl.java

License:Mozilla Public License

/**
 * Load events log by user.//from  w ww .  java  2s.  co m
 * 
 * @param profile the profile
 * 
 * @return the list
 * 
 * @throws EMFUserError the EMF user error
 * 
 * @see it.eng.spagobi.events.dao.IEventLogDAO#loadEventsLogByUser(it.eng.spago.security.IEngUserProfile)
 */
public List loadEventsLogByUser(IEngUserProfile profile) throws EMFUserError {
    logger.debug("IN");
    Session aSession = null;
    Transaction tx = null;
    List realResult = new ArrayList();
    String hql = null;
    Query hqlQuery = null;
    Collection roles = null;

    try {
        roles = ((UserProfile) profile).getRolesForUse();
    } catch (EMFInternalError e) {
        logException(e);
        return new ArrayList();
    }

    if (roles == null || roles.size() == 0)
        return new ArrayList();
    boolean isFirtElement = true;
    String collectionRoles = "";
    List roleNames = new ArrayList();
    Iterator rolesIt = roles.iterator();
    while (rolesIt.hasNext()) {
        String roleName = (String) rolesIt.next();
        //if (isFirtElement) {
        //collectionRoles += roleName;
        //isFirtElement = false;
        //} else {
        //collectionRoles += "', '" + roleName;
        if (!roleNames.contains(roleName))
            roleNames.add(roleName);
        //}
    }
    try {
        aSession = getSession();
        tx = aSession.beginTransaction();

        /*hql = 
           "select " +
              "eventlog " +
           "from " +
              "SbiEventsLog as eventlog, " +
              "SbiEventRole as eventRole, " +
              "SbiExtRoles as roles " + 
              "where " +
          "eventlog.id = eventRole.id.event.id and " +
          "eventRole.id.role.extRoleId = roles.extRoleId " +
          "and " +
          "roles.name in ('" + collectionRoles + "') " +
              "order by " +
          "eventlog.date";*/

        hql = "select " + "eventlog " + "from " + "SbiEventsLog as eventlog, " + "SbiEventRole as eventRole, "
                + "SbiExtRoles as roles " + "where " + "eventlog.id = eventRole.id.event.id and "
                + "eventRole.id.role.extRoleId = roles.extRoleId " + "and " + "roles.name in (:ROLE_NAMES) "
                + "order by " + "eventlog.date";

        hqlQuery = aSession.createQuery(hql);
        //hqlQuery.setString(0, collectionRoles);
        hqlQuery.setParameterList("ROLE_NAMES", roleNames);
        List hibList = hqlQuery.list();

        Iterator it = hibList.iterator();

        while (it.hasNext()) {
            realResult.add(toEventsLog((SbiEventsLog) it.next()));
        }
        tx.commit();
    } catch (HibernateException he) {
        logException(he);

        if (tx != null)
            tx.rollback();

        throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

    } finally {
        if (aSession != null) {
            if (aSession.isOpen())
                aSession.close();
        }
    }
    logger.debug("OUT");
    return realResult;
}