Exemplo n.º 1
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();
  }
Exemplo n.º 2
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;
  }
  @Test
  public void shouldCreateValidNotification() throws XmlException, IOException, OXFException {
    String sesUrl = "http://ses.host";
    String dialect = "http://my-funny/dialect";
    ParameterContainer parameters = new ParameterContainer();
    parameters.addParameterShell(SESRequestBuilder_00.NOTIFY_SES_URL, sesUrl);
    parameters.addParameterShell(SESRequestBuilder_00.NOTIFY_TOPIC_DIALECT, dialect);
    parameters.addParameterShell(SESRequestBuilder_00.NOTIFY_TOPIC, "<start>topic</start>");
    parameters.addParameterShell(SESRequestBuilder_00.NOTIFY_XML_MESSAGE, readMessage());

    SESRequestBuilder_00 request = new SESRequestBuilder_00();
    String asText = request.buildNotifyRequest(parameters);
    EnvelopeDocument envelope = EnvelopeDocument.Factory.parse(asText);

    XMLBeansParser.registerLaxValidationCase(SASamplingPointCase.getInstance());
    Collection<XmlError> errors = XMLBeansParser.validate(envelope);
    Assert.assertTrue("Notification is not valid: " + errors, errors.isEmpty());

    XmlCursor bodyCur = envelope.getEnvelope().getBody().newCursor();
    bodyCur.toFirstChild();
    Assert.assertTrue(bodyCur.getObject() instanceof Notify);
    XmlCursor tmpCur =
        ((Notify) bodyCur.getObject()).getNotificationMessageArray()[0].getMessage().newCursor();
    tmpCur.toFirstChild();
    Assert.assertTrue(tmpCur.getObject() instanceof ObservationType);

    Assert.assertTrue(
        ((Notify) bodyCur.getObject())
            .getNotificationMessageArray()[0]
            .getTopic()
            .getDialect()
            .trim()
            .equals(dialect));

    tmpCur = ((Notify) bodyCur.getObject()).getNotificationMessageArray()[0].getTopic().newCursor();

    Assert.assertTrue(tmpCur.getObject().xmlText().contains("<start>"));
  }
 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());
   }
 }
 public QName getContentsQName(EDXLDistribution edxl) {
   QName qname = null;
   XmlCursor c =
       edxl.getContentObjectArray(0).getXmlContent().getEmbeddedXMLContentArray(0).newCursor();
   try {
     if (c.toFirstChild()) {
       qname = c.getObject().schemaType().getOuterType().getDocumentElementName();
     }
   } catch (Exception e) {
     log.error("Error finding EDXL-DE content type: " + e.getMessage());
     log.error("From EDXL-DE: " + edxl.toString());
   } finally {
     c.dispose();
   }
   return qname;
 }
Exemplo n.º 6
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;
   }
 }
  @Test
  public void shouldCreateValidLevel1SubscribeRequest() throws OXFException, XmlException {
    String consumer = "http://*****:*****@xlink:href='urn:ogc:object:procedure:CITE:WeatherService:LGA'";

    ParameterContainer parameter = new ParameterContainer();
    parameter.addParameterShell(ISESRequestBuilder.SUBSCRIBE_SES_URL, host);
    parameter.addParameterShell(ISESRequestBuilder.SUBSCRIBE_CONSUMER_REFERENCE_ADDRESS, consumer);
    parameter.addParameterShell(ISESRequestBuilder.SUBSCRIBE_FILTER_TOPIC, topicString);
    parameter.addParameterShell(
        ISESRequestBuilder.SUBSCRIBE_FILTER_MESSAGE_CONTENT_DIALECT, dialect);
    parameter.addParameterShell(ISESRequestBuilder.SUBSCRIBE_FILTER_MESSAGE_CONTENT, xpath);

    SESRequestBuilder_00 request = new SESRequestBuilder_00();
    String asText = request.buildSubscribeRequest(parameter);
    EnvelopeDocument envelope = EnvelopeDocument.Factory.parse(asText);

    Collection<XmlError> errors = XMLBeansParser.validate(envelope);
    Assert.assertTrue("SubscribeRequest is not valid: " + errors, errors.isEmpty());

    Body body = envelope.getEnvelope().getBody();
    XmlCursor cur = body.newCursor();
    cur.toFirstChild();
    XmlObject subscribeRequestObject = cur.getObject();
    cur.dispose();

    if (!(subscribeRequestObject instanceof Subscribe))
      throw new IllegalStateException("Body does not contain a Subscribe request.");

    Subscribe subscribeRequest = (Subscribe) subscribeRequestObject;
    Assert.assertTrue(
        subscribeRequest
            .getConsumerReference()
            .getAddress()
            .getStringValue()
            .trim()
            .equals(consumer.trim()));

    cur = subscribeRequest.getFilter().newCursor();
    cur.toFirstChild();
    do {
      XmlObject filterElement = cur.getObject();
      if (filterElement instanceof QueryExpressionType) {
        QueryExpressionType qet = (QueryExpressionType) filterElement;
        Assert.assertTrue(qet.getDialect().trim().equals(dialect.trim()));
        XmlCursor tmpCur = qet.newCursor();
        Assert.assertTrue(tmpCur.toFirstContentToken() == TokenType.TEXT);
        Assert.assertTrue(tmpCur.getChars().trim().equals(xpath.trim()));
      } else if (filterElement instanceof TopicExpressionType) {
        TopicExpressionType tet = (TopicExpressionType) filterElement;
        Assert.assertTrue(
            tet.getDialect().trim().equals(SESRequestBuilder_00.DEFAULT_TOPIC_DIALECT));
        XmlCursor tmpCur = tet.newCursor();
        Assert.assertTrue(tmpCur.toFirstContentToken() == TokenType.TEXT);
        Assert.assertTrue(tmpCur.getChars().trim().equals(topicString.trim()));
      }
    } while (cur.toNextSibling());
  }
Exemplo n.º 8
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);
    }
  }