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.whichdoctor.search.sql; import com.sfs.DataFilter; import com.sfs.Formatter; import com.sfs.beans.BuilderBean; import com.sfs.beans.UserBean; import com.sfs.whichdoctor.beans.CreditBean; import com.sfs.whichdoctor.beans.SearchBean; import com.sfs.whichdoctor.beans.TagBean; import com.sfs.whichdoctor.dao.CreditDAO; import com.sfs.whichdoctor.search.TagSearchDAO; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; /** * The Class CreditSqlHandler. * * @author David Harrison */ public class CreditSqlHandler extends SqlHandlerBase { /** The data logger. */ private static Logger dataLogger = Logger.getLogger(CreditSqlHandler.class); /** The Constant LIMIT. */ private static final int LIMIT = 50; /** The tag search dao. */ @Resource private TagSearchDAO tagSearchDAO; /** The credit dao. */ @Resource private CreditDAO creditDAO; /** * Instantiates a new credit sql handler. */ public CreditSqlHandler() { super(); this.setType("credit"); this.setIdentifierColumn("credit.GUID"); this.setDefaultOrder("CreditNo"); } /** * Initiate a SearchBean for the search type. * * @param user the user * * @return configured SearchBean */ public final SearchBean initiate(final UserBean user) { SearchBean search = new SearchBean(); CreditBean searchCriteria = new CreditBean(); CreditBean searchConstraints = new CreditBean(); searchCriteria.setCancelled(false); searchConstraints.setCancelled(true); searchCriteria.setGSTRate(-1); /** * If user is not an Administrator or in the Finances group then they * shouldn't be able to view secured credits. */ if (user != null && !user.isFinancialUser()) { searchCriteria.setSecurity("Standard"); } search.setRequestedPage(1); search.setLimit(LIMIT); search.setOrderColumn("credit.CreditNo"); search.setOrderColumn2(""); search.setOrderColumn3(""); search.setOrderAscending(true); search.setType("credit"); search.setSearchCriteria(searchCriteria); search.setSearchConstraints(searchConstraints); return search; } /** * Gets the group by. * * @return the group by */ public final String getGroupBy() { return ""; } /** * Gets the count sql. * * @return the count sql */ public final String getCountSql() { return "SELECT count(DISTINCT credit.GUID) " + this.getSQL().getValue("credit/search"); } /** * Gets the select sql. * * @return the select sql */ public final String getSelectSql() { return "SELECT DISTINCT credit.GUID " + getSQL().getValue("credit/search"); } /** * Load the identified objects and return results as a Collection of * Objects. * * @param uniqueIds the unique ids * @param loadDetails the load details * * @return a Collection of Objects */ public final Collection<Object> load(final Collection<Integer> uniqueIds, final BuilderBean loadDetails) { Collection<Object> results = new ArrayList<Object>(); if (uniqueIds != null) { for (Integer uniqueId : uniqueIds) { try { CreditBean credit = this.creditDAO.loadGUID(uniqueId, loadDetails); results.add(credit); } catch (Exception e) { dataLogger.error("Error loading credit (" + uniqueId + ") for search: " + e.getMessage()); } } } return results; } /** * Construct the SQL string, description and parameters. * * @param objCriteria Object containing search criteria values * @param objConstraints Object containing search constraint values * * @return Map containing a String[] { sql, description } => * Collection< Object > parameters * * @throws IllegalArgumentException the illegal argument exception */ public final Map<String[], Collection<Object>> construct(final Object objCriteria, final Object objConstraints) throws IllegalArgumentException { CreditBean searchCriteria = null; CreditBean searchConstraints = null; if (objCriteria instanceof CreditBean) { searchCriteria = (CreditBean) objCriteria; } if (objConstraints instanceof CreditBean) { searchConstraints = (CreditBean) objConstraints; } if (searchCriteria == null) { throw new IllegalArgumentException("The search criteria must " + "be a valid CreditBean"); } if (searchConstraints == null) { throw new IllegalArgumentException("The search constraints must " + "be a valid CreditBean"); } StringBuffer sqlWHERE = new StringBuffer(); StringBuffer description = new StringBuffer(); Collection<Object> parameters = new ArrayList<Object>(); if (searchCriteria.getTags() != null) { try { for (TagBean tag : searchCriteria.getTags()) { Map<String[], Collection<Object>> results = this.tagSearchDAO.construct(tag, new TagBean()); for (String[] index : results.keySet()) { String tagWHERE = index[0]; String tagDescription = index[1]; Collection<Object> tagParameters = results.get(index); if (tagWHERE.compareTo("") != 0) { /* A WHERE condition is defined */ sqlWHERE.append( " " + this.getSQL().getValue("credit/searchTags") + " WHERE " + tagWHERE + ")"); /* Add to the description and process the arrays */ description.append(tagDescription); if (tagParameters != null) { parameters.addAll(tagParameters); } } } } } catch (Exception e) { dataLogger.error("Error setting tag search options: " + e.getMessage()); } } if (searchCriteria.getBasicSearch() != null) { if (searchCriteria.getBasicSearch().compareTo("") != 0) { String searchString = searchCriteria.getBasicSearch().trim(); int basicSearch = 0; try { basicSearch = Integer.parseInt(searchString); } catch (NumberFormatException nfe) { dataLogger.debug("Error parsing basic search parameter: " + nfe.getMessage()); } if (basicSearch == 0) { // If the search string has : in the first ten // characters the financial abbreviation is probably // included - strip it out for search purposes if (searchString.indexOf(": ") > 3 && searchString.indexOf(": ") < 10) { searchString = searchString.substring(3, searchString.length()); } String field = "%" + searchString + "%"; sqlWHERE.append(" AND (concat(credit.CreditNo, ': '," + " credit.Description) LIKE ?)"); description.append(" and a credit description like '" + searchString + "'"); parameters.add(field); } else { sqlWHERE.append(" AND (credit.CreditNo LIKE ?)"); description.append(" and a credit number of '" + searchString + "'"); parameters.add("%" + searchString); } } } if (searchCriteria.getNumber() != null) { boolean blSearchConstraints = false; if (searchCriteria.getNumber().compareTo("") != 0) { if (searchConstraints.getNumber() != null) { if (searchConstraints.getNumber().compareTo("") != 0) { blSearchConstraints = true; } } if (blSearchConstraints) { if (searchConstraints.getNumber().compareTo("-") == 0) { // Less than Credit specified String field = searchCriteria.getNumber(); sqlWHERE.append(" AND credit.CreditNo <= ?"); description.append(" and a credit number less than '" + field + "'"); parameters.add(field); } else if (searchConstraints.getNumber().compareTo("+") == 0) { // Greater then Credit specified String field = searchCriteria.getNumber(); sqlWHERE.append(" AND credit.CreditNo >= ?"); description.append(" and a credit number greater than '" + field + "'"); parameters.add(field); } else { // Range between a and b - find whether greater than or // less than int intA = 0; int intB = 0; try { intA = Integer.parseInt(searchCriteria.getNumber()); } catch (NumberFormatException nfe) { dataLogger.debug("Error parsing CreditNo: " + nfe.getMessage()); } try { intB = Integer.parseInt(searchConstraints.getNumber()); } catch (NumberFormatException nfe) { dataLogger.debug("Error parsing CreditNo: " + nfe.getMessage()); } if (intA == intB) { // criteria A and B are the same sqlWHERE.append(" AND credit.CreditNo LIKE ?"); description.append(" and a credit number of '" + searchCriteria.getNumber() + "'"); parameters.add("%" + searchCriteria.getNumber()); } if (intA < intB) { // criteria A is less than B sqlWHERE.append(" AND credit.CreditNo BETWEEN ? AND ?"); description.append(" and a credit number between '" + searchCriteria.getNumber() + "' and '" + searchConstraints.getNumber() + "'"); parameters.add(searchCriteria.getNumber()); parameters.add(searchConstraints.getNumber()); } if (intA > intB) { // Criteria A is greater than B sqlWHERE.append(" AND credit.CreditNo BETWEEN ? AND ?"); description.append(" and a credit number between '" + searchConstraints.getNumber() + "' and '" + searchCriteria.getNumber() + "'"); parameters.add(searchConstraints.getNumber()); parameters.add(searchCriteria.getNumber()); } } } else { sqlWHERE.append(" AND credit.CreditNo LIKE ?"); description.append(" and a credit number of '" + searchCriteria.getNumber() + "'"); parameters.add("%" + searchCriteria.getNumber()); } } } if (searchCriteria.getGUIDList() != null) { final StringBuffer guidWHERE = new StringBuffer(); for (String guid : searchCriteria.getGUIDList()) { if (StringUtils.isNotBlank(guid)) { guidWHERE.append(" OR credit.GUID = ?"); parameters.add(guid); } } if (guidWHERE.length() > 0) { // Append the guidWHERE buffer to the sqlWHERE buffer sqlWHERE.append(" AND ("); // Append the guidWHERE but strip the first OR statement sqlWHERE.append(guidWHERE.toString().substring(4)); sqlWHERE.append(")"); description.append(" and has a GUID in the supplied list"); } } if (searchCriteria.getIdentifierList() != null) { final StringBuffer identifierWHERE = new StringBuffer(); for (String identifier : searchCriteria.getIdentifierList()) { if (StringUtils.isNotBlank(identifier)) { identifierWHERE.append(" OR credit.CreditNo LIKE ?"); parameters.add("%" + identifier); } } if (identifierWHERE.length() > 0) { // Append the identifierWHERE buffer to the sqlWHERE buffer sqlWHERE.append(" AND ("); // Append the identifierWHERE but strip the first OR statement sqlWHERE.append(identifierWHERE.toString().substring(4)); sqlWHERE.append(")"); description.append(" and has a credit number in the supplied list"); } } if (searchCriteria.getPersonId() > 0) { sqlWHERE.append(" AND credit.PersonId = ?"); description.append(" and a person GUID equal to '" + searchCriteria.getPersonId() + "'"); parameters.add(searchCriteria.getPersonId()); } if (searchCriteria.getOrganisationId() > 0) { sqlWHERE.append(" AND credit.OrganisationId = ?"); description.append(" and a organisation GUID equal to '" + searchCriteria.getOrganisationId() + "'"); parameters.add(searchCriteria.getOrganisationId()); } if (searchCriteria.getCancelled()) { if (searchConstraints.getCancelled()) { // Only cancelled sqlWHERE.append(" AND credit.Cancelled = true"); description.append(" and the credit is cancelled"); } } else { if (!searchConstraints.getCancelled()) { // Only active sqlWHERE.append(" AND credit.Cancelled = false"); description.append(" and the credit is not cancelled"); } } if (searchCriteria.getTypeName() != null) { if (searchCriteria.getTypeName().compareTo("") != 0) { sqlWHERE.append(" AND financialtype.Name LIKE ?"); description.append(" and a credit type like '" + searchCriteria.getTypeName() + "'"); parameters.add("%" + searchCriteria.getTypeName() + "%"); } } if (searchCriteria.getClassName() != null) { if (searchCriteria.getClassName().compareTo("") != 0) { sqlWHERE.append(" AND financialtype.Class LIKE ?"); description.append(" and a credit class like '" + searchCriteria.getClassName() + "'"); parameters.add("%" + searchCriteria.getClassName() + "%"); } } if (searchCriteria.getGSTRate() >= 0) { sqlWHERE.append(" AND credit.GSTRate = ?"); description.append(" and GST is " + Formatter.toPercent(searchCriteria.getGSTRate() / 100, 1, "%") + " in the credit"); parameters.add(searchCriteria.getGSTRate()); } if (StringUtils.isNotBlank(searchCriteria.getDescription())) { if (searchCriteria.getDescription().indexOf("\"") > -1) { // Description contains "" so treat as a specific search sqlWHERE.append(" AND credit.Description LIKE ?"); description.append(" and has a credit description like '" + searchCriteria.getDescription() + "'"); parameters.add(StringUtils.replace(searchCriteria.getDescription(), "\"", "")); } else { sqlWHERE.append(" AND credit.Description LIKE ?"); description.append(" and has a credit description like '" + searchCriteria.getDescription() + "'"); parameters.add("%" + searchCriteria.getDescription() + "%"); } } if (searchCriteria.getSecurity() != null) { if (searchCriteria.getSecurity().compareTo("") != 0) { sqlWHERE.append(" AND financialtype.Security = ?"); description.append(" and has a security setting of '" + searchCriteria.getSecurity() + "'"); parameters.add(searchCriteria.getSecurity()); } } if (searchCriteria.getIssued() != null) { if (searchConstraints.getIssued() != null) { int larger = searchCriteria.getIssued().compareTo(searchConstraints.getIssued()); if (larger > 0) { // SearchCriteria date after SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getIssued()); String fieldB = this.getDf().format(searchConstraints.getIssued()); sqlWHERE.append(" AND credit.Issued BETWEEN ? AND ?"); description.append(" and was issued between '" + fieldB + "' and '" + fieldA + "'"); parameters.add(fieldB); parameters.add(fieldA); } if (larger < 0) { // SearchCriteria date before SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getIssued()); String fieldB = this.getDf().format(searchConstraints.getIssued()); sqlWHERE.append(" AND credit.Issued BETWEEN ? AND ?"); description.append(" and was issued between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } if (larger == 0) { // SearchCritier and SearchConstraint are equal String field = this.getDf().format(searchCriteria.getIssued()); sqlWHERE.append(" AND credit.Issued = ?"); description.append(" and was issued on '" + field + "'"); parameters.add(field); } } else { String field = this.getDf().format(searchCriteria.getIssued()); sqlWHERE.append(" AND credit.Issued = ?"); description.append(" and was issued on '" + field + "'"); parameters.add(field); } } if (searchCriteria.getDebit() != null && searchCriteria.getDebit().getGUID() > 0) { sqlWHERE.append(" AND credit.InvoiceId = ?"); description.append(" and a debit GUID of '" + searchCriteria.getDebit().getGUID() + "'"); parameters.add(searchCriteria.getDebit().getGUID()); } if (searchCriteria.getCreatedDate() != null) { if (searchConstraints.getCreatedDate() != null) { int larger = searchCriteria.getCreatedDate().compareTo(searchConstraints.getCreatedDate()); if (larger > 0) { // SearchCriteria date after SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getCreatedDate()); String fieldB = this.getDf().format(searchConstraints.getCreatedDate()); sqlWHERE.append(" AND guid.CreatedDate BETWEEN ? AND ?"); description.append(" and was created between '" + fieldB + "' and '" + fieldA + "'"); parameters.add(fieldB); parameters.add(fieldA); } if (larger < 0) { // SearchCriteria date before SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getCreatedDate()); String fieldB = this.getDf().format(searchConstraints.getCreatedDate()); sqlWHERE.append(" AND guid.CreatedDate BETWEEN ? AND ?"); description.append(" and was created between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } if (larger == 0) { // SearchCritier and SearchConstraint are equal String field = this.getDf().format(searchCriteria.getCreatedDate()); sqlWHERE.append(" AND guid.CreatedDate = ?"); description.append(" and was created on '" + field + "'"); parameters.add(field); } } else { String field = this.getDf().format(searchCriteria.getCreatedDate()); sqlWHERE.append(" AND guid.CreatedDate = ?"); description.append(" and was created on '" + field + "'"); parameters.add(field); } } if (searchCriteria.getModifiedDate() != null) { if (searchConstraints.getModifiedDate() != null) { int larger = searchCriteria.getModifiedDate().compareTo(searchConstraints.getModifiedDate()); if (larger > 0) { // SearchCriteria date after SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getModifiedDate()); String fieldB = this.getDf().format(searchConstraints.getModifiedDate()); sqlWHERE.append(" AND guid.ModifiedDate BETWEEN ? AND ?"); description.append(" and was modified between '" + fieldB + "' and '" + fieldA + "'"); parameters.add(fieldB); parameters.add(fieldA); } if (larger < 0) { // SearchCriteria date before SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getModifiedDate()); String fieldB = this.getDf().format(searchConstraints.getModifiedDate()); sqlWHERE.append(" AND guid.ModifiedDate BETWEEN ? AND ?"); description.append(" and was modified between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } if (larger == 0) { // SearchCritier and SearchConstraint are equal String field = this.getDf().format(searchCriteria.getModifiedDate()); sqlWHERE.append(" AND guid.ModifiedDate = ?"); description.append(" and was modified on '" + field + "'"); parameters.add(field); } } else { String field = this.getDf().format(searchCriteria.getModifiedDate()); sqlWHERE.append(" AND guid.ModifiedDate = ?"); description.append(" and was modified on '" + field + "'"); parameters.add(field); } } if (searchCriteria.getIncludeGUIDList() != null) { final StringBuffer guidWHERE = new StringBuffer(); for (String guid : searchCriteria.getIncludeGUIDList()) { if (StringUtils.isNotBlank(guid)) { guidWHERE.append(" OR credit.GUID = ?"); parameters.add(guid); } } if (guidWHERE.length() > 0) { // Append the guidWHERE buffer to the sqlWHERE buffer sqlWHERE.append(" OR ("); // Append the guidWHERE but strip the first OR statement sqlWHERE.append(guidWHERE.toString().substring(4)); sqlWHERE.append(")"); description.append(" and has a GUID in the supplied list"); } } String[] index = new String[] { sqlWHERE.toString(), DataFilter.getHtml(description.toString()) }; Map<String[], Collection<Object>> results = new HashMap<String[], Collection<Object>>(); results.put(index, parameters); return results; } }