private PrivateInstanceLocal getPrivateInstance(
     InstanceLocal instance, int type, PrivateSeriesLocal privSeries)
     throws FinderException, CreateException {
   Collection col = privInstHome.findBySopIuid(type, instance.getSopIuid());
   PrivateInstanceLocal privInstance;
   if (col.isEmpty()) {
     if (privSeries == null) {
       privSeries = getPrivateSeries(instance.getSeries(), type, null, false);
     }
     privInstance = privInstHome.create(type, instance.getAttributes(true), privSeries);
   } else {
     privInstance = (PrivateInstanceLocal) col.iterator().next();
   }
   Object[] files = instance.getFiles().toArray();
   FileLocal file;
   for (int i = 0; i < files.length; i++) {
     file = (FileLocal) files[i];
     privFileHome.create(
         file.getFilePath(),
         file.getFileTsuid(),
         file.getFileSize(),
         file.getFileMd5(),
         file.getFileStatus(),
         privInstance,
         file.getFileSystem());
     try {
       file.remove();
     } catch (Exception x) {
       log.warn("Can not remove File record:" + file, x);
     }
   }
   return privInstance;
 }
  /**
   * Delete a list of instances, i.e., move them to trash bin
   *
   * @ejb.interface-method
   * @param iuids A list of instance uid
   * @param cascading True to delete the series/study if there's no instance/series
   * @return a collection of Dataset containing the actuall detetion information per study
   * @throws RemoteException
   */
  public Collection moveInstancesToTrash(String[] iuids, boolean cascading) throws RemoteException {
    try {
      // These instances may belong to multiple studies,
      // although mostly they should be the same study
      Map mapStudies = new HashMap();
      for (int i = 0; i < iuids.length; i++) {
        InstanceLocal instance = instHome.findBySopIuid(iuids[i]);
        SeriesLocal series = instance.getSeries();
        StudyLocal study = series.getStudy();
        if (!mapStudies.containsKey(study)) mapStudies.put(study, new HashMap());
        Map mapSeries = (Map) mapStudies.get(study);
        if (!mapSeries.containsKey(series)) mapSeries.put(series, new ArrayList());
        Collection colInstances = (Collection) mapSeries.get(series);
        colInstances.add(instance);
      }

      List dss = new ArrayList();
      Iterator iter = mapStudies.keySet().iterator();
      while (iter.hasNext()) {
        StudyLocal study = (StudyLocal) iter.next();
        dss.add(getStudyMgtDataset(study, (Map) mapStudies.get(study)));
        Iterator iter2 = ((Map) mapStudies.get(study)).keySet().iterator();
        while (iter2.hasNext()) {
          SeriesLocal series = (SeriesLocal) iter2.next();
          List instances = (List) ((Map) mapStudies.get(study)).get(series);
          for (int i = 0; i < instances.size(); i++) {
            // Delete the instance now, i.e., move to trash bin,
            // becoming private instance
            getPrivateInstance((InstanceLocal) instances.get(i), DELETED, null);
            ((InstanceLocal) instances.get(i)).remove();
          }
          if (series.getInstances().size() == 0 && cascading) {
            // Delete the series too since there's no instance left
            getPrivateSeries(series, DELETED, null, false);
            series.remove();
          } else UpdateDerivedFieldsUtils.updateDerivedFieldsOf(series);
        }
        if (study.getSeries().size() == 0 && cascading) {
          // Delete the study too since there's no series left
          getPrivateStudy(study, DELETED, null, false);
          study.remove();
        } else UpdateDerivedFieldsUtils.updateDerivedFieldsOf(study);
      }

      return dss;
    } catch (CreateException e) {
      throw new RemoteException(e.getMessage());
    } catch (EJBException e) {
      throw new RemoteException(e.getMessage());
    } catch (FinderException e) {
      throw new RemoteException(e.getMessage());
    } catch (RemoveException e) {
      throw new RemoteException(e.getMessage());
    }
  }
  private Dataset getStudyMgtDataset(StudyLocal study, Map mapSeries) {
    Dataset ds = dof.newDataset();
    ds.putUI(Tags.StudyInstanceUID, study.getStudyIuid());
    ds.putOB(PrivateTags.StudyPk, Convert.toBytes(study.getPk().longValue()));
    ds.putSH(Tags.AccessionNumber, study.getAccessionNumber());
    ds.putLO(Tags.PatientID, study.getPatient().getPatientId());
    ds.putLO(Tags.IssuerOfPatientID, study.getPatient().getIssuerOfPatientId());
    ds.putPN(Tags.PatientName, study.getPatient().getPatientName());

    log.debug("getStudyMgtDataset: studyIUID:" + study.getStudyIuid());
    DcmElement refSeriesSeq = ds.putSQ(Tags.RefSeriesSeq);

    Iterator iter =
        (mapSeries == null) ? study.getSeries().iterator() : mapSeries.keySet().iterator();
    while (iter.hasNext()) {
      SeriesLocal sl = (SeriesLocal) iter.next();
      Dataset dsSer = refSeriesSeq.addNewItem();
      dsSer.putUI(Tags.SeriesInstanceUID, sl.getSeriesIuid());
      Collection instances =
          (mapSeries == null) ? sl.getInstances() : (Collection) mapSeries.get(sl);
      Iterator iter2 = instances.iterator();
      DcmElement refSopSeq = null;
      if (iter2.hasNext()) refSopSeq = dsSer.putSQ(Tags.RefSOPSeq);
      while (iter2.hasNext()) {
        InstanceLocal il = (InstanceLocal) iter2.next();
        Dataset dsInst = refSopSeq.addNewItem();
        dsInst.putUI(Tags.RefSOPClassUID, il.getSopCuid());
        dsInst.putUI(Tags.RefSOPInstanceUID, il.getSopIuid());
        dsInst.putAE(Tags.RetrieveAET, il.getRetrieveAETs());
      }
    }
    if (log.isDebugEnabled()) {
      log.debug("return StgMgtDataset:");
      log.debug(ds);
    }
    return ds;
  }
 /** @ejb.interface-method */
 public Dataset moveInstanceToTrash(long instance_pk) throws RemoteException {
   try {
     InstanceLocal instance = instHome.findByPrimaryKey(new Long(instance_pk));
     Collection colInstance = new ArrayList();
     colInstance.add(instance);
     SeriesLocal series = instance.getSeries();
     Map mapSeries = new HashMap();
     mapSeries.put(series, colInstance);
     Dataset ds = getStudyMgtDataset(series.getStudy(), mapSeries);
     getPrivateInstance(instance, DELETED, null);
     instance.remove();
     UpdateDerivedFieldsUtils.updateDerivedFieldsOf(series);
     UpdateDerivedFieldsUtils.updateDerivedFieldsOf(series.getStudy());
     return ds;
   } catch (CreateException e) {
     throw new RemoteException(e.getMessage());
   } catch (EJBException e) {
     throw new RemoteException(e.getMessage());
   } catch (FinderException e) {
     throw new RemoteException(e.getMessage());
   } catch (RemoveException e) {
     throw new RemoteException(e.getMessage());
   }
 }