Пример #1
0
/**
 * This Class is used to Add/Edit data in the database.
 *
 * @author gautam_shetty
 */
public class CommonAddEditAction extends SecureAction {

  /** LOGGER Logger - Generic LOGGER. */
  private static final Logger LOGGER = Logger.getCommonLogger(CommonAddEditAction.class);

  /**
   * Overrides the execute method of Action class. Adds / Updates the data in the database.
   *
   * @param mapping ActionMapping
   * @param form ActionForm
   * @param request HttpServletRequest
   * @param response HttpServletResponse
   * @return ActionForward
   * @throws Exception Exception
   */
  public ActionForward executeSecureAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    LOGGER.info("in execute method");
    BaseAddEditAction addEditAction;
    AbstractActionForm abstractForm = (AbstractActionForm) form;
    ActionForward actionfwd;
    try {
      if (!isTokenValid(request)) {
        actionfwd = mapping.findForward(Constants.FAILURE);
        ActionErrors actionErrors = new ActionErrors();
        ActionError actionError =
            new ActionError("errors.item", "Invalid request for add/edit operation");
        actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError);
        saveErrors(request, actionErrors);
      } else {
        resetToken(request);
        if (abstractForm.isAddOperation()) {
          addEditAction = new CommonAddAction();
        } else {
          addEditAction = new CommonEdtAction();
        }
        actionfwd = addEditAction.executeXSS(mapping, abstractForm, request, response);
      }
    } catch (ApplicationException applicationException) {
      LOGGER.error("Common Add/Edit failed.." + applicationException.getCustomizedMsg());

      ActionErrors actionErrors = new ActionErrors();
      ActionError actionError =
          new ActionError("errors.item", applicationException.getCustomizedMsg());
      actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError);
      saveErrors(request, actionErrors);

      actionfwd = mapping.findForward(Constants.FAILURE);
    }
    return actionfwd;
  }
}
Пример #2
0
  /**
   * Overrides the execute method of Action class. Adds / Updates the data in the database.
   *
   * @param mapping ActionMapping
   * @param form ActionForm
   * @param request HttpServletRequest
   * @param response HttpServletResponse
   * @return ActionForward
   * @throws Exception Exception
   */
  public ActionForward executeSecureAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    LOGGER.info("in execute method");
    BaseAddEditAction addEditAction;
    AbstractActionForm abstractForm = (AbstractActionForm) form;
    ActionForward actionfwd;
    try {
      if (!isTokenValid(request)) {
        actionfwd = mapping.findForward(Constants.FAILURE);
        ActionErrors actionErrors = new ActionErrors();
        ActionError actionError =
            new ActionError("errors.item", "Invalid request for add/edit operation");
        actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError);
        saveErrors(request, actionErrors);
      } else {
        resetToken(request);
        if (abstractForm.isAddOperation()) {
          addEditAction = new CommonAddAction();
        } else {
          addEditAction = new CommonEdtAction();
        }
        actionfwd = addEditAction.executeXSS(mapping, abstractForm, request, response);
      }
    } catch (ApplicationException applicationException) {
      LOGGER.error("Common Add/Edit failed.." + applicationException.getCustomizedMsg());

      ActionErrors actionErrors = new ActionErrors();
      ActionError actionError =
          new ActionError("errors.item", applicationException.getCustomizedMsg());
      actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError);
      saveErrors(request, actionErrors);

      actionfwd = mapping.findForward(Constants.FAILURE);
    }
    return actionfwd;
  }
  /**
   * Populates all the fields from the domain object to the form bean.
   *
   * @param abstractDomain An AbstractDomain Object
   */
  @Override
  public void setAllValues(AbstractDomainObject abstractDomain) {
    super.setAllValues(abstractDomain);
    final TissueSpecimenReviewEventParameters tissueSpecimenReviewParametersObject =
        (TissueSpecimenReviewEventParameters) abstractDomain;

    this.neoplasticCellularityPercentage =
        CommonUtilities.toString(
            tissueSpecimenReviewParametersObject.getNeoplasticCellularityPercentage());
    this.necrosisPercentage =
        CommonUtilities.toString(tissueSpecimenReviewParametersObject.getNecrosisPercentage());
    this.lymphocyticPercentage =
        CommonUtilities.toString(tissueSpecimenReviewParametersObject.getLymphocyticPercentage());
    this.totalCellularityPercentage =
        CommonUtilities.toString(
            tissueSpecimenReviewParametersObject.getTotalCellularityPercentage());
    this.histologicalQuality =
        CommonUtilities.toString(tissueSpecimenReviewParametersObject.getHistologicalQuality());
    logger.debug("this.neoplasticCellularityPercentage : " + this.neoplasticCellularityPercentage);
    logger.debug("this.necrosisPercentage : " + this.necrosisPercentage);
    logger.debug("this.lymphocyticPercentage : " + this.lymphocyticPercentage);
    logger.debug("this.totalCellularityPercentage : " + this.totalCellularityPercentage);
  }
Пример #4
0
/** @author hrishikesh_rajpathak */
public class PopularCategoryCache {

  private static PopularCategoryCache popularCategoryCache = null;

  private static Collection<CategoryPopularity> popularCategories;

  private static final Logger logger =
      edu.wustl.common.util.logger.Logger.getLogger(CommonUtils.class);

  /**
   * Method to get singleton instance of PopularCategoryCache
   *
   * @return singleton object of PopularCategoryCache
   */
  public static synchronized PopularCategoryCache getInstance() {
    if (popularCategoryCache == null) {
      popularCategoryCache = new PopularCategoryCache();
    }
    return popularCategoryCache;
  }

  /** Private constructor for singleton class */
  private PopularCategoryCache() {
    cachePopularCategories();
  }

  /**
   * Gets all the popular categories from database and sets it as the value of
   * "popularCategoriesCollection"
   */
  private void cachePopularCategories() {
    CategoryBusinessInterface categoryOperations =
        (CategoryBusinessInterface)
            CommonUtils.getBusinessInterface(
                EjbNamesConstants.CATEGORY_BEAN, CategoryHomeInterface.class);
    try {
      popularCategories = categoryOperations.getPopularCategories();
    } catch (RemoteException e) {
      logger.error(e.getStackTrace());
      CommonUtils.handleException(e, NewWelcomePanel.getMainFrame(), true, true, true, true);
    }
  }

  /** @return Returns the popularCategoriesCollection. */
  public Collection<CategoryPopularity> getPopularCategories() {
    return popularCategories;
  }
}
Пример #5
0
/**
 * This class has functions to read PrintServiceImplementor Properties file.
 *
 * @author falguni sachde
 */
public final class PropertyHandler {

  /** Generic logger. */
  private static final Logger logger = Logger.getCommonLogger(PropertyHandler.class);
  /** printimplClass Properties. */
  private static Properties printimplClassProperties = null;

  /** private constructor. */
  private PropertyHandler() {}

  /**
   * @param path path.
   * @throws Exception Exception
   */
  public static void init(String path) throws Exception {
    try {
      final String absolutePath =
          CommonServiceLocator.getInstance().getPropDirPath() + File.separator + path;
      final InputStream inpurStream = new FileInputStream(new File(absolutePath));
      printimplClassProperties = new Properties();
      printimplClassProperties.load(inpurStream);

      /*printimplClassProperties = new Properties();
      printimplClassProperties.
      load(PropertyHandler.class.getClassLoader().getResourceAsStream(path));*/

    } catch (final Exception e) {
      PropertyHandler.logger.error(e.getMessage(), e);
    }
  }

  /**
   * Description:This method takes the property name as String argument and returns the properties
   * value as String.
   *
   * @param propertyName name of property Key
   * @return String property value
   * @throws Exception Exception
   */
  public static String getValue(String propertyName) throws Exception {

    if (printimplClassProperties == null) {
      init("PrintServiceImplementor.properties");
    }
    return (String) printimplClassProperties.get(propertyName);
  }
}
Пример #6
0
/**
 * Common class which is a thread to stop caties servers depending on there port.
 *
 * @author vijay_pande
 */
public class StopServer extends Thread {
  /** logger. */
  private final transient Logger logger = Logger.getCommonLogger(StopServer.class);
  /** port. */
  private final String port;

  /**
   * Constructor for the class.
   *
   * @param port key to fetch port number from catissueCore-properties.xml file
   */
  public StopServer(String port) {
    super();
    this.port = port;
  }

  /**
   * Default method for the thread, which listen to socket and stop current thread when recieve any
   * responce.
   */
  @Override
  public void run() {
    try {
      // get port number for server from catissueCore-properties.xml file
      final int port = Integer.parseInt(CaTIESProperties.getValue(this.port));
      final ServerSocket serv = new ServerSocket(port);
      BufferedReader bufferedReader;
      final Socket sock = serv.accept();
      bufferedReader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      new PrintWriter(new OutputStreamWriter(sock.getOutputStream()), true);
      bufferedReader.readLine();

      this.logger.info("Stopping server");
      bufferedReader.close();
      sock.close();
      // close server socket
      serv.close();
      // stop server
      System.exit(0);
    } catch (final Exception e) {
      this.logger.error("Error stopping server " + e.getMessage(), e);
      e.printStackTrace();
    }
  }
}
/** @author mandar_deshmukh This Class handles the Tissue Specimen Review event parameters. */
public class TissueSpecimenReviewEventParametersForm extends SpecimenEventParametersForm {

  private static final long serialVersionUID = 1L;

  /** logger Logger - Generic logger. */
  private static Logger logger =
      Logger.getCommonLogger(TissueSpecimenReviewEventParametersForm.class);
  /** Percentage of histologically evident neoplastic cells present in the tissue specimen. */
  protected String neoplasticCellularityPercentage;

  /** Percentage of specimen that is histologically necrotic. */
  protected String necrosisPercentage;

  /** Percentage of histologically evident lymphocytes in the tissue specimen. */
  protected String lymphocyticPercentage;

  /**
   * Percentage of total cellularity of the specimen. Note that TOTCELL-NEOCELL-LYMPHCELL= %
   * cellularity of other stromal, etc. cell types. Also Note that 100-TOTCELL-NECROSIS= % of tissue
   * containing a cellular material.
   */
  protected String totalCellularityPercentage;

  /**
   * Name : Virender Mehta Reviewer: Sachin Lale Bug ID: defaultValueConfiguration_BugID Patch
   * ID:defaultValueConfiguration_BugID_16 Description: Configuration for default value for
   * Histological Quality
   */
  /** Histological Quality of the specimen. */
  protected String histologicalQuality =
      (String) DefaultValueManager.getDefaultValue(Constants.DEFAULT_HISTOLOGICAL_QUALITY);

  /**
   * Returns the percentage of histologically evident neoplastic cells present in the tissue
   * specimen.
   *
   * @return The percentage of histologically evident neoplastic cells present in the tissue
   *     specimen.
   * @see #setNeoplasticCellularityPercentage(double)
   */
  public String getNeoplasticCellularityPercentage() {
    return this.neoplasticCellularityPercentage;
  }

  /**
   * Sets the percentage of histologically evident neoplastic cells present in the specimen.
   *
   * @param neoplasticCellularityPercentage the percentage of histologically evident neoplastic
   *     cells present in the specimen.
   * @see #getNeoplasticCellularityPercentage()
   */
  public void setNeoplasticCellularityPercentage(String neoplasticCellularityPercentage) {
    this.neoplasticCellularityPercentage = neoplasticCellularityPercentage;
  }

  /**
   * Returns the percentage of specimen that is histologically necrotic.
   *
   * @return The percentage of specimen that is histologically necrotic.
   * @see #setNecrosisPercentage(double)
   */
  public String getNecrosisPercentage() {
    return this.necrosisPercentage;
  }

  /**
   * Sets the percentage of specimen that is histologically necrotic.
   *
   * @param necrosisPercentage the percentage of specimen that is histologically necrotic.
   * @see #getNecrosisPercentage()
   */
  public void setNecrosisPercentage(String necrosisPercentage) {
    this.necrosisPercentage = necrosisPercentage;
  }

  /**
   * Returns the percentage of histologically evident lymphocytes in the tissue specimen.
   *
   * @return The percentage of histologically evident lymphocytes in the tissue specimen.
   * @see #setLymphocyticPercentage(double)
   */
  public String getLymphocyticPercentage() {
    return this.lymphocyticPercentage;
  }

  /**
   * Sets the percentage of histologically evident lymphocytes in the tissue specimen.
   *
   * @param lymphocyticPercentage the percentage of histologically evident lymphocytes in the tissue
   *     specimen.
   * @see #getLymphocyticPercentage()
   */
  public void setLymphocyticPercentage(String lymphocyticPercentage) {
    this.lymphocyticPercentage = lymphocyticPercentage;
  }

  /**
   * Returns the total cellularity percentage.
   *
   * @return The total cellularity percentage.
   * @see #setTotalCellularityPercentage(double)
   */
  public String getTotalCellularityPercentage() {
    return this.totalCellularityPercentage;
  }

  /**
   * Sets the total cellularity percentage.
   *
   * @param totalCellularityPercentage the total cellularity percentage.
   * @see #getTotalCellularityPercentage()
   */
  public void setTotalCellularityPercentage(String totalCellularityPercentage) {
    this.totalCellularityPercentage = totalCellularityPercentage;
  }

  /**
   * Returns Histological Quality of the specimen.
   *
   * @return Histological Quality of the specimen.
   * @see #setHistologicalQuality(String)
   */
  public String getHistologicalQuality() {
    return this.histologicalQuality;
  }

  /**
   * Sets Histological Quality of the specimen.
   *
   * @param histologicalQuality Histological Quality of the specimen.
   * @see #getHistologicalQuality()
   */
  public void setHistologicalQuality(String histologicalQuality) {
    this.histologicalQuality = histologicalQuality;
  }

  //	 ----- SUPERCLASS METHODS
  /** @return TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID */
  @Override
  public int getFormId() {
    return Constants.TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID;
  }

  /**
   * Populates all the fields from the domain object to the form bean.
   *
   * @param abstractDomain An AbstractDomain Object
   */
  @Override
  public void setAllValues(AbstractDomainObject abstractDomain) {
    super.setAllValues(abstractDomain);
    final TissueSpecimenReviewEventParameters tissueSpecimenReviewParametersObject =
        (TissueSpecimenReviewEventParameters) abstractDomain;

    this.neoplasticCellularityPercentage =
        CommonUtilities.toString(
            tissueSpecimenReviewParametersObject.getNeoplasticCellularityPercentage());
    this.necrosisPercentage =
        CommonUtilities.toString(tissueSpecimenReviewParametersObject.getNecrosisPercentage());
    this.lymphocyticPercentage =
        CommonUtilities.toString(tissueSpecimenReviewParametersObject.getLymphocyticPercentage());
    this.totalCellularityPercentage =
        CommonUtilities.toString(
            tissueSpecimenReviewParametersObject.getTotalCellularityPercentage());
    this.histologicalQuality =
        CommonUtilities.toString(tissueSpecimenReviewParametersObject.getHistologicalQuality());
    logger.debug("this.neoplasticCellularityPercentage : " + this.neoplasticCellularityPercentage);
    logger.debug("this.necrosisPercentage : " + this.necrosisPercentage);
    logger.debug("this.lymphocyticPercentage : " + this.lymphocyticPercentage);
    logger.debug("this.totalCellularityPercentage : " + this.totalCellularityPercentage);
  }

  /**
   * Overrides the validate method of ActionForm.
   *
   * @return error ActionErrors instance
   * @param mapping Actionmapping instance
   * @param request HttpServletRequest instance
   */
  @Override
  public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    final ActionErrors errors = super.validate(mapping, request);
    final Validator validator = new Validator();

    try {

      //         	// checks the neoplasticCellularityPercentage
      if (!Validator.isEmpty(this.neoplasticCellularityPercentage)
          && !validator.isDouble(this.neoplasticCellularityPercentage, false)) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.format",
                ApplicationProperties.getValue(
                    "tissuespecimenrevieweventparameters.neoplasticcellularitypercentage")));
      }
      //

      //         	// checks the necrosisPercentage
      if (!Validator.isEmpty(this.necrosisPercentage)
          && !validator.isDouble(this.necrosisPercentage, false)) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.format",
                ApplicationProperties.getValue(
                    "tissuespecimenrevieweventparameters.necrosispercentage")));
      }
      //

      //         	// checks the lymphocyticPercentage
      if (!Validator.isEmpty(this.lymphocyticPercentage)
          && !validator.isDouble(this.lymphocyticPercentage, false)) {

        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.format",
                ApplicationProperties.getValue(
                    "tissuespecimenrevieweventparameters.lymphocyticpercentage")));
      }
      //

      //         	// checks the totalCellularityPercentage
      if (!Validator.isEmpty(this.totalCellularityPercentage)
          && !validator.isDouble(this.totalCellularityPercentage, false)) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.format",
                ApplicationProperties.getValue(
                    "tissuespecimenrevieweventparameters.totalcellularitypercentage")));
      }
      //

      //         	// checks the histologicalQuality
      //           	if (!validator.isValidOption(histologicalQuality) )
      //            {
      //           		errors.add(ActionErrors.GLOBAL_ERROR, new
      // ActionError("errors.item.required",ApplicationProperties.getValue("tissuespecimenrevieweventparameters.histologicalquality")));
      //            }
      //
    } catch (final Exception excp) {
      TissueSpecimenReviewEventParametersForm.logger.error(excp.getMessage(), excp);
      excp.printStackTrace();
    }
    return errors;
  }

  /** Resets the values of all the fields. */
  @Override
  protected void reset() {
    //	 	super.reset();
    //        this.necrosisPercentage = null;
    //        this.neoplasticCellularityPercentage = null;
    //        this.lymphocyticPercentage = null;
    //        this.totalCellularityPercentage = null;
    //        this.histologicalQuality = null;

  }

  @Override
  public void setAddNewObjectIdentifier(String arg0, Long arg1) {
    // TODO Auto-generated method stub

  }
}
Пример #8
0
/**
 * This bean handles user based operations
 *
 * @author hrishikesh_rajpathak
 */
public class UserBean extends AbstractStatelessSessionBean implements UserBusinessInterface {
  private static final long serialVersionUID = -9088505042791608055L;

  Logger logger = edu.wustl.common.util.logger.Logger.getLogger(UserBean.class);

  /**
   * Insert given user as a new user in database
   *
   * @param dref
   * @param idP
   * @return User that has been inserted
   * @throws RemoteException
   */
  public UserInterface insertUser(String serializedDCR) throws RemoteException {
    String usersGridId = AuthenticationUtility.getUsersGridId(serializedDCR);
    User user = new User(usersGridId, null, false);

    return new UserOperations().insertUser(user);
  }

  /**
   * Update present user in database
   *
   * @param user
   * @throws RemoteException
   */
  public void updateUser(UserInterface user) throws RemoteException {
    new UserOperations().updateUser(user);
  }

  /**
   * Get a map of entity group name vs related list of service urls for the given user
   *
   * @param user
   * @return Service Urls for a user
   * @throws DynamicExtensionsSystemException
   * @throws DynamicExtensionsApplicationException
   * @throws RemoteException
   */
  public Map<String, List<String>> getServiceUrlsForUser(UserInterface user)
      throws DynamicExtensionsSystemException, DynamicExtensionsApplicationException,
          RemoteException {
    return new UserOperations().getServiceURLsForUser(user);
  }

  /* (non-Javadoc)
   * @see edu.wustl.cab2b.common.ejb.user.UserBusinessInterface#getUserByName(java.lang.String)
   * If user not found, it returns null
   */
  /**
   * Get user by user name. If user of that name not found in database, it returns null.
   *
   * @param dref
   * @param idP
   * @return
   * @throws RemoteException
   */
  public UserInterface getUserByName(String serializedDCR) throws RemoteException {
    String usersGridId = AuthenticationUtility.getUsersGridId(serializedDCR);
    return new UserOperations().getUserByName(usersGridId);
  }

  /**
   * Returns globus credential
   *
   * @param dref
   * @param idP
   * @return
   * @throws RemoteException
   */
  public GlobusCredential getGlobusCredential(String serializedDCR) throws RemoteException {
    return AuthenticationUtility.getGlobusCredential(serializedDCR);
  }

  /** @return Anonymous User */
  public UserInterface getAnonymousUser() throws RemoteException {
    return new UserOperations().getUserByName("Anonymous");
  }
}
Пример #9
0
/** @author sagar_baldwa */
public class ComboDataBizLogic extends CatissueDefaultBizLogic {

  private final transient Logger logger = Logger.getCommonLogger(ComboDataBizLogic.class);

  /**
   * This method would return the Clinical Diagnosis List
   *
   * @return List which contains the Clinical Diagnosis Data
   * @throws BizLogicException
   * @throws BizLogicException
   */
  public List getClinicalDiagnosisList(String query, boolean showSubset) throws BizLogicException {
    // populating clinical Diagnosis field
    final List<NameValueBean> clinicalDiagnosisList = new ArrayList();
    final String sourceObjectName = PermissibleValueImpl.class.getName();
    final String[] selectColumnName = {"value"};
    DAO dao = null;
    try {

      new DefaultBizLogic();

      dao = this.openDAOSession(null);

      String hql =
          "Select PermissibleValueImpl.value from edu.wustl.common.cde.PermissibleValueImpl "
              + "PermissibleValueImpl WHERE LOWER(PermissibleValueImpl.value) like LOWER('%"
              + query
              + "%') AND PermissibleValueImpl.cde.publicId = 'Clinical_Diagnosis_PID' "
              + "order by PermissibleValueImpl.value desc";

      List dataList = dao.executeQuery(hql);

      clinicalDiagnosisList.add(
          new NameValueBean(Constants.SELECT_OPTION, "" + Constants.SELECT_OPTION_VALUE));
      if (showSubset) {
        clinicalDiagnosisList.add(
            new NameValueBean(Constants.SHOW_SUBSET + "start", Constants.SHOW_SUBSET));
      }
      int cnt = 1;
      final Iterator<String> iterator = dataList.iterator();
      while (iterator.hasNext()) {
        final String clinicaDiagnosisvalue = iterator.next();
        if (clinicaDiagnosisvalue.toString().toLowerCase().startsWith(query.toLowerCase())) {
          clinicalDiagnosisList.add(
              1, new NameValueBean(clinicaDiagnosisvalue, clinicaDiagnosisvalue));
          cnt++;
        } else {
          clinicalDiagnosisList.add(
              cnt, new NameValueBean(clinicaDiagnosisvalue, clinicaDiagnosisvalue));
        }
      }

      if (showSubset) {
        clinicalDiagnosisList.add(
            new NameValueBean(Constants.SHOW_SUBSET + "end", Constants.SHOW_SUBSET));
      }

      this.closeDAOSession(dao);

    } catch (final DAOException exp) {
      this.logger.error(exp.getMessage(), exp);
      exp.printStackTrace();
      throw this.getBizLogicException(exp, exp.getErrorKeyName(), exp.getMsgValues());
    } finally {
      this.closeDAOSession(dao);
    }
    return clinicalDiagnosisList;
  }

  /**
   * This method fetches the required number of records from Clinical Diagnosis List and poplulates
   * in the Combo Box on UI.
   *
   * @param limitFetch is the limit to fetch and display the Clinical Diagnosis records in Combo Box
   *     on UI
   * @param startFetch is the position from where you fetch the Clinical Diagnosis data from the
   *     List
   * @param query holds the string which the user has typed down in combo box for autocomplete
   *     feature
   * @return JSONObject which holds the list to eb poplulated on UI front
   */
  public JSONObject getClinicalDiagnosisData(
      Integer limitFetch,
      Integer startFetch,
      String query,
      Collection<NameValueBean> clinicalDiagnosisBean,
      String showOption) {
    JSONObject jsonObject = null;
    JSONArray jsonArray = null;
    try {
      jsonArray = new JSONArray();
      jsonObject = new JSONObject();
      final List<NameValueBean> clinicalDiagnosisList;
      boolean showSubset = false;

      if (!clinicalDiagnosisBean.isEmpty() && Constants.SHOW_ALL_VALUES.equals(showOption)) {
        showSubset = true;
      }

      if (clinicalDiagnosisBean == null
          || clinicalDiagnosisBean.isEmpty()
          || Constants.SHOW_ALL_VALUES.equals(showOption)) {
        clinicalDiagnosisList = this.getClinicalDiagnosisList(query, showSubset);
      } else {
        clinicalDiagnosisList = (List<NameValueBean>) clinicalDiagnosisBean;
      }
      jsonObject.put("totalCount", new Integer(clinicalDiagnosisList.size()));
      final ListIterator<NameValueBean> iterator =
          clinicalDiagnosisList.listIterator(startFetch + 1);
      final Integer total = limitFetch + startFetch;
      // 1st record in List has value -1, so startFetch is incremented and
      // made to fetch data from 2nd element from the List
      startFetch++;
      boolean flag = false;
      while (startFetch < total + 1) {
        if (iterator.hasNext()) {
          final NameValueBean nameValueBean = iterator.next();
          if (nameValueBean.getName().toLowerCase().contains(query.toLowerCase())
              || query == null) {
            final JSONObject innerJsonObject = new JSONObject();
            // nameValueBean = (NameValueBean) iterator.next();
            innerJsonObject.put("id", nameValueBean.getName());
            innerJsonObject.put("field", nameValueBean.getValue());
            jsonArray.put(innerJsonObject);
            flag = true;
          } else if (flag) {
            break;
          }
        }
        startFetch++;
      }
      jsonObject.put("row", jsonArray);
    } catch (final Exception e) {
      this.logger.error(e.getMessage(), e);
      e.printStackTrace();
      // System.out.println(e);
    }
    return jsonObject;
  }
}
/** The Class CreateSpecimenTemplateForm. */
public class CreateSpecimenTemplateForm extends AbstractActionForm {

  /** serial version id. */
  private static final long serialVersionUID = 1L;

  /** logger Logger - Generic logger. */
  private static Logger logger = Logger.getCommonLogger(CreateSpecimenTemplateForm.class);

  /** Display Name. */
  protected String displayName;

  /** Type of specimen. e.g. Tissue, Molecular, Cell, Fluid */
  protected String className;

  /** Sub Type of specimen. e.g. Serum, Plasma, Blood, Fresh Tissue etc. */
  protected String type;

  /** Anatomic site from which the specimen was derived. */
  private String tissueSite;

  /** For bilateral sites, left or right. */
  private String tissueSide;

  /**
   * Histopathological character of the specimen e.g. Non-Malignant, Malignant, Non-Malignant
   * Diseased, Pre-Malignant.
   */
  private String pathologicalStatus;

  /** The storage location for specimen. */
  private String storageLocationForSpecimen;

  /** The storage location for aliquot specimen. */
  private String storageLocationForAliquotSpecimen;

  /** Concentration of specimen. */
  protected String concentration = "0";

  /** Amount of Specimen. */
  protected String quantity;

  /**
   * A historical information about the specimen i.e. whether the specimen is a new specimen or a
   * derived specimen or an aliquot.
   */
  private String lineage;

  /** Unit of specimen. */
  protected String unit;

  /** A number that tells how many aliquots to be created. */
  private String noOfAliquots;

  /** Initial quantity per aliquot. */
  private String quantityPerAliquot;

  /** Collection of aliquot specimens derived from this specimen. */
  protected Collection aliquotSpecimenCollection;

  /** Collection of derive specimens derived from this specimen. */
  protected Collection deriveSpecimenCollection;

  /** The collection event id. */
  private long collectionEventId; // Mandar : CollectionEvent 10-July-06

  /** The collection event specimen id. */
  private long collectionEventSpecimenId;

  /** The collection event user id. */
  private long collectionEventUserId;

  /** The collection user name. */
  private String collectionUserName = null;

  /**
   * Gets the collection user name.
   *
   * @return collectionUserName
   */
  public String getCollectionUserName() {
    return this.collectionUserName;
  }

  /**
   * Sets the collection user name.
   *
   * @param collectionUserName collectionUserName
   */
  public void setCollectionUserName(String collectionUserName) {
    this.collectionUserName = collectionUserName;
  }

  /** The received event id. */
  private long receivedEventId;

  /** The received event specimen id. */
  private long receivedEventSpecimenId;

  /** The received event user id. */
  private long receivedEventUserId;

  /** The received user name. */
  private String receivedUserName = null;

  /**
   * Gets the received user name.
   *
   * @return receivedUserName
   */
  public String getReceivedUserName() {
    return this.receivedUserName;
  }

  /**
   * Sets the received user name.
   *
   * @param receivedUserName receivedUserName
   */
  public void setReceivedUserName(String receivedUserName) {
    this.receivedUserName = receivedUserName;
  }

  /** The collection event collection procedure. */
  private String collectionEventCollectionProcedure;

  /** The collection event container. */
  private String collectionEventContainer;

  /** The received event received quality. */
  private String receivedEventReceivedQuality;

  /** The no of derive specimen. */
  private int noOfDeriveSpecimen;

  /** The derive specimen values. */
  private Map deriveSpecimenValues = new LinkedHashMap();

  /** The node key. */
  private String nodeKey = null;

  /**
   * Gets the class name.
   *
   * @return the class name
   */
  public String getClassName() {
    return this.className;
  }

  /**
   * Sets the class name.
   *
   * @param className the new class name
   */
  public void setClassName(String className) {
    this.className = className;
  }

  /**
   * Gets the type.
   *
   * @return the type
   */
  public String getType() {
    return this.type;
  }

  /**
   * Sets the type.
   *
   * @param type the new type
   */
  public void setType(String type) {
    this.type = type;
  }

  /**
   * Gets the tissue site.
   *
   * @return the tissue site
   */
  public String getTissueSite() {
    return this.tissueSite;
  }

  /**
   * Sets the tissue site.
   *
   * @param tissueSite the new tissue site
   */
  public void setTissueSite(String tissueSite) {
    this.tissueSite = tissueSite;
  }

  /**
   * Gets the concentration.
   *
   * @return the concentration
   */
  public String getConcentration() {
    return this.concentration;
  }

  /**
   * Sets the concentration.
   *
   * @param concentration the new concentration
   */
  public void setConcentration(String concentration) {
    this.concentration = concentration;
  }

  /**
   * Gets the quantity.
   *
   * @return the quantity
   */
  public String getQuantity() {
    return this.quantity;
  }

  /**
   * Sets the quantity.
   *
   * @param quantity the new quantity
   */
  public void setQuantity(String quantity) {
    this.quantity = quantity;
  }

  /**
   * Gets the no of aliquots.
   *
   * @return the no of aliquots
   */
  public String getNoOfAliquots() {
    return this.noOfAliquots;
  }

  /**
   * Sets the no of aliquots.
   *
   * @param noOfAliquots the new no of aliquots
   */
  public void setNoOfAliquots(String noOfAliquots) {
    this.noOfAliquots = noOfAliquots;
    if (noOfAliquots != null && noOfAliquots.equals("0")) {
      this.noOfAliquots = "";
    }
  }

  /**
   * Gets the quantity per aliquot.
   *
   * @return the quantity per aliquot
   */
  public String getQuantityPerAliquot() {
    return this.quantityPerAliquot;
  }

  /**
   * Sets the quantity per aliquot.
   *
   * @param quantityPerAliquot the new quantity per aliquot
   */
  public void setQuantityPerAliquot(String quantityPerAliquot) {
    this.quantityPerAliquot = quantityPerAliquot;
  }

  /**
   * Gets the collection event collection procedure.
   *
   * @return the collection event collection procedure
   */
  public String getCollectionEventCollectionProcedure() {
    return this.collectionEventCollectionProcedure;
  }

  /**
   * Sets the collection event collection procedure.
   *
   * @param collectionEventCollectionProcedure the new collection event collection procedure
   */
  public void setCollectionEventCollectionProcedure(String collectionEventCollectionProcedure) {
    this.collectionEventCollectionProcedure = collectionEventCollectionProcedure;
  }

  /**
   * Gets the collection event container.
   *
   * @return the collection event container
   */
  public String getCollectionEventContainer() {
    return this.collectionEventContainer;
  }

  /**
   * Sets the collection event container.
   *
   * @param collectionEventContainer the new collection event container
   */
  public void setCollectionEventContainer(String collectionEventContainer) {
    this.collectionEventContainer = collectionEventContainer;
  }

  /**
   * Gets the received event received quality.
   *
   * @return the received event received quality
   */
  public String getReceivedEventReceivedQuality() {
    return this.receivedEventReceivedQuality;
  }

  /**
   * Sets the received event received quality.
   *
   * @param receivedEventReceivedQuality the new received event received quality
   */
  public void setReceivedEventReceivedQuality(String receivedEventReceivedQuality) {
    this.receivedEventReceivedQuality = receivedEventReceivedQuality;
  }

  /**
   * Gets the no of derive specimen.
   *
   * @return the no of derive specimen
   */
  public int getNoOfDeriveSpecimen() {
    return this.noOfDeriveSpecimen;
  }

  /**
   * Sets the no of derive specimen.
   *
   * @param noOfDeriveSpecimen the new no of derive specimen
   */
  public void setNoOfDeriveSpecimen(int noOfDeriveSpecimen) {
    this.noOfDeriveSpecimen = noOfDeriveSpecimen;
  }

  /**
   * Gets the derive specimen value.
   *
   * @param key the key
   * @return the derive specimen value
   */
  public Object getDeriveSpecimenValue(String key) {
    return this.deriveSpecimenValues.get(key);
  }

  /**
   * Sets the derive specimen value.
   *
   * @param key the key
   * @param value the value
   */
  public void setDeriveSpecimenValue(String key, Object value) {
    if (this.isMutable()) {
      if (this.deriveSpecimenValues == null) {
        this.deriveSpecimenValues = new LinkedHashMap();
      }
      this.deriveSpecimenValues.put(key, value);
    }
  }

  /**
   * Gets the derive specimen values.
   *
   * @return the derive specimen values
   */
  public Map getDeriveSpecimenValues() {
    return this.deriveSpecimenValues;
  }

  /**
   * Sets the derive specimen values.
   *
   * @param deriveSpecimenValues the new derive specimen values
   */
  public void setDeriveSpecimenValues(Map deriveSpecimenValues) {
    this.deriveSpecimenValues = deriveSpecimenValues;
  }

  /**
   * Gets the all derive specimen valuess.
   *
   * @return Returns the values.
   */
  public Collection getAllDeriveSpecimenValuess() {
    return this.deriveSpecimenValues.values();
  }

  /* (non-Javadoc)
   * @see edu.wustl.common.actionForm.AbstractActionForm#getFormId()
   */
  @Override
  public int getFormId() {
    // TODO Auto-generated method stub
    return 0;
  }

  /* (non-Javadoc)
   * @see edu.wustl.common.actionForm.AbstractActionForm#reset()
   */
  @Override
  protected void reset() {}

  /* (non-Javadoc)
   * @see edu.wustl.common.actionForm.IValueObject#setAllValues(edu.wustl.common.domain.AbstractDomainObject)
   */
  public void setAllValues(AbstractDomainObject arg0) {
    // TODO Auto-generated method stub

  }

  /**
   * Gets the lineage.
   *
   * @return the lineage
   */
  public String getLineage() {
    return this.lineage;
  }

  /**
   * Sets the lineage.
   *
   * @param lineage the new lineage
   */
  public void setLineage(String lineage) {
    this.lineage = lineage;
  }

  /**
   * Gets the aliquot specimen collection.
   *
   * @return the aliquot specimen collection
   */
  public Collection getAliquotSpecimenCollection() {
    return this.aliquotSpecimenCollection;
  }

  /**
   * Sets the aliquot specimen collection.
   *
   * @param aliquotSpecimenCollection the new aliquot specimen collection
   */
  public void setAliquotSpecimenCollection(Collection aliquotSpecimenCollection) {
    this.aliquotSpecimenCollection = aliquotSpecimenCollection;
  }

  /**
   * Gets the derive specimen collection.
   *
   * @return the derive specimen collection
   */
  public Collection getDeriveSpecimenCollection() {
    return this.deriveSpecimenCollection;
  }

  /**
   * Sets the derive specimen collection.
   *
   * @param deriveSpecimenCollection the new derive specimen collection
   */
  public void setDeriveSpecimenCollection(Collection deriveSpecimenCollection) {
    this.deriveSpecimenCollection = deriveSpecimenCollection;
  }

  /**
   * Gets the display name.
   *
   * @return the display name
   */
  public String getDisplayName() {
    return this.displayName;
  }

  /**
   * Sets the display name.
   *
   * @param displayName the new display name
   */
  public void setDisplayName(String displayName) {
    this.displayName = displayName;
  }

  /**
   * Gets the unit.
   *
   * @return the unit
   */
  public String getUnit() {
    return this.unit;
  }

  /**
   * Sets the unit.
   *
   * @param unit the new unit
   */
  public void setUnit(String unit) {
    this.unit = unit;
  }

  /**
   * Gets the collection event id.
   *
   * @return the collection event id
   */
  public long getCollectionEventId() {
    return this.collectionEventId;
  }

  /**
   * Sets the collection event id.
   *
   * @param collectionEventId the new collection event id
   */
  public void setCollectionEventId(long collectionEventId) {
    this.collectionEventId = collectionEventId;
  }

  /**
   * Gets the collection event specimen id.
   *
   * @return the collection event specimen id
   */
  public long getCollectionEventSpecimenId() {
    return this.collectionEventSpecimenId;
  }

  /**
   * Gets the collection event user id.
   *
   * @return the collection event user id
   */
  public long getCollectionEventUserId() {
    return this.collectionEventUserId;
  }

  /**
   * Sets the collection event specimen id.
   *
   * @param collectionEventSpecimenId the new collection event specimen id
   */
  public void setCollectionEventSpecimenId(long collectionEventSpecimenId) {
    this.collectionEventSpecimenId = collectionEventSpecimenId;
  }

  /**
   * Gets the received event id.
   *
   * @return the received event id
   */
  public long getReceivedEventId() {
    return this.receivedEventId;
  }

  /**
   * Sets the collection event user id.
   *
   * @param collectionEventUserId the new collection event user id
   */
  public void setCollectionEventUserId(long collectionEventUserId) {
    this.collectionEventUserId = collectionEventUserId;
  }

  /**
   * Sets the received event id.
   *
   * @param receivedEventId the new received event id
   */
  public void setReceivedEventId(long receivedEventId) {
    this.receivedEventId = receivedEventId;
  }

  /**
   * Sets the received event specimen id.
   *
   * @param receivedEventSpecimenId the new received event specimen id
   */
  public void setReceivedEventSpecimenId(long receivedEventSpecimenId) {
    this.receivedEventSpecimenId = receivedEventSpecimenId;
  }

  /**
   * Gets the received event user id.
   *
   * @return the received event user id
   */
  public long getReceivedEventUserId() {
    return this.receivedEventUserId;
  }

  /**
   * Gets the received event specimen id.
   *
   * @return the received event specimen id
   */
  public long getReceivedEventSpecimenId() {
    return this.receivedEventSpecimenId;
  }

  /**
   * Sets the received event user id.
   *
   * @param receivedEventUserId the new received event user id
   */
  public void setReceivedEventUserId(long receivedEventUserId) {
    this.receivedEventUserId = receivedEventUserId;
  }

  /**
   * Gets the storage location for specimen.
   *
   * @return the storage location for specimen
   */
  public String getStorageLocationForSpecimen() {
    return this.storageLocationForSpecimen;
  }

  /**
   * Sets the storage location for specimen.
   *
   * @param storageLocationForSpecimen the new storage location for specimen
   */
  public void setStorageLocationForSpecimen(String storageLocationForSpecimen) {
    this.storageLocationForSpecimen = storageLocationForSpecimen;
  }

  /**
   * Gets the storage location for aliquot specimen.
   *
   * @return the storage location for aliquot specimen
   */
  public String getStorageLocationForAliquotSpecimen() {
    return this.storageLocationForAliquotSpecimen;
  }

  /**
   * Sets the storage location for aliquot specimen.
   *
   * @param storageLocationForAliquotSpecimen the new storage location for aliquot specimen
   */
  public void setStorageLocationForAliquotSpecimen(String storageLocationForAliquotSpecimen) {
    this.storageLocationForAliquotSpecimen = storageLocationForAliquotSpecimen;
  }

  /**
   * Gets the tissue side.
   *
   * @return the tissue side
   */
  public String getTissueSide() {
    return this.tissueSide;
  }

  /**
   * Sets the tissue side.
   *
   * @param tissueSide the new tissue side
   */
  public void setTissueSide(String tissueSide) {
    this.tissueSide = tissueSide;
  }

  /**
   * Gets the pathological status.
   *
   * @return the pathological status
   */
  public String getPathologicalStatus() {
    return this.pathologicalStatus;
  }

  /**
   * Sets the pathological status.
   *
   * @param pathologicalStatus the new pathological status
   */
  public void setPathologicalStatus(String pathologicalStatus) {
    this.pathologicalStatus = pathologicalStatus;
  }

  /* (non-Javadoc)
   * @see org.apache.struts.action.ActionForm#validate(org.apache.struts.action.ActionMapping, javax.servlet.http.HttpServletRequest)
   */
  public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    final ActionErrors errors = new ActionErrors();
    final Validator validator = new Validator();
    double aliquotQuantity = 0;
    double initialQuantity = 0;
    try {
      if (validator.isEmpty(this.className)) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.required", ApplicationProperties.getValue("specimen.type")));
      }
      //			if(this.labelGenType.equals("2") && validator.isEmpty(this.labelFormat))
      //			{
      //				errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(
      //						"collectionProtocol.labelformat", ApplicationProperties
      //						.getValue("collectionProtocol.labelformat")));
      //			}
      if (validator.isEmpty(this.type)) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.required", ApplicationProperties.getValue("specimen.subType")));
      }
      final List specimenClassList =
          CDEManager.getCDEManager()
              .getPermissibleValueList(Constants.CDE_NAME_SPECIMEN_CLASS, null);
      if (!Validator.isEnumeratedValue(specimenClassList, this.className)) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.invalid", ApplicationProperties.getValue("specimen.type")));
      }

      if (!Validator.isEnumeratedValue(AppUtility.getSpecimenTypes(this.className), this.type)) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.invalid", ApplicationProperties.getValue("specimen.subType")));
      }

      if (!validator.isEmpty(this.quantity)) {
        try {
          this.quantity = new BigDecimal(this.quantity).toPlainString();
          if (AppUtility.isQuantityDouble(this.className, this.type)) {
            if (!validator.isDouble(this.quantity, true)) {
              errors.add(
                  ActionErrors.GLOBAL_ERROR,
                  new ActionError(
                      "errors.item.required", ApplicationProperties.getValue("specimen.quantity")));
            }
          } else {
            if (!validator.isNumeric(this.quantity, 0)) {
              errors.add(
                  ActionErrors.GLOBAL_ERROR,
                  new ActionError(
                      "errors.item.format", ApplicationProperties.getValue("specimen.quantity")));
            }
          }
        } catch (final NumberFormatException exp) {
          CreateSpecimenTemplateForm.logger.info(exp.getMessage(), exp);
          exp.printStackTrace();
          errors.add(
              ActionErrors.GLOBAL_ERROR,
              new ActionError(
                  "errors.item.format", ApplicationProperties.getValue("specimen.quantity")));
        }

      } else {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.format", ApplicationProperties.getValue("specimen.quantity")));
      }

      if (!this.quantityPerAliquot.equals("")) {
        if (this.quantityPerAliquot != null && this.quantityPerAliquot.trim().length() != 0) {
          try {
            this.quantityPerAliquot = new BigDecimal(this.quantityPerAliquot).toPlainString();
            if (AppUtility.isQuantityDouble(this.className, this.type)) {
              if (!validator.isDouble(this.quantityPerAliquot.trim())) {
                errors.add(
                    ActionErrors.GLOBAL_ERROR,
                    new ActionError(
                        "errors.item.format",
                        ApplicationProperties.getValue("aliquots.qtyPerAliquot")));
              }
            } else {
              if (!validator.isPositiveNumeric(this.quantityPerAliquot.trim(), 1)) {
                errors.add(
                    ActionErrors.GLOBAL_ERROR,
                    new ActionError(
                        "errors.item.format",
                        ApplicationProperties.getValue("aliquots.qtyPerAliquot")));
              }
            }
          } catch (final NumberFormatException exp) {
            CreateSpecimenTemplateForm.logger.error(exp.getMessage(), exp);
            exp.printStackTrace();
            errors.add(
                ActionErrors.GLOBAL_ERROR,
                new ActionError(
                    "errors.item.format",
                    ApplicationProperties.getValue("aliquots.qtyPerAliquot")));
          }
        }
      }

      if (!this.noOfAliquots.equals("")) {
        this.noOfAliquots = AppUtility.isValidCount(this.noOfAliquots, errors);

        if (!validator.isNumeric(this.noOfAliquots, 1)) {
          errors.add(
              ActionErrors.GLOBAL_ERROR,
              new ActionError(
                  "errors.item.format",
                  ApplicationProperties.getValue("specimenArrayAliquots.noOfAliquots")));
        } else {
          try {
            if (this.quantityPerAliquot.equals("")) {
              if (this.quantity.equals("0") || this.quantity.equals("0")) {
                errors.add(
                    ActionErrors.GLOBAL_ERROR,
                    new ActionError(
                        "errors.invalid", ApplicationProperties.getValue("specimen.quantity")));
              } else {
                aliquotQuantity =
                    Double.parseDouble(this.quantity) / Double.parseDouble(this.noOfAliquots);
                initialQuantity =
                    Double.parseDouble(this.quantity)
                        - (aliquotQuantity * Double.parseDouble(this.noOfAliquots));
              }
            } else {
              aliquotQuantity = Double.parseDouble(this.quantityPerAliquot);
              initialQuantity = Double.parseDouble(this.quantity);
              initialQuantity =
                  initialQuantity - (aliquotQuantity * Double.parseDouble(this.noOfAliquots));
            }
            if (initialQuantity < 0) {
              errors.add(
                  ActionErrors.GLOBAL_ERROR,
                  new ActionError(
                      "errors.invalid",
                      ApplicationProperties.getValue("cpbasedentry.quantityperaliquot")));
            }
            //						if(this.labelGenTypeForAliquot.equals("2") &&
            // validator.isEmpty(this.labelFormatForAliquot))
            //						{
            //							errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(
            //									"sp.req.aliquot.labelformat", ApplicationProperties
            //									.getValue("sp.req.aliquot.labelformat")));
            //						}
          } catch (final NumberFormatException exp) {
            CreateSpecimenTemplateForm.logger.error(exp.getMessage(), exp);
            errors.add(
                ActionErrors.GLOBAL_ERROR,
                new ActionError(
                    "errors.item.format", ApplicationProperties.getValue("specimen.quantity")));
          }
        }
      }

      if (this.tissueSite.equals("")) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.required", ApplicationProperties.getValue("specimen.tissueSite")));
      }

      if (this.tissueSide.equals("")) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.required", ApplicationProperties.getValue("specimen.tissueSide")));
      }

      if (this.noOfAliquots != null && !this.noOfAliquots.equals("")) {
        if (!this.storageLocationForAliquotSpecimen.equals("Auto")
            && !this.storageLocationForAliquotSpecimen.equals("Manual")
            && !this.storageLocationForAliquotSpecimen.equals("Virtual")) {
          errors.add(
              ActionErrors.GLOBAL_ERROR,
              new ActionError(
                  "errors.item.required",
                  ApplicationProperties.getValue("cpbasedentry.aliquotstoragelocation")));
        }
      }
      if (!this.storageLocationForSpecimen.equals("Auto")
          && !this.storageLocationForSpecimen.equals("Manual")
          && !this.storageLocationForSpecimen.equals("Virtual")) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.required",
                ApplicationProperties.getValue("cpbasedentry.specimenstoragelocation")));
      }
      if (this.pathologicalStatus.equals("")) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.required",
                ApplicationProperties.getValue("specimen.pathologicalStatus")));
      }
      final List tissueSiteList =
          CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_TISSUE_SITE, null);
      if (!Validator.isEnumeratedValue(tissueSiteList, this.tissueSite)) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.invalid", ApplicationProperties.getValue("specimen.tissueSite")));
      }

      final List tissueSideList =
          CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_TISSUE_SIDE, null);
      if (!Validator.isEnumeratedValue(tissueSideList, this.tissueSide)) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.invalid", ApplicationProperties.getValue("specimen.tissueSide")));
      }

      final List pathologicalStatusList =
          CDEManager.getCDEManager()
              .getPermissibleValueList(Constants.CDE_NAME_PATHOLOGICAL_STATUS, null);

      if (!Validator.isEnumeratedValue(pathologicalStatusList, this.pathologicalStatus)) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.invalid",
                ApplicationProperties.getValue("specimen.pathologicalStatus")));
      }

      if ((this.collectionEventUserId) == 0L) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError("errors.item.required", "Collection Event's user"));
      }

      // checks the collectionProcedure
      if (!validator.isValidOption(this.getCollectionEventCollectionProcedure())) {
        final String message =
            ApplicationProperties.getValue("collectioneventparameters.collectionprocedure");
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.required", message));
      }

      final List procedureList =
          CDEManager.getCDEManager()
              .getPermissibleValueList(Constants.CDE_NAME_COLLECTION_PROCEDURE, null);
      if (!Validator.isEnumeratedValue(
          procedureList, this.getCollectionEventCollectionProcedure())) {
        final String message = ApplicationProperties.getValue("cpbasedentry.collectionprocedure");
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.invalid", message));
      }
      // Container validation
      if (!validator.isValidOption(this.getCollectionEventContainer())) {
        final String message =
            ApplicationProperties.getValue("collectioneventparameters.container");
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.required", message));
      }
      final List containerList =
          CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CONTAINER, null);
      if (!Validator.isEnumeratedValue(containerList, this.getCollectionEventContainer())) {
        final String message =
            ApplicationProperties.getValue("collectioneventparameters.container");
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.invalid", message));
      }
      if ((this.receivedEventUserId) == 0L) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError("errors.item.required", "Received Event's user"));
      }
      final List qualityList =
          CDEManager.getCDEManager()
              .getPermissibleValueList(Constants.CDE_NAME_RECEIVED_QUALITY, null);
      if (!Validator.isEnumeratedValue(qualityList, this.receivedEventReceivedQuality)) {
        final String message = ApplicationProperties.getValue("cpbasedentry.receivedquality");
        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.invalid", message));
      }

      if (this.className.equals(Constants.MOLECULAR)) {
        if (!validator.isDouble(this.concentration, true)) {
          errors.add(
              ActionErrors.GLOBAL_ERROR,
              new ActionError(
                  "errors.item.format", ApplicationProperties.getValue("specimen.concentration")));
        }
      }

      if (this.noOfDeriveSpecimen >= 1) {
        boolean bSpecimenClass = false;
        boolean bSpecimenType = false;
        //				boolean validateLabel = false;
        //				boolean labelGenType = false;
        //				boolean labelFormat = false;
        final Map deriveSpecimenMap = this.deriveSpecimenMap();
        final Iterator it = deriveSpecimenMap.keySet().iterator();
        while (it.hasNext()) {
          final String key = (String) it.next();
          String mapValue = (String) deriveSpecimenMap.get(key);
          if (!bSpecimenClass) {
            if (key.indexOf("specimenClass") != -1 && !validator.isValidOption(mapValue)) {
              errors.add(
                  ActionErrors.GLOBAL_ERROR,
                  new ActionError(
                      "errors.item.selected",
                      ApplicationProperties.getValue("collectionprotocol.specimenclass")));
              bSpecimenClass = true;
            }
          }
          //					if(!labelGenType)
          //					{
          //						if ((key.indexOf("_labelGenType")) != -1 && mapValue != null)
          //						{
          //							if (mapValue.equals("2"))
          //							{
          //								validateLabel=true;
          //								labelGenType = true;
          //							}
          //						}
          //
          //					}
          //					if(!labelFormat && labelGenType)
          //					{
          //						if(validateLabel && (key.indexOf("_labelFormat")) != -1 &&
          // validator.isEmpty(mapValue))
          //						{
          //							labelFormat = true;
          //							errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(
          //									"sp.req.derivative.labelformat", ApplicationProperties
          //									.getValue("sp.req.derivative.labelformat")));
          //						}
          //					}
          if ((key.indexOf("_concentration")) != -1 && mapValue != null) {
            mapValue = new BigDecimal(mapValue).toPlainString();
            if (!validator.isDouble(mapValue, true)) {
              errors.add(
                  ActionErrors.GLOBAL_ERROR,
                  new ActionError(
                      "errors.item.format",
                      ApplicationProperties.getValue("specimen.concentration")));
            }
          }

          if (!bSpecimenType) {
            if (key.indexOf("specimenType") != -1 && !validator.isValidOption(mapValue)) {
              errors.add(
                  ActionErrors.GLOBAL_ERROR,
                  new ActionError(
                      "errors.item.selected",
                      ApplicationProperties.getValue("collectionprotocol.specimetype")));
              bSpecimenType = true;
            }
          }

          if ((key.indexOf("_quantity")) != -1) {
            if (!validator.isEmpty(mapValue)) {
              try {
                mapValue = new BigDecimal(mapValue).toPlainString();
                if (AppUtility.isQuantityDouble(this.className, this.type)) {
                  if (!validator.isDouble(mapValue, true)) {
                    errors.add(
                        ActionErrors.GLOBAL_ERROR,
                        new ActionError(
                            "errors.item.required",
                            ApplicationProperties.getValue("specimen.quantity")));
                  }
                } else {
                  if (!validator.isNumeric(mapValue, 0)) {
                    errors.add(
                        ActionErrors.GLOBAL_ERROR,
                        new ActionError(
                            "errors.item.format",
                            ApplicationProperties.getValue(
                                "cpbasedentry.derivedspecimen.quantity")));
                  }
                }
              } catch (final NumberFormatException exp) {
                CreateSpecimenTemplateForm.logger.error(exp.getMessage(), exp);
                errors.add(
                    ActionErrors.GLOBAL_ERROR,
                    new ActionError(
                        "errors.item.format",
                        ApplicationProperties.getValue("cpbasedentry.derivedspecimen.quantity")));
              }
            } else {
              errors.add(
                  ActionErrors.GLOBAL_ERROR,
                  new ActionError(
                      "errors.item.format",
                      ApplicationProperties.getValue("cpbasedentry.derivedspecimen.quantity")));
            }
          }
        }
      }
    } catch (final Exception excp) {
      CreateSpecimenTemplateForm.logger.error(excp.getMessage(), excp);
      excp.printStackTrace();
    }
    return errors;
  }

  /**
   * Derive specimen map.
   *
   * @return the map
   */
  public Map deriveSpecimenMap() {
    int iCount;
    boolean genLabel = false;
    final Map deriveSpecimenMap = new LinkedHashMap<String, String>();
    for (iCount = 1; iCount <= this.noOfDeriveSpecimen; iCount++) {
      String key = null;
      key = "DeriveSpecimenBean:" + iCount + "_specimenClass";
      final String specimenClass = (String) this.deriveSpecimenValues.get(key);
      deriveSpecimenMap.put(key, specimenClass);

      key = "DeriveSpecimenBean:" + iCount + "_id";
      final String id = (String) this.deriveSpecimenValues.get(key);
      deriveSpecimenMap.put(key, id);

      key = "DeriveSpecimenBean:" + iCount + "_specimenType";
      final String specimenType = (String) this.deriveSpecimenValues.get(key);
      deriveSpecimenMap.put(key, specimenType);

      key = "DeriveSpecimenBean:" + iCount + "_quantity";
      final String quantity = (String) this.deriveSpecimenValues.get(key);
      deriveSpecimenMap.put(key, quantity);

      key = "DeriveSpecimenBean:" + iCount + "_concentration";
      final String conc = (String) this.deriveSpecimenValues.get(key);
      deriveSpecimenMap.put(key, conc);

      key = "DeriveSpecimenBean:" + iCount + "_storageLocation";
      final String storageLocation = (String) this.deriveSpecimenValues.get(key);
      deriveSpecimenMap.put(key, storageLocation);

      key = "DeriveSpecimenBean:" + iCount + "_labelFormat";
      final String labelFormat = (String) this.deriveSpecimenValues.get(key);
      deriveSpecimenMap.put(key, labelFormat);
    }
    return deriveSpecimenMap;
  }

  /**
   * Gets the node key.
   *
   * @return the node key
   */
  public String getNodeKey() {
    return this.nodeKey;
  }

  /**
   * Sets the node key.
   *
   * @param nodeKey the new node key
   */
  public void setNodeKey(String nodeKey) {
    this.nodeKey = nodeKey;
  }

  /* (non-Javadoc)
   * @see edu.wustl.common.actionForm.AbstractActionForm#setAddNewObjectIdentifier(java.lang.String, java.lang.Long)
   */
  @Override
  public void setAddNewObjectIdentifier(String arg0, Long arg1) {
    // TODO Auto-generated method stub

  }

  /** For SCG labeling,this will be exposed through API and not in the model. */
  private String labelFormat;

  /**
   * For SCG labeling,this will be exposed through API and not in the model.
   *
   * @return the label format
   */
  public String getLabelFormat() {
    return this.labelFormat;
  }

  /**
   * For SCG labeling,this will be exposed through API and not in the model.
   *
   * @param labelFormat the label format
   */
  public void setLabelFormat(String labelFormat) {
    this.labelFormat = labelFormat;
  }

  /**
   * Gets the label format for aliquot.
   *
   * @return the label format for aliquot
   */
  public String getLabelFormatForAliquot() {
    return labelFormatForAliquot;
  }

  /**
   * Sets the label format for aliquot.
   *
   * @param labelFormatForAliquot the new label format for aliquot
   */
  public void setLabelFormatForAliquot(String labelFormatForAliquot) {
    this.labelFormatForAliquot = labelFormatForAliquot;
  }

  /** The label format for aliquot. */
  private String labelFormatForAliquot;
}
/**
 * StorageContainerHDAO is used to add Storage Container information into the database using
 * Hibernate.
 *
 * @author Vaishali_Khandelwal
 */
public class SimilarContainerBizLogic extends StorageContainerBizLogic {

  private final transient Logger logger = Logger.getCommonLogger(SimilarContainerBizLogic.class);

  /**
   * Saves the storageContainer object in the database.
   *
   * @param dao : dao
   * @param obj The storageType object to be saved.
   * @param sessionDataBean The session in which the object is saved.
   * @throws BizLogicException : BizLogicException
   */
  @Override
  protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean)
      throws BizLogicException {
    final StorageContainer container = (StorageContainer) obj;
    container.setActivityStatus(Status.ACTIVITY_STATUS_ACTIVE.toString());

    final List contList = new ArrayList();
    final int noOfContainers = container.getNoOfContainers().intValue();
    final Map simMap = container.getSimilarContainerMap();
    // --- common values for all similar containers ---
    new StorageTypeBizLogic().loadStorageType(dao, container);
    this.logger.debug(simMap);
    final int checkButton = Integer.parseInt((String) simMap.get("checkedButton"));
    // int checkButton = 1;

    try {
      for (int i = 1; i <= noOfContainers; i++) {
        final String simContPrefix = "simCont:" + i + "_";
        final String IdKey = simContPrefix + "Id";
        final String parentContNameKey = simContPrefix + "parentContName";
        final String contName = (String) simMap.get(simContPrefix + "name");
        String barcode = (String) simMap.get(simContPrefix + "barcode");

        if (barcode != null && barcode.equals("")) // this is done
        // because barcode
        // is empty string
        // set by struts
        { // but barcode in DB is unique but can be null.
          barcode = null;
        }
        final StorageContainer cont = new StorageContainer(container);
        if (checkButton == 1) // site
        {
          final String siteId = (String) simMap.get(simContPrefix + "siteId");
          final String siteName = (String) simMap.get(simContPrefix + "siteName");

          final Site site = new Site();

          /**
           * Start: Change for API Search --- Jitendra 06/10/2006 In Case of Api Search, previoulsy
           * it was failing since there was default class level initialization on domain object. For
           * example in User object, it was initialized as protected String lastName=""; So we
           * removed default class level initialization on domain object and are initializing in
           * method setAllValues() of domain object. But in case of Api Search, default values will
           * not get set since setAllValues() method of domainObject will not get called. To avoid
           * null pointer exception, we are setting the default values same as we were setting in
           * setAllValues() method of domainObject.
           */
          ApiSearchUtil.setSiteDefault(site);
          site.setId(new Long(siteId));
          site.setName(siteName);
          cont.setSite(site);
          new SiteBizLogic().loadSite(dao, cont);

        } else
        // parentContainer
        {
          StorageContainer parentContainer = null;
          final String parentId = (String) simMap.get(simContPrefix + "parentContainerId");
          final String posOne = (String) simMap.get(simContPrefix + "positionDimensionOne");
          final String posTwo = (String) simMap.get(simContPrefix + "positionDimensionTwo");

          final Object object =
              dao.retrieveById(StorageContainer.class.getName(), new Long(parentId));
          if (object != null) {

            parentContainer = (StorageContainer) object;
            cont.setSite(parentContainer.getSite());
          }

          final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
          final StorageContainerBizLogic storageContainerBizLogic =
              (StorageContainerBizLogic) factory.getBizLogic(Constants.STORAGE_CONTAINER_FORM_ID);
          storageContainerBizLogic.checkContainer(
              dao,
              StorageContainerUtil.setparameterList(
                  parentContainer.getId().toString(), posOne, posTwo, false),
              sessionDataBean,
              null);
          ContainerPosition cntPos = cont.getLocatedAtPosition();
          if (cntPos == null) {
            cntPos = new ContainerPosition();
          }

          cntPos.setPositionDimensionOne(new Integer(posOne));
          cntPos.setPositionDimensionTwo(new Integer(posTwo));
          cntPos.setOccupiedContainer(cont);
          cntPos.setParentContainer(parentContainer);
          cont.setLocatedAtPosition(cntPos);
          // Have to set Site object for parentContainer
          SiteBizLogic siteBiz = new SiteBizLogic();
          siteBiz.loadSite(dao, parentContainer);
          siteBiz.loadSiteFromContainerId(dao, parentContainer);

          cntPos.setPositionDimensionOne(new Integer(posOne));
          cntPos.setPositionDimensionTwo(new Integer(posTwo));
          cntPos.setOccupiedContainer(cont);
          cont.setLocatedAtPosition(cntPos);
          cont.setSite(parentContainer.getSite());
          this.logger.debug("^^>> " + parentContainer.getSite());
          simMap.put(parentContNameKey, parentContainer.getName());
        }
        // StorageContainer cont = new StorageContainer();
        cont.setName(contName); // <<----
        cont.setBarcode(barcode); // <<----
        // by falguni
        // Storage container label generator

        // Call Storage container label generator if its specified to
        // use automatic label generator
        if (edu.wustl.catissuecore.util.global.Variables.isStorageContainerLabelGeneratorAvl) {
          LabelGenerator storagecontLblGenerator;
          storagecontLblGenerator =
              LabelGeneratorFactory.getInstance(
                  Constants.STORAGECONTAINER_LABEL_GENERATOR_PROPERTY_NAME);
          try {
            storagecontLblGenerator.setLabel(cont);
          } catch (LabelGenException e) {
            this.logger.error(e.getMessage(), e);
          }
        }

        simMap.put(simContPrefix + "name", cont.getName());

        this.logger.debug(
            "cont.getCollectionProtocol().size() " + cont.getCollectionProtocolCollection().size());
        cont.setActivityStatus("Active");
        dao.insert(cont.getCapacity());
        dao.insert(cont);
        contList.add(cont);
        container.setId(cont.getId());
        simMap.put(IdKey, cont.getId().toString());
      }
    } catch (final DAOException daoExp) {
      this.logger.error(daoExp.getMessage(), daoExp);
      daoExp.printStackTrace();
      throw this.getBizLogicException(daoExp, daoExp.getErrorKeyName(), daoExp.getMsgValues());
    } catch (final NameGeneratorException e) {
      this.logger.error(e.getMessage(), e);
      e.printStackTrace();
      throw this.getBizLogicException(e, "utility.error", "");
    }
  }

  /**
   * @param obj : obj
   * @param dao : dao
   * @param sessionDataBean : sessionDataBean
   * @throws BizLogicException : BizLogicException
   */
  @Override
  public synchronized void postInsert(Object obj, DAO dao, SessionDataBean sessionDataBean)
      throws BizLogicException {
    final StorageContainer container = (StorageContainer) obj;
    try {
      final int noOfContainers = container.getNoOfContainers().intValue();
      final Map simMap = container.getSimilarContainerMap();
      final int checkButton = Integer.parseInt((String) simMap.get("checkedButton"));
      for (int i = 1; i <= noOfContainers; i++) {

        final String simContPrefix = "simCont:" + i + "_";
        final String contName = (String) simMap.get(simContPrefix + "name");
        final String identifier = (String) simMap.get(simContPrefix + "Id");
        final StorageContainer cont = new StorageContainer(container);
        // Logger.out.info("contName:" + contName);

        cont.setId(new Long(identifier));
        cont.setName(contName); // by falguni ...Container name is
        // generated via label generator.
        if (checkButton == 2) {
          final String parentId = (String) simMap.get(simContPrefix + "parentContainerId");
          final String posOne = (String) simMap.get(simContPrefix + "positionDimensionOne");
          final String posTwo = (String) simMap.get(simContPrefix + "positionDimensionTwo");
          final String parentContName = (String) simMap.get(simContPrefix + "parentContName");
          final StorageContainer parentContainer = new StorageContainer();
          parentContainer.setId(new Long(parentId));
          parentContainer.setName(parentContName);

          final ContainerPosition cntPos = cont.getLocatedAtPosition();

          cntPos.setPositionDimensionOne(new Integer(posOne));
          cntPos.setPositionDimensionTwo(new Integer(posTwo));
          cntPos.setOccupiedContainer(cont);
          cntPos.setParentContainer(parentContainer);

          // cont.setParent(parentContainer); // <<----

        }
      }

    } catch (final Exception e) {
      this.logger.error(e.getMessage(), e);
      e.printStackTrace();
    }
    super.postInsert(obj, dao, sessionDataBean);
  }

  /**
   * Overriding the parent class's method to validate the enumerated attribute values
   *
   * @param obj : obj
   * @param dao : dao
   * @param operation : operation
   * @throws BizLogicException : BizLogicException
   * @return boolean
   */
  @Override
  protected boolean validate(Object obj, DAO dao, String operation) throws BizLogicException {
    try {
      final StorageContainer container = (StorageContainer) obj;
      final Map similarContainerMap = container.getSimilarContainerMap();
      final String containerPrefixKey = "simCont:";
      final String parentContainerId = "_parentContainerId";
      final List positionsToBeAllocatedList = new ArrayList();
      final List usedPositionsList = new ArrayList();

      for (int i = 1; i <= container.getNoOfContainers().intValue(); i++) {
        StorageContainerUtil.prepareContainerMap(
            dao,
            similarContainerMap,
            containerPrefixKey,
            positionsToBeAllocatedList,
            usedPositionsList,
            i,
            parentContainerId);
      }
      /*for (int i = 0; i < positionsToBeAllocatedList.size(); i++)
      {
      	StorageContainerUtil.allocatePositionToSingleContainerOrSpecimen(
      			positionsToBeAllocatedList.get(i), similarContainerMap, usedPositionsList,
      			containerPrefixKey, parentContainerId);
      }*/
      if (container.getNoOfContainers().intValue() > 1 && similarContainerMap.size() > 0) {
        for (int i = 1; i <= container.getNoOfContainers().intValue(); i++) {
          final int checkedButtonStatus =
              Integer.parseInt((String) similarContainerMap.get("checkedButton"));
          final String siteId = (String) similarContainerMap.get("simCont:" + i + "_siteId");
          if (checkedButtonStatus == 2 || siteId == null) {
            final String parentContId =
                (String) similarContainerMap.get("simCont:" + i + "_parentContainerId");
            final String positionDimensionOne =
                (String) similarContainerMap.get("simCont:" + i + "_positionDimensionOne");
            final String positionDimensionTwo =
                (String) similarContainerMap.get("simCont:" + i + "_positionDimensionTwo");
            if (parentContId.equals("-1")
                || positionDimensionOne.equals("-1")
                || positionDimensionTwo.equals("-1")) {

              throw this.getBizLogicException(
                  null,
                  "errors.item.required",
                  ApplicationProperties.getValue("similarcontainers.location"));
            }
          } else {
            if (siteId.equals("-1")) {
              throw this.getBizLogicException(
                  null,
                  "errors.item.required",
                  ApplicationProperties.getValue("storageContainer.site"));
            }
          }
        }
      }
    } catch (final ApplicationException exp) {
      this.logger.error(exp.getMessage(), exp);
      exp.printStackTrace();
      throw this.getBizLogicException(exp, exp.getErrorKeyName(), exp.getMsgValues());
    }
    return true;
  }

  /**
   * Called from DefaultBizLogic to get ObjectId for authorization check (non-Javadoc)
   *
   * @param dao : dao
   * @param domainObject : domainObject
   * @return String
   * @see edu.wustl.common.bizlogic.DefaultBizLogic#getObjectId(edu.wustl.common.dao.DAO,
   *     java.lang.Object)
   */
  @Override
  public String getObjectId(DAO dao, Object domainObject) {
    final StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(Site.class.getName());
    try {
      if (domainObject instanceof StorageContainer) {
        final StorageContainer storageContainer = (StorageContainer) domainObject;
        final Map similarContainerMap = storageContainer.getSimilarContainerMap();
        final Object keys[] = similarContainerMap.keySet().toArray();
        final Set<Long> scIds = new HashSet<Long>();
        final Set<Long> siteIds = new HashSet<Long>();

        for (final Object key : keys) {
          if (key.toString().contains("parentContainerId")) {
            scIds.add(Long.valueOf(similarContainerMap.get(key).toString()));
          }
          if (key.toString().contains("siteId")) {
            siteIds.add(Long.valueOf(similarContainerMap.get(key).toString()));
          }
        }

        for (final Long scId : scIds) {
          Site site = null;
          Object object = null;

          object = dao.retrieveById(StorageContainer.class.getName(), scId);

          if (object != null) {
            final StorageContainer parentContainer = (StorageContainer) object;
            site = parentContainer.getSite();
          }
          if (site != null) {
            if (!siteIds.contains(site.getId())) {
              stringBuffer.append("_" + site.getId().toString());
            }
            siteIds.add(site.getId());
          }
        }

        for (final Long siteId : siteIds) {
          stringBuffer.append("_" + siteId.toString());
        }
      }
    } catch (final DAOException daoExp) {
      this.logger.error(daoExp.getMessage(), daoExp);
      daoExp.printStackTrace();
    }
    return stringBuffer.toString();
  }

  /**
   * To get PrivilegeName for authorization check from 'PermissionMapDetails.xml' (non-Javadoc)
   *
   * @param domainObject : domainObject
   * @return String
   * @see edu.wustl.common.bizlogic.DefaultBizLogic#getPrivilegeName(java.lang.Object)
   */
  @Override
  protected String getPrivilegeKey(Object domainObject) {
    return new StorageContainerBizLogic().getPrivilegeKey(domainObject);
  }
}
Пример #12
0
/** @author renuka_bajpai */
public class ConflictResolverAction extends BaseAction {

  /** logger. */
  private final transient Logger logger = Logger.getCommonLogger(ConflictResolverAction.class);

  /**
   * Overrides the executeSecureAction method of SecureAction class.
   *
   * @param mapping object of ActionMapping
   * @param form object of ActionForm
   * @param request object of HttpServletRequest
   * @param response object of HttpServletResponse
   * @throws Exception generic exception
   * @return ActionForward : ActionForward
   */
  @Override
  public ActionForward executeAction(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    final HttpSession session = request.getSession();
    final String participantIdToAssociate =
        (String) session.getAttribute(Constants.PARTICIPANT_ID_TO_ASSOCIATE);
    final String specimenCollGrpId = (String) session.getAttribute(Constants.SCG_ID_TO_ASSOCIATE);
    final String reportQueueId = request.getParameter(Constants.REPORT_ID);
    final String button = request.getParameter(Constants.CONFLICT_BUTTON);
    String errorMessage = null;

    // overwrite the existing report
    if (button.trim().equalsIgnoreCase(Constants.OVERWRITE_REPORT)) {
      this.overwriteReport(request, reportQueueId);
    }

    // Ignore new Report
    if (button.trim().equalsIgnoreCase(Constants.IGNORE_NEW_REPORT)) {
      this.ignoreNewReport(reportQueueId);
    }

    // Creating a new Participant
    if (button.trim().equalsIgnoreCase(Constants.CREATE_NEW_PARTICIPANT)) {
      errorMessage = this.createNewParticipant(request, reportQueueId);
      if (errorMessage != null) {
        this.setActionError(request, errorMessage);
      }
    } else {
      if (button.trim().equalsIgnoreCase(Constants.USE_SELECTED_PARTICIPANT)) {
        if (participantIdToAssociate != null && !participantIdToAssociate.equals("")) {
          // Associate existing participant with Report
          this.createNewSCG(request, reportQueueId, participantIdToAssociate);
        }
      } else if (button.trim().equalsIgnoreCase(Constants.USE_SELECTED_SCG)) {

        if (specimenCollGrpId != null && !specimenCollGrpId.equals("")) {
          // Associate existing SCG with Report
          this.associateSCGWithReport(
              request, reportQueueId, participantIdToAssociate, specimenCollGrpId);
        }
      }
    }
    this.resetSessionAttributes(session);
    return mapping.findForward(Constants.SUCCESS);
  }

  /**
   * To create new participant and associate it to the report.
   *
   * @param request : request
   * @param reportQueueId : reportQueueId
   * @return String : String
   * @throws Exception : Exception
   */
  private String createNewParticipant(HttpServletRequest request, String reportQueueId)
      throws Exception {

    String errorMessage = null;
    ReportLoaderQueue reportLoaderQueue = null;
    reportLoaderQueue = Utility.getReportQueueObject(reportQueueId);

    final Participant participant = Utility.getParticipantFromReportLoaderQueue(reportQueueId);

    final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
    final ParticipantBizLogic participantBizLogic =
        (ParticipantBizLogic) factory.getBizLogic(Participant.class.getName());
    try {
      participantBizLogic.insert(participant, this.getSessionData(request), 0);
    } catch (final Exception e) {
      this.logger.error(e.getMessage(), e);
      // System.out.println("Error Occurred !!!!!");
      errorMessage = ApplicationProperties.getValue("errors.caTies.conflict.genericmessage");
      // Setting the status to NEW
      // reportLoaderQueue.setParticipantCollection(null);
      // reportLoaderQueue.setStatus(CaTIESConstants.
      // PARTICIPANT_CREATION_ERROR);
      // updateReportLoaderQueue(reportLoaderQueue,request);
      return errorMessage;
    }

    final Collection participantColl = new HashSet();
    // Adding the new participant
    participantColl.add(participant);
    reportLoaderQueue.setParticipantCollection(participantColl);
    // The new SCG for this participant will be inserted by the
    // FileProcessorThread

    // Setting the status to NEW
    reportLoaderQueue.setStatus(CaTIESConstants.NEW);
    reportLoaderQueue.setSpecimenCollectionGroup(null);
    this.updateReportLoaderQueue(reportLoaderQueue, request);

    return errorMessage;
  }

  /**
   * To associate existing participant to the report and to create new SCG.
   *
   * @param request : request
   * @param reportQueueId : reportQueueId
   * @param participantIdToAssociate : participantIdToAssociate
   * @throws NumberFormatException : NumberFormatException
   * @throws BizLogicException : BizLogicException
   */
  private void createNewSCG(
      HttpServletRequest request, String reportQueueId, String participantIdToAssociate)
      throws NumberFormatException, BizLogicException {

    ReportLoaderQueue reportLoaderQueue = null;
    reportLoaderQueue = Utility.getReportQueueObject(reportQueueId);

    // Changing the status of the report in the queue to NEW
    reportLoaderQueue.setStatus(CaTIESConstants.NEW);

    // Create new SCG
    reportLoaderQueue.setSpecimenCollectionGroup(null);

    // removing all participants from CATISSUE_REPORT_PARTICIP_REL other
    // than the selected participant
    final Collection participantColl = reportLoaderQueue.getParticipantCollection();
    final Iterator iter = participantColl.iterator();
    final Set tempColl = new HashSet();
    while (iter.hasNext()) {
      final Participant participant = (Participant) iter.next();
      if (participant.getId().toString().equals(participantIdToAssociate.trim())) {
        tempColl.add(participant);
      }
    }
    reportLoaderQueue.setParticipantCollection(tempColl);

    // Updating the report queue obj
    this.updateReportLoaderQueue(reportLoaderQueue, request);
  }

  /**
   * Associate the existing SCG to the report.
   *
   * @param request : request
   * @param reportQueueId : reportQueueId
   * @param participantIdToAssociate : participantIdToAssociate
   * @param specimenCollGrpId : specimenCollGrpId
   * @throws DAOException : DAOException
   * @throws BizLogicException : BizLogicException
   * @throws UserNotAuthorizedException : UserNotAuthorizedException
   */
  private void associateSCGWithReport(
      HttpServletRequest request,
      String reportQueueId,
      String participantIdToAssociate,
      String specimenCollGrpId)
      throws DAOException, BizLogicException, UserNotAuthorizedException {
    Long cprId = null;
    ReportLoaderQueue reportLoaderQueue = null;
    reportLoaderQueue = Utility.getReportQueueObject(reportQueueId);

    // Changing the status of the report in the queue to NEW
    reportLoaderQueue.setStatus(CaTIESConstants.NEW);

    // Associating the SCG
    if (specimenCollGrpId != null && !specimenCollGrpId.equals("")) {
      SpecimenCollectionGroup scg = null;
      final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
      final ReportLoaderQueueBizLogic reportLoaderQueueBizLogic =
          (ReportLoaderQueueBizLogic) factory.getBizLogic(ReportLoaderQueue.class.getName());
      final Object object =
          reportLoaderQueueBizLogic.retrieve(
              SpecimenCollectionGroup.class.getName(), new Long(specimenCollGrpId));
      if (object != null) {
        scg = (SpecimenCollectionGroup) object;
      }
      cprId = scg.getCollectionProtocolRegistration().getId();
      reportLoaderQueue.setSpecimenCollectionGroup(scg);
    }

    // Retrieving participantID if it is null
    if (participantIdToAssociate == null || participantIdToAssociate.equals("")) {
      final DefaultBizLogic defaultBizLogic = new DefaultBizLogic();
      final Long partID =
          (Long)
              defaultBizLogic.retrieveAttribute(
                  CollectionProtocolRegistration.class.getName(),
                  cprId,
                  Constants.COLUMN_NAME_PARTICIPANT_ID);
      participantIdToAssociate = partID.toString();
    }

    // removing all participants from CATISSUE_REPORT_PARTICIP_REL other
    // than the selected participant
    final Collection participantColl = reportLoaderQueue.getParticipantCollection();
    final Iterator iter = participantColl.iterator();
    final Set tempColl = new HashSet();
    Participant participant = null;
    while (iter.hasNext()) {
      participant = (Participant) iter.next();
      if (participant.getId().toString().equals(participantIdToAssociate.trim())) {
        tempColl.add(participant);
      }
    }
    reportLoaderQueue.setParticipantCollection(tempColl);

    // Updating the report queue obj
    this.updateReportLoaderQueue(reportLoaderQueue, request);
  }

  /**
   * updating the reportloaderQueue obj.
   *
   * @param reportLoaderQueue : reportLoaderQueue
   * @param request : request
   */
  private void updateReportLoaderQueue(
      ReportLoaderQueue reportLoaderQueue, HttpServletRequest request) {

    try {
      final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
      final ReportLoaderQueueBizLogic reportLoaderQueueBizLogic =
          (ReportLoaderQueueBizLogic) factory.getBizLogic(ReportLoaderQueue.class.getName());
      reportLoaderQueueBizLogic.update(
          reportLoaderQueue, reportLoaderQueue, 0, this.getSessionData(request));

    } catch (final Exception e) {
      this.logger.error("Error Updating ReportQueue" + e);
    }
  }

  /**
   * @param request : request
   * @return SessionDataBean : SessionDataBean
   */
  @Override
  protected SessionDataBean getSessionData(HttpServletRequest request) {
    Object obj = request.getSession().getAttribute(Constants.SESSION_DATA);
    /** This if loop is specific to Password Security feature. */
    if (obj == null) {
      obj = request.getSession().getAttribute(Constants.TEMP_SESSION_DATA);
    }
    if (obj != null) {
      final SessionDataBean sessionData = (SessionDataBean) obj;
      return sessionData;
    }
    return null;
  }

  /**
   * To generate the errors.
   *
   * @param request : request
   * @param errorMessage : errorMessage
   */
  private void setActionError(HttpServletRequest request, String errorMessage) {
    final ActionErrors errors = new ActionErrors();
    final ActionError error = new ActionError("errors.item", errorMessage);
    errors.add(ActionErrors.GLOBAL_ERROR, error);
    this.saveErrors(request, errors);
  }

  /** @param session : session */
  protected void resetSessionAttributes(HttpSession session) {
    // Removing the session objects
    session.removeAttribute(Constants.PARTICIPANT_ID_TO_ASSOCIATE);
    session.removeAttribute(Constants.SCG_ID_TO_ASSOCIATE);
  }

  /**
   * Ignore the new report and use the existing one.
   *
   * @param reportQueueId : reportQueueId
   * @throws DAOException : DAOException
   * @throws UserNotAuthorizedException : UserNotAuthorizedException
   * @throws BizLogicException : BizLogicException
   */
  protected void ignoreNewReport(String reportQueueId)
      throws DAOException, UserNotAuthorizedException, BizLogicException {
    // Long cprId = null;
    ReportLoaderQueue reportLoaderQueue = null;
    reportLoaderQueue = Utility.getReportQueueObject(reportQueueId);
    final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
    final ReportLoaderQueueBizLogic reportLoaderQueueBizLogic =
        (ReportLoaderQueueBizLogic) factory.getBizLogic(ReportLoaderQueue.class.getName());

    // deleting the reportloaderQueue object
    reportLoaderQueueBizLogic.delete(reportLoaderQueue, 0);
  }

  /**
   * To overwrite the existing report.
   *
   * @param request : request
   * @param reportQueueId : reportQueueId
   * @throws BizLogicException : BizLogicException
   * @throws NumberFormatException : NumberFormatException
   * @throws BizLogicException : BizLogicException
   */
  protected void overwriteReport(HttpServletRequest request, String reportQueueId)
      throws NumberFormatException, BizLogicException {
    ReportLoaderQueue reportLoaderQueue = null;
    reportLoaderQueue = Utility.getReportQueueObject(reportQueueId);

    // Changing the status of the report in the queue to NEW
    reportLoaderQueue.setStatus(CaTIESConstants.OVERWRITE_REPORT);
    this.updateReportLoaderQueue(reportLoaderQueue, request);
  }
}
/**
 * This panel is a container panel for all different panel in simple view of search results. This
 * panel has a bread crumb panel for easy navigation.
 *
 * @author chetan_bh
 */
public class SimpleSearchResultBreadCrumbPanel extends Cab2bPanel {
  private static final Logger logger =
      edu.wustl.common.util.logger.Logger.getLogger(SimpleSearchResultBreadCrumbPanel.class);

  private static final long serialVersionUID = 1L;

  // private HashMap<String, List<AttributeInterface>> mapResultLabel = new HashMap<String,
  // List<AttributeInterface>>();

  private int panelCount = 0;

  /** A vector of display strings for bread crumbs hyperlink. */
  private Vector<String> m_vBreadCrumbs = new Vector<String>();

  /** The breadcrumPanel common to all cards. */
  private JXPanel m_breadCrumbPanel = null;

  /**
   * The panel will house cards, where each card is a panel depicting some details on the results.
   */
  private JXPanel m_resultsPanel = null;

  /** Action listener for bread crumbs hyperlink. */
  private ActionListener breadCrumbsAL;

  /** Pagination components hyperlinks action listener. */
  private ActionListener hyperlinkAL;

  /** Associated Data hyperlinks action listener; */
  private ActionListener associatedDataAL;

  // private List<AttributeInterface> attributeList = null;

  private ViewSearchResultsPanel viewPanel;

  private String currentBreadCrumbName;

  public SimpleSearchResultBreadCrumbPanel(
      IQueryResult queryResult, ViewSearchResultsPanel viewPanel) {
    this.viewPanel = viewPanel;
    initData();
    initGUI(queryResult);
  }

  /** Initialize data. */
  private void initData() {}

  public void addPanel(JXPanel panel, String panelName) {
    this.m_resultsPanel.add(panel, panelName);
  }

  /** Shows a panel represented by a name, by bringing that panel to the top. */
  private void showPanel(String panelName) {
    logger.debug("panel name : " + panelName);
    CardLayout layout = (CardLayout) this.m_resultsPanel.getLayout();
    layout.show(this.m_resultsPanel, panelName);
    int totalCardPanels = m_resultsPanel.getComponentCount();
    /** have to add My Data list summary panel */
    for (int i = 0; i < totalCardPanels; i++) {
      Component comp = m_resultsPanel.getComponent(i);
      if (true == comp.isVisible()) {
        if (comp instanceof ViewSearchResultsSimplePanel) {
          ViewSearchResultsSimplePanel showingPanel =
              (ViewSearchResultsSimplePanel) m_resultsPanel.getComponent(i);
          showingPanel.addDataSummaryPanel();
          break;
        } else if (comp instanceof ResultObjectDetailsPanel) {
          ResultObjectDetailsPanel showingPanel =
              (ResultObjectDetailsPanel) m_resultsPanel.getComponent(i);
          showingPanel.addDataSummaryPanel();
          break;
        }
      }
    }
  }

  /** Addes a new panel to the top of the stack of existing breadcrumbs panels. */
  private void addBreadCrumbPanel(JXPanel panel, String panelName) {
    this.m_breadCrumbPanel.add(panel, panelName);
  }

  /** @see showPanel(String panelName) */
  private void showBreadcrumbPanel(String panelName) {
    CardLayout layout = (CardLayout) this.m_breadCrumbPanel.getLayout();
    layout.show(this.m_breadCrumbPanel, panelName);
  }

  /**
   * Initialize GUI.
   *
   * @param queryResult
   */
  private void initGUI(IQueryResult queryResult) {
    this.setLayout(new RiverLayout(5, 5));
    currentBreadCrumbName = null;

    breadCrumbsAL = new BreadCrumbActionListener(this);
    hyperlinkAL = new HyperlinlActionListener(this);
    associatedDataAL = new AssociatedDataActionListener(this);

    /*
     * The breadcrumb panel should be common to all cards, and hence should
     * not be part of any card.
     */
    String key =
        this.panelCount
            + "#"
            + edu.wustl.cab2b.common.util.Utility.getDisplayName(queryResult.getOutputEntity());
    this.m_vBreadCrumbs.add(key);

    this.m_breadCrumbPanel = new Cab2bPanel();
    this.m_breadCrumbPanel.setLayout(new CardLayout());
    BreadcrumbPanel breadCrumbPanel =
        new BreadcrumbPanel(breadCrumbsAL, m_vBreadCrumbs, this.viewPanel);
    currentBreadCrumbName = breadCrumbPanel.getCurrentBreadCrumbName();
    this.m_breadCrumbPanel.add(breadCrumbPanel, "" + this.panelCount);

    // Check if you got only one record
    JXPanel simpleSearchResultPanel =
        ResultPanelFactory.getResultPanel(this, queryResult, null, null);

    /*
     * Initialize the panel that will house all cards, and add the first
     * card.
     */
    this.m_resultsPanel = new Cab2bPanel();
    this.m_resultsPanel.setLayout(new CardLayout());
    this.m_resultsPanel.add(simpleSearchResultPanel, "" + this.panelCount);

    /* Add the main result panel to the current panel. */
    this.add("hfill", this.m_breadCrumbPanel);
    this.add("br vfill hfill", this.m_resultsPanel);
  }

  /** Gets bread-crumbs hyperlink action listener. */
  private ActionListener getBreadCrumbsAL() {
    return breadCrumbsAL;
  }

  /** Sets bread-crumbs hyperlink action listener. */
  public void setBreadCrumbsAL(ActionListener breadCrumbsAL) {
    this.breadCrumbsAL = breadCrumbsAL;
  }

  /** Gets pagination elements hyperlink action listener. */
  public ActionListener getHyperlinkAL() {
    return hyperlinkAL;
  }

  /** Sets pagination elements hyperlink action listener. */
  public void setHyperlinkAL(ActionListener hyperlinkAL) {
    this.hyperlinkAL = hyperlinkAL;
  }

  /** Gets associated data hyperlink action listener. */
  public ActionListener getAssociatedDataAL() {
    return associatedDataAL;
  }

  /** Sets associated data hyperlinks action listner. */
  public void setAssociatedDataAL(ActionListener associatedDataAL) {
    this.associatedDataAL = associatedDataAL;
  }

  /**
   * This action listener class should take care of creating new/existinf panels in the Card layout.
   *
   * @author chetan_bh
   */
  private class BreadCrumbActionListener implements ActionListener {
    SimpleSearchResultBreadCrumbPanel breadCrumbPanel;

    public BreadCrumbActionListener(SimpleSearchResultBreadCrumbPanel panel) {
      this.breadCrumbPanel = panel;
    }

    public void actionPerformed(ActionEvent evt) {
      logger.debug("bread crumbs ActionListener : " + evt.getActionCommand());
      Cab2bHyperlink hyperlink = (Cab2bHyperlink) evt.getSource();
      /*
       * Get the user object for the hyperlink. This contains the whole
       * string.
       */
      String hyperlinkText = (String) hyperlink.getUserObject();

      int i;
      for (i = 0; i < m_vBreadCrumbs.size(); i++) {
        String breadCrumbValue = (String) m_vBreadCrumbs.get(i);
        if (breadCrumbValue.trim().equals(hyperlinkText.trim())) {
          break;
        }
      }
      panelCount = i++;

      for (int j = i; j < m_vBreadCrumbs.size(); j++) {
        m_vBreadCrumbs.remove(j--);
        m_resultsPanel.remove(i);
      }

      /*
       * Get the number from the hyperlink text and use that to show the
       * panel.
       */
      String strIndex = hyperlinkText.substring(0, hyperlinkText.indexOf('#'));
      breadCrumbPanel.showPanel(strIndex);

      BreadcrumbPanel breadcrumbPanel =
          new BreadcrumbPanel(
              breadCrumbPanel.getBreadCrumbsAL(), m_vBreadCrumbs, this.breadCrumbPanel.viewPanel);
      currentBreadCrumbName = breadcrumbPanel.getCurrentBreadCrumbName();

      this.breadCrumbPanel.addBreadCrumbPanel(breadcrumbPanel, strIndex);
      this.breadCrumbPanel.showBreadcrumbPanel(strIndex);
    }
  }

  /**
   * This action listener class should take care of creating new/existing panels in the Card layout.
   *
   * @author chetan_bh
   */
  private class HyperlinlActionListener implements ActionListener {
    SimpleSearchResultBreadCrumbPanel searchPanel;

    public HyperlinlActionListener(SimpleSearchResultBreadCrumbPanel searchPanel) {
      this.searchPanel = searchPanel;
    }

    public void actionPerformed(ActionEvent evt) {
      Cab2bHyperlink<JPageElement> hyperlink = (Cab2bHyperlink<JPageElement>) evt.getSource();

      String hyperlinkText = hyperlink.getText();
      JPageElement jPageElement = hyperlink.getUserObject();
      PageElement pageElement = jPageElement.getPageElement();

      /* Get the data row corresponding to the clicked element. */
      Vector recordListUserObject = (Vector) pageElement.getUserObject();

      DataRow dataRow = (DataRow) recordListUserObject.get(0);
      IRecord record = (IRecord) recordListUserObject.get(1);

      ViewSearchResultsSimplePanel currentPanel =
          (ViewSearchResultsSimplePanel) m_resultsPanel.getComponent(panelCount);

      /*
       * Refresh the breadcrumb vector, and pass that instance onto a new
       * instance of the breadcrumb panel.
       */
      int currentCount = ++panelCount;

      m_vBreadCrumbs.add(currentCount + "#" + hyperlinkText);
      BreadcrumbPanel breadcrumbPanel =
          new BreadcrumbPanel(getBreadCrumbsAL(), m_vBreadCrumbs, this.searchPanel.viewPanel);
      currentBreadCrumbName = hyperlinkText;

      JXPanel detailsPanel =
          ResultPanelFactory.getSearchResultPanel(
              searchPanel,
              record,
              dataRow,
              currentPanel.getIncomingAssociationCollection(),
              currentPanel.getIntraModelAssociationCollection());

      addBreadCrumbPanel(breadcrumbPanel, "" + currentCount);
      showBreadcrumbPanel("" + currentCount);

      addPanel(detailsPanel, "" + currentCount);
      showPanel("" + currentCount);
    }
  }

  /**
   * This action listener is to handle actions on associated data hyperlinks.
   *
   * @author chetan_bh
   */
  private class AssociatedDataActionListener implements ActionListener {

    private String breadCrumbText;

    SimpleSearchResultBreadCrumbPanel breadCrumbPanel;

    public AssociatedDataActionListener(SimpleSearchResultBreadCrumbPanel panel) {
      this.breadCrumbPanel = panel;
    }

    public void actionPerformed(ActionEvent actionEvent) {
      Cab2bHyperlink hyperlink = (Cab2bHyperlink) actionEvent.getSource();

      /* Get the user object associated with that source. */
      final HyperLinkUserObject hyperLinkUserObject =
          (HyperLinkUserObject) hyperlink.getUserObject();
      IQuery tempQuery = null;

      AbstractAssociatedDataPanel linkContainer =
          (AbstractAssociatedDataPanel) hyperlink.getParent();
      try {
        tempQuery = linkContainer.getQuery((hyperLinkUserObject.getAssociation()));
      } catch (RemoteException e) {
        CommonUtils.handleException(e, breadCrumbPanel, true, true, true, false);
      }
      final IQuery query = tempQuery;
      breadCrumbText = Utility.getDisplayName(hyperLinkUserObject.getTargetEntity());

      /* Get result by executing the Query in a worker thread. */
      CustomSwingWorker swingWorker =
          new CustomSwingWorker((JXPanel) breadCrumbPanel, SimpleSearchResultBreadCrumbPanel.this) {

            IQueryResult queryResult = null;

            protected void doNonUILogic() throws Exception {
              queryResult = CommonUtils.executeQuery((ICab2bQuery) query);
            }

            protected void doUIUpdateLogic() throws RuntimeException {
              /*
               * Get attributes and set in map, for later when the user is
               * navigating, and for now directly set it.
               */
              IAssociation association = hyperLinkUserObject.getAssociation();
              IDataRow parentDataRow = hyperLinkUserObject.getParentDataRow();

              currentBreadCrumbName = breadCrumbText;
              JXPanel resultPanel =
                  ResultPanelFactory.getResultPanel(
                      breadCrumbPanel, queryResult,
                      parentDataRow, association);
              addToPanel(resultPanel, breadCrumbText);
            }
          };
      if (query != null) {
        swingWorker.start();
      } else {
        addToPanel(ResultPanelFactory.getNoResultFoundPopup(breadCrumbText), breadCrumbText);
      }
    }
  }

  /**
   * @param simpleSearchResultPanelNew
   * @param breadCrumbText
   */
  private void addToPanel(JXPanel simpleSearchResultPanelNew, String breadCrumbText) {
    int currentCount = ++panelCount;

    addPanel(simpleSearchResultPanelNew, "" + currentCount);
    showPanel("" + currentCount);

    /*
     * Also we need to refresh the breadcrumb panel,so do the same with the
     * breadcrumb panel.
     */
    m_vBreadCrumbs.add(currentCount + "#" + breadCrumbText);
    BreadcrumbPanel breadcrumbPanel =
        new BreadcrumbPanel(getBreadCrumbsAL(), m_vBreadCrumbs, this.viewPanel);
    currentBreadCrumbName = breadCrumbText;

    addBreadCrumbPanel(breadcrumbPanel, "" + currentCount);
    showBreadcrumbPanel("" + currentCount);
  }

  /** @return the currentBreadCrumbName */
  public String getCurrentBreadCrumbName() {
    return currentBreadCrumbName;
  }
}
Пример #14
0
/** @author mandar_deshmukh Handles attributes associated with a review event of a cell specimen. */
public class CellSpecimenReviewParametersForm extends SpecimenEventParametersForm {

  private static final long serialVersionUID = 1L;
  /** logger Logger - Generic logger. */
  private static Logger logger = Logger.getCommonLogger(CellSpecimenReviewParametersForm.class);

  /** Percentage of histologically evident neoplastic cells present in the specimen. */
  protected String neoplasticCellularityPercentage;

  /** Percentage of viable cells in the specimen. */
  protected String viableCellPercentage;

  /**
   * Returns the percentage of histologically evident neoplastic cells present in the specimen.
   *
   * @return The percentage of histologically evident neoplastic cells present in the specimen.
   * @see #setNeoplasticCellularityPercentage(double)
   */
  public String getNeoplasticCellularityPercentage() {
    return this.neoplasticCellularityPercentage;
  }

  /**
   * Sets the percentage of histologically evident neoplastic cells present in the specimen.
   *
   * @param neoplasticCellularityPercentage the percentage of histologically evident neoplastic
   *     cells present in the specimen.
   * @see #getNeoplasticCellularityPercentage()
   */
  public void setNeoplasticCellularityPercentage(String neoplasticCellularityPercentage) {
    this.neoplasticCellularityPercentage = neoplasticCellularityPercentage;
  }

  /**
   * Returns the percentage of viable cells in the specimen.
   *
   * @return The percentage of viable cells in the specimen.
   * @see #setViableCellPercentage(Double)
   */
  public String getViableCellPercentage() {
    return this.viableCellPercentage;
  }

  /**
   * Sets the percentage of viable cells in the specimen.
   *
   * @param viableCellPercentage the percentage of viable cells in the specimen.
   * @see #getViableCellPercentage()
   */
  public void setViableCellPercentage(String viableCellPercentage) {
    this.viableCellPercentage = viableCellPercentage;
  }

  //	 ----- SUPERCLASS METHODS
  /**
   * @see edu.wustl.catissuecore.actionForm.AbstractActionForm#getFormId()
   * @return CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID
   */
  @Override
  public int getFormId() {
    return Constants.CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID;
  }

  /**
   * @see
   *     edu.wustl.catissuecore.actionForm.AbstractActionForm#setAllValues(edu.wustl.catissuecore.domain.AbstractDomainObject)
   * @param abstractDomain An object of Specimen class.
   */
  @Override
  public void setAllValues(AbstractDomainObject abstractDomain) {
    super.setAllValues(abstractDomain);
    final CellSpecimenReviewParameters cellSpecimenReviewParametersObject =
        (CellSpecimenReviewParameters) abstractDomain;
    this.neoplasticCellularityPercentage =
        CommonUtilities.toString(
            cellSpecimenReviewParametersObject.getNeoplasticCellularityPercentage());
    this.viableCellPercentage =
        CommonUtilities.toString(cellSpecimenReviewParametersObject.getViableCellPercentage());
  }

  /**
   * Overrides the validate method of ActionForm.
   *
   * @return error ActionErrors instance
   * @param mapping Actionmapping instance
   * @param request HttpServletRequest instance
   */
  @Override
  public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    final ActionErrors errors = super.validate(mapping, request);
    final Validator validator = new Validator();

    try {
      // checks the neoplasticCellularityPercentage
      if (!Validator.isEmpty(this.neoplasticCellularityPercentage)
          && !validator.isDouble(this.neoplasticCellularityPercentage, false)) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.format",
                ApplicationProperties.getValue(
                    "cellspecimenreviewparameters.neoplasticcellularitypercentage")));
      }
      // checks the viableCellPercentage
      if (!Validator.isEmpty(this.viableCellPercentage)
          && !validator.isDouble(this.viableCellPercentage, false)) {
        errors.add(
            ActionErrors.GLOBAL_ERROR,
            new ActionError(
                "errors.item.format",
                ApplicationProperties.getValue(
                    "cellspecimenreviewparameters.viablecellpercentage")));
      }
    } catch (final Exception excp) {
      CellSpecimenReviewParametersForm.logger.error(excp.getMessage(), excp);
      excp.printStackTrace();
    }
    return errors;
  }

  /** Method for reset class attributes */
  @Override
  protected void reset() {
    // super.reset();
    //     	this.neoplasticCellularityPercentage = null;
    //     	this.viableCellPercentage = null;
  }

  @Override
  public void setAddNewObjectIdentifier(String arg0, Long arg1) {
    // TODO Auto-generated method stub

  }
}
/**
 * @author ravindra_jain creation date : 14th April, 2008
 * @version 1.0
 */
public final class PrivilegeManager {

  /** logger Logger - Generic logger. */
  private static org.apache.log4j.Logger logger = Logger.getLogger(PrivilegeManager.class);

  /** Singleton instance of PrivilegeCacheManager. */
  private static PrivilegeManager instance = new PrivilegeManager();

  /** the map of login name and corresponding PrivilegeCache. */
  private Map<String, PrivilegeCache> privilegeCaches;
  /** privilegeUtility. */
  private PrivilegeUtility privilegeUtility;
  /** lazyobjs. */
  private List<String> lazyObjects;
  /** classes. */
  private List<String> classes;
  /** eager objects. */
  private List<String> eagerObjects;
  /** isSuccessful false if ant exc occurs at instantiation. */
  private static boolean isSuccessful = true;

  /** private constructor to make the class singleton. */
  private PrivilegeManager() {
    lazyObjects = new ArrayList<String>();
    classes = new ArrayList<String>();
    eagerObjects = new ArrayList<String>();
    privilegeUtility = new PrivilegeUtility();
    privilegeCaches = new HashMap<String, PrivilegeCache>();
    try {
      readXmlFile("CacheableObjects.xml");
    } catch (SMException e) {
      isSuccessful = false;
      logger.error(e.getStackTrace());
    }
  }

  /**
   * return the Singleton PrivilegeCacheManager instance.
   *
   * @throws SMException ex
   * @return PrivilegeManager pManager
   */
  public static PrivilegeManager getInstance() throws SMException {
    if (!isSuccessful) {
      String mess = "error occured in instantiation of PrivilegeManager";
      Utility.getInstance().throwSMException(null, mess, "sm.operation.error");
    }
    return instance;
  }

  /**
   * to return the PrivilegeCache object from the Map of PrivilegeCaches.
   *
   * @param loginName login name
   * @return PrivilegeCache cache
   */
  public PrivilegeCache getPrivilegeCache(String loginName) {
    PrivilegeCache privilegeCache = privilegeCaches.get(loginName);
    if (privilegeCache == null) {
      privilegeCache = new PrivilegeCache(loginName);
      privilegeCaches.put(loginName, privilegeCache);
    }

    return privilegeCache;
  }

  /**
   * To get all PrivilegeCache objects.
   *
   * @return Collection of cache
   */
  public Collection<PrivilegeCache> getPrivilegeCaches() {
    return privilegeCaches.values();
  }

  /**
   * This method will generally be called from CatissueCoreSesssionListener.sessionDestroyed. in
   * order to remove the corresponding PrivilegeCache from the Session.
   *
   * @param userId user id
   */
  public void removePrivilegeCache(String userId) {
    privilegeCaches.remove(userId);
  }

  /**
   * This Utility method is called dynamically as soon as a Site or CollectionProtocol object gets
   * created through the UI & adds detials regarding that object to the PrivilegeCaches of
   * appropriate users in Session.
   *
   * @param objectId id
   * @throws SMException e
   */
  private void addObjectToPrivilegeCaches(String objectId) throws SMException {
    try {
      Collection<PrivilegeCache> listOfPrivCaches = getPrivilegeCaches();
      ProtectionElement protectionElement =
          privilegeUtility.getUserProvisioningManager().getProtectionElement(objectId);
      Collection<ProtectionElement> protElements = new ArrayList<ProtectionElement>();
      protElements.add(protectionElement);

      for (PrivilegeCache privilegeCache : listOfPrivCaches) {
        Collection<ObjectPrivilegeMap> objPrivMapCol =
            privilegeUtility
                .getUserProvisioningManager()
                .getPrivilegeMap(privilegeCache.getLoginName(), protElements);
        if (!objPrivMapCol.isEmpty()) {
          privilegeCache.addObject(objectId, objPrivMapCol.iterator().next().getPrivileges());
        }
      }
    } catch (CSObjectNotFoundException e) {
      Utility.getInstance().throwSMException(e, e.getMessage(), "sm.operation.error");
    } catch (CSException e) {
      Utility.getInstance().throwSMException(e, e.getMessage(), "sm.operation.error");
    }
  }

  /**
   * @param authorizationData data
   * @param protectionObjects protObjs
   * @param dynamicGroups set
   * @param objectId id
   * @throws SMException e
   */
  public void insertAuthorizationData(
      List authorizationData, Set protectionObjects, String[] dynamicGroups, String objectId)
      throws SMException {
    PrivilegeUtility utility = new PrivilegeUtility();
    try {
      utility.insertAuthorizationData(authorizationData, protectionObjects, dynamicGroups);
    } catch (SMException exception) {
      String mess = "Exception in insertAuthorizationData:" + exception;
      Utility.getInstance().throwSMException(exception, mess, "sm.operation.error");
    }
    addObjectToPrivilegeCaches(objectId);
  }

  /**
   * @param fileName name of the file
   * @throws SMException e
   */
  private void readXmlFile(String fileName) throws SMException {
    Document doc = createDoc(fileName);
    if (doc != null) {
      Element root = doc.getDocumentElement();
      getClasses(root);
      getObjects(root);
    }
  }

  /** @param root root */
  private void getObjects(Element root) {
    NodeList nodeList1 = root.getElementsByTagName("ObjectType");

    int length1 = nodeList1.getLength();

    for (int counter = 0; counter < length1; counter++) {
      Element element = (Element) (nodeList1.item(counter));
      String temp = element.getAttribute("pattern");
      String lazily = element.getAttribute("cacheLazily");

      if (lazily.equalsIgnoreCase("false") || lazily.equalsIgnoreCase("")) {
        eagerObjects.add(temp);
      } else {
        lazyObjects.add(temp.replace('*', '_'));
      }
    }
  }

  /** @param root root */
  private void getClasses(Element root) {
    NodeList nodeList = root.getElementsByTagName("Class");

    int length = nodeList.getLength();

    for (int counter = 0; counter < length; counter++) {
      Element element = (Element) (nodeList.item(counter));
      String temp = element.getAttribute("name");
      classes.add(temp);
    }
  }

  /**
   * @param fileName name of the file
   * @throws SMException e
   * @return Doc
   */
  private Document createDoc(String fileName) throws SMException {
    String xmlFileName = fileName;
    Document doc = null;
    InputStream inputXmlFile = this.getClass().getClassLoader().getResourceAsStream(xmlFileName);

    if (inputXmlFile == null) {
      logger.debug("FileNotFound with name : " + fileName);
    } else {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder;
      try {
        builder = factory.newDocumentBuilder();
        doc = builder.parse(inputXmlFile);
      } catch (ParserConfigurationException excp) {
        String mess = "DocumentBuilder cannot be created:";
        Utility.getInstance().throwSMException(excp, mess, "sm.operation.error");
      } catch (SAXException excp) {
        String mess = "Not able to parse xml file:" + fileName;
        Utility.getInstance().throwSMException(excp, mess, "sm.operation.error");
      } catch (IOException excp) {
        String mess = "Not able to parse xml file: IOException" + fileName;
        Utility.getInstance().throwSMException(excp, mess, "sm.operation.error");
      }
    }
    return doc;
  }
  /** @return List of classes */
  public List<String> getClasses() {
    return Collections.unmodifiableList(classes);
  }
  /** @return List of lazy objs */
  public List<String> getLazyObjects() {
    return Collections.unmodifiableList(lazyObjects);
  }
  /** @return List of eager objs */
  public List<String> getEagerObjects() {
    return Collections.unmodifiableList(eagerObjects);
  }

  /**
   * get a set of login names of users having given privilege on given object.
   *
   * @param objectId id
   * @param privilege priv
   * @return Set of users
   * @throws SMException e
   */
  public Set<String> getAccesibleUsers(String objectId, String privilege) throws SMException {
    Set<String> result = new HashSet<String>();
    try {
      UserProvisioningManager userProvManager = privilegeUtility.getUserProvisioningManager();

      List<Group> list = userProvManager.getAccessibleGroups(objectId, privilege);
      if (list != null) {
        for (Group group : list) {
          Set<User> users = userProvManager.getUsers(String.valueOf(group.getGroupId()));
          for (User user : users) {
            result.add(user.getLoginName());
          }
        }
      }
    } catch (CSException excp) {
      String mess = "Not able to get instance of UserProvisioningManager:";
      Utility.getInstance().throwSMException(excp, mess, "sm.operation.error");
    }
    return result;
  }
  /**
   * Creates a ROle object.
   *
   * @param roleName rolename
   * @param privileges set of privileges
   * @throws SMException
   */
  public void createRole(String roleName, Set<String> privileges) throws SMException {
    PrivilegeUtility privilegeUtility = new PrivilegeUtility();
    Role role = null;
    try {
      role = privilegeUtility.getRole(roleName);
    } catch (Exception e) {
      role = new Role();
      role.setName(roleName);
      role.setDesc("Dynamically created role");
      role.setApplication(
          privilegeUtility.getApplication(
              SecurityManagerPropertiesLocator.getInstance().getApplicationCtxName()));
      Set<Privilege> privilegeList = new HashSet<Privilege>();
      try {
        for (String privilegeId : privileges) {
          Privilege privilege =
              privilegeUtility.getUserProvisioningManager().getPrivilegeById(privilegeId);
          privilegeList.add(privilege);
        }
        role.setPrivileges(privilegeList);
        UserProvisioningManager userProvisioningManager =
            privilegeUtility.getUserProvisioningManager();

        userProvisioningManager.createRole(role);
      } catch (CSObjectNotFoundException e1) {
        Utility.getInstance().throwSMException(e1, e1.getMessage(), "sm.operation.error");
      } catch (CSTransactionException e2) {
        Utility.getInstance().throwSMException(e2, e2.getMessage(), "sm.operation.error");
      }
    }
  }
  /**
   * This is a temporary method written for StorageContainer - special case Used for
   * StorageContainerBizLogic.isDeAssignable() method.
   *
   * @param roleId roleid
   * @param objectId obj id
   * @param privilegeName name of the priv
   * @return boolean whether has privilege
   * @throws SMException
   */
  public boolean hasGroupPrivilege(String roleId, String objectId, String privilegeName)
      throws SMException {
    boolean hasPriv = true;
    PrivilegeUtility utility = new PrivilegeUtility();
    String groupId = utility.getGroupIdForRole(roleId);
    Set<User> users;
    try {
      users = utility.getUserProvisioningManager().getUsers(groupId);

      for (User user : users) {
        if (!getPrivilegeCache(user.getLoginName()).hasPrivilege(objectId, privilegeName)) {
          hasPriv = false;
        }
      }
    } catch (CSObjectNotFoundException e) {
      Utility.getInstance().throwSMException(e, e.getMessage(), "sm.operation.error");
    }
    return hasPriv;
  }
}
/**
 * This Class is used to define method for Specimen label printing.
 *
 * @author falguni_sachde
 */
public class SpecimenLabelPrinterImpl implements LabelPrinter {

  /** Generic logger. */
  private final transient Logger logger = Logger.getCommonLogger(SpecimenLabelPrinterImpl.class);

  /**
   * This method prints label.
   *
   * @param abstractDomainObject abstract Domain Object
   * @param ipAddress IP Address
   * @param userObj user Object
   * @param printerType printer Type
   * @param printerLocation printer Location
   * @return true or false status.
   * @see edu.wustl.catissuecore.printserviceclient.LabelPrinter#printLabel
   *     (edu.wustl.common.domain.AbstractDomainObject, java.lang.String,
   *     gov.nih.nci.security.authorization.domainobjects.User)
   */
  public boolean printLabel(
      AbstractDomainObject abstractDomainObject,
      String ipAddress,
      User userObj,
      String printerType,
      String printerLocation) {

    final ArrayList listMap = new ArrayList();
    // createObjectMap(abstractDomainObject,listMap);
    this.createObjectMap(abstractDomainObject, listMap, printerType, printerLocation, ipAddress);
    return callToPrinter(listMap);
  }

  /**
   * This method prints label.
   *
   * @param abstractDomainObjectList abstract Domain Object list.
   * @param ipAddress IP Address
   * @param userObj user Object
   * @param printerType printer Type
   * @param printerLocation printer Location
   * @return true or false status.
   * @see edu.wustl.catissuecore.print.LabelPrinter#printLabel (java.util.List, java.lang.String,
   *     gov.nih.nci.security.authorization.domainobjects.User)
   */
  public boolean printLabel(
      List<AbstractDomainObject> abstractDomainObjectList,
      String ipAddress,
      User userObj,
      String printerType,
      String printerLocation) {
    // Iterate through all objects in List ,crate map of each object.
    final ArrayList listMap = new ArrayList();
    this.createObjectMap(
        abstractDomainObjectList, listMap, printerType, printerLocation, ipAddress);
    return callToPrinter(listMap);
  }

  /**
   * This method will call PrintServiceInputParserInterface for printing.
   *
   * @param listMap List of objects
   * @return boolean
   */
  private boolean callToPrinter(final List listMap) {
    try {
      final PrintServiceInputParserInterface objParser = new PrintServiceInputXMLParser();
      return objParser.callPrintService(listMap);
    } catch (final Exception exp) {
      this.logger.error(exp.getMessage(), exp);
      return false;
    }
  }

  /**
   * This method creates Object Map.
   *
   * @param abstractDomainObjectList abstract Domain Object List
   * @param listMap list Map
   * @param printerType printer Type
   * @param printerLocation printer Location
   * @param ipAddress IP Address
   */
  void createObjectMap(
      List<AbstractDomainObject> abstractDomainObjectList,
      List listMap,
      String printerType,
      String printerLocation,
      String ipAddress) {
    // Bug 11509
    Collections.sort(abstractDomainObjectList, new IdComparator());
    iterateSpecimenList(abstractDomainObjectList, ipAddress, printerType, printerLocation, listMap);
  }

  /**
   * This method adds Data To Print.
   *
   * @param specimen Specimen instance.
   * @param listMap list Map
   * @param printerType printer Type
   * @param printerLocation printer Location
   * @param ipAddress IP Address
   */
  protected void addDataToPrint(
      Specimen specimen,
      List listMap,
      String printerType,
      String printerLocation,
      String ipAddress) {
    final LinkedHashMap dataMap = new LinkedHashMap();
    String label = specimen.getLabel();
    // bug 13100
    // if any property is null the Null pointer exception is thrown while creating
    // string data from Document in getStringFromDocument()
    if (label == null) {
      label = " ";
    }
    String barcode = specimen.getBarcode();
    if (barcode == null) {
      barcode = " ";
    }
    dataMap.put("class", specimen.getClassName());
    dataMap.put("id", specimen.getId().toString());
    dataMap.put("label", label);
    dataMap.put("barcode", barcode);
    dataMap.put("printerType", printerType);
    dataMap.put("printerLocation", printerLocation);
    listMap.add(dataMap);
  }

  /**
   * @param abstractDomainObject Specimen Object
   * @param listMap List of Specimen details including all child specimen.
   * @param printerType printer Type
   * @param printerLocation printer Location
   * @param ipAddress IP Address
   */
  void createObjectMap(
      AbstractDomainObject abstractDomainObject,
      List listMap,
      String printerType,
      String printerLocation,
      String ipAddress) {

    if (abstractDomainObject instanceof Specimen) {

      final Specimen objSpecimen = (Specimen) abstractDomainObject;
      final ArrayList specimenList = new ArrayList();
      specimenList.add(objSpecimen);
      this.getAllSpecimenList(objSpecimen, specimenList);
      // Bug 11509
      Collections.sort(specimenList, new IdComparator());
      for (int cnt = 0; cnt < specimenList.size(); cnt++) {
        final Specimen obj = (Specimen) specimenList.get(cnt);
        this.addDataToPrint(obj, listMap, printerType, printerLocation, ipAddress);
      }
    }
  }

  /**
   * @param objSpecimen Specimen Object
   * @param specimenList List of Specimen including all child specimen.
   */
  void getAllSpecimenList(Specimen objSpecimen, List specimenList) {

    final Collection childSpecimen = objSpecimen.getChildSpecimenCollection();
    if (childSpecimen != null && !childSpecimen.isEmpty()) {

      final Iterator itr = childSpecimen.iterator();
      while (itr.hasNext()) {
        final Specimen specimen = (Specimen) itr.next();
        specimenList.add(specimen);
        this.getAllSpecimenList(specimen, specimenList);
      }
    }
  }

  /**
   * This method prints label.
   *
   * @param abstractDomainObjectList abstract Domain Object list.
   * @param ipAddress IP Address
   * @param userObj user Object
   * @param printerType printer Type
   * @param printerLocation printer Location
   * @param printSpecimanlabel Specimen Label
   * @return true or false status.
   */
  public boolean printLabel(
      List<AbstractDomainObject> abstractDomainObjectList,
      String ipAddress,
      User userObj,
      String printerType,
      String printerLocation,
      String printSpecimanlabel) {
    // Iterate through all objects in List ,crate map of each object.
    final ArrayList listMap = new ArrayList();
    iterateSpecimenList(abstractDomainObjectList, ipAddress, printerType, printerLocation, listMap);
    return callToPrinter(listMap);
  }
  /**
   * This method will iterate over specimen list.
   *
   * @param abstractDomainObjectList Specimen object list
   * @param printerType printer Type
   * @param printerLocation printer Location
   * @param listMap ArrayList
   * @param ipAddress ipAddress of system
   */
  private void iterateSpecimenList(
      List<AbstractDomainObject> abstractDomainObjectList,
      String ipAddress,
      String printerType,
      String printerLocation,
      final List listMap) {
    for (final AbstractDomainObject abstractDomainObject : abstractDomainObjectList) {
      if (abstractDomainObject instanceof Specimen) {
        final Specimen obj = (Specimen) abstractDomainObject;
        this.addDataToPrint(obj, listMap, printerType, printerLocation, ipAddress);
      }
    }
  }
}
Пример #17
0
/**
 * @author kalpana_thakur This class will handle insert/update of all the hashed values as per the
 *     database type.
 */
public class HashedDataHandler {
  /** Class Logger. */
  private static org.apache.log4j.Logger logger = Logger.getLogger(HashedDataHandler.class);

  /**
   * This method returns the metaData associated to the table specified in tableName.
   *
   * @param tableName Name of the table whose metaData is requested
   * @param columnNames Table columns
   * @param jdbcDAO : Database connections to retrieve meta data.
   * @return It will return the metaData associated to the table.
   * @throws DAOException : DAOException
   * @throws SQLException :
   */
  protected final ResultSetMetaData getMetaData(
      String tableName, List<String> columnNames, JDBCDAO jdbcDAO)
      throws DAOException, SQLException {

    ResultSetMetaData metaData;
    StringBuffer sqlBuff = new StringBuffer(DAOConstants.TAILING_SPACES);
    sqlBuff.append("Select").append(DAOConstants.TAILING_SPACES);

    for (int i = 0; i < columnNames.size(); i++) {
      sqlBuff.append(columnNames.get(i));
      if (i != columnNames.size() - 1) {
        sqlBuff.append("  ,");
      }
    }
    sqlBuff.append(" from " + tableName + " where 1!=1");
    metaData = jdbcDAO.getQueryResultSet(sqlBuff.toString()).getMetaData();

    return metaData;
  }

  /**
   * This method will returns the metaData associated to the table specified in tableName and update
   * the list columnNames.
   *
   * @param tableName Name of the table whose metaData is requested
   * @param columnNames Table columns
   * @param jdbcDAO : Database connections to retrieve meta data.
   * @return It will return the metaData associated to the table.
   * @throws DAOException : DAOException
   */
  protected final ResultSetMetaData getMetaDataAndUpdateColumns(
      String tableName, List<String> columnNames, JDBCDAO jdbcDAO) throws DAOException {
    ResultSetMetaData metaData;
    try {

      StringBuffer sqlBuff = new StringBuffer(DAOConstants.TAILING_SPACES);
      sqlBuff.append("Select * from ").append(tableName).append(" where 1!=1");
      metaData = jdbcDAO.getQueryResultSet(sqlBuff.toString()).getMetaData();

      for (int i = 1; i <= metaData.getColumnCount(); i++) {
        columnNames.add(metaData.getColumnName(i));
      }
    } catch (SQLException sqlExp) {
      logger.fatal(sqlExp.getMessage(), sqlExp);
      ErrorKey errorKey = ErrorKey.getErrorKey("db.operation.error");
      throw new DAOException(
          errorKey, sqlExp, "HashedDataHandler.java :" + DAOConstants.RS_METADATA_ERROR);
    }

    return metaData;
  }

  /**
   * This method generates the Insert query.
   *
   * @param tableName : Name of the table given to insert query
   * @param columnNamesList : List of columns of the table.
   * @return query String.
   */
  protected String createInsertQuery(String tableName, List<String> columnNamesList) {
    StringBuffer query = new StringBuffer("INSERT INTO " + tableName + "(");
    StringBuffer colValues = new StringBuffer();
    Iterator<String> columnIterator = columnNamesList.iterator();
    while (columnIterator.hasNext()) {
      query.append(columnIterator.next());
      colValues.append(DAOConstants.INDEX_VALUE_OPERATOR).append(DAOConstants.TAILING_SPACES);
      if (columnIterator.hasNext()) {
        query.append(DAOConstants.SPLIT_OPERATOR).append(DAOConstants.TAILING_SPACES);
        colValues.append(DAOConstants.SPLIT_OPERATOR);
      } else {
        query.append(") values(");
        colValues.append(") ");
        query.append(colValues.toString());
      }
    }

    return query.toString();
  }

  /**
   * @param columnValues :
   * @param metaData :
   * @param stmt :
   * @throws SQLException :
   * @throws DAOException :
   */
  private void setStmtIndexValue(
      List<Object> columnValues, ResultSetMetaData metaData, PreparedStatement stmt)
      throws SQLException, DAOException {
    for (int i = 0; i < columnValues.size(); i++) {
      Object obj = columnValues.get(i);
      int index = i;
      index++;
      if (isDateColumn(metaData, index)) {
        setDateColumns(stmt, index, obj);
        continue;
      }
      if (isTinyIntColumn(metaData, index)) {
        setTinyIntColumns(stmt, index, obj);
        continue;
      }
      /*if(isTimeStampColumn(stmt,i,obj))
      {
      	continue;
      }*/
      if (isNumberColumn(metaData, index)) {
        setNumberColumns(stmt, index, obj);
        continue;
      }
      stmt.setObject(index, obj);
    }
  }

  /**
   * @param metaData :
   * @param index :
   * @return true if column type date.
   * @throws SQLException :Exception
   */
  private boolean isDateColumn(ResultSetMetaData metaData, int index) throws SQLException {
    boolean isDateType = false;
    String type = metaData.getColumnTypeName(index);
    if ("DATE".equals(type)) {
      isDateType = true;
    }
    return isDateType;
  }

  /**
   * @param metaData :
   * @param index :
   * @return true if column type TinyInt.
   * @throws SQLException :Exception
   */
  private boolean isTinyIntColumn(ResultSetMetaData metaData, int index) throws SQLException {
    boolean isTinyIntType = false;
    String type = metaData.getColumnTypeName(index);
    if ("TINYINT".equals(type)) {
      isTinyIntType = true;
    }
    return isTinyIntType;
  }

  /**
   * @param metaData :
   * @param index :
   * @return true if column type is Number.
   * @throws SQLException :Exception
   */
  private boolean isNumberColumn(ResultSetMetaData metaData, int index) throws SQLException {
    boolean isNumberType = false;
    String type = metaData.getColumnTypeName(index);
    if ("NUMBER".equals(type)) {
      isNumberType = true;
    }
    return isNumberType;
  }

  /**
   * This method called to set Number value to PreparedStatement.
   *
   * @param stmt : TODO
   * @param index : TODO
   * @param obj : Object
   * @throws SQLException : SQLException
   */
  protected void setNumberColumns(PreparedStatement stmt, int index, Object obj)
      throws SQLException {
    if (obj != null && obj.toString().equals("##")) {
      stmt.setObject(index, Integer.valueOf(-1));
    } else {
      stmt.setObject(index, obj);
    }
  }

  /**
   * This method called to set TimeStamp value to PreparedStatement.
   *
   * @param stmt :PreparedStatement
   * @param index :
   * @param obj :
   * @return return true if column type is timeStamp.
   * @throws SQLException SQLException
   */
  protected boolean isTimeStampColumn(PreparedStatement stmt, int index, Object obj)
      throws SQLException {
    boolean isTimeStampColumn = false;
    Timestamp date = isColumnValueDate(obj);
    if (date != null) {
      stmt.setObject(index, date);
      isTimeStampColumn = true;
    }
    return isTimeStampColumn;
  }

  /**
   * This method is called to set TinyInt value to prepared statement.
   *
   * @param stmt : TODO
   * @param index :
   * @param obj :
   * @throws SQLException : SQLException
   */
  private void setTinyIntColumns(PreparedStatement stmt, int index, Object obj)
      throws SQLException {
    if (obj != null && (Boolean.parseBoolean(obj.toString()) || obj.equals("1"))) {
      stmt.setObject(index, 1);
    } else {
      stmt.setObject(index, 0);
    }
  }

  /**
   * This method used to set Date values. to prepared statement
   *
   * @param stmt :TODO
   * @param index :
   * @param obj :
   * @throws SQLException : SQLException
   * @throws DAOException : DAOException
   */
  protected void setDateColumns(PreparedStatement stmt, int index, Object obj)
      throws SQLException, DAOException {
    if (obj != null && obj.toString().equals("##")) {
      java.util.Date date = null;
      try {
        date = Utility.parseDate("1-1-9999", "mm-dd-yyyy");
      } catch (ParseException exp) {
        // TODO have to replace this by parse key
        ErrorKey errorKey = ErrorKey.getErrorKey("db.operation.error");
        throw new DAOException(errorKey, exp, "HashedDataHandler.java :");
      }
      Date sqlDate = new Date(date.getTime());
      stmt.setDate(index, sqlDate);
    }
  }

  /**
   * This method checks the TimeStamp value.
   *
   * @param obj :
   * @return It returns the TimeStamp value
   */
  private Timestamp isColumnValueDate(Object obj) {
    Timestamp timestamp = null;
    try {
      DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy", Locale.getDefault());
      formatter.setLenient(false);
      java.util.Date date;
      date = formatter.parse(obj.toString());
      /*
       * Recheck if some issues occurs.
       */
      Timestamp timestampInner = new Timestamp(date.getTime());
      if (obj != null && !DAOConstants.TAILING_SPACES.equals(obj.toString())) {
        timestamp = timestampInner;
      }
    } catch (ParseException parseExp) {
      logger.error(parseExp.getMessage(), parseExp);
    }

    return timestamp;
  }

  /**
   * This method will be called to insert hashed data values.
   *
   * @param tableName :Name of the table
   * @param columnValues :List of column values
   * @param columnNames :List of column names.
   * @param jdbcDAO : Database jdbcDAO
   * @throws DAOException :DAOException
   * @throws SQLException : SQLException
   */
  public void insertHashedValues(
      String tableName, List<Object> columnValues, List<String> columnNames, JDBCDAO jdbcDAO)
      throws DAOException, SQLException {

    List<String> columnNamesList = new ArrayList<String>();
    ResultSetMetaData metaData;

    PreparedStatement stmt = null;
    try {
      if (columnNames != null && !columnNames.isEmpty()) {
        metaData = getMetaData(tableName, columnNames, jdbcDAO);
        columnNamesList = columnNames;
      } else {
        metaData = getMetaDataAndUpdateColumns(tableName, columnNamesList, jdbcDAO);
      }

      String insertQuery = createInsertQuery(tableName, columnNamesList);
      stmt = jdbcDAO.getPreparedStatement(insertQuery);
      setStmtIndexValue(columnValues, metaData, stmt);
      stmt.executeUpdate();
    } catch (SQLException sqlExp) {
      logger.error(sqlExp.getMessage(), sqlExp);
      ErrorKey errorKey = ErrorKey.getErrorKey("db.operation.error");
      throw new DAOException(
          errorKey, sqlExp, "HashedDataHandler.java :" + DAOConstants.INSERT_OBJ_ERROR);
    }
  }
}