예제 #1
0
 protected void ensureContentAvailable() {
   if (!isContentAvailable()) {
     DicomInputStream dis = null;
     try {
       List<org.dcm4chee.archive.entity.File> files =
           ((TCQueryLocal) JNDIUtils.lookup(TCQueryLocal.JNDI_NAME))
               .findInstanceByUID(getSOPInstanceUID())
               .getFiles();
       String fsId = files.get(0).getFileSystem().getDirectoryPath();
       String fileId = files.get(0).getFilePath();
       dis =
           new DicomInputStream(
               fsId.startsWith("tar:")
                   ? TarRetrieveDelegate.getInstance().retrieveFileFromTar(fsId, fileId)
                   : FileUtils.resolve(new File(fsId, fileId)));
       metaData = dis.readDicomObject();
     } catch (Exception e) {
       log.error("Unable to retrieve instance!", e); // $NON-NLS-1$
     } finally {
       if (dis != null) {
         try {
           dis.close();
         } catch (Exception e2) {
         }
       }
     }
   }
 }
예제 #2
0
 private void fixRecursive(File source, File target, int[] counts) {
   if (!source.exists()) {
     System.err.println("no such file or directory `" + source + "'");
   } else if (source.isDirectory()) {
     if (!target.exists()) {
       if (!target.mkdir()) System.err.println("failed to create directory `" + target + "'");
     }
     if (target.isFile()) {
       System.err.println(
           "cannot overwrite non-directory `" + target + "' with directory `" + source + "'");
       return;
     }
     String[] ss = source.list();
     for (String s : ss) {
       fixRecursive(new File(source, s), new File(target, s), counts);
     }
   } else if (target.isDirectory()) {
     System.err.println(
         "cannot overwrite directory `" + target + "' with non-directory `" + source + "'");
   } else {
     Replacements replacements = new Replacements();
     try {
       counts[0]++;
       DicomInputStream din = new DicomInputStream(source);
       try {
         din.setHandler(replacements);
         din.readDicomObject();
       } finally {
         try {
           din.close();
         } catch (IOException ignore) {
         }
       }
       if (replacements.numItems == 0) throw new NoFixException("no Pixel Data Fragments");
       replacements.applyTo(source, target);
       counts[1]++;
       System.out.println(
           "PATCHED " + source + ": JPEG-LS " + replacements.bitsStored + "-bit -> " + target);
     } catch (Exception e) {
       System.out.println("skipped " + source + ": " + e.getMessage());
     }
   }
 }
예제 #3
0
    private byte[] getDocumentContent() {
      if (data != null) {
        return data;
      } else if (dicomFile != null) {
        DicomInputStream dis = null;
        try {
          dis = new DicomInputStream(dicomFile);
          return dis.readDicomObject().getBytes(Tag.EncapsulatedDocument);
        } catch (Exception e) {
          log.error("Unable to get content of encapsulated document!", e);
        } finally {
          if (dis != null) {
            try {
              dis.close();
            } catch (Exception e) {
              log.error(null, e);
            }
          }
        }
      }

      return null;
    }
예제 #4
0
    public boolean readValue(DicomInputStream in) throws IOException {
      int tag = in.tag();
      int len = in.valueLength();
      long pos = in.getStreamPosition();
      DicomObject attrs = in.getDicomObject();
      String uid;
      if (fmi && tag >= 0x00080000) {
        if (replacements == null)
          throw new NoFixException("File Meta Information (0002,eeee) is missing");
        if (FixJpegLS.this.implClassUID != null) {
          uid = attrs.getString(Tag.ImplementationClassUID);
          if (!FixJpegLS.this.implClassUID.equals(uid))
            throw new NoFixException("Implementation Class UID (0002,0012) = " + uid);
        }
        fmi = false;
      }
      switch (tag) {
        case Tag.FileMetaInformationGroupLength:
        case Tag.ItemDelimitationItem:
        case Tag.SequenceDelimitationItem:
          return in.readValue(in);
        case Tag.TransferSyntaxUID:
          in.readValue(in);
          uid = attrs.getString(Tag.TransferSyntaxUID);
          if (!UID.JPEGLSLossless.equals(uid))
            throw new NoFixException("Transfer Syntax UID (0002,0010) = " + DICT.prompt(uid));
          replacements = new ArrayList<Replacement>();
          return true;
        case Tag.ImplementationClassUID:
          if (replacements == null)
            throw new NoFixException("File Meta Information (0002,eeee) is missing");

          in.readValue(in);
          if (FixJpegLS.this.newImplClassUID != null)
            addImplClassUIDReplacements(pos, len, (int) in.getEndOfFileMetaInfoPosition());
          return true;
        case Tag.PixelData:
          if (in.level() == 0) {
            if (len != -1)
              throw new NoFixException("Pixel Data is not encapsulated into Data Fragments");

            pixelData = true;
          }
          return in.readValue(in);
        case Tag.Item:
          if (pixelData) {
            if (len == 0) return true;
            byte[] jpegheader = new byte[17];
            in.readFully(jpegheader);
            byte[] lse = selectLSE(jpegheader);
            in.skipFully(len - 18);
            addItemReplacements(pos, len, lse, in.read() == 0);
            numItems++;
            return true;
          }
      }
      pixelData = false;
      if (len == -1) return in.readValue(in);
      in.skipFully(len);
      return true;
    }
예제 #5
0
  /**
   * insert the given file into the database
   *
   * @param f
   * @param insertDCMSeriesStmt
   * @param insertDCMObjectStmt
   * @param insertDCMTagsStmt
   * @param currentDbConnection
   */
  private void insertFile2DB(
      File f,
      PreparedStatement insertDCMSeriesStmt,
      PreparedStatement insertDCMObjectStmt,
      PreparedStatement insertDCMTagsStmt,
      Connection currentDbConnection) {

    logger.info(
        " \r\n\r\n"
            + "#######################################################\r\n"
            + "#\r\n"
            + "#  STARTING IMPORT FOR "
            + f.getName()
            + "\r\n"
            + "#\r\n"
            + "#######################################################");

    used_files++;

    long start = System.currentTimeMillis();

    boolean importFile = true;

    try {
      DicomHeader dh = new DicomHeader(f);
      DicomObject dcmObjectHeader = dh.getDicomObject();

      // if a rule to filter exist -> no import
      if (!filterTags.isEmpty()) {
        for (Iterator<String> iter = filterTags.keySet().iterator(); iter.hasNext(); ) {
          String tag = (String) iter.next();

          // check comma separated filter e. g. 0008,0060=MR, UR, NM, US
          if (filterTags.get(tag).contains(",")) {
            String[] splittedValue = filterTags.get(tag).split(", ");
            for (int i = 0; i < splittedValue.length; i++) {
              if (splittedValue[i].equals(dh.getHeaderStringValue(tag))) {
                importFile = false;
                logger.info("NOT importing File, matches Filtertags: " + filterTags.get(tag));
                break;
              }
            }
          } else if (dh.getHeaderStringValue(tag).equals(filterTags.get(tag))) {
            importFile = false;
            logger.info("NOT importing File, matches Filtertags: " + filterTags.get(tag));
            break;
          }
        }
      }

      // filter the reconstruction-images
      if (importFile && CHECK_RECONSTRUCTION) {
        importFile = checkRecontruction(currentDbConnection, dh);
      }

      if (importFile) {

        // insert dcmSeries if it not exists
        if (!seriesExists(currentDbConnection, dh)) {
          try {
            int i = 1; // index for database-fields in series
            for (Iterator<String> iter = dicomTags.keySet().iterator(); iter.hasNext(); i++) {
              String tag = (String) iter.next();
              String VR = DicomHeader.getHeaderFieldType(tag);

              // if Date
              if ("DA".equals(VR)) {
                try {
                  Date d = dh.getHeaderDateValue(tag);
                  insertDCMSeriesStmt.setDate(i, new java.sql.Date(d.getTime()));
                } catch (Exception e) {
                  insertDCMSeriesStmt.setDate(i, null);
                }
                // if Time
              } else if ("TM".equals(VR)) {
                try {
                  Date d = dh.getHeaderDateValue(tag);
                  insertDCMSeriesStmt.setTime(i, new java.sql.Time(d.getTime()));
                } catch (Exception e) {
                  insertDCMSeriesStmt.setTime(i, null);
                }
                // else String
              } else {
                String s = dh.getHeaderStringValue(tag);
                s = s.replaceAll("\0", "");
                insertDCMSeriesStmt.setString(i, s);
              }
            }
            insertDCMSeriesStmt.execute();

            // Exception if Seriesuid exist
          } catch (SQLException sqle) {
            if (sqle.getMessage().indexOf("duplicate key") < 0) {
              logger.error("Error adding series: ", sqle);
            } else {
              logger.warn("Series allready in DB");
            }
            currentDbConnection.rollback();
          }
        }

        // insert the dicom-object and the tags
        try {
          int j = 1; // index for database-fields in dicom-objects
          insertDCMObjectStmt.setString(j++, dh.getDicomObject().getString(Tag.SeriesInstanceUID));
          insertDCMObjectStmt.setString(j++, dh.getDicomObject().getString(Tag.SOPInstanceUID));
          insertDCMObjectStmt.setTimestamp(j++, new Timestamp(System.currentTimeMillis()));

          // storing the md5 of pixel-data in database, if CHECKSUM is true
          if (CHECKSUM) {
            DicomInputStream dis = new DicomInputStream(f);
            DicomObject dcmObj = new BasicDicomObject();
            dis.readDicomObject(dcmObj, -1);
            DicomElement de = dcmObj.get(Tag.PixelData);
            byte[] bytes = de.getBytes();

            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            byte[] md5 = md.digest();
            BigInteger bi = new BigInteger(1, md5);
            insertDCMObjectStmt.setString(j++, bi.toString(16));
          } else {
            insertDCMObjectStmt.setString(j++, null);
          }

          insertDCMObjectStmt.setString(j++, SOFTWARE_VERSION);
          insertDCMObjectStmt.execute();

          //                            currentDbConnection.commit();

          int parentID =
              getDCMObjectID(
                  currentDbConnection, dh.getDicomObject().getString(Tag.SOPInstanceUID));

          itemOrder = 1;
          // recursive insert of dicom-tags
          insertDCMTagsStmt.clearBatch();
          insertDicomTags(parentID, dcmObjectHeader, null, insertDCMTagsStmt);
          insertDCMTagsStmt.executeBatch();

          currentDbConnection.commit();

          logger.info("File inserted");
          imported_files++;
        } catch (SQLException sqle) {
          currentDbConnection.rollback();
          if (sqle.getMessage().indexOf("duplicate key") < 0) {
            logger.error("Error importing image: ", sqle);
          } else {
            logger.warn(
                "File with UID="
                    + dh.getDicomObject().getString(Tag.SOPInstanceUID)
                    + " allready in db");
          }
        }
      }

      if (DELETE_FILES_AFTER_IMPORT) {
        f.delete();
      } else {
        boolean success = f.renameTo(new File(OK_DIR, f.getName()));
        if (success) {
          logger.info("moved file to: " + OK_DIR + File.separator + f.getName());
        } else {
          logger.warn("unable to move file to: " + OK_DIR + File.separator + f.getName());
        }
      }

    } catch (Exception e) {
      boolean success = f.renameTo(new File(ERROR_DIR, f.getName()));
      logger.log(
          Level.WARN, "Failed to insert file: " + f.getAbsolutePath() + " " + e.getMessage(), e);
      if (success) {
        logger.info("moved file to: " + ERROR_DIR + File.separator + f.getName());
      } else {
        logger.warn("unable to move file to: " + ERROR_DIR + File.separator + f.getName());
      }
      try {
        currentDbConnection.rollback();
      } catch (SQLException e1) {
        logger.log(Level.ERROR, e1.getMessage(), e1);
      }
    }

    logger.info(
        "END OF IMPORT FOR "
            + f.getName()
            + " took "
            + (System.currentTimeMillis() - start)
            + "µsec. \r\n"
            + "Files used: "
            + used_files
            + "  Files imported: "
            + imported_files
            + " \r\n"
            + "#######################################################");
  }