Java tutorial
/******************************************************************************* * Copyright (c) 2009 David Harrison. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl-3.0.html * * Contributors: * David Harrison - initial API and implementation ******************************************************************************/ package com.sfs.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.ArrayList; import java.util.HashMap; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import com.sfs.DataFilter; import com.sfs.beans.GadgetBean; import com.sfs.beans.GadgetPreferencesBean; import com.sfs.beans.GadgetsPreferencesBean; import org.apache.log4j.Logger; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.RowMapper; /** * The Class GadgetPreferencesDAOImpl. * * @author David Harrison 20th July 2007 - heavily modified 3rd June 2008 */ public class GadgetPreferencesDAOImpl extends BaseDAOImpl implements GadgetPreferencesDAO { /** The data logger. */ private static Logger dataLogger = Logger.getLogger(GadgetPreferencesDAOImpl.class); /** The gadget dao. */ @Resource private GadgetDAO gadgetDAO; /** * Sets the gadget preference. * * @param gadgetsPreferences the gadgets preferences * @param gadgetPreferences the gadget preferences * * @return the gadgets preferences bean * * @throws SFSDaoException the SFS dao exception */ public final GadgetsPreferencesBean setGadgetPreference(final GadgetsPreferencesBean gadgetsPreferences, final GadgetPreferencesBean gadgetPreferences) throws SFSDaoException { GadgetsPreferencesBean returnPreferences = gadgetsPreferences; // Test if the gadget has a gadgetId and if it exists in the hash. If it // has an id and it exists in the hash then the preferences are being // updated If the gadget does not have an id then it is new and needs to // be created // Set the UserDN to that of the GadgetsPreferencesBean gadgetPreferences.setUserDn(returnPreferences.getUserDn()); if (gadgetPreferences.getId() == 0) { // The gadget is new and needs to be created before adding to the // hash try { final int gadgetPreferencesId = this.create(gadgetPreferences); gadgetPreferences.setId(gadgetPreferencesId); } catch (Exception e) { throw new SFSDaoException("Error adding gadget preference: " + e.getMessage()); } } if (gadgetPreferences.getId() > 0) { // Load the gadget to ensure it is valid try { GadgetPreferencesBean storedGadget = this.load(gadgetPreferences.getId()); if (storedGadget != null) { // Add it to the gadgets hashmap returnPreferences.addGadgetPreference(storedGadget); // With the gadget added to the hash add it to the order map returnPreferences = this.rebuildOrder(returnPreferences, storedGadget); } } catch (Exception e) { throw new SFSDaoException("Error rebuilding gadget preferences: " + e.getMessage()); } } return returnPreferences; } /** * Removes the supplied gadget preference from the supplied * GadgetsPreferencesBean. * * @param gadgetsPreferences the gadgets preferences * @param gadgetPreferences the gadget preferences * * @return the gadgets preferences bean * * @throws com.sfs.dao.SFSDaoException * @throws SFSDaoException the SFS dao * exception */ public final GadgetsPreferencesBean removeGadgetPreference(final GadgetsPreferencesBean gadgetsPreferences, final GadgetPreferencesBean gadgetPreferences) throws SFSDaoException { GadgetsPreferencesBean returnPreferences = gadgetsPreferences; if (gadgetPreferences.getId() == 0) { throw new SFSDaoException("Cannot remove a gadget preference with an Id of 0"); } // Set the UserDN to that of the GadgetsPreferencesBean gadgetPreferences.setUserDn(returnPreferences.getUserDn()); if (returnPreferences.hasGadgetPreference(gadgetPreferences.getId())) { // Gadget exists in the GadgetsPreferencesBean, remove it and // rebuild index try { this.delete(gadgetPreferences); returnPreferences.removeGadgetPreference(gadgetPreferences.getId()); } catch (Exception e) { throw new SFSDaoException("Error deleting gadget preference: " + e.getMessage()); } try { // With the gadget added to the hash add it to the order map returnPreferences = this.rebuildOrder(returnPreferences); } catch (Exception e) { throw new SFSDaoException("Error rebuilding gadget preferences: " + e.getMessage()); } } return returnPreferences; } /** * Rebuild the gadget preferences array order based on the string of gadget * ids. * * @param gadgetsPreferences the gadgets preferences * @param orderVal the order string * * @return the gadgets preferences bean */ public final GadgetsPreferencesBean reorderGadgets(final GadgetsPreferencesBean gadgetsPreferences, final String orderVal) { String orderString = ""; if (orderVal != null) { orderString = orderVal; } // Tokenize string based on ',' character StringTokenizer tokenizer = new StringTokenizer(orderString, ","); int orderId = 0; // Refresh the GadgetsPreferencesBean order gadgetsPreferences.voidOrder(); while (tokenizer.hasMoreElements()) { String strGadgetId = tokenizer.nextToken(); int gadgetId = 0; try { gadgetId = Integer.parseInt(strGadgetId); } catch (Exception e) { // Error parsing gadget preference id gadgetId = 0; } if (gadgetId > 0) { // Check that the gadget preference exists if (gadgetsPreferences.hasGadgetPreference(gadgetId)) { // Gadget exists, set gadgetId/order gadgetsPreferences.addGadgetPreferenceRef(gadgetId, orderId); orderId++; } } } // Persist the GadgetsPreferencesBean order to the datastore try { final boolean success = this.persistOrder(gadgetsPreferences); if (success) { dataLogger.debug("The GadgetsPreferencesBean order was persisted"); } else { dataLogger.debug("The GadgetsPreferencesBean order could not be persisted"); } } catch (Exception e) { dataLogger.error("Error persisting GadgetsPreferencesBean order: " + e.getMessage()); } return gadgetsPreferences; } /** * Load a GadgetPreferencesBean for the supplied userDn. * * @param userDn the user dn * * @return the gadgets preferences bean * * @throws SFSDaoException the SFS dao exception */ @SuppressWarnings("unchecked") public final GadgetsPreferencesBean load(final String userDn) throws SFSDaoException { if (userDn == null) { throw new SFSDaoException("User DN cannot be null"); } if (userDn.compareTo("") == 0) { throw new SFSDaoException("User DN cannot be an empty string"); } GadgetsPreferencesBean gadgetsPreferences = new GadgetsPreferencesBean(); gadgetsPreferences.setUserDn(userDn); dataLogger.debug("Load gadget preferences for: " + userDn); Collection<GadgetPreferencesBean> gadgetCollection = new ArrayList<GadgetPreferencesBean>(); try { gadgetCollection = this.getJdbcTemplateReader().query(getSQL().getValue("gadget/preferences/load"), new Object[] { userDn }, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return loadGadgetPreferences(rs); } }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } for (GadgetPreferencesBean gadgetPreferences : gadgetCollection) { gadgetsPreferences.addGadgetPreference(gadgetPreferences); gadgetsPreferences.addGadgetPreferenceRef(gadgetPreferences.getId(), gadgetPreferences.getPosition()); } return gadgetsPreferences; } /** * Load a HashMap of GadgetPreferencesBean for a supplied userDn. * * @param userDn the user dn * * @return the hash map< integer, gadget preferences bean> * * @throws SFSDaoException the SFS dao exception */ @SuppressWarnings("unchecked") public final HashMap<Integer, GadgetPreferencesBean> loadMap(final String userDn) throws SFSDaoException { if (userDn == null) { throw new SFSDaoException("User DN cannot be null"); } if (userDn.compareTo("") == 0) { throw new SFSDaoException("User DN cannot be an empty string"); } HashMap<Integer, GadgetPreferencesBean> gadgetMap = new HashMap<Integer, GadgetPreferencesBean>(); Collection<GadgetPreferencesBean> gadgetCollection = new ArrayList<GadgetPreferencesBean>(); dataLogger.debug("Load gadget preferences for: " + userDn); try { gadgetCollection = this.getJdbcTemplateReader().query(getSQL().getValue("gadget/preferences/load"), new Object[] { userDn }, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return loadGadgetPreferences(rs); } }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } for (GadgetPreferencesBean gadgetPreferences : gadgetCollection) { gadgetMap.put(gadgetPreferences.getId(), gadgetPreferences); } return gadgetMap; } /** * Load a GadgetPreferencesBean with the specified gadgetPreferencesId. * * @param gadgetPreferenceId the gadget preference id * * @return the gadget preferences bean * * @throws SFSDaoException the SFS dao exception */ public final GadgetPreferencesBean load(final int gadgetPreferenceId) throws SFSDaoException { if (gadgetPreferenceId == 0) { throw new SFSDaoException("Cannot load a Gadget preference with an Id of 0"); } GadgetPreferencesBean gadgetPreferences = null; dataLogger.debug("Load gadget preferences for gadget preference id: " + gadgetPreferenceId); try { gadgetPreferences = (GadgetPreferencesBean) this.getJdbcTemplateReader().queryForObject( getSQL().getValue("gadget/preferences/loadId"), new Object[] { gadgetPreferenceId }, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return loadGadgetPreferences(rs); } }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } return gadgetPreferences; } /** * Build a GadgetPrefenrecesBean from the parameters within the supplied * HttpServletRequest. * * @param request the request * * @return the gadget preferences bean * * @throws SFSDaoException the SFS dao exception */ public final GadgetPreferencesBean load(final HttpServletRequest request) throws SFSDaoException { GadgetPreferencesBean gadgetPreferences = new GadgetPreferencesBean(); // Get the URL for the gadget preference gadgetPreferences.setUrl(DataFilter.getHtml(request.getParameter("URL"))); if (gadgetPreferences.getUrl() != null) { gadgetPreferences.setGadget(gadgetDAO.load(gadgetPreferences.getUrl())); } else { throw new SFSDaoException("Cannot load a gadget preference without a valid URL"); } // Load the submitted values from the request gadgetPreferences.setTitle(DataFilter.getHtml(request.getParameter("Title"))); try { gadgetPreferences.setWidth(Integer.parseInt(request.getParameter("Width"))); } catch (Exception e) { gadgetPreferences.setWidth(GadgetPreferencesBean.DEFAULT_WIDTH); } try { gadgetPreferences.setHeight(Integer.parseInt(request.getParameter("Height"))); } catch (Exception e) { gadgetPreferences.setHeight(GadgetPreferencesBean.DEFAULT_HEIGHT); } // Cycle through the user preference parameters ArrayList<String> userKeys = gadgetPreferences.getUserPrefKeys(); // Reset the user preferences gadgetPreferences.resetUserPrefs(); for (int i = 0; i < userKeys.size(); i++) { final String key = userKeys.get(i); final String upKey = "UP_" + key; final String value = DataFilter.getHtml(request.getParameter(upKey)); if (value != null) { // Load the user preference gadgetPreferences.setUserPref(key, value); } } return gadgetPreferences; } /** * Persist the supplied GadgetPreferencesBean object to the datastore. * * @param gadgetPreferences the gadget preferences * * @return the int * * @throws SFSDaoException the SFS dao exception */ public final int create(final GadgetPreferencesBean gadgetPreferences) throws SFSDaoException { if (gadgetPreferences.getUrl().compareTo("") == 0) { throw new SFSDaoException("Gadget preferences URL cannot be an empty string"); } if (gadgetPreferences.getUserDn() == null) { throw new SFSDaoException("User DN cannot be null"); } if (gadgetPreferences.getUserDn().compareTo("") == 0) { throw new SFSDaoException("User DN cannot be an empty string"); } int gadgetPreferenceId = 0; dataLogger.info(gadgetPreferences.getUserDn() + " attempting to create gadget preferences"); if (gadgetPreferences.getPosition() == 0) { // A gadget position has not been defined - get the last position int maxPosition = 0; try { maxPosition = this.getJdbcTemplateReader().queryForInt( getSQL().getValue("gadget/preferences/maxPosition"), new Object[] { gadgetPreferences.getUserDn() }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } gadgetPreferences.setPosition(maxPosition); } int insertCount = 0; try { insertCount = this.getJdbcTemplateWriter().update(getSQL().getValue("gadget/preferences/create"), new Object[] { gadgetPreferences.getUrl(), gadgetPreferences.getUserDn(), gadgetPreferences.getTitle(), writeGadgetPreferences(gadgetPreferences.getUserPrefs()), gadgetPreferences.getPosition(), gadgetPreferences.getHeight(), gadgetPreferences.getWidth() }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } if (insertCount > 0) { // Gadget preferences created - get id dataLogger.info(gadgetPreferences.getUserDn() + " successfully created gadget preference entry"); try { // Use the TemplateWriter to read as the change may not have // reached slave yet gadgetPreferenceId = this.getJdbcTemplateWriter() .queryForInt(getSQL().getValue("gadget/preferences/findMax")); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } } return gadgetPreferenceId; } /** * Update the supplied GadgetPreferencesBean within the datastore. * * @param gadgetPreferences the gadget preferences * * @return true, if update * * @throws SFSDaoException the SFS dao exception */ public final boolean update(final GadgetPreferencesBean gadgetPreferences) throws SFSDaoException { if (gadgetPreferences.getId() == 0) { throw new SFSDaoException("Gadget preference Id cannot be 0"); } if (gadgetPreferences.getUrl().compareTo("") == 0) { throw new SFSDaoException("Gadget preferences URL cannot be an empty string"); } if (gadgetPreferences.getUserDn() == null) { throw new SFSDaoException("User DN cannot be null"); } if (gadgetPreferences.getUserDn().compareTo("") == 0) { throw new SFSDaoException("User DN cannot be an empty string"); } boolean success = false; dataLogger.info(gadgetPreferences.getUserDn() + " attempting to update gadget preferences"); int updateCount = 0; try { updateCount = this.getJdbcTemplateWriter().update(getSQL().getValue("gadget/preferences/update"), new Object[] { gadgetPreferences.getUrl(), gadgetPreferences.getUserDn(), gadgetPreferences.getTitle(), writeGadgetPreferences(gadgetPreferences.getUserPrefs()), gadgetPreferences.getPosition(), gadgetPreferences.getHeight(), gadgetPreferences.getWidth(), gadgetPreferences.getId() }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } if (updateCount > 0) { dataLogger.info(gadgetPreferences.getUserDn() + " successfully updated gadget preference entry"); success = true; } return success; } /** * Delete the supplied GadgetPreferencesBean from the datastore. * * @param gadgetPreferences the gadget preferences * * @return true, if delete * * @throws SFSDaoException the SFS dao exception */ public final boolean delete(final GadgetPreferencesBean gadgetPreferences) throws SFSDaoException { if (gadgetPreferences.getId() == 0) { throw new SFSDaoException("Gadget preference Id cannot be zero"); } if (gadgetPreferences.getUserDn() == null) { throw new SFSDaoException("User DN cannot be null"); } if (gadgetPreferences.getUserDn().compareTo("") == 0) { throw new SFSDaoException("User DN cannot be an empty string"); } boolean success = false; dataLogger.info(gadgetPreferences.getUserDn() + " attempting to delete gadget preference id: " + gadgetPreferences.getId()); int deleteCount = 0; try { deleteCount = this.getJdbcTemplateWriter().update(getSQL().getValue("gadget/preferences/delete"), new Object[] { gadgetPreferences.getId() }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } if (deleteCount > 0) { dataLogger.info(gadgetPreferences.getUserDn() + " successfully deleted gadget preference entry"); success = true; } return success; } /** * Loads a gadgetspreferences bean based on the submitted userDN If * successful the bean is passed to the persistOrder function. * * @param userDN the user dn * * @return true, if refresh order * * @throws SFSDaoException the SFS dao exception */ public final boolean refreshOrder(final String userDN) throws SFSDaoException { boolean success = false; GadgetsPreferencesBean gadgetsPreferences = null; try { gadgetsPreferences = this.load(userDN); } catch (Exception e) { dataLogger.error("Error loading gadget preferences: " + e.getMessage()); } if (gadgetsPreferences != null) { try { success = this.persistOrder(gadgetsPreferences); } catch (NullPointerException npe) { dataLogger.error("The gadget order cannot be refreshed: " + npe.getMessage()); } } return success; } /** * Persisits the gadget preferences order in the database Loads a * gadgetspreferences bean and cycles through updating the position value. * * @param gadgetsPreferences the gadgets preferences * * @return true, if persist order * * @throws SFSDaoException the SFS dao exception */ public final boolean persistOrder(final GadgetsPreferencesBean gadgetsPreferences) throws SFSDaoException { if (gadgetsPreferences == null) { throw new SFSDaoException("GadgetsPreferences cannot be null"); } boolean success = false; Collection<Integer> gadgetIds = gadgetsPreferences.getOrderedGadgetIds(); int orderId = 0; for (int gadgetId : gadgetIds) { try { this.getJdbcTemplateWriter().update(getSQL().getValue("gadget/preferences/refreshOrder"), new Object[] { orderId, gadgetId }); success = true; } catch (Exception e) { dataLogger.error( "Error refreshing order for gadget preference id " + gadgetId + ": " + e.getMessage()); } orderId++; } return success; } /** * Rebuild order. * * @param gadgetsPreferences the gadgets preferences * * @return the gadgets preferences bean * * @throws Exception the exception */ private GadgetsPreferencesBean rebuildOrder(final GadgetsPreferencesBean gadgetsPreferences) throws Exception { return this.rebuildOrder(gadgetsPreferences, new GadgetPreferencesBean()); } /** * Rebuilds the order of the gadget preferences. * * @param gadgetsPreferences the gadgets preferences * @param gadgetPreferences the gadget preferences * * @return the gadgets preferences bean * * @throws Exception the exception */ private GadgetsPreferencesBean rebuildOrder(final GadgetsPreferencesBean gadgetsPreferences, final GadgetPreferencesBean gadgetPreferences) throws Exception { // Build an array of gadget preferences sans the gadget preferences ArrayList<GadgetPreferencesBean> tempGadgets = new ArrayList<GadgetPreferencesBean>(); for (final int orderId : gadgetsPreferences.getGadgetPreferencesOrder().keySet()) { final int gadgetId = gadgetsPreferences.getGadgetPreferencesOrder().get(orderId); GadgetPreferencesBean tempGadget = gadgetsPreferences.getGadgetPreferenceId(gadgetId); // Cannot assume gadget still exists in map so check if null if (tempGadget != null) { // Check if this gadget is the one we are working with // If it is do not add it to the array if (tempGadget.getId() != gadgetPreferences.getId()) { tempGadgets.add(tempGadget); } } } // Refresh the gadget preferences order gadgetsPreferences.voidOrder(); // Cycle through the temp array and add a reference to the new gadget at // the right place. Variable Y holds the actual position value. int y = 0; for (int x = 0; x < tempGadgets.size(); x++) { GadgetPreferencesBean tempGadget = tempGadgets.get(x); if (gadgetPreferences.getId() > 0 && gadgetPreferences.getPosition() == x) { // Add the supplied gadget gadgetPreferences.setPosition(y); gadgetsPreferences.addGadgetPreference(gadgetPreferences); gadgetsPreferences.addGadgetPreferenceRef(gadgetPreferences.getId(), y); y++; } tempGadget.setPosition(y); gadgetsPreferences.addGadgetPreference(tempGadget); gadgetsPreferences.addGadgetPreferenceRef(tempGadget.getId(), y); y++; } if (gadgetPreferences.getId() > 0 && y == tempGadgets.size()) { // The submitted gadget has not yet been added to the gadget array gadgetPreferences.setPosition(y); gadgetsPreferences.addGadgetPreference(gadgetPreferences); gadgetsPreferences.addGadgetPreferenceRef(gadgetPreferences.getId(), y); } // Persist the GadgetsPreferencesBean order to the data-store try { final boolean success = this.persistOrder(gadgetsPreferences); if (success) { dataLogger.debug("The GadgetsPreferencesBean order was persisted"); } else { dataLogger.debug("The GadgetsPreferencesBean order could not be persisted"); } } catch (Exception e) { dataLogger.error("Error persisting GadgetsPreferencesBean order: " + e.getMessage()); } return gadgetsPreferences; } /** * Load gadget preferences. * * @param rs the rs * * @return the gadget preferences bean * * @throws SQLException the SQL exception */ private GadgetPreferencesBean loadGadgetPreferences(final ResultSet rs) throws SQLException { GadgetPreferencesBean gadgetPreferences = new GadgetPreferencesBean(); gadgetPreferences.setId(rs.getInt("Id")); gadgetPreferences.setUserDn(rs.getString("UserDn")); gadgetPreferences.setUrl(rs.getString("Url")); gadgetPreferences.setTitle(rs.getString("Title")); gadgetPreferences.setPosition(rs.getInt("Position")); gadgetPreferences.setHeight(rs.getInt("Height")); gadgetPreferences.setWidth(rs.getInt("Width")); try { GadgetBean gadget = gadgetDAO.load(gadgetPreferences.getUrl()); gadgetPreferences.setGadget(gadget); } catch (Exception e) { dataLogger.error("Error loading gadget for preferences: " + e.getMessage()); } // Parse user preferences into tree map String userPrefs = rs.getString("UserPrefs"); gadgetPreferences.setUserPrefs(readGadgetPreferences(userPrefs)); return gadgetPreferences; } /** * Converts the string stored in the data-store to a key/value TreeMap. * * @param userPrefs the user prefs * * @return the tree map< string, string> */ private TreeMap<String, String> readGadgetPreferences(final String userPrefs) { TreeMap<String, String> keyValues = new TreeMap<String, String>(); if (userPrefs != null) { StringTokenizer lineBreaks = new StringTokenizer(userPrefs, "\n"); while (lineBreaks.hasMoreTokens()) { String prefLine = lineBreaks.nextToken(); StringTokenizer keyValue = new StringTokenizer(prefLine, "="); while (keyValue.hasMoreTokens()) { String key = keyValue.nextToken(); String value = ""; if (keyValue.hasMoreTokens()) { value = keyValue.nextToken(); } keyValues.put(key, value); } } } return keyValues; } /** * Converts the key/value TreeMap into a string for persisting to the * data-store. * * @param keyValues the key values * * @return the string */ private String writeGadgetPreferences(final TreeMap<String, String> keyValues) { StringBuffer userPrefs = new StringBuffer(); if (keyValues != null) { for (String key : keyValues.keySet()) { String value = keyValues.get(key); // Add key and value to StringBuffer userPrefs.append(key); userPrefs.append("="); userPrefs.append(value); userPrefs.append("\n"); } } return userPrefs.toString(); } }