예제 #1
0
  public static Element[] filterChildElements(Element parent, String ns, String lname) {
    /*
    way too noisy
            if (LOGGER.isDebugEnabled()) {
                StringBuilder buf = new StringBuilder(100);
                buf.append("XmlaUtil.filterChildElements: ");
                buf.append(" ns=\"");
                buf.append(ns);
                buf.append("\", lname=\"");
                buf.append(lname);
                buf.append("\"");
                LOGGER.debug(buf.toString());
            }
    */

    List<Element> elems = new ArrayList<Element>();
    NodeList nlst = parent.getChildNodes();
    for (int i = 0, nlen = nlst.getLength(); i < nlen; i++) {
      Node n = nlst.item(i);
      if (n instanceof Element) {
        Element e = (Element) n;
        if ((ns == null || ns.equals(e.getNamespaceURI()))
            && (lname == null || lname.equals(e.getLocalName()))) {
          elems.add(e);
        }
      }
    }
    return elems.toArray(new Element[elems.size()]);
  }
예제 #2
0
  //	@Test
  public void testElementsByTagNameWithNamespace() throws Exception {
    builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);

    String xml =
        "<?xml version=\"1.0\"?>"
            + "<t:root xmlns=\"http://void.com/\" xmlns:t=\"http://t.com/\" id=\"stella\" t:type=\"police\">"
            + "<t:item id=\"a\"/>"
            + "<child id=\"1\"/>"
            + "<t:item id=\"b\"/>"
            + "<child id=\"2\"/>"
            + "</t:root>";

    // TODO: Can I utilize xmlSearchNs or xmlSearchNsByHref? the problem is it searchs a specific
    // node and recurse up.
    // I don't have such a node

    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
    Element root = doc.getDocumentElement();

    List<String> expectedList = Arrays.asList("1", "2");
    List<String> actualList = new ArrayList<String>();
    NodeList nl = root.getElementsByTagNameNS("http://void.com/", "child");
    for (int i = 0; i < nl.getLength(); i++) {
      Element elem = (Element) nl.item(i);
      actualList.add(elem.getAttribute("id"));
    }
    Assert.assertArrayEquals("elementsByTagName", expectedList.toArray(), actualList.toArray());

    expectedList = Arrays.asList("a", "b");
    actualList.clear();
    nl = root.getElementsByTagNameNS("http://t.com/", "item");
    for (int i = 0; i < nl.getLength(); i++) {
      Element elem = (Element) nl.item(i);
      actualList.add(elem.getAttribute("id"));
    }
  }
예제 #3
0
  /**
   * Obtains an array of <code>Document</code>s to be processed by {@link
   * ConfigManager#FACES_CONFIG_PROCESSOR_CHAIN}.
   *
   * @param sc the <code>ServletContext</code> for the application to be processed
   * @param providers <code>List</code> of <code>ConfigurationResourceProvider</code> instances that
   *     provide the URL of the documents to parse.
   * @param executor the <code>ExecutorService</code> used to dispatch parse request to
   * @param validating flag indicating whether or not the documents should be validated
   * @return an array of <code>Document</code>s
   */
  private static Document[] getConfigDocuments(
      ServletContext sc,
      List<ConfigurationResourceProvider> providers,
      ExecutorService executor,
      boolean validating) {

    List<FutureTask<Collection<URL>>> urlTasks =
        new ArrayList<FutureTask<Collection<URL>>>(providers.size());
    for (ConfigurationResourceProvider p : providers) {
      FutureTask<Collection<URL>> t = new FutureTask<Collection<URL>>(new URLTask(p, sc));
      urlTasks.add(t);
      executor.execute(t);
    }

    List<FutureTask<Document>> docTasks =
        new ArrayList<FutureTask<Document>>(providers.size() << 1);

    for (FutureTask<Collection<URL>> t : urlTasks) {
      try {
        Collection<URL> l = t.get();
        for (URL u : l) {
          FutureTask<Document> d = new FutureTask<Document>(new ParseTask(validating, u));
          docTasks.add(d);
          executor.execute(d);
        }
      } catch (InterruptedException ignored) {
      } catch (Exception e) {
        throw new ConfigurationException(e);
      }
    }

    List<Document> docs = new ArrayList<Document>(docTasks.size());
    for (FutureTask<Document> t : docTasks) {
      try {
        docs.add(t.get());
      } catch (ExecutionException e) {
        throw new ConfigurationException(e);
      } catch (InterruptedException ignored) {
      }
    }

    return docs.toArray(new Document[docs.size()]);
  }
예제 #4
0
  /**
   * Sort the <code>faces-config</code> documents found on the classpath and those specified by the
   * <code>javax.faces.CONFIG_FILES</code> context init parameter.
   *
   * @param facesDocuments an array of <em>all</em> <code>faces-config</code> documents
   * @param facesConfig WebInfoFacesConfigInfo for this app
   * @return the sorted documents
   */
  private Document[] sortDocuments(Document[] facesDocuments, WebInfFacesConfigInfo facesConfig) {

    int len = (facesConfig.exists() ? facesDocuments.length - 1 : facesDocuments.length);

    List<String> absoluteOrdering = facesConfig.getAbsoluteOrdering();

    if (len > 1) {
      List<DocumentOrderingWrapper> list = new ArrayList<DocumentOrderingWrapper>();
      for (int i = 1; i < len; i++) {
        list.add(new DocumentOrderingWrapper(facesDocuments[i]));
      }
      DocumentOrderingWrapper[] ordering = list.toArray(new DocumentOrderingWrapper[list.size()]);
      if (absoluteOrdering == null) {
        DocumentOrderingWrapper.sort(ordering);
        // sorting complete, now update the appropriate locations within
        // the original array with the sorted documentation.
        for (int i = 1; i < len; i++) {
          facesDocuments[i] = ordering[i - 1].getDocument();
        }
        return facesDocuments;
      } else {
        DocumentOrderingWrapper[] result = DocumentOrderingWrapper.sort(ordering, absoluteOrdering);
        Document[] ret =
            new Document[((facesConfig.exists()) ? (result.length + 2) : (result.length + 1))];
        for (int i = 1; i < len; i++) {
          ret[i] = result[i - 1].getDocument();
        }
        // add the impl specific config file
        ret[0] = facesDocuments[0];
        // add the WEB-INF if necessary
        if (facesConfig.exists()) {
          ret[ret.length - 1] = facesDocuments[facesDocuments.length - 1];
        }
        return ret;
      }
    }

    return facesDocuments;
  }
예제 #5
0
  /**
   * Creates nodes from index entries
   *
   * @param theIndexEntries index entries
   * @param theTargetDocument target document
   * @param theIndexEntryComparator comparator to sort the index entries. if it is null the index
   *     entries will be unsorted
   * @return nodes for the target document
   */
  private Node[] transformToNodes(
      final IndexEntry[] theIndexEntries,
      final Document theTargetDocument,
      final Comparator<IndexEntry> theIndexEntryComparator) {
    if (null != theIndexEntryComparator) {
      Arrays.sort(theIndexEntries, theIndexEntryComparator);
    }

    final List<Element> result = new ArrayList<Element>();
    for (final IndexEntry indexEntry : theIndexEntries) {
      final Element indexEntryNode = createElement(theTargetDocument, "index.entry");

      final Element formattedStringElement = createElement(theTargetDocument, "formatted-value");
      if (indexEntry.getContents() != null) {
        for (final Iterator<Node> i = indexEntry.getContents().iterator(); i.hasNext(); ) {
          final Node child = i.next();
          final Node clone = theTargetDocument.importNode(child, true);
          if (!i.hasNext() && clone.getNodeType() == Node.TEXT_NODE) {
            final Text t = (Text) clone;
            t.setData(t.getData().replaceAll("[\\s\\n]+$", ""));
          }
          formattedStringElement.appendChild(clone);
        }
      } else {
        final Text textNode = theTargetDocument.createTextNode(indexEntry.getFormattedString());
        textNode.normalize();
        formattedStringElement.appendChild(textNode);
      }
      indexEntryNode.appendChild(formattedStringElement);

      final String[] refIDs = indexEntry.getRefIDs();
      for (final String refID : refIDs) {
        final Element referenceIDElement = createElement(theTargetDocument, "refID");
        referenceIDElement.setAttribute("value", refID);
        indexEntryNode.appendChild(referenceIDElement);
      }

      final String val = indexEntry.getValue();
      if (null != val) {
        indexEntryNode.setAttribute("value", val);
      }

      final String sort = indexEntry.getSortString();
      if (null != sort) {
        indexEntryNode.setAttribute("sort-string", sort);
      }

      if (indexEntry.isStartingRange()) {
        indexEntryNode.setAttribute("start-range", "true");
      } else if (indexEntry.isEndingRange()) {
        indexEntryNode.setAttribute("end-range", "true");
      }
      if (indexEntry.isSuppressesThePageNumber()) {
        indexEntryNode.setAttribute("no-page", "true");
      } else if (indexEntry.isRestoresPageNumber()) {
        indexEntryNode.setAttribute("single-page", "true");
      }

      final IndexEntry[] childIndexEntries = indexEntry.getChildIndexEntries();

      final Node[] nodes =
          transformToNodes(childIndexEntries, theTargetDocument, theIndexEntryComparator);

      for (final Node node : nodes) {
        indexEntryNode.appendChild(node);
      }

      final IndexEntry[] seeChildIndexEntries = indexEntry.getSeeChildIndexEntries();
      if (seeChildIndexEntries != null) {
        final Element seeElement = createElement(theTargetDocument, "see-childs");
        final Node[] seeNodes =
            transformToNodes(seeChildIndexEntries, theTargetDocument, theIndexEntryComparator);
        for (final Node node : seeNodes) {
          seeElement.appendChild(node);
        }

        indexEntryNode.appendChild(seeElement);
      }

      final IndexEntry[] seeAlsoChildIndexEntries = indexEntry.getSeeAlsoChildIndexEntries();
      if (seeAlsoChildIndexEntries != null) {
        final Element seeAlsoElement = createElement(theTargetDocument, "see-also-childs");
        final Node[] seeAlsoNodes =
            transformToNodes(seeAlsoChildIndexEntries, theTargetDocument, theIndexEntryComparator);
        for (final Node node : seeAlsoNodes) {
          seeAlsoElement.appendChild(node);
        }

        indexEntryNode.appendChild(seeAlsoElement);
      }

      result.add(indexEntryNode);
    }
    return (Node[]) result.toArray(new Node[result.size()]);
  }
 /**
  * Unmarshall a Chromosome instance from a given XML Element representation.
  *
  * @param a_activeConfiguration current Configuration object
  * @param a_xmlElement the XML Element representation of the Chromosome
  * @return a new Chromosome instance setup with the data from the XML Element representation
  * @throws ImproperXMLException if the given Element is improperly structured or missing data
  * @throws UnsupportedRepresentationException if the actively configured Gene implementation does
  *     not support the string representation of the alleles used in the given XML document
  * @throws GeneCreationException if there is a problem creating or populating a Gene instance
  * @author Neil Rotstan
  * @since 1.0
  */
 public static Gene[] getGenesFromElement(
     Configuration a_activeConfiguration, Element a_xmlElement)
     throws ImproperXMLException, UnsupportedRepresentationException, GeneCreationException {
   // Do some sanity checking. Make sure the XML Element isn't null and
   // that it in fact represents a set of genes.
   // -----------------------------------------------------------------
   if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(GENES_TAG))) {
     throw new ImproperXMLException(
         "Unable to build Chromosome instance from XML Element: "
             + "given Element is not a 'genes' element.");
   }
   List genes = Collections.synchronizedList(new ArrayList());
   // Extract the nested gene elements.
   // ---------------------------------
   NodeList geneElements = a_xmlElement.getElementsByTagName(GENE_TAG);
   if (geneElements == null) {
     throw new ImproperXMLException(
         "Unable to build Gene instances from XML Element: "
             + "'"
             + GENE_TAG
             + "'"
             + " sub-elements not found.");
   }
   // For each gene, get the class attribute so we know what class
   // to instantiate to represent the gene instance, and then find
   // the child text node, which is where the string representation
   // of the allele is located, and extract the representation.
   // -------------------------------------------------------------
   int numberOfGeneNodes = geneElements.getLength();
   for (int i = 0; i < numberOfGeneNodes; i++) {
     Element thisGeneElement = (Element) geneElements.item(i);
     thisGeneElement.normalize();
     // Fetch the class attribute and create an instance of that
     // class to represent the current gene.
     // --------------------------------------------------------
     String geneClassName = thisGeneElement.getAttribute(CLASS_ATTRIBUTE);
     Gene thisGeneObject;
     Class geneClass = null;
     try {
       geneClass = Class.forName(geneClassName);
       try {
         Constructor constr = geneClass.getConstructor(new Class[] {Configuration.class});
         thisGeneObject = (Gene) constr.newInstance(new Object[] {a_activeConfiguration});
       } catch (NoSuchMethodException nsme) {
         // Try it by calling method newGeneInternal.
         // -----------------------------------------
         Constructor constr = geneClass.getConstructor(new Class[] {});
         thisGeneObject = (Gene) constr.newInstance(new Object[] {});
         thisGeneObject =
             (Gene)
                 PrivateAccessor.invoke(
                     thisGeneObject, "newGeneInternal", new Class[] {}, new Object[] {});
       }
     } catch (Throwable e) {
       throw new GeneCreationException(geneClass, e);
     }
     // Find the text node and fetch the string representation of
     // the allele.
     // ---------------------------------------------------------
     NodeList children = thisGeneElement.getChildNodes();
     int childrenSize = children.getLength();
     String alleleRepresentation = null;
     for (int j = 0; j < childrenSize; j++) {
       Element alleleElem = (Element) children.item(j);
       if (alleleElem.getTagName().equals(ALLELE_TAG)) {
         alleleRepresentation = alleleElem.getAttribute("value");
       }
       if (children.item(j).getNodeType() == Node.TEXT_NODE) {
         // We found the text node. Extract the representation.
         // ---------------------------------------------------
         alleleRepresentation = children.item(j).getNodeValue();
         break;
       }
     }
     // Sanity check: Make sure the representation isn't null.
     // ------------------------------------------------------
     if (alleleRepresentation == null) {
       throw new ImproperXMLException(
           "Unable to build Gene instance from XML Element: "
               + "value (allele) is missing representation.");
     }
     // Now set the value of the gene to that reflect the
     // string representation.
     // -------------------------------------------------
     try {
       thisGeneObject.setValueFromPersistentRepresentation(alleleRepresentation);
     } catch (UnsupportedOperationException e) {
       throw new GeneCreationException(
           "Unable to build Gene because it does not support the "
               + "setValueFromPersistentRepresentation() method.");
     }
     // Finally, add the current gene object to the list of genes.
     // ----------------------------------------------------------
     genes.add(thisGeneObject);
   }
   return (Gene[]) genes.toArray(new Gene[genes.size()]);
 }
예제 #7
0
  /**
   * Validate message with a XML schema.
   *
   * @param receivedMessage
   * @param validationContext
   */
  protected void validateXMLSchema(
      Message receivedMessage, XmlMessageValidationContext validationContext) {
    if (receivedMessage.getPayload() == null
        || !StringUtils.hasText(receivedMessage.getPayload(String.class))) {
      return;
    }

    try {
      Document doc = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class));

      if (!StringUtils.hasText(doc.getFirstChild().getNamespaceURI())) {
        return;
      }

      log.info("Starting XML schema validation ...");

      XmlValidator validator = null;
      XsdSchemaRepository schemaRepository = null;
      if (validationContext.getSchema() != null) {
        validator =
            applicationContext
                .getBean(validationContext.getSchema(), XsdSchema.class)
                .createValidator();
      } else if (validationContext.getSchemaRepository() != null) {
        schemaRepository =
            applicationContext.getBean(
                validationContext.getSchemaRepository(), XsdSchemaRepository.class);
      } else if (schemaRepositories.size() == 1) {
        schemaRepository = schemaRepositories.get(0);
      } else if (schemaRepositories.size() > 0) {
        for (XsdSchemaRepository repository : schemaRepositories) {
          if (repository.canValidate(doc)) {
            schemaRepository = repository;
          }
        }

        if (schemaRepository == null) {
          throw new CitrusRuntimeException(
              String.format(
                  "Failed to find proper schema repository in Spring bean context for validating element '%s(%s)'",
                  doc.getFirstChild().getLocalName(), doc.getFirstChild().getNamespaceURI()));
        }
      } else {
        log.warn(
            "Neither schema instance nor schema repository defined - skipping XML schema validation");
        return;
      }

      if (schemaRepository != null) {
        if (!schemaRepository.canValidate(doc)) {
          throw new CitrusRuntimeException(
              String.format(
                  "Unable to find proper XML schema definition for element '%s(%s)' in schema repository '%s'",
                  doc.getFirstChild().getLocalName(),
                  doc.getFirstChild().getNamespaceURI(),
                  schemaRepository.getName()));
        }

        List<Resource> schemas = new ArrayList<>();
        for (XsdSchema xsdSchema : schemaRepository.getSchemas()) {
          if (xsdSchema instanceof XsdSchemaCollection) {
            for (Resource resource : ((XsdSchemaCollection) xsdSchema).getSchemaResources()) {
              schemas.add(resource);
            }
          } else if (xsdSchema instanceof WsdlXsdSchema) {
            for (Resource resource : ((WsdlXsdSchema) xsdSchema).getSchemaResources()) {
              schemas.add(resource);
            }
          } else {
            synchronized (transformerFactory) {
              ByteArrayOutputStream bos = new ByteArrayOutputStream();
              try {
                transformerFactory
                    .newTransformer()
                    .transform(xsdSchema.getSource(), new StreamResult(bos));
              } catch (TransformerException e) {
                throw new CitrusRuntimeException(
                    "Failed to read schema " + xsdSchema.getTargetNamespace(), e);
              }
              schemas.add(new ByteArrayResource(bos.toByteArray()));
            }
          }
        }

        validator =
            XmlValidatorFactory.createValidator(
                schemas.toArray(new Resource[schemas.size()]), WsdlXsdSchema.W3C_XML_SCHEMA_NS_URI);
      }

      SAXParseException[] results = validator.validate(new DOMSource(doc));
      if (results.length == 0) {
        log.info("Schema of received XML validated OK");
      } else {
        log.error(
            "Schema validation failed for message:\n"
                + XMLUtils.prettyPrint(receivedMessage.getPayload(String.class)));

        // Report all parsing errors
        log.debug("Found " + results.length + " schema validation errors");
        StringBuilder errors = new StringBuilder();
        for (SAXParseException e : results) {
          errors.append(e.toString());
          errors.append("\n");
        }
        log.debug(errors.toString());

        throw new ValidationException("Schema validation failed:", results[0]);
      }
    } catch (IOException e) {
      throw new CitrusRuntimeException(e);
    } catch (SAXException e) {
      throw new CitrusRuntimeException(e);
    }
  }