public List<String> removeAccesses(Sample sample, Boolean removeLater)
     throws SampleException, NoAccessException {
   List<String> ids = new ArrayList<String>();
   try {
     if (!securityService.checkCreatePermission(sample.getId().toString())) {
       throw new NoAccessException();
     }
     ids.add(sample.getId().toString());
     // fully load sample
     Sample fullSample = this.findFullyLoadedSampleByName(sample.getName());
     // find sample accesses
     List<AccessibilityBean> sampleAccesses = super.findSampleAccesses(sample.getId().toString());
     for (AccessibilityBean access : sampleAccesses) {
       if (fullSample.getCharacterizationCollection() != null) {
         for (Characterization achar : fullSample.getCharacterizationCollection()) {
           ids.addAll(accessUtils.removeAccessibility(access, achar, removeLater));
         }
       }
       if (fullSample.getSampleComposition() != null) {
         ids.addAll(
             accessUtils.removeAccessibility(
                 access, fullSample.getSampleComposition(), removeLater));
       }
     }
   } catch (NoAccessException e) {
     throw e;
   } catch (Exception e) {
     String error = "Error in removing sample accesses";
     throw new SampleException(error, e);
   }
   return ids;
 }
 public void loadAccessesForBasicSampleBean(SampleBasicBean sampleBean) throws Exception {
   Sample sample = sampleBean.getDomain();
   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);
   }
 }
 /**
  * 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 deleteSampleWhenError(String sampleName) throws Exception {
    Sample sample = this.findFullyLoadedSampleByName(sampleName);
    CaNanoLabApplicationService appService =
        (CaNanoLabApplicationService) ApplicationServiceProvider.getApplicationService();
    // delete characterizations
    if (sample.getCharacterizationCollection() != null) {
      for (Characterization achar : sample.getCharacterizationCollection()) {
        charService.deleteCharacterization(achar);
      }
    }

    // delete composition
    if (sample.getSampleComposition() != null) {
      compService.deleteComposition(sample.getSampleComposition());
    }
    sample.setSampleComposition(null);

    // remove publication associations
    if (sample.getPublicationCollection() != null) {
      sample.setPublicationCollection(null);
    }
    // remove keyword associations
    if (sample.getKeywordCollection() != null) {
      sample.setKeywordCollection(null);
    }
    appService.saveOrUpdate(sample);
    appService.delete(sample);
    // remove all csm entries associated with sample
    this.accessUtils.removeCSMEntries(sample.getId().toString());
  }
 public void removeAccessibility(AccessibilityBean access, Sample sample)
     throws SampleException, NoAccessException {
   if (!isOwnerByCreatedBy(sample.getCreatedBy())) {
     throw new NoAccessException();
   }
   String sampleId = sample.getId().toString();
   try {
     super.deleteAccessibility(access, sampleId);
     // fully load sample
     sample = this.findFullyLoadedSampleByName(sample.getName());
     // keep POC public
     // remove characterization accessibility
     if (sample.getCharacterizationCollection() != null) {
       for (Characterization achar : sample.getCharacterizationCollection()) {
         accessUtils.removeAccessibility(access, achar, false);
       }
     }
     // remove composition accessibility
     if (sample.getSampleComposition() != null) {
       accessUtils.removeAccessibility(access, sample.getSampleComposition(), false);
     }
   } catch (NoAccessException e) {
     throw e;
   } catch (Exception e) {
     String err = "Error in deleting the access for sample " + sampleId;
     logger.error(err, e);
     throw new SampleException(err, e);
   }
 }
  private SampleBasicBean loadSampleBean(Sample sample, boolean checkReadPermission)
      throws Exception {
    SampleBasicBean sampleBean = new SampleBasicBean(sample);
    if (user != null) {
      logger.debug("=== Loading group accesses");
      List<AccessibilityBean> groupAccesses =
          super.findGroupAccessibilities(sample.getId().toString(), checkReadPermission);
      logger.debug("=== Done Loading group accesses");

      logger.debug("=== Loading user accesses");
      List<AccessibilityBean> userAccesses =
          super.findUserAccessibilities(sample.getId().toString(), checkReadPermission);
      logger.debug("=== Done Loading user accesses");
      sampleBean.setUserAccesses(userAccesses);
      sampleBean.setGroupAccesses(groupAccesses);
      sampleBean.setUser(user);
    }
    return sampleBean;
  }
  private Sample findFullyLoadedSampleByName(String sampleName) throws Exception {
    CaNanoLabApplicationService appService =
        (CaNanoLabApplicationService) ApplicationServiceProvider.getApplicationService();
    // load composition and characterization separate because of Hibernate
    // join limitation
    DetachedCriteria crit =
        DetachedCriteria.forClass(Sample.class)
            .add(Property.forName("name").eq(sampleName).ignoreCase());
    Sample sample = null;

    // load composition and characterization separate because of
    // Hibernate join limitation
    crit.setFetchMode("primaryPointOfContact", FetchMode.JOIN);
    crit.setFetchMode("primaryPointOfContact.organization", FetchMode.JOIN);
    crit.setFetchMode("otherPointOfContactCollection", FetchMode.JOIN);
    crit.setFetchMode("otherPointOfContactCollection.organization", FetchMode.JOIN);
    crit.setFetchMode("keywordCollection", FetchMode.JOIN);
    crit.setFetchMode("publicationCollection", FetchMode.JOIN);
    crit.setFetchMode("publicationCollection.authorCollection", FetchMode.JOIN);
    crit.setFetchMode("publicationCollection.keywordCollection", FetchMode.JOIN);
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    List result = appService.query(crit);
    if (!result.isEmpty()) {
      sample = (Sample) result.get(0);
    }
    if (sample == null) {
      throw new NotExistException("Sample doesn't exist in the database");
    }

    // fully load composition
    SampleComposition comp = this.loadComposition(sample.getId().toString());
    sample.setSampleComposition(comp);

    // fully load characterizations
    List<Characterization> chars = this.loadCharacterizations(sample.getId().toString());
    if (chars != null && !chars.isEmpty()) {
      sample.setCharacterizationCollection(new HashSet<Characterization>(chars));
    } else {
      sample.setCharacterizationCollection(null);
    }
    return sample;
  }
  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;
  }
  public void assignAccessibility(AccessibilityBean access, Sample sample)
      throws SampleException, NoAccessException {
    if (!isOwnerByCreatedBy(sample.getCreatedBy())) {
      throw new NoAccessException();
    }
    String sampleId = sample.getId().toString();
    try {
      if (!isOwnerByCreatedBy(sample.getCreatedBy())) {
        throw new NoAccessException();
      }
      // get existing accessibilities
      List<AccessibilityBean> groupAccesses = this.findGroupAccessibilities(sampleId);
      List<AccessibilityBean> userAccesses = this.findUserAccessibilities(sampleId);

      // if access is Public, remove all other access except Public
      // Curator and owner
      if (access.getGroupName().equals(AccessibilityBean.CSM_PUBLIC_GROUP)) {
        for (AccessibilityBean acc : groupAccesses) {
          // remove group accesses that are not public or curator
          if (!acc.getGroupName().equals(AccessibilityBean.CSM_PUBLIC_GROUP)
              && !acc.getGroupName().equals((AccessibilityBean.CSM_DATA_CURATOR))) {
            this.removeAccessibility(acc, sample);
          }
        }
        SecuredDataBean securedDataBean = new SecuredDataBean();
        for (AccessibilityBean acc : userAccesses) {
          // remove accesses that are not owner
          if (!securedDataBean.retrieveUserIsOwner(acc.getUserBean(), sample.getCreatedBy())) {
            this.removeAccessibility(acc, sample);
          }
        }
      }
      // if sample is already public, retract from public
      else {
        if (groupAccesses.contains(AccessibilityBean.CSM_PUBLIC_ACCESS)) {
          this.removeAccessibility(AccessibilityBean.CSM_PUBLIC_ACCESS, sample);
        }
      }
      super.saveAccessibility(access, sampleId);

      // fully load sample
      sample = this.findFullyLoadedSampleByName(sample.getName());
      // assign POC to public is handled when adding POC
      // TODO check this logic when working with COPPA on organization

      // assign characterization accessibility
      if (sample.getCharacterizationCollection() != null) {
        for (Characterization achar : sample.getCharacterizationCollection()) {
          accessUtils.assignAccessibility(access, achar);
        }
      }
      // assign composition accessibility
      if (sample.getSampleComposition() != null) {
        accessUtils.assignAccessibility(access, sample.getSampleComposition());
      }
    } catch (NoAccessException e) {
      throw e;
    } catch (Exception e) {
      String err = "Error in assigning accessibility to the sample " + sampleId;
      logger.error(err, e);
      throw new SampleException(err, e);
    }
  }