private void saveClonedPOCs(SampleBean sampleBean) throws Exception {
   savePointOfContact(sampleBean.getPrimaryPOCBean());
   if (sampleBean.getOtherPOCBeans() != null && !sampleBean.getOtherPOCBeans().isEmpty()) {
     for (PointOfContactBean pocBean : sampleBean.getOtherPOCBeans()) {
       savePointOfContact(pocBean);
     }
   }
 }
 /**
  * Persist a new sample or update an existing canano sample
  *
  * @param sample
  * @throws SampleException , DuplicateEntriesException
  */
 public void saveSample(SampleBean sampleBean)
     throws SampleException, DuplicateEntriesException, NoAccessException {
   if (user == null) {
     throw new NoAccessException();
   }
   Boolean newSample = true;
   if (sampleBean.getDomain().getId() != null) {
     newSample = false;
   }
   Sample sample = sampleBean.getDomain();
   try {
     if (!newSample
         && !securityService.checkCreatePermission(sampleBean.getDomain().getId().toString())) {
       throw new NoAccessException();
     }
     CaNanoLabApplicationService appService =
         (CaNanoLabApplicationService) ApplicationServiceProvider.getApplicationService();
     Sample dbSample = (Sample) appService.getObject(Sample.class, "name", sample.getName());
     if (dbSample != null && !dbSample.getId().equals(sample.getId())) {
       throw new DuplicateEntriesException();
     }
     if (sample.getKeywordCollection() != null) {
       Collection<Keyword> keywords = new HashSet<Keyword>(sample.getKeywordCollection());
       sample.getKeywordCollection().clear();
       for (Keyword keyword : keywords) {
         Keyword dbKeyword =
             (Keyword) appService.getObject(Keyword.class, "name", keyword.getName());
         if (dbKeyword != null) {
           keyword.setId(dbKeyword.getId());
         } else {
           keyword.setId(null);
         }
         // turned off cascade save-update in order to share the same
         // keyword instance with File keywords.
         appService.saveOrUpdate(keyword);
         sample.getKeywordCollection().add(keyword);
       }
     }
     appService.saveOrUpdate(sample);
     // save default access
     if (newSample) {
       super.saveDefaultAccessibilities(sample.getId().toString());
     }
   } catch (NoAccessException e) {
     throw e;
   } catch (DuplicateEntriesException e) {
     throw e;
   } catch (Exception e) {
     String err = "Error in saving the sample";
     logger.error(err, e);
     throw new SampleException(err, e);
   }
 }
 private SampleBean loadSampleBean(Sample sample) throws Exception {
   SampleBean sampleBean = new SampleBean(sample);
   if (user != null) {
     List<AccessibilityBean> groupAccesses =
         super.findGroupAccessibilities(sample.getId().toString());
     List<AccessibilityBean> userAccesses =
         super.findUserAccessibilities(sample.getId().toString());
     sampleBean.setUserAccesses(userAccesses);
     sampleBean.setGroupAccesses(groupAccesses);
     sampleBean.setUser(user);
   }
   return sampleBean;
 }
 private void saveClonedPublications(SampleBean origSampleBean, SampleBean sampleBean)
     throws Exception {
   if (sampleBean.getDomain().getPublicationCollection() != null) {
     for (Publication pub : sampleBean.getDomain().getPublicationCollection()) {
       PublicationBean pubBean = new PublicationBean(pub);
       pubBean.setFromSamplePage(true);
       // don't need to reset sample names because savePublication
       // takes care of empty sample names.
       publicationService.savePublication(pubBean);
       // don't need to save access because the cloned publications
       // shared the same IDs with the source publications
     }
   }
 }
  public void transferSampleBeanForDataAvailability(
      SampleBean sampleBean, HttpServletRequest request, String[] availableEntityNames) {

    if (sampleBean == null) return;

    setSampleName(sampleBean.getDomain().getName());
    setDataAvailability(sampleBean.getDataAvailabilityMetricsScore());

    this.setCaNanoLabScore(sampleBean.getCaNanoLabScore());
    this.setMincharScore(sampleBean.getMincharScore());

    setCaNanoLabScore(sampleBean.getCaNanoLabScore());
    setMincharScore(sampleBean.getMincharScore());

    SortedSet<String> ca =
        (SortedSet<String>) request.getSession().getServletContext().getAttribute("chemicalAssocs");
    setChemicalAssocs(new ArrayList<String>(ca));

    setCaNano2MINChar(
        (Map<String, String>)
            request.getSession().getServletContext().getAttribute("caNano2MINChar"));

    SortedSet<String> pc =
        (SortedSet<String>) request.getSession().getServletContext().getAttribute("physicoChars");
    setPhysicoChars(new ArrayList<String>(pc));
    SortedSet<String> iv =
        (SortedSet<String>) request.getSession().getServletContext().getAttribute("invitroChars");
    setInvitroChars(new ArrayList<String>(iv));
    SortedSet<String> invivo =
        (SortedSet<String>) request.getSession().getServletContext().getAttribute("invivoChars");
    setInvivoChars(new ArrayList<String>(invivo));

    if (availableEntityNames != null)
      this.availableEntityNames = new ArrayList<String>(Arrays.asList(availableEntityNames));

    // setSampleName(sampleBean.getDomain().getName());

    //		SortedSet<String> ca = (SortedSet<String>)
    // request.getSession().getServletContext().getAttribute("chemicalAssocs");
    //		this.chemicalAssocs = SampleUtil.getStringArrayFromSortedSet(ca);
    //				// SampleUtil.getDefaultListFromSessionByType("chemicalAssocs", request.getSession());
    //
    //
    //		this.caNano2MINChar = (Map<String, String>) request.getSession().getServletContext()
    //				.getAttribute("caNano2MINChar");
    //
    //		SortedSet<String> pc = (SortedSet<String>)
    // request.getSession().getServletContext().getAttribute("physicoChars");
    //		this.physicoChars = SampleUtil.getStringArrayFromSortedSet(pc);
    //		SortedSet<String> iv = (SortedSet<String>)
    // request.getSession().getServletContext().getAttribute("invitroChars");
    //		this.invitroChars = SampleUtil.getStringArrayFromSortedSet(iv);
    //		SortedSet<String> invivo = (SortedSet<String>)
    // request.getSession().getServletContext().getAttribute("invivoChars");
    //		this.invivoChars = SampleUtil.getStringArrayFromSortedSet(invivo);
    //

  }
 private void saveClonedCharacterizations(String origSampleName, SampleBean sampleBean)
     throws Exception {
   if (sampleBean.getDomain().getCharacterizationCollection() != null) {
     String newSampleName = sampleBean.getDomain().getName();
     for (Characterization achar : sampleBean.getDomain().getCharacterizationCollection()) {
       CharacterizationBean charBean = new CharacterizationBean(achar);
       if (charBean.getExperimentConfigs() != null) {
         for (ExperimentConfigBean configBean : charBean.getExperimentConfigs()) {
           charService.saveExperimentConfig(configBean);
         }
       }
       if (charBean.getFindings() != null) {
         for (FindingBean findingBean : charBean.getFindings()) {
           for (FileBean fileBean : findingBean.getFiles()) {
             fileUtils.updateClonedFileInfo(fileBean, origSampleName, newSampleName);
           }
           charService.saveFinding(findingBean);
         }
       }
       charService.saveCharacterization(sampleBean, charBean);
     }
   }
 }
  private void saveClonedComposition(SampleBean origSampleBean, SampleBean sampleBean)
      throws Exception {
    String origSampleName = origSampleBean.getDomain().getName();
    String newSampleName = sampleBean.getDomain().getName();

    if (sampleBean.getDomain().getSampleComposition() != null) {
      // save files
      if (sampleBean.getDomain().getSampleComposition().getFileCollection() != null) {
        for (File file : sampleBean.getDomain().getSampleComposition().getFileCollection()) {
          FileBean fileBean = new FileBean(file);
          fileUtils.updateClonedFileInfo(fileBean, origSampleName, newSampleName);
          compService.saveCompositionFile(sampleBean, fileBean);
        }
      }

      // save nanomaterial entities
      if (sampleBean.getDomain().getSampleComposition().getNanomaterialEntityCollection() != null) {
        for (NanomaterialEntity entity :
            sampleBean.getDomain().getSampleComposition().getNanomaterialEntityCollection()) {
          NanomaterialEntityBean entityBean = new NanomaterialEntityBean(entity);
          for (FileBean fileBean : entityBean.getFiles()) {
            fileUtils.updateClonedFileInfo(fileBean, origSampleName, newSampleName);
          }
          compService.saveNanomaterialEntity(sampleBean, entityBean);
        }
      }
      // save functionalizing entities
      if (sampleBean.getDomain().getSampleComposition().getFunctionalizingEntityCollection()
          != null) {
        for (FunctionalizingEntity entity :
            sampleBean.getDomain().getSampleComposition().getFunctionalizingEntityCollection()) {
          FunctionalizingEntityBean entityBean = new FunctionalizingEntityBean(entity);
          for (FileBean fileBean : entityBean.getFiles()) {
            fileUtils.updateClonedFileInfo(fileBean, origSampleName, newSampleName);
          }
          compService.saveFunctionalizingEntity(sampleBean, entityBean);
        }
      }
      // save chemical association
      if (sampleBean.getDomain().getSampleComposition().getChemicalAssociationCollection()
          != null) {
        for (ChemicalAssociation assoc :
            sampleBean.getDomain().getSampleComposition().getChemicalAssociationCollection()) {
          ChemicalAssociationBean assocBean = new ChemicalAssociationBean(assoc);
          // set the correct IDs for associated elements
          updateAssociatedElementId(
              sampleBean.getDomain().getSampleComposition(), assoc.getAssociatedElementA());
          updateAssociatedElementId(
              sampleBean.getDomain().getSampleComposition(), assoc.getAssociatedElementB());
          for (FileBean fileBean : assocBean.getFiles()) {
            fileUtils.updateClonedFileInfo(fileBean, origSampleName, newSampleName);
          }
          compService.saveChemicalAssociation(sampleBean, assocBean);
        }
      }
    }
  }
  public SampleBean cloneSample(String originalSampleName, String newSampleName)
      throws SampleException, NoAccessException, DuplicateEntriesException, NotExistException {
    if (user == null) {
      throw new NoAccessException();
    }
    SampleBean newSampleBean = null;
    Sample origSample = null;
    SampleBean origSampleBean = null;
    Sample newSample0 = new Sample();
    try {
      CaNanoLabApplicationService appService =
          (CaNanoLabApplicationService) ApplicationServiceProvider.getApplicationService();
      Sample dbNewSample = (Sample) appService.getObject(Sample.class, "name", newSampleName);
      if (dbNewSample != null) {
        throw new DuplicateEntriesException();
      }
      // fully load original sample
      origSample = findFullyLoadedSampleByName(originalSampleName);
      origSampleBean = new SampleBean(origSample);
      newSample0.setName(newSampleName);
      newSample0.setCreatedBy(user.getLoginName() + ":" + Constants.AUTO_COPY_ANNOTATION_PREFIX);
      newSample0.setCreatedDate(new Date());
      // save the sample so later up just update the cloned the
      // associations.
      SampleBean newSampleBean0 = new SampleBean(newSample0);
      // save the sample to get an ID before saving associations
      saveSample(newSampleBean0);
    } catch (NotExistException e) {
      throw e;
    } catch (DuplicateEntriesException e) {
      throw e;
    } catch (Exception e) {
      String err = "Error in loading the original sample " + originalSampleName;
      logger.error(err, e);
      throw new SampleException(err, e);
    }
    try {
      // clone the sample
      Sample newSample = origSampleBean.getDomainCopy(user.getLoginName());
      newSample.setName(newSampleName);
      // keep the id
      newSample.setId(newSample0.getId());
      newSampleBean = new SampleBean(newSample);

      // retrieve accessibilities of the original sample
      List<AccessibilityBean> groupAccesses =
          super.findGroupAccessibilities(origSample.getId().toString());
      List<AccessibilityBean> userAccesses =
          super.findUserAccessibilities(origSample.getId().toString());
      origSampleBean.setGroupAccesses(groupAccesses);
      origSampleBean.setUserAccesses(userAccesses);

      // need to save associations one by one (except keywords)
      // Hibernate mapping settings for most use cases
      saveClonedPOCs(newSampleBean);
      saveClonedCharacterizations(origSample.getName(), newSampleBean);
      saveClonedComposition(origSampleBean, newSampleBean);
      saveClonedPublications(origSampleBean, newSampleBean);
      saveSample(newSampleBean);
      newSampleBean.setUser(user);
      // assign accessibility for the new sample
      for (AccessibilityBean access : origSampleBean.getAllAccesses()) {
        this.assignAccessibility(access, newSampleBean.getDomain());
      }
    } catch (Exception e) {
      // delete the already persisted new sample in case of error
      try {
        this.deleteSampleWhenError(newSample0.getName());
      } catch (Exception ex) {
        String err = "Error in deleting the errored cloned-sample " + newSample0.getName();
        logger.error(err, e);
        throw new SampleException(err, ex);
      }
      String err = "Error in cloning the sample " + originalSampleName;
      logger.error(err, e);
      throw new SampleException(err, e);
    }
    return newSampleBean;
  }