コード例 #1
0
  private void emitReferencedValue(AttributeList attrs) throws SAXException {
    if (expectingTarget) {
      String previousElement = "";
      if (!elementStack.empty()) {
        previousElement = (String) elementStack.peek();
      }

      int prevSrxId = XmiMapping.getSrxId(previousElement);
      // enabledOutput = toProcess(prevSrxId);
      if (!enabledOutput) {
        return;
      }

      if (attrs != null) {
        for (int i = 0; i < attrs.getLength(); i++) {
          String attr = attrs.getName(i);
          if (attr.equals(kTarget)) {
            String key = attrs.getValue(i);
            String name = (String) idTable.get(key);
            if (name != null) {
              emit(name + eol);
            }
            expectingTarget = false;
          }
        } // end for
      } // end if
    } // end if
  } // end emitReferencedValue()
 /**
  * Read a DICOM dataset and write an XML representation of it to the standard output, or vice
  * versa.
  *
  * @param arg either one filename of the file containing the DICOM dataset, or a direction
  *     argument (toDICOM or toXML, case insensitive) and an input filename
  */
 public static void main(String arg[]) {
   try {
     boolean bad = true;
     boolean toXML = true;
     String filename = null;
     if (arg.length == 1) {
       bad = false;
       toXML = true;
       filename = arg[0];
     } else if (arg.length == 2) {
       filename = arg[1];
       if (arg[0].toLowerCase(java.util.Locale.US).equals("toxml")) {
         bad = false;
         toXML = true;
       } else if (arg[0].toLowerCase(java.util.Locale.US).equals("todicom")
           || arg[0].toLowerCase(java.util.Locale.US).equals("todcm")) {
         bad = false;
         toXML = false;
       }
     }
     if (bad) {
       System.err.println(
           "usage: XMLRepresentationOfDicomObjectFactory [toDICOM|toXML] inputfile");
     } else {
       if (toXML) {
         AttributeList list = new AttributeList();
         // System.err.println("reading list");
         list.read(filename, null, true, true);
         // System.err.println("making document");
         Document document = new XMLRepresentationOfDicomObjectFactory().getDocument(list);
         // System.err.println(toString(document));
         write(System.out, document);
       } else {
         // long startReadTime = System.currentTimeMillis();
         AttributeList list =
             new XMLRepresentationOfDicomObjectFactory().getAttributeList(filename);
         // System.err.println("AttributeList.main(): read XML and create DICOM AttributeList -
         // done in "+(System.currentTimeMillis()-startReadTime)+" ms");
         String sourceApplicationEntityTitle =
             Attribute.getSingleStringValueOrEmptyString(
                 list, TagFromName.SourceApplicationEntityTitle);
         list.removeMetaInformationHeaderAttributes();
         FileMetaInformation.addFileMetaInformation(
             list, TransferSyntax.ExplicitVRLittleEndian, sourceApplicationEntityTitle);
         list.write(
             System.out,
             TransferSyntax.ExplicitVRLittleEndian,
             true /*useMeta*/,
             true /*useBufferedStream*/);
       }
     }
   } catch (Exception e) {
     e.printStackTrace(System.err);
   }
 }
コード例 #3
0
  private static boolean checkAttrs(String what, AttributeList attrs) {
    if (attrs.size() != 1) {
      System.out.println(
          "TEST FAILS: list returned by " + what + " does not have size 1: " + attrs);
      return false;
    }
    Attribute attr = (Attribute) attrs.get(0);
    if (!"Exotic".equals(attr.getName())) {
      System.out.println("TEST FAILS: " + what + " returned wrong " + "attribute: " + attr);
      return false;
    }

    return true;
  }
コード例 #4
0
 CreateCommand(UnicoreInvokeServer is, String requestId) throws Command.Exception {
   super(is);
   this.requestId = requestId;
   String line;
   while ((line = is.readLine()) != null) {
     if (line.trim().equals(CMD_CREATE_END)) {
       terminated = true;
       break;
     } else {
       try {
         StringTokenizer st = new StringTokenizer(line);
         String key = st.nextToken();
         String value = line.substring(key.length());
         list.put(key, value);
       } catch (java.lang.Exception e) {
         Log.printStackTrace(e);
       }
     }
   }
   if (terminated) {
     job = new UnicoreJob(this);
   } else {
     new Command.Exception("the command was not terminated!");
   }
 }
コード例 #5
0
  /**
   * @exception IOException
   * @exception DicomException
   */
  public CEchoRequestCommandMessage() throws DicomException, IOException {

    commandField = MessageServiceElementCommand.C_ECHO_RQ;
    messageID = super.getNextAvailableMessageID();
    int dataSetType = 0x0101; // none

    // NB. The Affected SOP Class UID should have no extra trailing padding, otherwise the
    // SCP may fail and send an A-ABORT :) (Part 5 says one null (not space) is allowed)
    // This is taken care of by the Attribute.write()

    AttributeList list = new AttributeList();
    {
      AttributeTag t = groupLengthTag;
      Attribute a = new UnsignedLongAttribute(t);
      a.addValue(0);
      list.put(t, a);
    }
    {
      AttributeTag t = TagFromName.AffectedSOPClassUID;
      Attribute a = new UniqueIdentifierAttribute(t);
      a.addValue(SOPClass.Verification);
      list.put(t, a);
    }
    {
      AttributeTag t = TagFromName.CommandField;
      Attribute a = new UnsignedShortAttribute(t);
      a.addValue(commandField);
      list.put(t, a);
    }
    {
      AttributeTag t = TagFromName.MessageID;
      Attribute a = new UnsignedShortAttribute(t);
      a.addValue(messageID);
      list.put(t, a);
    }
    {
      AttributeTag t = TagFromName.CommandDataSetType;
      Attribute a = new UnsignedShortAttribute(t);
      a.addValue(dataSetType);
      list.put(t, a);
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DicomOutputStream dout =
        new DicomOutputStream(
            bout, null /* no meta-header */, TransferSyntax.ImplicitVRLittleEndian);
    list.write(dout);
    bytes = bout.toByteArray();

    groupLength = bytes.length - 12;
    bytes[8] = (byte) groupLength; // little endian
    bytes[9] = (byte) (groupLength >> 8);
    bytes[10] = (byte) (groupLength >> 16);
    bytes[11] = (byte) (groupLength >> 24);
    // System.err.println("CEchoRequestCommandMessage: bytes="+HexDump.dump(bytes));
  }
コード例 #6
0
  private void emitNewOccurrence(int srxId, AttributeList attrs) throws SAXException {

    enabledOutput = toProcess(srxId);
    if (!enabledOutput) {
      return;
    }

    currentSrxId = srxId;
    String mappedName = XmiMapping.getMappingName(srxId);
    emit(eol + kOccurrenceType + " " + mappedName + eol);

    // if it's a component, write its composite
    String composite = XmiMapping.getComposite(srxId);
    if (composite != null) {
      if (!occurrenceNameStack.empty()) {
        String compositeName = (String) occurrenceNameStack.peek();
        if (compositeName != null) {
          emit(composite + " " + compositeName + eol);
        }
      } // end if
    } // end if

    // Keep its XMI.id
    if (attrs != null) {
      for (int i = 0; i < attrs.getLength(); i++) {
        String attr = attrs.getName(i);
        if (attr.equals(kXmiId)) {
          currentXmiId = attrs.getValue(i);
        } // end if
      } // end for
    } // end if

    // Keep its current XMI name & SRX name
    currentXmiName = XmiMapping.getXmiName(srxId);
    currentSrxName = XmiMapping.getSrxName(srxId);
  }
コード例 #7
0
ファイル: ChestImageViewer.java プロジェクト: kullen/MRI
 /**
  * @param list
  * @return array of two String values, row then column orientation, else array of two nulls if
  *     cannot be obtained
  */
 private static String[] getPatientOrientation(AttributeList list) {
   String[] vPatientOrientation = null;
   Attribute aPatientOrientation = list.get(TagFromName.PatientOrientation);
   if (aPatientOrientation != null && aPatientOrientation.getVM() == 2) {
     try {
       vPatientOrientation = aPatientOrientation.getStringValues();
       if (vPatientOrientation != null && vPatientOrientation.length != 2) {
         vPatientOrientation = null;
       }
     } catch (DicomException e) {
       vPatientOrientation = null;
     }
   }
   if (vPatientOrientation == null) {
     vPatientOrientation = new String[2];
   }
   return vPatientOrientation;
 }
  /**
   * @param list
   * @param document
   * @param parent
   */
  void addAttributesFromListToNode(AttributeList list, Document document, Node parent) {
    DicomDictionary dictionary = list.getDictionary();
    Iterator i = list.values().iterator();
    while (i.hasNext()) {
      Attribute attribute = (Attribute) i.next();
      AttributeTag tag = attribute.getTag();

      String elementName = dictionary.getNameFromTag(tag);
      if (elementName == null) {
        elementName = makeElementNameFromHexadecimalGroupElementValues(tag);
      }
      Node node = document.createElement(elementName);
      parent.appendChild(node);

      {
        Attr attr = document.createAttribute("group");
        attr.setValue(HexDump.shortToPaddedHexString(tag.getGroup()));
        node.getAttributes().setNamedItem(attr);
      }
      {
        Attr attr = document.createAttribute("element");
        attr.setValue(HexDump.shortToPaddedHexString(tag.getElement()));
        node.getAttributes().setNamedItem(attr);
      }
      {
        Attr attr = document.createAttribute("vr");
        attr.setValue(ValueRepresentation.getAsString(attribute.getVR()));
        node.getAttributes().setNamedItem(attr);
      }

      if (attribute instanceof SequenceAttribute) {
        int count = 0;
        Iterator si = ((SequenceAttribute) attribute).iterator();
        while (si.hasNext()) {
          SequenceItem item = (SequenceItem) si.next();
          Node itemNode = document.createElement("Item");
          Attr numberAttr = document.createAttribute("number");
          numberAttr.setValue(Integer.toString(++count));
          itemNode.getAttributes().setNamedItem(numberAttr);
          node.appendChild(itemNode);
          addAttributesFromListToNode(item.getAttributeList(), document, itemNode);
        }
      } else {
        // Attr attr = document.createAttribute("value");
        // attr.setValue(attribute.getDelimitedStringValuesOrEmptyString());
        // node.getAttributes().setNamedItem(attr);

        // node.appendChild(document.createTextNode(attribute.getDelimitedStringValuesOrEmptyString()));

        String values[] = null;
        try {
          values = attribute.getStringValues();
        } catch (DicomException e) {
          // e.printStackTrace(System.err);
        }
        if (values != null) {
          for (int j = 0; j < values.length; ++j) {
            Node valueNode = document.createElement("value");
            Attr numberAttr = document.createAttribute("number");
            numberAttr.setValue(Integer.toString(j + 1));
            valueNode.getAttributes().setNamedItem(numberAttr);
            valueNode.appendChild(document.createTextNode(values[j]));
            node.appendChild(valueNode);
          }
        }
      }
    }
  }
 /**
  * @param list
  * @param parent
  * @exception NumberFormatException
  * @exception DicomException
  */
 void addAttributesFromNodeToList(AttributeList list, Node parent)
     throws NumberFormatException, DicomException {
   if (parent != null) {
     Node node = parent.getFirstChild();
     while (node != null) {
       String elementName = node.getNodeName();
       NamedNodeMap attributes = node.getAttributes();
       if (attributes != null) {
         Node vrNode = attributes.getNamedItem("vr");
         Node groupNode = attributes.getNamedItem("group");
         Node elementNode = attributes.getNamedItem("element");
         if (vrNode != null && groupNode != null && elementNode != null) {
           String vrString = vrNode.getNodeValue();
           String groupString = groupNode.getNodeValue();
           String elementString = elementNode.getNodeValue();
           if (vrString != null && groupString != null && elementString != null) {
             byte[] vr = vrString.getBytes();
             int group = Integer.parseInt(groupString, 16);
             int element = Integer.parseInt(elementString, 16);
             AttributeTag tag = new AttributeTag(group, element);
             if ((group % 2 == 0 && element == 0)
                 || (group == 0x0008 && element == 0x0001)
                 || (group == 0xfffc && element == 0xfffc)) {
               // System.err.println("ignoring group length or length to end or dataset trailing
               // padding "+tag);
             } else {
               if (vrString.equals("SQ")) {
                 SequenceAttribute a = new SequenceAttribute(tag);
                 // System.err.println("Created "+a);
                 if (node.hasChildNodes()) {
                   Node childNode = node.getFirstChild();
                   while (childNode != null) {
                     String childNodeName = childNode.getNodeName();
                     // System.err.println("childNodeName = "+childNodeName);
                     if (childNodeName != null && childNodeName.equals("Item")) {
                       // should check item number, but ignore for now :(
                       // System.err.println("Adding item to sequence");
                       AttributeList itemList = new AttributeList();
                       addAttributesFromNodeToList(itemList, childNode);
                       a.addItem(itemList);
                     }
                     // else may be a #text element in between
                     childNode = childNode.getNextSibling();
                   }
                 }
                 // System.err.println("Sequence Attribute is "+a);
                 list.put(tag, a);
               } else {
                 Attribute a = AttributeFactory.newAttribute(tag, vr);
                 // System.err.println("Created "+a);
                 if (node.hasChildNodes()) {
                   Node childNode = node.getFirstChild();
                   while (childNode != null) {
                     String childNodeName = childNode.getNodeName();
                     // System.err.println("childNodeName = "+childNodeName);
                     if (childNodeName != null && childNodeName.equals("value")) {
                       // should check value number, but ignore for now :(
                       String value = childNode.getTextContent();
                       // System.err.println("Value value = "+value);
                       if (value != null) {
                         value =
                             StringUtilities.removeLeadingOrTrailingWhitespaceOrISOControl(
                                 value); // just in case
                         a.addValue(value);
                       }
                     }
                     // else may be a #text element in between
                     childNode = childNode.getNextSibling();
                   }
                 }
                 // System.err.println("Attribute is "+a);
                 list.put(tag, a);
               }
             }
           }
         }
       }
       node = node.getNextSibling();
     }
   }
 }
コード例 #10
0
ファイル: ChestImageViewer.java プロジェクト: kullen/MRI
  /**
   * @param filenames
   * @exception Exception if internal error
   */
  public void loadMultiPanelFromSpecifiedFiles(String filenames[]) throws Exception {

    int nFiles = filenames.length;

    SingleImagePanel imagePanels[] = new SingleImagePanel[nFiles];

    String orientations[][] = new String[nFiles][];
    String views[] = new String[nFiles];
    String lateralityViewAndModifiers[] = new String[nFiles];
    String lateralities[] = new String[nFiles];
    int widths[] = new int[nFiles];
    int heights[] = new int[nFiles];
    PixelSpacing spacing[] = new PixelSpacing[nFiles];

    String rowOrientations[] = new String[nFiles];
    String columnOrientations[] = new String[nFiles];

    HashMap eventContexts = new HashMap();

    double maximumHorizontalExtentInMm = 0;
    double maximumVerticalExtentInMm = 0;

    StructuredReport sr[] = new StructuredReport[nFiles];

    int nImages = 0;
    int nCAD = 0;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    for (int f = 0; f < nFiles; ++f) {
      try {
        String filename = filenames[f];
        DicomInputStream distream = null;
        InputStream in = classLoader.getResourceAsStream(filename);
        if (in != null) {
          distream = new DicomInputStream(in);
        } else {
          distream = new DicomInputStream(new File(filename));
        }
        AttributeList list = new AttributeList();
        list.read(distream);
        if (list.isImage()) {
          int i = nImages++;
          System.err.println("IMAGE [" + i + "] is file " + f + " (" + filenames[f] + ")");

          orientations[i] = getPatientOrientation(list);
          // System.err.println("IMAGE ["+i+"] orientation="+(orientations[i] == null &&
          // orientations[i].length == 2 ? "" : (orientations[i][0] + " " + orientations[i][1])));
          views[i] = getView(list);
          // System.err.println("IMAGE ["+i+"] view="+views[i]);
          lateralityViewAndModifiers[i] = getImageLateralityViewModifierAndViewModifier(list);
          // System.err.println("IMAGE ["+i+"]
          // lateralityViewAndModifiers="+lateralityViewAndModifiers[i]);
          // System.err.println("File "+filenames[f]+": "+lateralityViewAndModifiers[i]);
          lateralities[i] = getLaterality(list);
          // System.err.println("IMAGE ["+i+"] laterality="+lateralities[i]);
          spacing[i] = new PixelSpacing(list);
          // System.err.println("IMAGE ["+i+"] spacing="+spacing[i]);

          SourceImage sImg = new SourceImage(list);
          BufferedImage img = sImg.getBufferedImage();

          widths[i] = sImg.getWidth();
          heights[i] = sImg.getHeight();

          boolean shareVOIEventsInStudy =
              false; // does not seem to work anyway, since adding VOITransform to panel constructor
                     // :(

          EventContext eventContext = new EventContext(Integer.toString(i));

          SingleImagePanel imagePanel = makeNewImagePanel(sImg, eventContext);
          imagePanel.setDemographicAndTechniqueAnnotations(
              new DemographicAndTechniqueAnnotations(list),
              "SansSerif",
              Font.PLAIN,
              10,
              Color.pink);
          imagePanel.setOrientationAnnotations(
              new OrientationAnnotations(rowOrientations[i], columnOrientations[i]),
              "SansSerif",
              Font.PLAIN,
              20,
              Color.pink);
          imagePanel.setPixelSpacingInSourceImage(
              spacing[i].getSpacing(), spacing[i].getDescription());
          if (Attribute.getSingleStringValueOrEmptyString(list, TagFromName.VOILUTFunction)
              .equals("SIGMOID")) {
            imagePanel.setVOIFunctionToLogistic();
          }
          imagePanels[i] = imagePanel;
        } else {
          throw new DicomException("Unsupported SOP Class in file " + filenames[f]);
        }
      } catch (Exception e) { // FileNotFoundException,IOException,DicomException
        e.printStackTrace(System.err);
      }
    }

    // int imagesPerRow = nImages;			// i.e., 1 -> 1, 2 -> 1, 4 -> 4, 5 -> 4, 8 -> 4
    // int imagesPerCol = 1;

    int imagesPerRow = nImages >= 8 ? 8 : nImages; // i.e., 1 -> 1, 2 -> 1, 4 -> 4, 5 -> 4, 8 -> 4
    int imagesPerCol =
        (nImages - 1) / imagesPerRow + 1; // i.e., 1 -> 1, 2 -> 2, 4 -> 1, 5 -> 2, 8 -> 2

    int singleWidth = frameWidth / imagesPerRow;
    int singleHeight = frameHeight / imagesPerCol;

    if (nImages == 1 && singleWidth > singleHeight) {
      singleWidth =
          singleWidth / 2; // use only half the screen for a single view and a landscape monitor
    }

    for (int i = 0; i < nImages; ++i) {
      DisplayedAreaSelection displayedAreaSelection = null;
      displayedAreaSelection =
          new DisplayedAreaSelection(
              widths[i],
              heights[i],
              0,
              0,
              widths[i],
              heights[i],
              true, // in case spacing was not supplied
              0,
              0,
              0,
              0,
              0,
              false /*crop*/);
      imagePanels[i].setDisplayedAreaSelection(displayedAreaSelection);
      imagePanels[i].setPreTransformImageRelativeCoordinates(null);
    }

    SingleImagePanel.deconstructAllSingleImagePanelsInContainer(multiPanel);
    multiPanel.removeAll();
    multiPanel.setLayout(new GridLayout(imagesPerCol, imagesPerRow));
    multiPanel.setBackground(Color.black);

    for (int x = 0; x < imagesPerCol; ++x) {
      for (int y = 0; y < imagesPerRow; ++y) {
        int i = x * imagesPerRow + y;
        if (i < nImages) {
          imagePanels[i].setPreferredSize(new Dimension(singleWidth, singleHeight));
          multiPanel.add(imagePanels[i]);
        }
      }
    }
    frame.getContentPane().validate();
    frame.getContentPane().repaint();
  }
コード例 #11
0
 private static Object attrValue(AttributeList attrs) {
   return ((Attribute) attrs.get(0)).getValue();
 }
コード例 #12
0
  private static boolean test(String proto, MBeanServer mbs, ObjectName on) throws Exception {
    System.out.println("Testing for protocol " + proto);

    JMXConnectorServer cs;
    JMXServiceURL url = new JMXServiceURL(proto, null, 0);
    try {
      cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    } catch (MalformedURLException e) {
      System.out.println("System does not recognize URL: " + url + "; ignoring");
      return true;
    }
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector client = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = client.getMBeanServerConnection();
    Object getAttributeExotic = mbsc.getAttribute(on, "Exotic");
    AttributeList getAttrs = mbsc.getAttributes(on, new String[] {"Exotic"});
    AttributeList setAttrs = new AttributeList();
    setAttrs.add(new Attribute("Exotic", new Exotic()));
    setAttrs = mbsc.setAttributes(on, setAttrs);
    Object invokeExotic = mbsc.invoke(on, "anExotic", new Object[] {}, new String[] {});
    MBeanInfo exoticMBI = mbsc.getMBeanInfo(on);

    mbsc.setAttribute(on, new Attribute("Exception", Boolean.TRUE));
    Exception getAttributeException, setAttributeException, invokeException;
    try {
      try {
        mbsc.getAttribute(on, "Exotic");
        throw noException("getAttribute");
      } catch (Exception e) {
        getAttributeException = e;
      }
      try {
        mbsc.setAttribute(on, new Attribute("Exotic", new Exotic()));
        throw noException("setAttribute");
      } catch (Exception e) {
        setAttributeException = e;
      }
      try {
        mbsc.invoke(on, "anExotic", new Object[] {}, new String[] {});
        throw noException("invoke");
      } catch (Exception e) {
        invokeException = e;
      }
    } finally {
      mbsc.setAttribute(on, new Attribute("Exception", Boolean.FALSE));
    }
    client.close();
    cs.stop();

    boolean ok = true;

    ok &= checkAttrs("getAttributes", getAttrs);
    ok &= checkAttrs("setAttributes", setAttrs);

    ok &= checkType("getAttribute", getAttributeExotic, Exotic.class);
    ok &= checkType("getAttributes", attrValue(getAttrs), Exotic.class);
    ok &= checkType("setAttributes", attrValue(setAttrs), Exotic.class);
    ok &= checkType("invoke", invokeExotic, Exotic.class);
    ok &= checkType("getMBeanInfo", exoticMBI, ExoticMBeanInfo.class);

    ok &= checkExceptionType("getAttribute", getAttributeException, ExoticException.class);
    ok &= checkExceptionType("setAttribute", setAttributeException, ExoticException.class);
    ok &= checkExceptionType("invoke", invokeException, ExoticException.class);

    if (ok) System.out.println("Test passes for protocol " + proto);
    return ok;
  }