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.io.IOException; import java.sql.ResultSet; import java.sql.Timestamp; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import javax.annotation.Resource; import com.sfs.beans.ObjectTypeBean; import com.sfs.beans.PrivilegesBean; import com.sfs.beans.UserBean; import com.sfs.beans.GadgetBean; import com.sfs.beans.GadgetListBean; import org.apache.log4j.Logger; import org.jdom.JDOMException; import org.springframework.dao.DataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.RowMapper; /** * The Class GadgetDAOImpl. * * @author David Harrison 20th July 2007 - heavily modified 1 June 2008 */ public class GadgetDAOImpl extends BaseDAOImpl implements GadgetDAO { /** The data logger. */ private static Logger dataLogger = Logger.getLogger(GadgetDAOImpl.class); /** The object type dao. */ @Resource private ObjectTypeDAO objectTypeDAO = null; /** * Load a GadgetBean based on its url. * * @param url the url * * @return the gadget bean * * @throws SFSDaoException the SFS dao exception */ public final GadgetBean load(final String url) throws SFSDaoException { GadgetBean gadgetBean = null; if (url == null) { throw new SFSDaoException("Error: URL cannot be null"); } if (url.compareTo("") == 0) { throw new SFSDaoException("Error: URL cannot be an empty string"); } dataLogger.debug("Load gadget for: " + url); try { gadgetBean = (GadgetBean) this.getJdbcTemplateReader() .queryForObject(this.getSQL().getValue("gadget/load"), new Object[] { url }, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return loadGadget(rs); } }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } return gadgetBean; } /** * Save a GagetBean. * * @param gadget the gadget * @param checkUser the check user * @param privileges the privileges * * @return true, if successful * * @throws SFSDaoException the SFS dao exception */ public final boolean save(final GadgetBean gadget, final UserBean checkUser, final PrivilegesBean privileges) throws SFSDaoException { boolean success = false; if (gadget.getUrl() == null) { throw new SFSDaoException("Gadget URL cannot be null"); } if (gadget.getUrl().compareTo("") == 0) { throw new SFSDaoException("Gadget URL cannot be an empty string"); } if (gadget.getXml() == null) { throw new SFSDaoException("Gadget XML cannot be null"); } if (gadget.getXml().compareTo("") == 0) { throw new SFSDaoException("Gadget XML cannot be an empty string"); } if (gadget.getCategory() == null) { throw new SFSDaoException("Gadget category cannot be null"); } if (gadget.getCategory().compareTo("") == 0) { throw new SFSDaoException("Gadget category cannot be an empty string"); } if (!privileges.getPrivilege(checkUser, "gadgets", "modify")) { throw new SFSDaoException("Insufficient user credentials to save gadget"); } // Load the gadgettype id int gadgetTypeId = 0; try { ObjectTypeBean object = this.objectTypeDAO.load("Gadget Type", "", gadget.getCategory()); gadgetTypeId = object.getObjectTypeId(); } catch (Exception e) { dataLogger.error("Error loading objecttype for gadget: " + e.getMessage()); throw new SFSDaoException("Error loading objecttype for gadget: " + e.getMessage()); } Calendar calendar = Calendar.getInstance(); Timestamp currentTime = new Timestamp(calendar.getTimeInMillis()); final int updateCount = this.getJdbcTemplateWriter().update(this.getSQL().getValue("gadget/save"), new Object[] { // Insert options gadget.getUrl(), gadget.getTitle(), gadgetTypeId, gadget.getThumbnailUrl(), gadget.getScreenshotUrl(), gadget.getDescription(), gadget.getAuthor(), gadget.getXml(), currentTime, checkUser.getDN(), // Update options gadget.getTitle(), gadgetTypeId, gadget.getThumbnailUrl(), gadget.getScreenshotUrl(), gadget.getDescription(), gadget.getAuthor(), gadget.getXml(), currentTime, checkUser.getDN() }); if (updateCount > 0) { success = true; } return success; } /** * Delete a GadgetBean. * * @param gadget the gadget * @param checkUser the check user * @param privileges the privileges * * @return true, if successful * * @throws SFSDaoException the SFS dao exception */ public final boolean delete(final GadgetBean gadget, final UserBean checkUser, final PrivilegesBean privileges) throws SFSDaoException { boolean success = false; if (gadget.getUrl() == null) { throw new SFSDaoException("Gadget URL cannot be null"); } if (gadget.getUrl().compareTo("") == 0) { throw new SFSDaoException("Gadget URL cannot be an empty string"); } if (!privileges.getPrivilege(checkUser, "gadgets", "delete")) { throw new SFSDaoException("Insufficient user credentials to delete gadget"); } dataLogger.info(checkUser.getDN() + " attempting to delete gadget with URL of: " + gadget.getUrl()); final int deleteCount = this.getJdbcTemplateWriter().update(this.getSQL().getValue("gadget/delete"), new Object[] { gadget.getUrl() }); if (deleteCount > 0) { success = true; } return success; } /** * Search for a list of Gadgets based on the supplied GadgetListBean parameters. * * @param gadgetList the gadget list * * @return the gadget list bean * * @throws SFSDaoException the SFS dao exception */ @SuppressWarnings("unchecked") public final GadgetListBean search(final GadgetListBean gadgetList) throws SFSDaoException { GadgetListBean results = gadgetList.clone(); results.setCategories(this.getCategories()); String category = ""; if (gadgetList.getCategory().compareToIgnoreCase("All") != 0 && gadgetList.getCategory().compareToIgnoreCase("Latest") != 0) { category = gadgetList.getCategory(); } category += "%"; String searchSQL = getSQL().getValue("gadget/search"); if (gadgetList.getCategory().compareToIgnoreCase("Latest") == 0) { searchSQL += " ORDER BY gadgets.Created DESC LIMIT ?, ?"; } else { searchSQL += " ORDER BY gadgets.Title ASC LIMIT ?, ?"; } final String searchString = "%" + gadgetList.getSearchString() + "%"; try { final int totalResults = this.getJdbcTemplateReader().queryForInt(getSQL().getValue("gadget/count"), new Object[] { searchString, searchString, category }); results.setTotalResults(totalResults); } catch (DataAccessException de) { dataLogger.error("Error getting count: " + de.getMessage()); } try { Collection<GadgetBean> gadgets = this .getJdbcTemplateReader().query( searchSQL, new Object[] { searchString, searchString, category, gadgetList.getCurrentRecord(), gadgetList.getResultsPerPage() }, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return loadGadget(rs); } }); results.setResults(gadgets); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } return results; } /** * Gets the categories. * * @return the categories */ public final Collection<String> getCategories() { Collection<String> categories = new ArrayList<String>(); // Add the 'all' categories option categories.add("All"); if (this.objectTypeDAO != null) { try { Collection<ObjectTypeBean> categoryArray = this.objectTypeDAO.load("Gadget Type"); for (ObjectTypeBean categoryBean : categoryArray) { categories.add(categoryBean.getClassName()); } } catch (Exception e) { // Log exception dataLogger.error("Error loading gadget type categories: " + e.getMessage()); } } // Add an option for the latest gadgets categories.add("Latest"); return categories; } /** * Load gadget. * * @param rs the rs * * @return the gadget bean * * @throws SQLException the SQL exception */ private GadgetBean loadGadget(final ResultSet rs) throws SQLException { GadgetBean gadget = new GadgetBean(); gadget.setUrl(rs.getString("Url")); gadget.setTitle(rs.getString("Title")); gadget.setCategory(rs.getString("Category")); gadget.setAuthor(rs.getString("Author")); gadget.setThumbnailUrl(rs.getString("ThumbnailUrl")); gadget.setScreenshotUrl(rs.getString("ScreenshotUrl")); gadget.setDescription(rs.getString("Description")); gadget.setXml(rs.getString("Xml")); try { gadget.setCreated(rs.getDate("Created")); } catch (SQLException e) { gadget.setCreated(null); } gadget.setCreatedBy(rs.getString("CreatedBy")); // Load the data from the Xml file if (gadget.getXml().compareTo("") != 0) { try { gadget.readData(gadget.getXml(), gadget.getUrl(), gadget.getCategory()); } catch (JDOMException jde) { dataLogger.error("Error parsing gadget description XML: " + jde.getMessage()); } catch (IOException ioe) { dataLogger.error("Error reading gadget description XML file: " + ioe.getMessage()); } } return gadget; } }