Example usage for org.springframework.transaction.support TransactionCallback TransactionCallback

List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionCallback TransactionCallback.

Prototype

TransactionCallback

Source Link

Usage

From source file:org.jasig.portal.events.aggr.PortalEventAggregationManagerImpl.java

@Override
public boolean aggregateRawEvents() {
    TryLockFunctionResult<Boolean> result = null;
    do {//from w  w  w  .j av a2 s. co  m
        if (result != null) {
            logger.debug(
                    "doAggregateRawEvents signaled that not all events were aggregated in a single transaction, running again.");
        }

        result = aggrEventsTransactionOperations
                .execute(new TransactionCallback<TryLockFunctionResult<Boolean>>() {
                    @Override
                    public TryLockFunctionResult<Boolean> doInTransaction(TransactionStatus status) {
                        try {
                            return clusterLockService.doInTryLock(AGGREGATION_LOCK_NAME,
                                    new Function<String, Boolean>() {
                                        @Override
                                        public Boolean apply(String input) {
                                            return doAggregateRawEvents();
                                        }
                                    });
                        } catch (InterruptedException e) {
                            logger.warn("Interrupted while aggregating", e);
                            Thread.currentThread().interrupt();
                            return null;
                        }
                    }
                });

        //Loop if doAggregateRawEvents returns false, this means that there is more to aggregate 
    } while (result != null && result.isExecuted() && !result.getResult());

    return result != null && result.isExecuted();
}

From source file:org.jasig.portal.io.xml.AbstractIdentityImportExportTest.java

protected final <T> void testIdentityImportExport(final IDataImporter<T> dataImporter,
        final IDataExporter<?> dataExporter, Resource resource, Function<T, String> getName) throws Exception {

    final String importData = toString(resource);

    final XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
    final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new StringReader(importData));

    //Unmarshall from XML
    final Unmarshaller unmarshaller = dataImporter.getUnmarshaller();
    final StAXSource source = new StAXSource(xmlEventReader);
    @SuppressWarnings("unchecked")
    final T dataImport = (T) unmarshaller.unmarshal(source);

    //Make sure the data was unmarshalled
    assertNotNull("Unmarshalled import data was null", dataImport);

    //Import the data
    dataImporter.importData(dataImport);

    //Export the data
    final String name = getName.apply(dataImport);
    final Object dataExport = transactionOperations.execute(new TransactionCallback<Object>() {
        /* (non-Javadoc)
         * @see org.springframework.transaction.support.TransactionCallback#doInTransaction(org.springframework.transaction.TransactionStatus)
         *//*from  w  w  w .j  ava 2s  .  c  om*/
        @Override
        public Object doInTransaction(TransactionStatus status) {
            return dataExporter.exportData(name);
        }
    });

    //Make sure the data was exported
    assertNotNull("Exported data was null", dataExport);

    //Marshall to XML
    final Marshaller marshaller = dataExporter.getMarshaller();

    final StringWriter result = new StringWriter();
    marshaller.marshal(dataExport, new StreamResult(result));

    //Compare the exported XML data with the imported XML data, they should match
    final String resultString = result.toString();
    try {
        XMLUnit.setIgnoreWhitespace(true);
        Diff d = new Diff(new StringReader(importData), new StringReader(resultString));
        assertTrue("Export result differs from import" + d, d.similar());
    } catch (Exception e) {
        throw new XmlTestException("Failed to assert similar between import XML and export XML", resultString,
                e);
    } catch (Error e) {
        throw new XmlTestException("Failed to assert similar between import XML and export XML", resultString,
                e);
    }
}

From source file:org.jasig.portal.layout.simple.RDBMUserLayoutStore.java

/**
 * Return the next available structure id for a user
 * @param person/*ww  w  .j av a2s  . c o  m*/
 * @param prefix
 * @return next free structure ID
 * @exception Exception
 */
protected String getNextStructId(final IPerson person, final String prefix) {
    final int userId = person.getID();
    return this.nextStructTransactionOperations.execute(new TransactionCallback<String>() {
        @Override
        public String doInTransaction(TransactionStatus status) {
            return jdbcOperations.execute(new ConnectionCallback<String>() {
                @Override
                public String doInConnection(Connection con) throws SQLException, DataAccessException {

                    Statement stmt = con.createStatement();
                    try {
                        String sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID=" + userId;
                        if (log.isDebugEnabled())
                            log.debug("RDBMUserLayoutStore::getNextStructId(): " + sQuery);
                        ResultSet rs = stmt.executeQuery(sQuery);
                        int currentStructId;
                        try {
                            if (rs.next()) {
                                currentStructId = rs.getInt(1);
                            } else {
                                throw new SQLException("no rows returned for query [" + sQuery + "]");
                            }
                        } finally {
                            rs.close();
                        }
                        int nextStructId = currentStructId + 1;
                        String sUpdate = "UPDATE UP_USER SET NEXT_STRUCT_ID=" + nextStructId + " WHERE USER_ID="
                                + userId + " AND NEXT_STRUCT_ID=" + currentStructId;
                        if (log.isDebugEnabled())
                            log.debug("RDBMUserLayoutStore::getNextStructId(): " + sUpdate);
                        stmt.executeUpdate(sUpdate);
                        return prefix + nextStructId;
                    } finally {
                        stmt.close();
                    }
                }
            });
        }
    });
}

From source file:org.jasig.portal.layout.simple.RDBMUserLayoutStore.java

protected Document getPersonalUserLayout(final IPerson person, final IUserProfile profile) {
    final LocaleManager localeManager = profile.getLocaleManager();

    return jdbcOperations.execute(new ConnectionCallback<Document>() {
        @Override/* w w  w. ja v a  2  s .c  om*/
        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;
                                                    if (log.isDebugEnabled())
                                                        log.debug("RDBMUserLayoutStore::getUserLayout(): "
                                                                + sQuery);
                                                    ResultSet rs = stmt.executeQuery(sQuery);
                                                    try {
                                                        boolean hasRow = rs.next();
                                                        newUserId = rs.getInt(1);
                                                        newLayoutId = rs.getInt(2);
                                                    } 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;
                                                    if (log.isDebugEnabled())
                                                        log.debug("RDBMUserLayoutStore::getUserLayout(): "
                                                                + sQuery);
                                                    int nextStructId;
                                                    rs = stmt.executeQuery(sQuery);
                                                    try {
                                                        boolean hasRow = rs.next();
                                                        nextStructId = rs.getInt(1);
                                                    } 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;
                                                        if (log.isDebugEnabled())
                                                            log.debug("RDBMUserLayoutStore::getUserLayout(): "
                                                                    + sQuery);
                                                        rs = stmt.executeQuery(sQuery);
                                                        try {
                                                            boolean hasRow = rs.next();
                                                            realNextStructId = rs.getInt(1);
                                                        } finally {
                                                            rs.close();
                                                        }
                                                    }

                                                    if (nextStructId > realNextStructId) {
                                                        sQuery = "UPDATE UP_USER SET NEXT_STRUCT_ID="
                                                                + nextStructId + " WHERE USER_ID=" + realUserId;
                                                        if (log.isDebugEnabled())
                                                            log.debug("RDBMUserLayoutStore::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;

                //This loop is used to ensure a layout is found for a user. It tries
                //looking up the layout for the current userID. If one isn't found
                //the userID is replaced with the template user ID for this user and
                //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;
                    if (log.isDebugEnabled())
                        log.debug("RDBMUserLayoutStore::getUserLayout(): " + sQuery);
                    rs = stmt.executeQuery(sQuery);
                    try {
                        if (rs.next()) {
                            firstStructId = rs.getInt(1);
                        } else {
                            throw new RuntimeException(
                                    "RDBMUserLayoutStore::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";
                    if (log.isDebugEnabled())
                        log.debug("RDBMUserLayoutStore::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;
                        if (log.isDebugEnabled())
                            log.debug("RDBMUserLayoutStore::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);
                        // Result Set returns 0 by default if structId was null
                        // 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(5); // Some JDBC drivers require columns accessed in order
                            String temp6 = rs.getString(6); // Access 5 and 6 now, save till needed.

                            // 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, temp6); // Plug in saved column values
                            }
                            if (databaseMetadata.supportsOuterJoins()) {
                                do {
                                    String name = rs.getString(name_index);
                                    String value = rs.getString(value_index); // Oracle JDBC requires us to do this for longs
                                    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";

                    if (log.isDebugEnabled())
                        log.debug("RDBMUserLayoutStore::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";
                    if (log.isDebugEnabled())
                        log.debug("RDBMUserLayoutStore::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 (log.isDebugEnabled()) {
                        long stopTime = System.currentTimeMillis();
                        log.debug("RDBMUserLayoutStore::getUserLayout(): Layout document for user " + userId
                                + " took " + (stopTime - startTime) + " milliseconds to create");
                    }

                    doc.appendChild(root);
                }
            } finally {
                stmt.close();
                insertStmt.close();
            }
            return doc;
        }
    });
}

From source file:org.jasig.portal.layout.simple.RDBMUserLayoutStore.java

public void setUserBrowserMapping(final IPerson person, final String userAgentArg, final int profileId) {
    final int userId = person.getID();

    this.transactionOperations.execute(new TransactionCallback<Object>() {
        @Override/*w w  w  .  java 2s .  co m*/
        public Object doInTransaction(TransactionStatus status) {
            return jdbcOperations.execute(new ConnectionCallback<Object>() {
                @Override
                public Object doInConnection(Connection con) throws SQLException, DataAccessException {
                    final String userAgent;
                    if (userAgentArg.length() > 255) {
                        userAgent = userAgentArg.substring(0, 254);
                        log.debug("userAgent trimmed to 255 characters. userAgent: " + userAgentArg);
                    } else {
                        userAgent = userAgentArg;
                    }

                    // remove the old mapping and add the new one
                    PreparedStatement ps = null;
                    try {
                        ps = con.prepareStatement(
                                "DELETE FROM UP_USER_UA_MAP WHERE USER_ID=? AND USER_AGENT=?");
                        ps.setInt(1, userId);
                        ps.setString(2, userAgent);
                        ps.executeUpdate();
                    } finally {
                        try {
                            ps.close();
                        } catch (Exception e) {
                            //ignore
                        }
                    }
                    try {
                        log.debug("writing to UP_USER_UA_MAP: userId: " + userId + ", userAgent: " + userAgent
                                + ", profileId: " + profileId);
                        ps = con.prepareStatement(
                                "INSERT INTO UP_USER_UA_MAP (USER_ID,USER_AGENT,PROFILE_ID) VALUES (?,?,?)");
                        ps.setInt(1, userId);
                        ps.setString(2, userAgent);
                        ps.setInt(3, profileId);
                        ps.executeUpdate();
                    } finally {
                        try {
                            ps.close();
                        } catch (Exception e) {
                            //ignore
                        }
                    }

                    return null;
                }
            });
        }
    });
}

From source file:org.jasig.portal.layout.simple.RDBMUserLayoutStore.java

/**
 * Save the user layout.//from w  ww . ja  va 2 s .com
 * @param person
 * @param profile
 * @param layoutXML
 * @throws Exception
 */
public void setUserLayout(final IPerson person, final IUserProfile profile, final Document layoutXML,
        final boolean channelsAdded) {
    final long startTime = System.currentTimeMillis();
    final int userId = person.getID();
    final int profileId = profile.getProfileId();

    this.transactionOperations.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            return jdbcOperations.execute(new ConnectionCallback<Object>() {
                @Override
                public Object doInConnection(Connection con) throws SQLException, DataAccessException {

                    int layoutId = 0;
                    ResultSet rs;

                    // Eventually we want to be able to just get layoutId from the
                    // profile, but because of the template user layouts we have to do this for now ...
                    layoutId = getLayoutID(userId, profileId);

                    boolean firstLayout = false;
                    if (layoutId == 0) {
                        // First personal layout for this user/profile
                        layoutId = 1;
                        firstLayout = true;
                    }

                    String sql = "DELETE FROM UP_LAYOUT_PARAM WHERE USER_ID=? AND LAYOUT_ID=?";
                    PreparedStatement pstmt = con.prepareStatement(sql);
                    try {
                        pstmt.clearParameters();
                        pstmt.setInt(1, userId);
                        pstmt.setInt(2, layoutId);
                        if (log.isDebugEnabled())
                            log.debug(sql);
                        pstmt.executeUpdate();
                    } finally {
                        pstmt.close();
                    }

                    sql = "DELETE FROM UP_LAYOUT_STRUCT WHERE USER_ID=? AND LAYOUT_ID=?";
                    pstmt = con.prepareStatement(sql);
                    try {
                        pstmt.clearParameters();
                        pstmt.setInt(1, userId);
                        pstmt.setInt(2, layoutId);
                        if (log.isDebugEnabled())
                            log.debug(sql);
                        pstmt.executeUpdate();
                    } finally {
                        pstmt.close();
                    }

                    PreparedStatement structStmt = con.prepareStatement("INSERT INTO UP_LAYOUT_STRUCT "
                            + "(USER_ID, LAYOUT_ID, STRUCT_ID, NEXT_STRUCT_ID, CHLD_STRUCT_ID,EXTERNAL_ID,CHAN_ID,NAME,TYPE,HIDDEN,IMMUTABLE,UNREMOVABLE) "
                            + "VALUES (" + userId + "," + layoutId + ",?,?,?,?,?,?,?,?,?,?)");

                    PreparedStatement parmStmt = con.prepareStatement("INSERT INTO UP_LAYOUT_PARAM "
                            + "(USER_ID, LAYOUT_ID, STRUCT_ID, STRUCT_PARM_NM, STRUCT_PARM_VAL) " + "VALUES ("
                            + userId + "," + layoutId + ",?,?,?)");

                    int firstStructId;
                    try {
                        firstStructId = saveStructure(layoutXML.getFirstChild().getFirstChild(), structStmt,
                                parmStmt);
                    } finally {
                        structStmt.close();
                        parmStmt.close();
                    }

                    //Check to see if the user has a matching layout
                    sql = "SELECT * FROM UP_USER_LAYOUT WHERE USER_ID=? AND LAYOUT_ID=?";
                    pstmt = con.prepareStatement(sql);
                    try {
                        pstmt.clearParameters();
                        pstmt.setInt(1, userId);
                        pstmt.setInt(2, layoutId);
                        if (log.isDebugEnabled())
                            log.debug(sql);
                        rs = pstmt.executeQuery();

                        try {
                            if (!rs.next()) {
                                // If not, the default user is found and the layout rows from the default user are copied for the current user.
                                int defaultUserId;

                                sql = "SELECT USER_DFLT_USR_ID FROM UP_USER WHERE USER_ID=?";
                                PreparedStatement pstmt2 = con.prepareStatement(sql);
                                try {
                                    pstmt2.clearParameters();
                                    pstmt2.setInt(1, userId);
                                    if (log.isDebugEnabled())
                                        log.debug(sql);
                                    ResultSet rs2 = null;
                                    try {
                                        rs2 = pstmt2.executeQuery();
                                        rs2.next();
                                        defaultUserId = rs2.getInt(1);
                                    } finally {
                                        rs2.close();
                                    }
                                } finally {
                                    pstmt2.close();
                                }

                                // Add to UP_USER_LAYOUT
                                sql = "SELECT USER_ID,LAYOUT_ID,LAYOUT_TITLE,INIT_STRUCT_ID FROM UP_USER_LAYOUT WHERE USER_ID=?";
                                pstmt2 = con.prepareStatement(sql);
                                try {
                                    pstmt2.clearParameters();
                                    pstmt2.setInt(1, defaultUserId);
                                    if (log.isDebugEnabled())
                                        log.debug(sql);
                                    ResultSet rs2 = pstmt2.executeQuery();
                                    try {
                                        if (rs2.next()) {
                                            // There is a row for this user's template user...
                                            sql = "INSERT INTO UP_USER_LAYOUT (USER_ID, LAYOUT_ID, LAYOUT_TITLE, INIT_STRUCT_ID) VALUES (?,?,?,?)";
                                            PreparedStatement pstmt3 = con.prepareStatement(sql);
                                            try {
                                                pstmt3.clearParameters();
                                                pstmt3.setInt(1, userId);
                                                pstmt3.setInt(2, rs2.getInt("LAYOUT_ID"));
                                                pstmt3.setString(3, rs2.getString("LAYOUT_TITLE"));
                                                pstmt3.setInt(4, rs2.getInt("INIT_STRUCT_ID"));
                                                if (log.isDebugEnabled())
                                                    log.debug(sql);
                                                pstmt3.executeUpdate();
                                            } finally {
                                                pstmt3.close();
                                            }
                                        } else {
                                            // We can't rely on the template user, but we still need a row...
                                            sql = "INSERT INTO UP_USER_LAYOUT (USER_ID, LAYOUT_ID, LAYOUT_TITLE, INIT_STRUCT_ID) VALUES (?,?,?,?)";
                                            PreparedStatement pstmt3 = con.prepareStatement(sql);
                                            try {
                                                pstmt3.clearParameters();
                                                pstmt3.setInt(1, userId);
                                                pstmt3.setInt(2, layoutId);
                                                pstmt3.setString(3, "default layout");
                                                pstmt3.setInt(4, 1);
                                                if (log.isDebugEnabled())
                                                    log.debug(sql);
                                                pstmt3.executeUpdate();
                                            } finally {
                                                pstmt3.close();
                                            }
                                        }
                                    } finally {
                                        rs2.close();
                                    }
                                } finally {
                                    pstmt2.close();
                                }

                            }
                        } finally {
                            rs.close();
                        }
                    } finally {
                        pstmt.close();
                    }

                    //Update the users layout with the correct inital structure ID
                    sql = "UPDATE UP_USER_LAYOUT SET INIT_STRUCT_ID=? WHERE USER_ID=? AND LAYOUT_ID=?";
                    pstmt = con.prepareStatement(sql);
                    try {
                        pstmt.clearParameters();
                        pstmt.setInt(1, firstStructId);
                        pstmt.setInt(2, userId);
                        pstmt.setInt(3, layoutId);
                        if (log.isDebugEnabled())
                            log.debug(sql);
                        pstmt.executeUpdate();
                    } finally {
                        pstmt.close();
                    }

                    // Update the last time the user saw the list of available channels
                    if (channelsAdded) {
                        sql = "UPDATE UP_USER SET LST_CHAN_UPDT_DT=? WHERE USER_ID=?";
                        pstmt = con.prepareStatement(sql);
                        try {
                            pstmt.clearParameters();
                            pstmt.setDate(1, new java.sql.Date(System.currentTimeMillis()));
                            pstmt.setInt(2, userId);
                            log.debug(sql);
                            pstmt.executeUpdate();
                        } finally {
                            pstmt.close();
                        }
                    }

                    if (firstLayout) {
                        int defaultUserId;
                        int defaultLayoutId;
                        // Have to copy some of data over from the default user
                        sql = "SELECT USER_DFLT_USR_ID,USER_DFLT_LAY_ID FROM UP_USER WHERE USER_ID=?";
                        pstmt = con.prepareStatement(sql);
                        try {
                            pstmt.clearParameters();
                            pstmt.setInt(1, userId);
                            log.debug(sql);
                            rs = pstmt.executeQuery();
                            try {
                                rs.next();
                                defaultUserId = rs.getInt(1);
                                defaultLayoutId = rs.getInt(2);
                            } finally {
                                rs.close();
                            }
                        } finally {
                            pstmt.close();
                        }

                        sql = "UPDATE UP_USER_PROFILE SET LAYOUT_ID=1 WHERE USER_ID=? AND PROFILE_ID=?";
                        pstmt = con.prepareStatement(sql);
                        try {
                            pstmt.clearParameters();
                            pstmt.setInt(1, userId);
                            pstmt.setInt(2, profileId);
                            log.debug(sql);
                            pstmt.executeUpdate();
                        } finally {
                            pstmt.close();
                        }
                    }

                    return null;
                }
            });
        }
    });
    if (log.isDebugEnabled()) {
        long stopTime = System.currentTimeMillis();
        log.debug("RDBMUserLayoutStore::setUserLayout(): Layout document for user " + userId + " took "
                + (stopTime - startTime) + " milliseconds to save");
    }
}

From source file:org.jasig.portal.layout.simple.RDBMUserLayoutStore.java

public void updateUserProfile(final IPerson person, final IUserProfile profile) {
    final int userId = person.getID();
    this.transactionOperations.execute(new TransactionCallback<Object>() {
        @Override/*from   w w w  . ja  va2 s  . co  m*/
        public Object doInTransaction(TransactionStatus status) {
            return jdbcOperations.execute(new ConnectionCallback<Object>() {
                @Override
                public Object doInConnection(Connection con) throws SQLException, DataAccessException {

                    String query = "UPDATE UP_USER_PROFILE SET LAYOUT_ID=?,THEME_SS_ID=?,STRUCTURE_SS_ID=?,"
                            + "DESCRIPTION=?,PROFILE_NAME=?, PROFILE_FNAME=? WHERE USER_ID=? AND PROFILE_ID=?";
                    PreparedStatement pstmt = con.prepareStatement(query);
                    pstmt.setInt(1, profile.getLayoutId());
                    pstmt.setInt(2, profile.getThemeStylesheetId());
                    pstmt.setInt(3, profile.getStructureStylesheetId());
                    pstmt.setString(4, profile.getProfileDescription());
                    pstmt.setString(5, profile.getProfileName());
                    pstmt.setString(6, profile.getProfileFname());
                    pstmt.setInt(7, userId);
                    pstmt.setInt(8, profile.getProfileId());
                    try {
                        if (log.isDebugEnabled())
                            log.debug("RDBMUserLayoutStore::updateUserProfile() : " + query + " layout_id: "
                                    + profile.getLayoutId() + " theme_ss_id: " + profile.getThemeStylesheetId()
                                    + " structure_ss_id: " + profile.getStructureStylesheetId()
                                    + " description: " + profile.getProfileDescription() + " name: "
                                    + profile.getProfileName() + " user_id: " + userId + " fname: "
                                    + profile.getProfileFname());
                        pstmt.execute();
                    } finally {
                        pstmt.close();
                    }

                    return null;
                }
            });
        }
    });
}

From source file:org.jasig.portal.RDBMUserIdentityStore.java

protected void updateUser(final int userId, final IPerson person, final TemplateUser templateUser)
        throws Exception {
    // Remove my existing group memberships
    IGroupMember me = GroupService.getGroupMember(person.getEntityIdentifier());
    Iterator myExistingGroups = me.getContainingGroups();
    while (myExistingGroups.hasNext()) {
        IEntityGroup eg = (IEntityGroup) myExistingGroups.next();
        ILockableEntityGroup leg = getSafeLockableGroup(eg, me);
        if (leg != null) {
            removePersonFromGroup(person, me, leg);
        }/*from   w  ww . j a va2s .  co  m*/
    }

    // Copy template user's groups memberships
    IGroupMember template = GroupService.getEntity(templateUser.getUserName(),
            org.jasig.portal.security.IPerson.class);
    Iterator templateGroups = template.getContainingGroups();
    while (templateGroups.hasNext()) {
        IEntityGroup eg = (IEntityGroup) templateGroups.next();
        ILockableEntityGroup leg = getSafeLockableGroup(eg, me);
        if (leg != null) {
            addPersonToGroup(person, me, leg);
        }
    }

    this.transactionOperations.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            return jdbcOperations.execute(new ConnectionCallback<Object>() {
                @Override
                public Object doInConnection(Connection con) throws SQLException, DataAccessException {

                    PreparedStatement deleteStmt = null;
                    PreparedStatement queryStmt = null;
                    PreparedStatement insertStmt = null;
                    try {
                        // Update UP_USER
                        String update = "UPDATE UP_USER " + "SET USER_DFLT_USR_ID=?, " + "USER_DFLT_LAY_ID=?, "
                                + "NEXT_STRUCT_ID=null " + "WHERE USER_ID=?";

                        insertStmt = con.prepareStatement(update);
                        insertStmt.setInt(1, templateUser.getUserId());
                        insertStmt.setInt(2, templateUser.getDefaultLayoutId());
                        insertStmt.setInt(3, userId);

                        if (log.isDebugEnabled())
                            log.debug("RDBMUserIdentityStore::addNewUser(): " + update);
                        insertStmt.executeUpdate();
                        insertStmt.close();

                        // Start copying...
                        ResultSet rs = null;
                        String delete = null;
                        String query = null;
                        String insert = null;
                        try {
                            // Update UP_USER_PROFILE
                            delete = "DELETE FROM UP_USER_PROFILE " + "WHERE USER_ID=?";
                            deleteStmt = con.prepareStatement(delete);
                            deleteStmt.setInt(1, userId);
                            if (log.isDebugEnabled())
                                log.debug(
                                        "RDBMUserIdentityStore::updateUser(USER_ID=" + userId + "): " + delete);
                            deleteStmt.executeUpdate();
                            deleteStmt.close();

                            query = "SELECT USER_ID, PROFILE_FNAME, PROFILE_NAME, DESCRIPTION, "
                                    + "STRUCTURE_SS_ID, THEME_SS_ID " + "FROM UP_USER_PROFILE "
                                    + "WHERE USER_ID=?";
                            queryStmt = con.prepareStatement(query);
                            queryStmt.setInt(1, templateUser.getUserId());
                            if (log.isDebugEnabled())
                                log.debug("RDBMUserIdentityStore::updateUser(USER_ID="
                                        + templateUser.getUserId() + "): " + query);
                            rs = queryStmt.executeQuery();

                            insert = "INSERT INTO UP_USER_PROFILE (USER_ID, PROFILE_ID, PROFILE_FNAME, PROFILE_NAME, DESCRIPTION, LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID) "
                                    + "VALUES(?, ?, ?, ?, ?, NULL, ?, ?)";
                            insertStmt = con.prepareStatement(insert);
                            while (rs.next()) {
                                int id = getNextKey();

                                String profileFname = rs.getString("PROFILE_FNAME");
                                String profileName = rs.getString("PROFILE_NAME");
                                String description = rs.getString("DESCRIPTION");
                                int structure = rs.getInt("STRUCTURE_SS_ID");
                                int theme = rs.getInt("THEME_SS_ID");

                                insertStmt.setInt(1, userId);
                                insertStmt.setInt(2, id);
                                insertStmt.setString(3, profileFname);
                                insertStmt.setString(4, profileName);
                                insertStmt.setString(5, description);
                                insertStmt.setInt(6, structure);
                                insertStmt.setInt(7, theme);

                                if (log.isDebugEnabled())
                                    log.debug("RDBMUserIdentityStore::updateUser(USER_ID=" + userId
                                            + ", PROFILE_FNAME=" + profileFname + ", PROFILE_NAME="
                                            + profileName + ", DESCRIPTION=" + description + "): " + insert);
                                insertStmt.executeUpdate();
                            }
                            rs.close();
                            queryStmt.close();
                            insertStmt.close();

                            // If we made it all the way though, commit the transaction
                            if (RDBMServices.getDbMetaData().supportsTransactions())
                                con.commit();

                        } finally {
                            try {
                                rs.close();
                            } catch (Exception e) {
                            }
                        }
                    } finally {
                        try {
                            deleteStmt.close();
                        } catch (Exception e) {
                        }
                        try {
                            queryStmt.close();
                        } catch (Exception e) {
                        }
                        try {
                            insertStmt.close();
                        } catch (Exception e) {
                        }
                    }

                    return null;
                }
            });
        }
    });
}

From source file:org.jasig.portal.RDBMUserIdentityStore.java

protected int addNewUser(final int newUID, final IPerson person, final TemplateUser templateUser)
        throws Exception {
    // Copy template user's groups memberships
    IGroupMember me = GroupService.getGroupMember(person.getEntityIdentifier());
    IGroupMember template = GroupService.getEntity(templateUser.getUserName(),
            Class.forName("org.jasig.portal.security.IPerson"));
    Iterator templateGroups = template.getContainingGroups();
    while (templateGroups.hasNext()) {
        IEntityGroup eg = (IEntityGroup) templateGroups.next();
        ILockableEntityGroup leg = getSafeLockableGroup(eg, me);
        if (leg != null) {
            addPersonToGroup(person, me, leg);
        }//from   w w  w. ja v a2s.  com
    }

    return this.transactionOperations.execute(new TransactionCallback<Integer>() {
        @Override
        public Integer doInTransaction(TransactionStatus status) {
            return jdbcOperations.execute(new ConnectionCallback<Integer>() {
                @Override
                public Integer doInConnection(Connection con) throws SQLException, DataAccessException {

                    int uPortalUID = -1;
                    PreparedStatement queryStmt = null;
                    PreparedStatement insertStmt = null;
                    try {
                        // Add to UP_USER
                        String insert = "INSERT INTO UP_USER (USER_ID, USER_NAME, USER_DFLT_USR_ID, USER_DFLT_LAY_ID, NEXT_STRUCT_ID, LST_CHAN_UPDT_DT)"
                                + "VALUES (?, ?, ?, ?, null, null)";

                        String userName = getUsername(person);

                        insertStmt = con.prepareStatement(insert);
                        insertStmt.setInt(1, newUID);
                        insertStmt.setString(2, userName);
                        insertStmt.setInt(3, templateUser.getUserId());
                        insertStmt.setInt(4, templateUser.getDefaultLayoutId());

                        if (log.isDebugEnabled())
                            log.debug("RDBMUserIdentityStore::addNewUser(USER_ID=" + newUID + ", USER_NAME="
                                    + userName + ", USER_DFLT_USR_ID=" + templateUser.getUserId()
                                    + ", USER_DFLT_LAY_ID=" + templateUser.getDefaultLayoutId() + "): "
                                    + insert);
                        insertStmt.executeUpdate();
                        insertStmt.close();
                        insertStmt = null;

                        // Start copying...
                        ResultSet rs = null;
                        String query = null;
                        try {
                            // Add to UP_USER_PROFILE
                            query = "SELECT USER_ID, PROFILE_FNAME, PROFILE_NAME, DESCRIPTION, "
                                    + "STRUCTURE_SS_ID, THEME_SS_ID " + "FROM UP_USER_PROFILE "
                                    + "WHERE USER_ID=?";
                            queryStmt = con.prepareStatement(query);
                            queryStmt.setInt(1, templateUser.getUserId());
                            if (log.isDebugEnabled())
                                log.debug("RDBMUserIdentityStore::addNewUser(USER_ID="
                                        + templateUser.getUserId() + "): " + query);
                            rs = queryStmt.executeQuery();

                            insert = "INSERT INTO UP_USER_PROFILE (USER_ID, PROFILE_ID, PROFILE_FNAME, PROFILE_NAME, DESCRIPTION, LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID) "
                                    + "VALUES(?, ?, ?, ?, ?, NULL, ?, ?)";
                            insertStmt = con.prepareStatement(insert);
                            while (rs.next()) {
                                int id = getNextKey();

                                String profileFname = rs.getString("PROFILE_FNAME");
                                String profileName = rs.getString("PROFILE_NAME");
                                String description = rs.getString("DESCRIPTION");
                                int structure = rs.getInt("STRUCTURE_SS_ID");
                                int theme = rs.getInt("THEME_SS_ID");

                                insertStmt.setInt(1, newUID);
                                insertStmt.setInt(2, id);
                                insertStmt.setString(3, profileFname);
                                insertStmt.setString(4, profileName);
                                insertStmt.setString(5, description);
                                insertStmt.setInt(6, structure);
                                insertStmt.setInt(7, theme);

                                if (log.isDebugEnabled())
                                    log.debug("RDBMUserIdentityStore::addNewUser(USER_ID=" + newUID
                                            + ", PROFILE_FNAME=" + profileFname + ", PROFILE_NAME="
                                            + profileName + ", DESCRIPTION=" + description + "): " + insert);
                                insertStmt.executeUpdate();
                            }
                            rs.close();
                            queryStmt.close();

                            if (insertStmt != null) {
                                insertStmt.close();
                                insertStmt = null;
                            }

                            // If we made it all the way though, commit the transaction
                            if (RDBMServices.getDbMetaData().supportsTransactions())
                                con.commit();

                            uPortalUID = newUID;

                        } finally {
                            try {
                                if (rs != null)
                                    rs.close();
                            } catch (Exception e) {
                            }
                        }
                    } finally {
                        try {
                            if (queryStmt != null)
                                queryStmt.close();
                        } catch (Exception e) {
                        }
                        try {
                            if (insertStmt != null)
                                insertStmt.close();
                        } catch (Exception e) {
                        }
                    }

                    return uPortalUID;

                }
            });
        }
    });
}

From source file:org.jspresso.framework.application.backend.AbstractBackendController.java

/**
 * Executes an action transactionally, e.g. when the @Transactional annotation
 * is present.//from www  .  j  a v  a2s .  c o m
 *
 * @param action
 *     the action to execute.
 * @param context
 *     the context
 * @return the action outcome
 */
public boolean executeTransactionally(final IAction action, final Map<String, Object> context) {
    Boolean ret = getTransactionTemplate().execute(new TransactionCallback<Boolean>() {

        @Override
        public Boolean doInTransaction(TransactionStatus status) {
            boolean executionStatus = executeBackend(action, context);
            if (!executionStatus) {
                status.setRollbackOnly();
            }
            return executionStatus;
        }
    });
    return ret;
}