/**
   * Check a segment
   *
   * @param segmentObj the segment object (from profile)
   * @param segment the segment string (from ER7)
   */
  private void checkSegment(XmlObject segmentObj, String segment) {
    locFieldInstanceNumber = -1;
    String segmentName = segmentObj.newCursor().getAttributeText(QName.valueOf("Name"));
    String segmentUsage = segmentObj.newCursor().getAttributeText(QName.valueOf("Usage"));
    XmlObject[] fieldsObj = segmentObj.selectChildren(QName.valueOf("Field"));

    if (fieldsObj.length > 0) {
      String[] fields = segment.split(((Er7Message) message).getFieldSeparator());
      if (fields.length - 1 > fieldsObj.length) {
        /* Extra fields */
        MessageFailureV2 mf = new MessageFailureV2(message.getEncoding());
        mf.setFailureType(AssertionTypeV2Constants.XTRA);
        mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
        mf.setDescription("Extra fields for segment " + segmentName);
        mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
        mf.setLine(lineNumber);
        mf.setPath(getCurrentLocation().toString());

        messageFailures.add(mf);
      } else {
        int fieldsIdx = 1;
        if (fields[0].equals("MSH")) {
          fieldsIdx = 0;
        }
        for (int i = 0; i < fieldsObj.length; i++, fieldsIdx++) {
          if (fieldsIdx == 0) {
            continue;
          }
          locFieldPosition = i + 1;
          locFieldInstanceNumber = 1;
          locComponentPosition = -1;
          if (fieldsIdx < fields.length) {
            checkField(fieldsObj[i], fields[fieldsIdx]);
          } else {
            /* Check Usage */
            checkUsage(fieldsObj[i], "");
          }
        }
      }
      // No Fields
      if ("R".equals(segmentUsage) && fields.length - 1 == 0) {
        locFieldPosition = -1;
        StringBuffer sb = new StringBuffer();
        MessageFailureV2 mf = new MessageFailureV2(message.getEncoding());
        sb.append("The element is missing at least one of its children");
        mf.setDescription(sb.toString());
        mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
        mf.setFailureType(AssertionTypeV2Constants.MESSAGE_STRUCTURE);
        mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
        mf.setLine(lineNumber);
        mf.setPath(getCurrentLocation().toString());
        messageFailures.add(mf);
        sb = null;
      }
    }
  }
Beispiel #2
0
  /**
   * Utility method to append the contents of the child docment to the end of the parent XmlObject.
   * This is useful when dealing with elements without generated methods (like elements with xs:any)
   *
   * @param parent Parent to append contents to
   * @param childDoc Xml document containing contents to be appended
   */
  public static void append(final XmlObject parent, final XmlObject childDoc) {
    final XmlCursor parentCursor = parent.newCursor();
    parentCursor.toEndToken();

    final XmlCursor childCursor = childDoc.newCursor();
    childCursor.toFirstChild();

    childCursor.moveXml(parentCursor);
    parentCursor.dispose();
    childCursor.dispose();
  }
Beispiel #3
0
  /**
   * Uses the XPath text() function to get values from <name> elements in received XML, then
   * collects those values as the value of a <names> element created here.
   *
   * <p>Demonstrates the following characteristics of the selectPath method:
   *
   * <p>- It supports expressions that include XPath function calls. - selectPath called from an
   * XmlCursor instance (instead of an XMLBeans type) places results (if any) into the cursor's
   * selection set.
   *
   * @param empDoc The incoming XML.
   * @return <code>true</code> if the XPath expression returned results; otherwise, <code>false
   *     </code>.
   */
  public boolean collectNames(XmlObject empDoc) {
    boolean hasResults = false;

    // Create a cursor with which to execute query expressions. The cursor
    // is inserted at the very beginning of the incoming XML, then moved to
    // the first element's START token.
    XmlCursor pathCursor = empDoc.newCursor();
    pathCursor.toFirstChild();

    // Execute the path expression, qualifying it with the namespace
    // declaration.
    pathCursor.selectPath(m_namespaceDeclaration + "$this//xq:employee/xq:name/text()");

    // If there are results, then go ahead and do stuff.
    if (pathCursor.getSelectionCount() > 0) {
      hasResults = true;

      // Create a new <names> element into which names from the XML
      // will be copied. Note that this element is in the default
      // namespace; it's not part of the schema.
      XmlObject namesElement = null;
      try {
        namesElement = XmlObject.Factory.parse("<names/>");
      } catch (XmlException e) {
        e.printStackTrace();
      }

      // Add a cursor the new element and put it between its START and END
      // tokens, where new values can be inserted.
      XmlCursor namesCursor = namesElement.newCursor();
      namesCursor.toFirstContentToken();
      namesCursor.toEndToken();

      // Loop through the selections, appending the incoming <name> element's
      // value to the new <name> element's value. (Of course, this could have
      // been done with a StringBuffer, but that wouldn't show the cursor in
      // use.)
      while (pathCursor.toNextSelection()) {
        namesCursor.insertChars(pathCursor.getTextValue());
        if (pathCursor.hasNextSelection()) {
          namesCursor.insertChars(", ");
        }
      }
      // Dispose of the cursors now that they're not needed.
      pathCursor.dispose();
      namesCursor.dispose();

      // Print the new element.
      System.out.println("\nNames collected by collectNames method: \n\n" + namesElement + "\n");
    }
    return hasResults;
  }
Beispiel #4
0
 public static Map<?, ?> getNamespaces(XmlObject xmlObject) {
   XmlCursor cursor = xmlObject.newCursor();
   Map<?, ?> nsMap = Maps.newHashMap();
   cursor.getAllNamespaces(nsMap);
   cursor.dispose();
   return nsMap;
 }
Beispiel #5
0
 public static void fixNamespaceForXsiType(XmlObject content, Map<?, ?> namespaces) {
   final XmlCursor cursor = content.newCursor();
   while (cursor.hasNextToken()) {
     if (cursor.toNextToken().isStart()) {
       final String xsiType = cursor.getAttributeText(W3CConstants.QN_XSI_TYPE);
       if (xsiType != null) {
         final String[] toks = xsiType.split(":");
         if (toks.length > 1) {
           String prefix = toks[0];
           String localName = toks[1];
           String namespace = (String) namespaces.get(prefix);
           if (Strings.isNullOrEmpty(namespace)) {
             namespace = CodingRepository.getInstance().getNamespaceFor(prefix);
           }
           if (StringHelper.isNotEmpty(namespace)) {
             cursor.setAttributeText(
                 W3CConstants.QN_XSI_TYPE,
                 Joiner.on(Constants.COLON_CHAR)
                     .join(
                         XmlHelper.getPrefixForNamespace(content, (String) namespaces.get(prefix)),
                         localName));
           }
         }
       }
     }
   }
   cursor.dispose();
 }
  /**
   * Check the element usage
   *
   * @param usage the usage
   * @param value the value
   * @return true if there is a usage error; false otherwise
   */
  private boolean checkUsage(XmlObject obj, String value) {
    boolean usageError = false;
    MessageFailureV2 mf = null;
    String usage = obj.newCursor().getAttributeText(QName.valueOf("Usage"));

    if (usage.equals("R") && value.matches("\\s*")) {
      /* A required element is empty */
      mf = new MessageFailureV2(message.getEncoding());
      mf.setFailureType(AssertionTypeV2Constants.USAGE);
      mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
      mf.setDescription(getCurrentLocation().toString() + " is missing");
      mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
      mf.setLine(lineNumber);
      mf.setPath(getCurrentLocation().toString());
      messageFailures.add(mf);
      usageError = true;
    } else if (usage.equals("X") && value.matches(".+")) {
      /* A X element has a value */
      mf = new MessageFailureV2(message.getEncoding());
      mf.setFailureType(AssertionTypeV2Constants.X_USAGE);
      mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
      mf.setDescription(
          getCurrentLocation().toString() + " is present whereas it is an X-Usage element");
      mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
      mf.setLine(lineNumber);
      mf.setPath(getCurrentLocation().toString());
      messageFailures.add(mf);
      usageError = true;
    }
    return usageError;
  }
Beispiel #7
0
  public static void fixNamespaceForXsiType(final XmlObject object, final QName value) {
    final XmlCursor cursor = object.newCursor();
    while (cursor.hasNextToken()) {
      if (cursor.toNextToken().isStart()) {
        final String xsiType = cursor.getAttributeText(W3CConstants.QN_XSI_TYPE);
        if (xsiType != null) {

          final String[] toks = xsiType.split(":");
          String localName;
          String prefix;
          if (toks.length > 1) {
            prefix = toks[0];
            localName = toks[1];
          } else {
            localName = toks[0];
          }
          if (localName.equals(value.getLocalPart())) {
            cursor.setAttributeText(
                W3CConstants.QN_XSI_TYPE,
                Joiner.on(Constants.COLON_CHAR)
                    .join(
                        XmlHelper.getPrefixForNamespace(object, value.getNamespaceURI()),
                        value.getLocalPart()));
          }
        }
      }
    }
    cursor.dispose();
  }
Beispiel #8
0
 /**
  * Creates the administrative metadata section of a mets document.
  *
  * @param id the id of this amdSec
  * @param owner the rights owner of the item
  * @param logo the logo of the organization
  * @param url the url of the organization
  * @param reference the items url
  */
 public void createAmdSec(String id, String owner, String logo, String url, String reference) {
   this.amdSec = this.mets.addNewAmdSec();
   this.amdSec.setID(id);
   // DVRights
   MdSecType rightsMD = this.amdSec.addNewRightsMD();
   rightsMD.setID("rights" + id);
   MdWrap wrap = rightsMD.addNewMdWrap();
   wrap.setMIMETYPE("text/xml");
   wrap.setMDTYPE(MdWrap.MDTYPE.OTHER);
   wrap.setOTHERMDTYPE("DVRIGHTS");
   XmlData xml = wrap.addNewXmlData();
   XmlObject dvrights = XmlObject.Factory.newInstance();
   XmlCursor cur = dvrights.newCursor();
   cur.toNextToken();
   cur.beginElement("rights", "http://dfg-viewer.de/");
   cur.insertElementWithText("owner", "http://dfg-viewer.de/", owner);
   cur.insertElementWithText("ownerLogo", "http://dfg-viewer.de/", logo);
   cur.insertElementWithText("ownerSiteURL", "http://dfg-viewer.de/", url);
   cur.insertElementWithText("contact", "http://dfg-viewer.de/", "*****@*****.**");
   cur.dispose();
   xml.set(dvrights);
   wrap.setXmlData(xml);
   rightsMD.setMdWrap(wrap);
   this.amdSec.setRightsMDArray(0, rightsMD);
   // DVLinks
   MdSecType digiprovMD = this.amdSec.addNewDigiprovMD();
   digiprovMD.setID("digiprov" + id);
   MdWrap dpWrap = digiprovMD.addNewMdWrap();
   dpWrap.setMIMETYPE("text/xml");
   dpWrap.setMDTYPE(MdWrap.MDTYPE.OTHER);
   dpWrap.setOTHERMDTYPE("DVLINKS");
   XmlData dpXml = dpWrap.addNewXmlData();
   XmlObject dvdigiprov = XmlObject.Factory.newInstance();
   XmlCursor dpCur = dvdigiprov.newCursor();
   dpCur.toNextToken();
   dpCur.beginElement("links", "http://dfg-viewer.de/");
   dpCur.insertElementWithText("reference", "http://dfg-viewer.de/", reference);
   dpCur.insertElementWithText(
       "presentation", "http://dfg-viewer.de/", "http://vm38.mpdl.mpg.de:8080/dlib-journals/");
   dpCur.dispose();
   dpXml.set(dvdigiprov);
   dpWrap.setXmlData(dpXml);
   digiprovMD.setMdWrap(dpWrap);
   this.amdSec.setDigiprovMDArray(0, digiprovMD);
 }
Beispiel #9
0
 /**
  * Remove namespace declarations from an xml fragment (useful for moving all declarations to a
  * document root
  *
  * @param x The fragment to localize
  */
 public static void removeNamespaces(final XmlObject x) {
   final XmlCursor c = x.newCursor();
   while (c.hasNextToken()) {
     if (c.isNamespace()) {
       c.removeXml();
     } else {
       c.toNextToken();
     }
   }
   c.dispose();
 }
  /**
   * Check the subcomponent
   *
   * @param subcomponentObj the subcomponent object (from profile)
   * @param subcomponent the subcomponent string (from ER7)
   */
  private void checkSubComponent(XmlObject subcomponentObj, String subcomponent) {
    XmlCursor cur = subcomponentObj.newCursor();
    /* Check usage */
    String usage = cur.getAttributeText(QName.valueOf("Usage"));
    boolean usageError = checkUsage(subcomponentObj, subcomponent);

    if (!usageError) {
      if (usage.equals("R") || !subcomponent.equals("")) {
        /* Check value */
        checkValue(subcomponentObj, subcomponent);
      }
    }
  }
Beispiel #11
0
  protected void setFormObject(Forms forms, XmlObject formObject) {
    // Create a cursor from the grants.gov form
    XmlCursor formCursor = formObject.newCursor();
    formCursor.toStartDoc();
    formCursor.toNextToken();

    // Create a cursor from the Forms object
    XmlCursor metaGrantCursor = forms.newCursor();
    metaGrantCursor.toNextToken();

    // Add the form to the Forms object.
    formCursor.moveXml(metaGrantCursor);
  }
 protected void addSchemaLocations(XmlObject xmlObject, Map<String, String> locations) {
   StringBuilder sb = new StringBuilder();
   for (Entry<String, String> entry : locations.entrySet()) {
     if (sb.length() > 0) {
       sb.append(" ");
     }
     sb.append(entry.getKey() + " " + entry.getValue());
   }
   XmlCursor cursor = xmlObject.newCursor();
   if (cursor.toFirstChild()) {
     cursor.setAttributeText(
         new QName("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation"), sb.toString());
   }
 }
Beispiel #13
0
  public void setNodeValue(String xpath, Object value) throws XmlException {
    xpath = initXPathNamespaces(xpath);

    XmlCursor cursor = xmlObject.newCursor();
    try {
      cursor.selectPath(xpath);

      if (cursor.toNextSelection()) {
        XmlUtils.setNodeValue(cursor.getDomNode(), value == null ? null : value.toString());
      }
    } finally {
      cursor.dispose();
    }
  }
Beispiel #14
0
 /**
  * Validate an XmlObject against the contained inferred schemas. Upon validation errors, the
  * ConflictHandler is used to determine if a schema should be adjusted, or if validation should
  * fail.
  *
  * @param xmlo An XmlObject containing the document to be validated.
  * @param handler A ConflictHandler to use on validation errors.
  * @throws XmlException On unresolvable validation error.
  */
 public void validate(XmlObject xmlo, ConflictHandler handler) throws XmlException {
   XmlCursor cursor = xmlo.newCursor();
   cursor.toFirstChild();
   Schema s = getSchemaForNamespace(cursor.getName().getNamespaceURI());
   boolean created = false;
   if (s == null) {
     s = newSchema(cursor.getName().getNamespaceURI());
     created = true;
   }
   Context context = new Context(this, handler, cursor);
   try {
     s.validate(context);
   } catch (XmlException e) {
     if (created) schemas.remove(s.getNamespace());
     throw e;
   }
 }
Beispiel #15
0
  public static String createSampleForElement(SchemaGlobalElement element) {
    XmlObject xml = XmlObject.Factory.newInstance();

    XmlCursor c = xml.newCursor();
    c.toNextToken();
    c.beginElement(element.getName());

    new SampleXmlUtil(false).createSampleForType(element.getType(), c);

    c.dispose();

    XmlOptions options = new XmlOptions();
    options.put(XmlOptions.SAVE_PRETTY_PRINT);
    options.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, 3);
    options.put(XmlOptions.SAVE_AGGRESSIVE_NAMESPACES);
    options.setSaveOuter();
    String result = xml.xmlText(options);

    return result;
  }
Beispiel #16
0
  public static String createSampleForType(SchemaType sType) {
    XmlObject object = XmlObject.Factory.newInstance();
    XmlCursor cursor = object.newCursor();
    // Skip the document node
    cursor.toNextToken();
    // Using the type and the cursor, call the utility method to get a
    // sample XML payload for that Schema element
    new SampleXmlUtil(false).createSampleForType(sType, cursor);
    // Cursor now contains the sample payload
    // Pretty print the result. Note that the cursor is positioned at the
    // end of the doc so we use the original xml object that the cursor was
    // created upon to do the xmlText() against.

    cursor.dispose();
    XmlOptions options = new XmlOptions();
    options.put(XmlOptions.SAVE_PRETTY_PRINT);
    options.put(XmlOptions.SAVE_PRETTY_PRINT_INDENT, 3);
    options.put(XmlOptions.SAVE_AGGRESSIVE_NAMESPACES);
    options.setSaveOuter();
    String result = object.xmlText(options);

    return result;
  }
  @Override
  protected void checkMessageStructure() throws MessageValidationException {
    boolean messageStructureFailure = false;
    try {
      // Create a pseudo XML message
      XmlObject pseudoMessage = XmlObject.Factory.newInstance();
      XmlCursor pmCursor = pseudoMessage.newCursor();
      pmCursor.toNextToken();
      pmCursor.beginElement(profile.getMessageStructureID(), "urn:hl7-org:v2xml");
      BufferedReader br = new BufferedReader(new StringReader(message.getMessageAsString()));
      String line = null;
      while ((line = br.readLine()) != null) {
        if (!line.matches("\\s*")) {
          String fieldSep = ((Er7Message) message).getFieldSeparatorChar();
          try {
            int idx = line.indexOf(fieldSep);
            if (idx == -1 && line.length() <= 3) {
              idx = 3;
            }
            line = line.substring(0, idx);
            if (!line.startsWith("Z")) {
              pmCursor.beginElement(line, "urn:hl7-org:v2xml");
              pmCursor.toNextToken();
            }
          } catch (StringIndexOutOfBoundsException e) {
            if (line.length() > 3) {
              System.out.println(line);
            }
          }
        }
      }
      pmCursor.dispose();

      // Create a schema
      StreamSource xsltStream =
          new StreamSource(
              MessageStructureValidationV2Er7.class
                  .getClassLoader()
                  .getResourceAsStream(MessageValidationConstants.XSLT_CHECK_STRUCTURE));
      Transformer t = TransformerFactory.newInstance().newTransformer(xsltStream);
      t.setParameter("groups", "false");
      t.setParameter("xml", "false");

      StreamSource src = new StreamSource(profile.getDocument().newInputStream());
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      t.transform(src, new StreamResult(out));
      XmlObject schemaDoc =
          XmlObject.Factory.parse(
              new ByteArrayInputStream(out.toByteArray()), (new XmlOptions()).setLoadLineNumbers());
      // pseudoMessage.save(new File("tmp/mu/PseudoMessage.xml"));
      // schemaDoc.save(new File("tmp/mu/Schema.xsd"));
      // Load the schema
      SchemaTypeLoader sLoader = null;
      Collection<Object> compErrors = new ArrayList<Object>();
      XmlOptions schemaOptions = new XmlOptions();
      schemaOptions.setErrorListener(compErrors);
      XmlObject[] schemas = new XmlObject[1];

      schemas[0] = schemaDoc;
      sLoader = XmlBeans.compileXsd(schemas, sLoader, schemaOptions);

      // Load the Message
      XmlObject xobj =
          sLoader.parse(pseudoMessage.toString(), null, (new XmlOptions()).setLoadLineNumbers());

      // Validate the Message against the schema
      Collection<XmlValidationError> errors = new ArrayList<XmlValidationError>();
      xobj.validate(new XmlOptions().setErrorListener(errors));
      Iterator<XmlValidationError> it = errors.iterator();
      while (it.hasNext()) {
        XmlValidationError xve = it.next();
        messageFailures.add(interpretSchemaError(xve));
        messageStructureFailure = true;
      }
    } catch (XmlException xmle) {
      // This type of exception is thrown when the generated schema is
      // ambiguous
      MessageFailureV2 mf = new MessageFailureV2(message.getEncoding());
      mf.setDescription(
          "The message validation can't be performed because the profile is ambiguous."
              + " Possible reasons for this problem include an ambiguous message definition"
              + " specified in the standard or an ambiguous message definition caused by the"
              + " user changing the Usage settings for segments during profile creation."
              + " Remember that a segment with the same name MUST be separated by at least one"
              + " non-optional segment with a different name.");
      mf.setFailureSeverity(ErrorSeverityConstants.FATAL);
      mf.setFailureType(AssertionTypeV2Constants.AMBIGUOUS_PROFILE);
      messageFailures.add(mf);
    } catch (Exception e) {
      throw new MessageValidationException(e.getMessage());
    } finally {
      if (!messageStructureFailure) {
        MessageFailureV2 mf = new MessageFailureV2(message.getEncoding());
        mf.setDescription("The message structure at the segment level is correct.");
        mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
        mf.setFailureType(AssertionTypeV2Constants.CHECKED);
        messageFailures.add(mf);
      }
    }
  }
  /**
   * Check a value
   *
   * @param obj the object associated (from profile)
   * @param value the value from ER7
   */
  private void checkValue(XmlObject obj, String value) {

    XmlCursor cur = obj.newCursor();

    /* Check X usage */
    String usage = cur.getAttributeText(QName.valueOf("Usage"));
    if (!usage.equals("X")) {
      if (!(usage.equals("O") && value.equals(""))) {
        /* Check extra separators */
        if (getCurrentLocation().getSegmentName().equals("MSH")
            && getCurrentLocation().getFieldPosition() == 2) {
          /* MSH.2 */
          checkSeparators(obj, value);
        }
        /* Check length */
        String maxLength = cur.getAttributeText(QName.valueOf("Length"));
        if (maxLength != null) {
          MessageFailureV2 mf = checkLength(value, Integer.parseInt(maxLength));
          if (mf != null) {
            mf.setLine(lineNumber);
            mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
            mf.setPath(getCurrentLocation().toString());

            messageFailures.add(mf);
          }
        }
        /* Check table */
        String table = cur.getAttributeText(QName.valueOf("Table"));
        if (table != null) {
          MessageFailureV2 mf = checkTable(value, table);
          if (mf != null) {
            mf.setLine(lineNumber);
            mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
            mf.setPath(getCurrentLocation().toString());

            messageFailures.add(mf);
          }
        }
        /* Check constant value */
        String constant = cur.getAttributeText(QName.valueOf("ConstantValue"));
        if (constant != null) {
          MessageFailureV2 mf = checkConstant(value, constant);
          if (mf != null) {
            mf.setLine(lineNumber);
            mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
            mf.setPath(getCurrentLocation().toString());

            messageFailures.add(mf);
          }
        }
        /* Check datatype */
        String datatype = cur.getAttributeText(QName.valueOf("Datatype"));
        MessageFailureV2 mf = checkDatatype(value, datatype);
        if (mf != null) {
          mf.setLine(lineNumber);
          mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
          mf.setPath(getCurrentLocation().toString());

          messageFailures.add(mf);
        }
      }
    }
  }
Beispiel #19
0
 public static String getPrefixForNamespace(final XmlObject element, final String namespace) {
   final XmlCursor cursor = element.newCursor();
   final String prefix = cursor.prefixForNamespace(namespace);
   cursor.dispose();
   return prefix;
 }
Beispiel #20
0
 /**
  * Remove the element from XML document
  *
  * @param element Element to remove
  * @return <code>true</code>, if element is removed
  */
 public static boolean removeElement(XmlObject element) {
   XmlCursor cursor = element.newCursor();
   boolean removed = cursor.removeXml();
   cursor.dispose();
   return removed;
 }
  /**
   * Check the component
   *
   * @param componentObj the component object (from profile)
   * @param component the component string (from ER7)
   */
  private void checkComponent(XmlObject componentObj, String component) {
    locSubComponentPosition = -1;
    XmlCursor cur = componentObj.newCursor();

    /* Check usage */
    String usage = cur.getAttributeText(QName.valueOf("Usage"));
    boolean usageError = checkUsage(componentObj, component);

    if (!usageError) {
      if (usage.equals("R") || !component.equals("")) {
        XmlObject[] subcomponentsObj = componentObj.selectChildren(QName.valueOf("SubComponent"));
        if (subcomponentsObj.length > 0) {
          if (((Er7Message) message).getSubComponentSeparatorChar().equals("")) {
            MessageFailureV2 mf = new MessageFailureV2(message.getEncoding());
            mf.setFailureType(AssertionTypeV2Constants.DATA);
            mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
            mf.setDescription("The subcomponent separator is not set. Check MSH.1");
            mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
            mf.setLine(lineNumber);
            mf.setPath(getCurrentLocation().toString());

            messageFailures.add(mf);
          } else {
            String[] subcomponents =
                component.split(((Er7Message) message).getSubComponentSeparator());
            if (subcomponents.length > subcomponentsObj.length) {
              /* Extra subcomponents */
              MessageFailureV2 mf = new MessageFailureV2(message.getEncoding());
              mf.setFailureType(AssertionTypeV2Constants.XTRA);
              mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
              mf.setDescription(
                  "Extra subcomponents for component " + getCurrentLocation().toString());
              mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
              mf.setLine(lineNumber);
              mf.setPath(getCurrentLocation().toString());

              messageFailures.add(mf);
            } else {
              for (int i = 0; i < subcomponentsObj.length; i++) {
                locSubComponentPosition = i + 1;
                // mLocation.setSubcompNumber(i + 1);
                if (i < subcomponents.length) {
                  checkSubComponent(subcomponentsObj[i], subcomponents[i]);
                } else {
                  /* Check Usage */
                  checkUsage(subcomponentsObj[i], "");
                }
              }
            }
          }
        } else {
          /* Check value */
          checkValue(componentObj, component);
        }
      }
    }
    // No SubComponents
    if ("R".equals(usage)
        && "".equals(component)
        && componentObj.selectChildren(QName.valueOf("SubComponent")).length > 0) {
      locSubComponentPosition = -1;
      StringBuffer sb = new StringBuffer();
      MessageFailureV2 mf = new MessageFailureV2(message.getEncoding());
      sb.append("The element is missing at least one of its children");
      mf.setDescription(sb.toString());
      mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
      mf.setFailureType(AssertionTypeV2Constants.MESSAGE_STRUCTURE);
      mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
      mf.setLine(lineNumber);
      mf.setPath(getCurrentLocation().toString());
      messageFailures.add(mf);
      sb = null;
    }
  }
  /**
   * Check a field
   *
   * @param fieldObj the field object (from profile)
   * @param field the field string (from ER7)
   */
  private void checkField(XmlObject fieldObj, String field) {
    fieldInstance = 1;
    locComponentPosition = -1;

    XmlCursor cur = fieldObj.newCursor();

    /* Check usage */
    String usage = cur.getAttributeText(QName.valueOf("Usage"));
    boolean usageError = checkUsage(fieldObj, field);

    if (!usageError) {
      if (usage.equals("R") || !field.equals("")) {
        /* Check cardinalities */
        String min = cur.getAttributeText(QName.valueOf("Min"));
        String max = cur.getAttributeText(QName.valueOf("Max"));

        if (getCurrentLocation().getSegmentName().equals("MSH")
            && getCurrentLocation().getFieldPosition() == 2) {
          /* MSH.2 */
          checkValue(fieldObj, field);
        } else {

          String[] repetitions = field.split(((Er7Message) message).getRepetitionSeparator());
          int occurences = repetitions.length;
          if (field.equals("")) {
            occurences = 0;
          }
          checkCardinalities(fieldObj, usage, min, max, occurences);

          XmlObject[] componentsObj = fieldObj.selectChildren(QName.valueOf("Component"));
          if (componentsObj.length > 0) {
            for (int i = 0; i < repetitions.length; i++) {
              locFieldInstanceNumber = i + 1;
              String[] components =
                  repetitions[i].split(((Er7Message) message).getComponentSeparator());
              if (components.length > componentsObj.length) {
                /* Extra components */
                MessageFailureV2 mf = new MessageFailureV2(message.getEncoding());
                mf.setFailureType(AssertionTypeV2Constants.XTRA);
                mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
                mf.setDescription("Extra components for field " + getCurrentLocation().toString());
                mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
                mf.setLine(lineNumber);
                mf.setPath(getCurrentLocation().toString());

                messageFailures.add(mf);
              } else {
                for (int j = 0; j < componentsObj.length; j++) {
                  locComponentPosition = j + 1;
                  locSubComponentPosition = -1;
                  if (j < components.length) {
                    checkComponent(componentsObj[j], components[j]);
                  } else {
                    /* check Usage */
                    checkUsage(componentsObj[j], "");
                  }
                }
              }
              fieldInstance++;
            }
          } else {
            for (int i = 0; i < repetitions.length; i++) {
              locFieldInstanceNumber = i + 1;
              if (!repetitions[i].matches("\\s*")) {
                /* Check value */
                checkValue(fieldObj, repetitions[i]);
              }
              fieldInstance++;
            }
          }
        }
      }
    }
    // No Components
    if ("R".equals(usage)
        && "".equals(field)
        && fieldObj.selectChildren(QName.valueOf("Component")).length > 0) {
      locComponentPosition = -1;
      StringBuffer sb = new StringBuffer();
      MessageFailureV2 mf = new MessageFailureV2(message.getEncoding());
      sb.append("The element is missing at least one of its children");
      mf.setDescription(sb.toString());
      mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
      mf.setFailureType(AssertionTypeV2Constants.MESSAGE_STRUCTURE);
      mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
      mf.setLine(lineNumber);
      mf.setPath(getCurrentLocation().toString());
      messageFailures.add(mf);
      sb = null;
    }
  }
Beispiel #23
0
  private x0.scimSchemasCore1.Resource internalEncode(
      Resource resource, List<String> attributesList) {
    try {
      Object xmlObject = createXmlObject(resource);

      x0.scimSchemasCore1.Resource xmlResource =
          (x0.scimSchemasCore1.Resource)
              new ComplexHandler().encodeXml(resource, attributesList, null, xmlObject);

      // TODO check include attributes for extensions too
      List<Object> extensions = resource.getExtensions();
      for (Object extension : extensions) {
        if (!extension.getClass().isAnnotationPresent(Extension.class)) {
          throw new RuntimeException(
              "The extension '"
                  + extension.getClass().getName()
                  + "' has no namespace, try to add Extension annotation to class");
        }

        Extension extensionMetaData = extension.getClass().getAnnotation(Extension.class);

        for (Method method : extension.getClass().getMethods()) {
          if (!method.isAnnotationPresent(Attribute.class)) {
            continue;
          }

          Object data = method.invoke(extension);
          if (data == null) {
            continue;
          }

          MetaData metaData = new MetaData(method.getAnnotation(Attribute.class));
          String attributeName = extensionMetaData.schema() + "." + metaData.getName();
          if (attributesList != null && !attributesList.contains(attributeName)) {
            continue;
          }

          Class<?> factory = ReflectionHelper.getFactory(metaData.getXmlDoc());
          XmlObject doc = (XmlObject) factory.getMethod("newInstance").invoke(null);
          Object innerXml = null;
          try {
            String adder = "addNew";
            adder += metaData.getName().substring(0, 1).toUpperCase();
            adder += metaData.getName().substring(1);
            innerXml = doc.getClass().getMethod(adder).invoke(doc);
          } catch (NoSuchMethodException e) {
            // It is okay this is a simple type
          }
          IEncodeHandler encoder = metaData.getEncoder();
          Object result =
              encoder.encodeXml(data, attributesList, metaData.getInternalMetaData(), innerXml);

          String setter = "set";
          setter += metaData.getName().substring(0, 1).toUpperCase();
          setter += metaData.getName().substring(1);
          ReflectionHelper.getMethod(setter, doc.getClass()).invoke(doc, result);

          XmlCursor docCursor = doc.newCursor();
          docCursor.toFirstChild();

          XmlCursor cursor = xmlResource.newCursor();
          cursor.toEndToken();
          docCursor.moveXml(cursor);
          cursor.dispose();
          docCursor.dispose();
        }
      }

      return xmlResource;
    } catch (SecurityException e) {
      throw new RuntimeException("Internal error, encoding xml", e);
    } catch (IllegalAccessException e) {
      throw new RuntimeException("Internal error, encoding xml", e);
    } catch (IllegalArgumentException e) {
      throw new RuntimeException("Internal error, encoding xml", e);
    } catch (InvocationTargetException e) {
      throw new RuntimeException("Internal error, encoding xml", e);
    } catch (FactoryNotFoundException e) {
      throw new RuntimeException("Internal error, encoding xml", e);
    } catch (NoSuchMethodException e) {
      throw new RuntimeException("Internal error, encoding xml", e);
    }
  }
  /**
   * Check the segments cardinalities
   *
   * @param segObj the Segment object
   */
  private void checkSegmentCardinalities(XmlObject segObj) {

    XmlCursor cur = segObj.newCursor();
    String usage = cur.getAttributeText(QName.valueOf("Usage"));
    String segName = cur.getAttributeText(QName.valueOf("Name"));
    if (!usage.equals("X")) {
      String min = cur.getAttributeText(QName.valueOf("Min"));
      String max = cur.getAttributeText(QName.valueOf("Max"));
      if (cur.toParent()) {
        if (cur.getName().toString().equals("SegGroup")) {
          ArrayList<Integer> list = profileMapping.get(segObj);
          if (list != null) {
            Iterator<Integer> it = list.iterator();
            ArrayList<ArrayList<Integer>> groups = new ArrayList<ArrayList<Integer>>();
            ArrayList<Integer> currentGroup = null;
            int previous = 0;
            while (it.hasNext()) {
              int lineNr = it.next();
              /* init */
              if (currentGroup == null) {
                ArrayList<Integer> group = new ArrayList<Integer>();
                currentGroup = group;
                currentGroup.add(lineNr);
              } else {
                /* does the line belong to the current group ? */
                boolean b = true;
                int i = previous + 1;
                while (i < lineNr && b) {
                  String line = er7Mapping.get(i);
                  if (!line.matches("\\s*")) {
                    b = false;
                  }
                }
                if (b) {
                  currentGroup.add(lineNr);
                } else {
                  groups.add(currentGroup);
                  ArrayList<Integer> group = new ArrayList<Integer>();
                  currentGroup = group;
                  currentGroup.add(lineNr);
                }
              }
              previous = lineNr;
            }
          }
        } else {
          ArrayList<Integer> list = profileMapping.get(segObj);
          if (list != null) {
            int occurrences = list.size();
            if (occurrences < Integer.parseInt(min)) {
              MessageFailureV2 mf = new MessageFailureV2(message.getEncoding());
              mf.setFailureType(AssertionTypeV2Constants.CARDINALITY);
              mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
              mf.setDescription(
                  segName
                      + " is present "
                      + occurrences
                      + " times whereas it must be present at least "
                      + min
                      + " times");
              mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
              mf.setLine(lineNumber);
              mf.setPath(getCurrentLocation().toString());
              messageFailures.add(mf);
            }
            if (!max.equals("*") && occurrences > Integer.parseInt(max)) {
              MessageFailureV2 mf = new MessageFailureV2(message.getEncoding());
              mf.setFailureType(AssertionTypeV2Constants.CARDINALITY);
              mf.setFailureSeverity(ErrorSeverityConstants.NORMAL);
              mf.setDescription(
                  segName
                      + " is present "
                      + occurrences
                      + " times whereas it is only allowed "
                      + max
                      + " times");
              mf.setColumn(((Er7Message) inputMessage).getColumn(getCurrentLocation()));
              mf.setLine(lineNumber);
              mf.setPath(getCurrentLocation().toString());

              messageFailures.add(mf);
            }
          }
        }
      }
    }
  }