Search in sources :

Example 1 with Tuple

use of org.apereo.portal.utils.Tuple in project uPortal by Jasig.

the class JpaBaseAggregationDaoTest method testUnclosedBaseAggregationRangeQuery.

@Test
public final void testUnclosedBaseAggregationRangeQuery() throws Exception {
    final IEntityGroup entityGroupA = mock(IEntityGroup.class);
    when(entityGroupA.getServiceName()).thenReturn(new CompositeName("local"));
    when(entityGroupA.getName()).thenReturn("Group A");
    when(compositeGroupService.findGroup("local.0")).thenReturn(entityGroupA);
    final IEntityGroup entityGroupB = mock(IEntityGroup.class);
    when(entityGroupB.getServiceName()).thenReturn(new CompositeName("local"));
    when(entityGroupB.getName()).thenReturn("Group B");
    when(compositeGroupService.findGroup("local.1")).thenReturn(entityGroupB);
    final MutableInt aggrs = new MutableInt();
    //Create 10 minutes of aggregations
    final DateTime start = new DateTime(1326734644000l, DateTimeZone.UTC).minuteOfDay().roundFloorCopy();
    final DateTime end = start.plusMinutes(10);
    final AggregationInterval interval = AggregationInterval.FIVE_MINUTE;
    final MutableObject startObj = new MutableObject();
    final MutableObject endObj = new MutableObject();
    this.executeInTransaction(new CallableWithoutResult() {

        @Override
        protected void callWithoutResult() {
            final Random r = new Random(0);
            final AggregatedGroupMapping groupA = aggregatedGroupLookupDao.getGroupMapping("local.0");
            final AggregatedGroupMapping groupB = aggregatedGroupLookupDao.getGroupMapping("local.1");
            populateDateTimeDimensions(start, end, new FunctionWithoutResult<Tuple<DateDimension, TimeDimension>>() {

                @Override
                protected void applyWithoutResult(Tuple<DateDimension, TimeDimension> input) {
                    final TimeDimension td = input.second;
                    final DateDimension dd = input.first;
                    final DateTime instant = td.getTime().toDateTime(dd.getDate());
                    if (startObj.getValue() == null) {
                        startObj.setValue(instant);
                    }
                    endObj.setValue(instant);
                    if (instant.equals(interval.determineStart(instant))) {
                        final AggregationIntervalInfo intervalInfo = aggregationIntervalHelper.getIntervalInfo(interval, instant);
                        final T baseAggregationA = getAggregationDao().createAggregation(createAggregationKey(intervalInfo, groupA));
                        final T baseAggregationB = getAggregationDao().createAggregation(createAggregationKey(intervalInfo, groupB));
                        for (int u = 0; u < r.nextInt(50); u++) {
                            updateAggregation(intervalInfo, baseAggregationA, r);
                            updateAggregation(intervalInfo, baseAggregationB, r);
                        }
                        if (aggrs.intValue() % 4 == 0) {
                            baseAggregationA.intervalComplete(5);
                        }
                        baseAggregationB.intervalComplete(5);
                        getAggregationDao().updateAggregation(baseAggregationA);
                        getAggregationDao().updateAggregation(baseAggregationB);
                        aggrs.add(2);
                    }
                }
            });
        }
    });
    //Verify all aggrs created
    assertEquals(4, aggrs.intValue());
    //Find unclosed 1 aggr
    this.execute(new CallableWithoutResult() {

        @Override
        protected void callWithoutResult() {
            final Collection<T> baseAggregations = getAggregationDao().getUnclosedAggregations(start.minusDays(1), end.plusDays(1), interval);
            assertEquals(1, baseAggregations.size());
            for (final T baseAggregationImpl : baseAggregations) {
                baseAggregationImpl.intervalComplete(5);
                getAggregationDao().updateAggregation(baseAggregationImpl);
            }
        }
    });
    //Find unclosed 0 aggr
    this.execute(new CallableWithoutResult() {

        @Override
        protected void callWithoutResult() {
            final Collection<T> baseAggregations = getAggregationDao().getUnclosedAggregations(start.minusDays(1), end.plusDays(1), interval);
            assertEquals(0, baseAggregations.size());
        }
    });
}
Also used : CompositeName(javax.naming.CompositeName) DateTime(org.joda.time.DateTime) CallableWithoutResult(org.apereo.portal.concurrency.CallableWithoutResult) IEntityGroup(org.apereo.portal.groups.IEntityGroup) FunctionWithoutResult(org.apereo.portal.concurrency.FunctionWithoutResult) AggregatedGroupMapping(org.apereo.portal.events.aggr.groups.AggregatedGroupMapping) Random(java.util.Random) MutableInt(org.apache.commons.lang.mutable.MutableInt) Collection(java.util.Collection) Tuple(org.apereo.portal.utils.Tuple) MutableObject(org.apache.commons.lang.mutable.MutableObject) Test(org.junit.Test) BaseAggrEventsJpaDaoTest(org.apereo.portal.test.BaseAggrEventsJpaDaoTest)

Example 2 with Tuple

use of org.apereo.portal.utils.Tuple in project uPortal by Jasig.

the class PortletEventCoordinatationService method supportsEvent.

protected boolean supportsEvent(Event event, IPortletDefinitionId portletDefinitionId) {
    final QName eventName = event.getQName();
    //The cache key to use
    final Tuple<IPortletDefinitionId, QName> key = new Tuple<IPortletDefinitionId, QName>(portletDefinitionId, eventName);
    //Check in the cache if the portlet definition supports this event
    final Element element = this.supportedEventCache.get(key);
    if (element != null) {
        final Boolean supported = (Boolean) element.getObjectValue();
        if (supported != null) {
            return supported;
        }
    }
    final PortletApplicationDefinition portletApplicationDescriptor = this.portletDefinitionRegistry.getParentPortletApplicationDescriptor(portletDefinitionId);
    if (portletApplicationDescriptor == null) {
        return false;
    }
    final Set<QName> aliases = this.getAllAliases(eventName, portletApplicationDescriptor);
    final String defaultNamespace = portletApplicationDescriptor.getDefaultNamespace();
    //No support found so far, do more complex namespace matching
    final PortletDefinition portletDescriptor = this.portletDefinitionRegistry.getParentPortletDescriptor(portletDefinitionId);
    if (portletDescriptor == null) {
        return false;
    }
    final List<? extends EventDefinitionReference> supportedProcessingEvents = portletDescriptor.getSupportedProcessingEvents();
    for (final EventDefinitionReference eventDefinitionReference : supportedProcessingEvents) {
        final QName qualifiedName = eventDefinitionReference.getQualifiedName(defaultNamespace);
        if (qualifiedName == null) {
            continue;
        }
        //Look for alias names
        if (qualifiedName.equals(eventName) || aliases.contains(qualifiedName)) {
            this.supportedEventCache.put(new Element(key, Boolean.TRUE));
            return true;
        }
        //Look for namespaced events
        if (StringUtils.isEmpty(qualifiedName.getNamespaceURI())) {
            final QName namespacedName = new QName(defaultNamespace, qualifiedName.getLocalPart());
            if (eventName.equals(namespacedName)) {
                this.supportedEventCache.put(new Element(key, Boolean.TRUE));
                return true;
            }
        }
    }
    this.supportedEventCache.put(new Element(key, Boolean.FALSE));
    return false;
}
Also used : IPortletDefinitionId(org.apereo.portal.portlet.om.IPortletDefinitionId) EventDefinitionReference(org.apache.pluto.container.om.portlet.EventDefinitionReference) PortletApplicationDefinition(org.apache.pluto.container.om.portlet.PortletApplicationDefinition) QName(javax.xml.namespace.QName) Element(net.sf.ehcache.Element) JAXBElement(javax.xml.bind.JAXBElement) Tuple(org.apereo.portal.utils.Tuple) IPortletDefinition(org.apereo.portal.portlet.om.IPortletDefinition) PortletDefinition(org.apache.pluto.container.om.portlet.PortletDefinition)

Example 3 with Tuple

use of org.apereo.portal.utils.Tuple in project uPortal by Jasig.

the class AbstractDom4jExporter method marshal.

/* (non-Javadoc)
     * @see org.springframework.oxm.Marshaller#marshal(java.lang.Object, javax.xml.transform.Result)
     */
@Override
public void marshal(Object graph, Result result) throws IOException, XmlMappingException {
    @SuppressWarnings("unchecked") final Tuple<String, Element> data = (Tuple<String, Element>) graph;
    final Transformer transformer;
    try {
        transformer = this.xmlUtilities.getIdentityTransformer();
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException("Failed to load identity Transformer", e);
    }
    //Setup the transformer to pretty-print the output
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    try {
        transformer.transform(new DocumentSource(data.second), result);
    } catch (TransformerException e) {
        throw new RuntimeException("Failed to write Element to Result for: " + data.first, e);
    }
}
Also used : Transformer(javax.xml.transform.Transformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) DocumentSource(org.dom4j.io.DocumentSource) Element(org.dom4j.Element) Tuple(org.apereo.portal.utils.Tuple) TransformerException(javax.xml.transform.TransformerException)

Example 4 with Tuple

use of org.apereo.portal.utils.Tuple in project uPortal by Jasig.

the class RDBMUserLayoutStore method getPersonalUserLayout.

protected Document getPersonalUserLayout(final IPerson person, final IUserProfile profile) {
    final LocaleManager localeManager = profile.getLocaleManager();
    return jdbcOperations.execute(new ConnectionCallback<Document>() {

        @Override
        public Document doInConnection(Connection con) throws SQLException, DataAccessException {
            ResultSet rs;
            int userId = person.getID();
            final int realUserId = userId;
            Document doc = DocumentFactory.getThreadDocument();
            Element root = doc.createElement("layout");
            final Statement stmt = con.createStatement();
            // A separate statement is needed so as not to interfere with ResultSet
            // of statements used for queries
            Statement insertStmt = con.createStatement();
            try {
                long startTime = System.currentTimeMillis();
                // eventually, we need to fix template layout implementations so you can just do this:
                //        int layoutId=profile.getLayoutId();
                // but for now:
                int layoutId = getLayoutID(userId, profile.getProfileId());
                if (layoutId == 0) {
                    // First time, grab the default layout for this user
                    final Tuple<Integer, Integer> userLayoutIds = transactionOperations.execute(new TransactionCallback<Tuple<Integer, Integer>>() {

                        @Override
                        public Tuple<Integer, Integer> doInTransaction(TransactionStatus status) {
                            return jdbcOperations.execute(new ConnectionCallback<Tuple<Integer, Integer>>() {

                                @Override
                                public Tuple<Integer, Integer> doInConnection(Connection con) throws SQLException, DataAccessException {
                                    int newLayoutId;
                                    int newUserId;
                                    String sQuery = "SELECT USER_DFLT_USR_ID, USER_DFLT_LAY_ID FROM UP_USER WHERE USER_ID=" + realUserId;
                                    logger.debug("getUserLayout(): {}", sQuery);
                                    ResultSet rs = stmt.executeQuery(sQuery);
                                    try {
                                        if (rs.next()) {
                                            newUserId = rs.getInt(1);
                                            newLayoutId = rs.getInt(2);
                                        } else {
                                            final String msg = "Unable to find default user for USER_ID=" + realUserId;
                                            throw new SQLException(msg);
                                        }
                                    } finally {
                                        rs.close();
                                    }
                                    // Make sure the next struct id is set in case the user adds a channel
                                    sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID=" + newUserId;
                                    logger.debug("getUserLayout(): {}", sQuery);
                                    int nextStructId;
                                    rs = stmt.executeQuery(sQuery);
                                    try {
                                        if (rs.next()) {
                                            nextStructId = rs.getInt(1);
                                        } else {
                                            final String msg = "Unable to find NEXT_STRUCT_ID for USER_ID=" + realUserId;
                                            throw new SQLException(msg);
                                        }
                                    } finally {
                                        rs.close();
                                    }
                                    int realNextStructId = 0;
                                    if (realUserId != newUserId) {
                                        // But never make the existing value SMALLER, change it only to make it LARGER
                                        // (so, get existing value)
                                        sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID=" + realUserId;
                                        logger.debug("getUserLayout(): {}", sQuery);
                                        rs = stmt.executeQuery(sQuery);
                                        try {
                                            if (rs.next()) {
                                                realNextStructId = rs.getInt(1);
                                            } else {
                                                final String msg = "Unable to find NEXT_STRUCT_ID for USER_ID=" + realUserId;
                                                throw new SQLException(msg);
                                            }
                                        } finally {
                                            rs.close();
                                        }
                                    }
                                    if (nextStructId > realNextStructId) {
                                        sQuery = "UPDATE UP_USER SET NEXT_STRUCT_ID=" + nextStructId + " WHERE USER_ID=" + realUserId;
                                        logger.debug("getUserLayout(): {}", sQuery);
                                        stmt.executeUpdate(sQuery);
                                    }
                                    return new Tuple<Integer, Integer>(newUserId, newLayoutId);
                                }
                            });
                        }
                    });
                    userId = userLayoutIds.first;
                    layoutId = userLayoutIds.second;
                }
                int firstStructId = -1;
                //Flags to enable a default layout lookup if it's needed
                boolean foundLayout = false;
                boolean triedDefault = false;
                //the layout is searched for again. This loop should only ever loop once.
                do {
                    String sQuery = "SELECT INIT_STRUCT_ID FROM UP_USER_LAYOUT WHERE USER_ID=" + userId + " AND LAYOUT_ID = " + layoutId;
                    logger.debug("getUserLayout(): {}", sQuery);
                    rs = stmt.executeQuery(sQuery);
                    try {
                        if (rs.next()) {
                            firstStructId = rs.getInt(1);
                        } else {
                            throw new RuntimeException("getUserLayout(): No INIT_STRUCT_ID in UP_USER_LAYOUT for USER_ID: " + userId + " and LAYOUT_ID: " + layoutId);
                        }
                    } finally {
                        rs.close();
                    }
                    String sql;
                    if (localeAware) {
                        // This needs to be changed to get the localized strings
                        sql = "SELECT ULS.STRUCT_ID,ULS.NEXT_STRUCT_ID,ULS.CHLD_STRUCT_ID,ULS.CHAN_ID,ULS.NAME,ULS.TYPE,ULS.HIDDEN," + "ULS.UNREMOVABLE,ULS.IMMUTABLE";
                    } else {
                        sql = "SELECT ULS.STRUCT_ID,ULS.NEXT_STRUCT_ID,ULS.CHLD_STRUCT_ID,ULS.CHAN_ID,ULS.NAME,ULS.TYPE,ULS.HIDDEN," + "ULS.UNREMOVABLE,ULS.IMMUTABLE";
                    }
                    if (databaseMetadata.supportsOuterJoins()) {
                        sql += ",USP.STRUCT_PARM_NM,USP.STRUCT_PARM_VAL FROM " + databaseMetadata.getJoinQuery().getQuery("layout");
                    } else {
                        sql += " FROM UP_LAYOUT_STRUCT ULS WHERE ";
                    }
                    sql += " ULS.USER_ID=" + userId + " AND ULS.LAYOUT_ID=" + layoutId + " ORDER BY ULS.STRUCT_ID";
                    logger.debug("getUserLayout(): {}", sql);
                    rs = stmt.executeQuery(sql);
                    //check for rows in the result set
                    foundLayout = rs.next();
                    if (!foundLayout && !triedDefault && userId == realUserId) {
                        //If we didn't find any rows and we haven't tried the default user yet
                        triedDefault = true;
                        rs.close();
                        //Get the default user ID and layout ID
                        sQuery = "SELECT USER_DFLT_USR_ID, USER_DFLT_LAY_ID FROM UP_USER WHERE USER_ID=" + userId;
                        logger.debug("getUserLayout(): {}", sQuery);
                        rs = stmt.executeQuery(sQuery);
                        try {
                            rs.next();
                            userId = rs.getInt(1);
                            layoutId = rs.getInt(2);
                        } finally {
                            rs.close();
                        }
                    } else {
                        //We tried the default or actually found a layout
                        break;
                    }
                } while (!foundLayout);
                HashMap layoutStructure = new HashMap();
                StringBuffer structChanIds = new StringBuffer();
                try {
                    int lastStructId = 0;
                    LayoutStructure ls = null;
                    String sepChar = "";
                    if (foundLayout) {
                        int structId = rs.getInt(1);
                        // Except if you are using poolman 2.0.4 in which case you get -1 back
                        if (rs.wasNull()) {
                            structId = 0;
                        }
                        readLayout: while (true) {
                            int nextId = rs.getInt(2);
                            if (rs.wasNull()) {
                                nextId = 0;
                            }
                            int childId = rs.getInt(3);
                            if (rs.wasNull()) {
                                childId = 0;
                            }
                            int chanId = rs.getInt(4);
                            if (rs.wasNull()) {
                                chanId = 0;
                            }
                            String temp5 = rs.getString(// Some JDBC drivers require columns accessed in order
                            5);
                            String temp6 = rs.getString(// Access 5 and 6 now, save till needed.
                            6);
                            // uPortal i18n
                            int name_index, value_index;
                            if (localeAware) {
                                Locale[] locales = localeManager.getLocales();
                                String locale = locales[0].toString();
                                ls = new LayoutStructure(structId, nextId, childId, chanId, rs.getString(7), rs.getString(8), rs.getString(9), locale);
                                name_index = 10;
                                value_index = 11;
                            } else {
                                ls = new LayoutStructure(structId, nextId, childId, chanId, rs.getString(7), rs.getString(8), rs.getString(9));
                                name_index = 10;
                                value_index = 11;
                            }
                            layoutStructure.put(new Integer(structId), ls);
                            lastStructId = structId;
                            if (!ls.isChannel()) {
                                ls.addFolderData(temp5, // Plug in saved column values
                                temp6);
                            }
                            if (databaseMetadata.supportsOuterJoins()) {
                                do {
                                    String name = rs.getString(name_index);
                                    String value = rs.getString(// Oracle JDBC requires us to do this for longs
                                    value_index);
                                    if (name != null) {
                                        // may not be there because of the join
                                        ls.addParameter(name, value);
                                    }
                                    if (!rs.next()) {
                                        break readLayout;
                                    }
                                    structId = rs.getInt(1);
                                    if (rs.wasNull()) {
                                        structId = 0;
                                    }
                                } while (structId == lastStructId);
                            } else {
                                // Do second SELECT later on for structure parameters
                                if (ls.isChannel()) {
                                    structChanIds.append(sepChar + ls.getChanId());
                                    sepChar = ",";
                                }
                                if (rs.next()) {
                                    structId = rs.getInt(1);
                                    if (rs.wasNull()) {
                                        structId = 0;
                                    }
                                } else {
                                    break readLayout;
                                }
                            }
                        }
                    // while
                    }
                } finally {
                    rs.close();
                }
                if (!databaseMetadata.supportsOuterJoins() && structChanIds.length() > 0) {
                    // Pick up structure parameters
                    // first, get the struct ids for the channels
                    String sql = "SELECT STRUCT_ID FROM UP_LAYOUT_STRUCT WHERE USER_ID=" + userId + " AND LAYOUT_ID=" + layoutId + " AND CHAN_ID IN (" + structChanIds.toString() + ") ORDER BY STRUCT_ID";
                    logger.debug("getUserLayout(): {}", sql);
                    StringBuffer structIdsSB = new StringBuffer("");
                    String sep = "";
                    rs = stmt.executeQuery(sql);
                    try {
                        // use the results to build a correct list of struct ids to look for
                        while (rs.next()) {
                            structIdsSB.append(sep + rs.getString(1));
                            sep = ",";
                        }
                    // while
                    } finally {
                        rs.close();
                    }
                    // be a good doobie
                    sql = "SELECT STRUCT_ID, STRUCT_PARM_NM,STRUCT_PARM_VAL FROM UP_LAYOUT_PARAM WHERE USER_ID=" + userId + " AND LAYOUT_ID=" + layoutId + " AND STRUCT_ID IN (" + structIdsSB.toString() + ") ORDER BY STRUCT_ID";
                    logger.debug("getUserLayout(): {}", sql);
                    rs = stmt.executeQuery(sql);
                    try {
                        if (rs.next()) {
                            int structId = rs.getInt(1);
                            readParm: while (true) {
                                LayoutStructure ls = (LayoutStructure) layoutStructure.get(new Integer(structId));
                                int lastStructId = structId;
                                do {
                                    ls.addParameter(rs.getString(2), rs.getString(3));
                                    if (!rs.next()) {
                                        break readParm;
                                    }
                                } while ((structId = rs.getInt(1)) == lastStructId);
                            }
                        }
                    } finally {
                        rs.close();
                    }
                }
                if (layoutStructure.size() > 0) {
                    // We have a layout to work with
                    createLayout(layoutStructure, doc, root, firstStructId);
                    layoutStructure.clear();
                    if (logger.isDebugEnabled()) {
                        long stopTime = System.currentTimeMillis();
                        long timeTook = stopTime - startTime;
                        logger.debug("getUserLayout(): Layout document for user {} took {} milliseconds to create", userId, timeTook);
                    }
                    doc.appendChild(root);
                }
            } finally {
                stmt.close();
                insertStmt.close();
            }
            return doc;
        }
    });
}
Also used : Locale(java.util.Locale) SQLException(java.sql.SQLException) HashMap(java.util.HashMap) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Element(org.w3c.dom.Element) Connection(java.sql.Connection) TransactionStatus(org.springframework.transaction.TransactionStatus) IJoinQueryString(org.apereo.portal.jdbc.IJoinQueryString) Document(org.w3c.dom.Document) TransactionCallback(org.springframework.transaction.support.TransactionCallback) LayoutStructure(org.apereo.portal.layout.LayoutStructure) ResultSet(java.sql.ResultSet) LocaleManager(org.apereo.portal.i18n.LocaleManager) DataAccessException(org.springframework.dao.DataAccessException) Tuple(org.apereo.portal.utils.Tuple)

Example 5 with Tuple

use of org.apereo.portal.utils.Tuple in project uPortal by Jasig.

the class RDBMUserLayoutStore method getUserProfileByFname.

public UserProfile getUserProfileByFname(final IPerson person, final String profileFname) {
    Tuple<String, String> key = null;
    final Cache<Tuple<String, String>, UserProfile> profileCache = getProfileImportExportCache();
    if (profileCache != null) {
        key = new Tuple<String, String>(person.getUserName(), profileFname);
        final UserProfile profile = profileCache.getIfPresent(key);
        if (profile != null) {
            return profile;
        }
    }
    logger.debug("Getting profile {} for user {}", profileFname, person.getID());
    final int userId = person.getID();
    final UserProfile userProfile = jdbcOperations.execute(new ConnectionCallback<UserProfile>() {

        @Override
        public UserProfile doInConnection(Connection con) throws SQLException, DataAccessException {
            String query = "SELECT USER_ID, PROFILE_ID, PROFILE_NAME, DESCRIPTION, " + "LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID FROM UP_USER_PROFILE WHERE " + "USER_ID=? AND PROFILE_FNAME=?";
            PreparedStatement pstmt = con.prepareStatement(query);
            pstmt.setInt(1, userId);
            pstmt.setString(2, profileFname);
            try {
                logger.debug("getUserProfileByFname(): {} userId: {} profileFname: {}", query, userId, profileFname);
                ResultSet rs = pstmt.executeQuery();
                try {
                    if (rs.next()) {
                        int profileId = rs.getInt(2);
                        String profileName = rs.getString(3);
                        String profileDesc = rs.getString(4);
                        int layoutId = rs.getInt(5);
                        if (rs.wasNull()) {
                            layoutId = 0;
                        }
                        int structSsId = rs.getInt(6);
                        if (rs.wasNull()) {
                            // This is probably a data issue and probably an export operation;  defer to the system user...
                            if (!person.equals(getSystemUser())) {
                                structSsId = getSystemProfileByFname(profileFname).getStructureStylesheetId();
                            } else {
                                String msg = "The system user profile has no structure stylesheet Id.";
                                throw new IllegalStateException(msg);
                            }
                        }
                        int themeSsId = rs.getInt(7);
                        if (rs.wasNull()) {
                            // This is probably a data issue and probably an export operation;  defer to the system user...
                            if (!person.equals(getSystemUser())) {
                                themeSsId = getSystemProfileByFname(profileFname).getThemeStylesheetId();
                            } else {
                                String msg = "The system user profile has no theme stylesheet Id.";
                                throw new IllegalStateException(msg);
                            }
                        }
                        UserProfile userProfile = new UserProfile(profileId, profileFname, profileName, profileDesc, layoutId, structSsId, themeSsId);
                        final Locale[] userLocales = localeStore.getUserLocales(person);
                        userProfile.setLocaleManager(new LocaleManager(person, userLocales));
                        return userProfile;
                    }
                    /* Try to copy the template profile. */
                    logger.debug("Copying template profile {} to user {}", profileFname, person.getID());
                    rs.close();
                    pstmt.close();
                    pstmt = con.prepareStatement("SELECT USER_DFLT_USR_ID FROM UP_USER WHERE USER_ID=?");
                    pstmt.setInt(1, person.getID());
                    rs = pstmt.executeQuery();
                    if (rs.next()) {
                        int defaultProfileUser = rs.getInt(1);
                        if (rs.wasNull()) {
                            throw new RuntimeException("Need to clone the '" + profileFname + "' profile from template user for " + person + " but they have no template user");
                        }
                        IPerson defaultProfilePerson = new PersonImpl();
                        defaultProfilePerson.setID(defaultProfileUser);
                        if (defaultProfilePerson.getID() != person.getID()) {
                            UserProfile templateProfile = getUserProfileByFname(defaultProfilePerson, profileFname);
                            if (templateProfile != null) {
                                UserProfile newUserProfile = new UserProfile(templateProfile);
                                final Locale[] userLocales = localeStore.getUserLocales(person);
                                newUserProfile.setLayoutId(0);
                                newUserProfile = addUserProfile(person, newUserProfile);
                                newUserProfile.setLocaleManager(new LocaleManager(person, userLocales));
                                return newUserProfile;
                            }
                        }
                    }
                    throw new RuntimeException("Unable to find User Profile for userId " + userId + " and profile " + profileFname);
                } finally {
                    rs.close();
                }
            } finally {
                pstmt.close();
            }
        }
    });
    if (profileCache != null && key != null) {
        profileCache.put(key, userProfile);
    }
    return userProfile;
}
Also used : IUserProfile(org.apereo.portal.IUserProfile) UserProfile(org.apereo.portal.UserProfile) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) IJoinQueryString(org.apereo.portal.jdbc.IJoinQueryString) IPerson(org.apereo.portal.security.IPerson) PersonImpl(org.apereo.portal.security.provider.PersonImpl) ResultSet(java.sql.ResultSet) LocaleManager(org.apereo.portal.i18n.LocaleManager) Tuple(org.apereo.portal.utils.Tuple) DataAccessException(org.springframework.dao.DataAccessException)

Aggregations

Tuple (org.apereo.portal.utils.Tuple)15 Random (java.util.Random)3 CompositeName (javax.naming.CompositeName)3 Element (net.sf.ehcache.Element)3 MutableInt (org.apache.commons.lang.mutable.MutableInt)3 MutableObject (org.apache.commons.lang.mutable.MutableObject)3 CallableWithoutResult (org.apereo.portal.concurrency.CallableWithoutResult)3 FunctionWithoutResult (org.apereo.portal.concurrency.FunctionWithoutResult)3 AggregatedGroupMapping (org.apereo.portal.events.aggr.groups.AggregatedGroupMapping)3 IEntityGroup (org.apereo.portal.groups.IEntityGroup)3 BaseAggrEventsJpaDaoTest (org.apereo.portal.test.BaseAggrEventsJpaDaoTest)3 Test (org.junit.Test)3 Connection (java.sql.Connection)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 SQLException (java.sql.SQLException)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 Transformer (javax.xml.transform.Transformer)2 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)2