Java Code Examples for javax.xml.parsers.DocumentBuilder

The following examples show how to use javax.xml.parsers.DocumentBuilder. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: lams   Source File: XMLMap.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static Document getXMLDom(Map<?, ?> tm)
{
	if ( tm == null ) return null;
	Document document = null;

	try{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
		factory.setFeature("http://xml.org/sax/features/external-general-entities", false); 
		factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); 
		DocumentBuilder parser = factory.newDocumentBuilder();
		document = parser.newDocument();
	} catch (Exception e) {
		return null;
	}

	iterateMap(document, document.getDocumentElement(), tm, 0);
	return document;
}
 
Example 2
Source Project: carbon-identity   Source File: IdentityUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Constructing the SAML or XACML Objects from a String
 *
 * @param xmlString Decoded SAML or XACML String
 * @return SAML or XACML Object
 * @throws org.wso2.carbon.identity.base.IdentityException
 */
public static XMLObject unmarshall(String xmlString) throws IdentityException {

    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);

        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        org.apache.xerces.util.SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        documentBuilderFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);

        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        Document document = docBuilder.parse(new ByteArrayInputStream(xmlString.trim().getBytes(Charsets.UTF_8)));
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
    } catch (ParserConfigurationException | UnmarshallingException | SAXException | IOException e) {
        String message = "Error in constructing XML Object from the encoded String";
        throw IdentityException.error(message, e);
    }
}
 
Example 3
Source Project: development   Source File: PaymentServiceProviderBean.java    License: Apache License 2.0 6 votes vote down vote up
private Document createDeregistrationRequestDocument(RequestData data)
        throws ParserConfigurationException,
        PSPIdentifierForSellerException {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();

    Element headerElement = setHeaderXMLParameters(doc);
    setSecurityHeaderXMLParameters(doc, headerElement, data);

    Element transactionElement = setTransactionXMLAttributes(doc,
            headerElement, true, data);

    setIdentificationXMLParameters(doc, transactionElement, data
            .getPaymentInfoKey().longValue(), data.getExternalIdentifier());

    // set the payment code to indicate deregistration
    Element paymentElement = doc
            .createElement(HeidelpayXMLTags.XML_ELEMENT_PAYMENT);
    paymentElement.setAttribute(HeidelpayXMLTags.XML_ATTRIBUTE_CODE,
            getHeidelPayPaymentType(data.getPaymentTypeId()) + ".DR");
    transactionElement.appendChild(paymentElement);
    return doc;
}
 
Example 4
Source Project: netbeans   Source File: Hk2DatasourceManager.java    License: Apache License 2.0 6 votes vote down vote up
private static Document readResourceFile(DocumentBuilder docBuilder, File sunResourcesXml) throws IOException{
    boolean newOne = false;
    if(!sunResourcesXml.exists()){
        FileUtil.createData(sunResourcesXml);//ensure file exist
        newOne = true;
    }
    Document doc = null;
    try {
        if(newOne) {
            if (sunResourcesXml.getAbsolutePath().contains("sun-resources.xml"))
                doc = docBuilder.parse(new InputSource(new StringReader(SUN_RESOURCES_XML_HEADER)));
            else
                doc = docBuilder.parse(new InputSource(new StringReader(GF_RESOURCES_XML_HEADER)));
        }
        else   {
            doc = docBuilder.parse(sunResourcesXml);
        }
    } catch (SAXException ex) {
        throw new IOException("Malformed XML: " +ex.getMessage());
    }

    return doc;
}
 
Example 5
/**
 * Creates a new instance of a {@link javax.xml.parsers.DocumentBuilder}
 * using the currently configured parameters.
 */
public DocumentBuilder newDocumentBuilder()
    throws ParserConfigurationException
{
    /** Check that if a Schema has been specified that neither of the schema properties have been set. */
    if (grammar != null && attributes != null) {
        if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_LANGUAGE)) {
            throw new ParserConfigurationException(
                    SAXMessageFormatter.formatMessage(null,
                    "schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_LANGUAGE}));
        }
        else if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_SOURCE)) {
            throw new ParserConfigurationException(
                    SAXMessageFormatter.formatMessage(null,
                    "schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_SOURCE}));
        }
    }

    try {
        return new DocumentBuilderImpl(this, attributes, features, fSecureProcess);
    } catch (SAXException se) {
        // Handles both SAXNotSupportedException, SAXNotRecognizedException
        throw new ParserConfigurationException(se.getMessage());
    }
}
 
Example 6
Source Project: jeddict   Source File: OrderColumnAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public AdaptedMap marshal(Map<String, String> map) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.newDocument();
    Element rootElement = document.createElement("map");
    document.appendChild(rootElement);

    for(Entry<String,String> entry : map.entrySet()) {
        Element mapElement = document.createElement(entry.getKey());
        mapElement.setTextContent(entry.getValue());
        rootElement.appendChild(mapElement);
    }

    AdaptedMap adaptedMap = new AdaptedMap();
    adaptedMap.setValue(document);
    return adaptedMap;
}
 
Example 7
Source Project: spring-analysis-note   Source File: AbstractStaxHandlerTestCase.java    License: MIT License 6 votes vote down vote up
@Test
public void namespacePrefixesDom() throws Exception {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setNamespaceAware(true);
	DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

	Document expected = documentBuilder.parse(new InputSource(new StringReader(SIMPLE_XML)));

	Document result = documentBuilder.newDocument();
	AbstractStaxHandler handler = createStaxHandler(new DOMResult(result));
	xmlReader.setContentHandler(handler);
	xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

	xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
	xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

	xmlReader.parse(new InputSource(new StringReader(SIMPLE_XML)));

	assertThat(expected, isSimilarTo(result).withNodeFilter(nodeFilter));
}
 
Example 8
Source Project: hadoop   Source File: TestRMWebServicesNodes.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleNodesXML() throws JSONException, Exception {
  rm.start();
  WebResource r = resource();
  MockNM nm1 = rm.registerNode("h1:1234", 5120);
  // MockNM nm2 = rm.registerNode("h2:1235", 5121);
  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("nodes").path("h1:1234").accept(MediaType.APPLICATION_XML)
      .get(ClientResponse.class);

  assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
  String xml = response.getEntity(String.class);

  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  InputSource is = new InputSource();
  is.setCharacterStream(new StringReader(xml));
  Document dom = db.parse(is);
  NodeList nodes = dom.getElementsByTagName("node");
  assertEquals("incorrect number of elements", 1, nodes.getLength());
  verifyNodesXML(nodes, nm1);
  rm.stop();
}
 
Example 9
Source Project: hadoop   Source File: TestNMWebServicesContainers.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNodeContainerXML() throws JSONException, Exception {
  WebResource r = resource();
  Application app = new MockApp(1);
  nmContext.getApplications().put(app.getAppId(), app);
  addAppContainers(app);
  Application app2 = new MockApp(2);
  nmContext.getApplications().put(app2.getAppId(), app2);
  addAppContainers(app2);

  ClientResponse response = r.path("ws").path("v1").path("node")
      .path("containers").accept(MediaType.APPLICATION_XML)
      .get(ClientResponse.class);
  assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
  String xml = response.getEntity(String.class);
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  InputSource is = new InputSource();
  is.setCharacterStream(new StringReader(xml));
  Document dom = db.parse(is);
  NodeList nodes = dom.getElementsByTagName("container");
  assertEquals("incorrect number of elements", 4, nodes.getLength());
}
 
Example 10
Source Project: netbeans   Source File: JaxRsStackSupportImpl.java    License: Apache License 2.0 6 votes vote down vote up
private DocumentBuilder getDocumentBuilder() {
    DocumentBuilder builder = null;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setIgnoringComments(false);
    factory.setIgnoringElementContentWhitespace(false);
    factory.setCoalescing(false);
    factory.setExpandEntityReferences(false);
    factory.setValidating(false);

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Exceptions.printStackTrace(ex);
    }

    return builder;
}
 
Example 11
Source Project: HttpSessionReplacer   Source File: WebXmlParser.java    License: MIT License 6 votes vote down vote up
/**
 * Parses web.xml stream if one was found.
 *
 * @param conf
 * @param is
 * @param logger
 */
static void parseStream(SessionConfiguration conf, InputStream is) {
  if (is != null) {
    try {
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      // We want to ignore schemas and dtd when parsing web.xml
      builder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) {
          // Ignore entites!
          return new InputSource(new StringReader(""));
        }
      });
      Document document = builder.parse(is);
      XPath xpath = XPathFactory.newInstance().newXPath();
      lookForSessionTimeout(conf, document, xpath);
      lookForSessionConf(conf, document, xpath);
      checkDistributable(conf, document, xpath);
    } catch (SAXException | IOException | XPathExpressionException | ParserConfigurationException e) {
      throw new IllegalStateException("An exception occured while parsing web.xml. "
          + "Using default configuration: " + conf, e);
    }
  }
}
 
Example 12
/**
 * Get a DOM Document builder.
 * @return The DocumentBuilder
 * @throws DomException
 */
protected DocumentBuilder getXmlDocumentBuilder()
{
  try
  {
    DocumentBuilderFactory factory;

    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
    factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

    return factory.newDocumentBuilder();
  }
  catch (Exception exception)
  {
    log.warn("Failed to get XML DocumentBuilder: " + exception);
  }
  return null;
}
 
Example 13
Source Project: development   Source File: TriggerServiceBean.java    License: Apache License 2.0 6 votes vote down vote up
private String retrieveValueByXpath(String xml, DocumentBuilder builder,
    XPathExpression expr) {
    try {
        Document document = builder
            .parse(new InputSource(new StringReader(xml)));
        NodeList nodes = (NodeList) expr.evaluate(document,
            XPathConstants.NODESET);
        if (nodes == null || nodes.item(0) == null
            || nodes.item(0).getFirstChild() == null) {
            return null;
        }
        return nodes.item(0).getFirstChild().getNodeValue();
    } catch (SAXException | XPathExpressionException | IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 14
Source Project: archivo   Source File: ArchiveHistory.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void save() {
    logger.info("Saving archive history to {}", location);
    try (BufferedWriter historyWriter = Files.newBufferedWriter(location)) {
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document doc = builder.newDocument();
        Element root = doc.createElement("HistoryItems");
        doc.appendChild(root);
        items.entrySet().forEach(entry -> {
            ArchiveHistoryItem item = entry.getValue();
            Element element = doc.createElement("Item");
            element.setAttribute(ATT_ID, item.getRecordingId());
            element.setAttribute(ATT_DATE, item.getDateArchived().toString());
            element.setAttribute(ATT_PATH, item.getLocation().toString());
            root.appendChild(element);
        });
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        DOMSource source = new DOMSource(doc);
        StreamResult historyFile = new StreamResult(historyWriter);
        transformer.transform(source, historyFile);
    } catch (ParserConfigurationException | TransformerException | IOException e) {
        logger.error("Error saving archive history: ", e);
    }
}
 
Example 15
@Test
public void testCheckForElements_servletClass() throws ParserConfigurationException {
  DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
  Document document = documentBuilder.newDocument();

  Element root = document.createElement("web-app");
  root.setUserData("version", "2.5", null);
  root.setUserData("location", new DocumentLocation(1, 1), null);

  Element element = document.createElement("servlet-class");
  element.setTextContent("DoesNotExist");
  element.setUserData("location", new DocumentLocation(2, 1), null);
  root.appendChild(element);
  document.appendChild(root);

  WebXmlValidator validator = new WebXmlValidator();
  ArrayList<ElementProblem> problems = validator.checkForProblems(resource, document);

  assertEquals(1, problems.size());
  String markerId = "com.google.cloud.tools.eclipse.appengine.validation.undefinedServletMarker";
  assertEquals(markerId, problems.get(0).getMarkerId());
}
 
Example 16
public Document toDocument( Query query ) {

    if ( query == null ) {
      logger.error( Messages.getErrorString( "QueryXmlHelper.ERROR_0000_QUERY_MUST_NOT_BE_NULL" ) ); //$NON-NLS-1$
      return null;
    }

    Document doc;
    try {
      // create an XML document
      DocumentBuilderFactory dbf = XmiParser.createSecureDocBuilderFactory();
      DocumentBuilder db = dbf.newDocumentBuilder();
      doc = db.newDocument();
      Element mqlElement = doc.createElement( "mql" ); //$NON-NLS-1$
      doc.appendChild( mqlElement );

      if ( addToDocument( mqlElement, doc, query ) ) {
        return doc;
      } else {
        return null;
      }
    } catch ( Exception e ) {
      logger.error( Messages.getErrorString( "QueryXmlHelper.ERROR_0002_TO_DOCUMENT_FAILED" ), e ); //$NON-NLS-1$
    }
    return null;
  }
 
Example 17
Source Project: openjdk-jdk9   Source File: UserController.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checking for Row 8 from the schema table when setting the schemaSource
 * without the schemaLanguage must report an error.
 *
 * @throws Exception If any errors occur.
 */
@Test(expectedExceptions = IllegalArgumentException.class)
public void testUserError() throws Exception {
    String xmlFile = XML_DIR + "userInfo.xml";
    String schema = "http://java.sun.com/xml/jaxp/properties/schemaSource";
    String schemaValue = "http://dummy.com/dummy.xsd";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute(schema, schemaValue);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    docBuilder.setErrorHandler(eh);
    docBuilder.parse(xmlFile);
    assertFalse(eh.isAnyError());
}
 
Example 18
private static void checkParsing( InputStream documentStream, Map<String, String> params, String tagName )
  throws Exception {
  DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
  Document document = documentBuilder.parse( documentStream );
  document.getDocumentElement().normalize();

  NodeList nList = document.getElementsByTagName( tagName );
  assertEquals( 1, nList.getLength() );
  Node nNode = nList.item( 0 );

  if ( nNode.getNodeType() == Node.ELEMENT_NODE ) {
    Element element = (Element) nNode;

    for ( Map.Entry<String, String> pair : params.entrySet() ) {
      assertEquals( pair.getValue(), element.getAttribute( pair.getKey() ) );
    }
  }
}
 
Example 19
Source Project: vertx-unit   Source File: JunitXmlReporterTest.java    License: Apache License 2.0 6 votes vote down vote up
private ReportStream reportTo(String name) {
  this.name = name;
  return new ReportStream() {
    private Buffer buf = Buffer.buffer();
    @Override
    public void info(Buffer msg) {
      buf.appendBuffer(msg);
    }
    @Override
    public void end() {
      latch.countDown();
      try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        doc = builder.parse(new ByteArrayInputStream(buf.getBytes()));
      } catch (Exception e) {
        fail(e.getMessage());
      }
    }
  };
}
 
Example 20
Source Project: sakai   Source File: I18nXmlUtility.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * Gets a DocumentBuilder instance
 */
public static DocumentBuilder getDocumentBuilder() {
	try {
		if (documentBuilderFactory == null) {
			documentBuilderFactory = DocumentBuilderFactory.newInstance();
		}
		if (documentBuilder == null) {
			documentBuilder = documentBuilderFactory.newDocumentBuilder();
		}

		return documentBuilder;
	}
	catch (Exception e) {
		throw new ContentReviewProviderException("Failed to produce an XML Document Builder", e);
	}
}
 
Example 21
Source Project: bt   Source File: ConfigReader.java    License: Apache License 2.0 6 votes vote down vote up
Document readFile(Path p) {
	Document document = null;
	try {
		// parse an XML document into a DOM tree
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder parser = factory.newDocumentBuilder();
		document = parser.parse(p.toFile());



		// create a Validator instance, which can be used to validate an instance document
		Validator validator = schema.newValidator();

		// validate the DOM tree

		validator.validate(new DOMSource(document));
	} catch (SAXException | IOException | ParserConfigurationException e) {
		throw new ParseException(e);
	}

	return document;
}
 
Example 22
Source Project: pmq   Source File: ClientConfigHelper.java    License: Apache License 2.0 6 votes vote down vote up
private Document loadDocument(InputStream inputStream) {
	Document document = null;
	DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
	try {
		DocumentBuilder builder = builderFactory.newDocumentBuilder();
		document = builder.parse(inputStream);
	} catch (Exception e) {
		log.error(String.format("配置文件加载异常,异常信息:%s", e.getMessage()), e);
		throw new RuntimeException(e);
	} finally {
		try {
			inputStream.close();
		} catch (Exception ex) {
			// ex.printStackTrace();
		}
	}
	return document;
}
 
Example 23
Source Project: netbeans   Source File: DDProvider.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the root of deployment descriptor bean graph for java.io.File object.
 *
 * @param inputSource source representing the ejb-jar.xml file
 * @return EjbJar object - root of the deployment descriptor bean graph
 */
public EjbJar getDDRoot(InputSource inputSource) throws IOException, SAXException {
    ErrorHandler errorHandler = new ErrorHandler();
    DocumentBuilder parser = createParser(errorHandler);
    parser.setEntityResolver(DDResolver.getInstance());
    Document document = parser.parse(inputSource);
    SAXParseException error = errorHandler.getError();
    String version = extractVersion(document);
    EjbJar original = createEjbJar(version, document);
    EjbJarProxy ejbJarProxy = new EjbJarProxy(original, version);
    ejbJarProxy.setError(error);
    if (error != null) {
        ejbJarProxy.setStatus(EjbJar.STATE_INVALID_PARSABLE);
    } else {
        ejbJarProxy.setStatus(EjbJar.STATE_VALID);
    }
    return ejbJarProxy;
}
 
Example 24
Source Project: localization_nifi   Source File: StandardFlowSerializer.java    License: Apache License 2.0 6 votes vote down vote up
public static void addTemplate(final Element element, final Template template) {
    try {
        final byte[] serialized = TemplateSerializer.serialize(template.getDetails());

        final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        final Document document;
        try (final InputStream in = new ByteArrayInputStream(serialized)) {
            document = docBuilder.parse(in);
        }

        final Node templateNode = element.getOwnerDocument().importNode(document.getDocumentElement(), true);
        element.appendChild(templateNode);
    } catch (final Exception e) {
        throw new FlowSerializationException(e);
    }
}
 
Example 25
Source Project: karate   Source File: XmlUtils.java    License: MIT License 6 votes vote down vote up
public static Document toXmlDoc(String xml) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        DtdEntityResolver dtdEntityResolver = new DtdEntityResolver();
        builder.setEntityResolver(dtdEntityResolver);
        InputStream is = FileUtils.toInputStream(xml);
        Document doc = builder.parse(is);
        if (dtdEntityResolver.dtdPresent) { // DOCTYPE present
            // the XML was not parsed, but I think it hangs at the root as a text node
            // so conversion to string and back has the effect of discarding the DOCTYPE !
            return toXmlDoc(toString(doc, false));
        } else {
            return doc;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 26
public JobDescriptor parse() throws IOException, SAXException, ParserConfigurationException {
    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    Document doc = docBuilder.parse(is);
    doc.getDocumentElement().normalize();

    List<PropertyDescriptor> properties = new ArrayList<>();

    properties.addAll(getChildNodes(null, doc.getChildNodes()));

    return new JobDescriptor(jobName, properties);
}
 
Example 27
@Test
public void deleteSubTagOfForbiddenTag() throws Exception {
    File fileToTest = getFile("OneForbiddenTagExist.pom");
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Element element = documentBuilder.parse(fileToTest).getDocumentElement();

    int subForbiddenItemsBeforeRemove = element.getElementsByTagName("test").getLength();
    xmlTagsRemover.removeTags(element);
    int subForbiddenItemsAfterRemove = element.getElementsByTagName("test").getLength();

    assertThat(subForbiddenItemsBeforeRemove, is(1));
    assertThat(subForbiddenItemsAfterRemove, is(0));
}
 
Example 28
Source Project: vespa   Source File: XML.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new XML DocumentBuilder
 *
 * @param implementation which jaxp implementation should be used
 * @param classLoader which class loader should be used when getting a new DocumentBuilder
 * @throws RuntimeException if we fail to create one
 * @return a DocumentBuilder
 */
public static DocumentBuilder getDocumentBuilder(String implementation, ClassLoader classLoader) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(implementation, classLoader);
        factory.setNamespaceAware(true);
        factory.setXIncludeAware(true);
        // Prevent XXE
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        return factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Could not create an XML builder", e);
    }
}
 
Example 29
Source Project: windup   Source File: JavaClassHandlerTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public void testJavaClassCondition(File fXmlFile) throws Exception
{
    RuleLoaderContext loaderContext = new RuleLoaderContext(Collections.singleton(fXmlFile.toPath()), null);
    ParserContext parser = new ParserContext(furnace, loaderContext);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    List<Element> javaClassList = $(doc).children("javaclass").get();

    Element firstJavaClass = javaClassList.get(0);
    JavaClass javaClassCondition = parser.<JavaClass> processElement(firstJavaClass);

    Assert.assertEquals("testVariable", javaClassCondition.getVarname());
    Assert.assertEquals(null, javaClassCondition.getInputVariablesName());
    Assert.assertEquals(1, javaClassCondition.getLocations().size());
    List<TypeReferenceLocation> locations = javaClassCondition.getLocations();
    Assert.assertEquals("METHOD_CALL", locations.get(0).name());
    Assert.assertEquals("org.apache.commons.{*}", javaClassCondition.getReferences().toString());

    Assert.assertEquals("{*}File1", javaClassCondition.getTypeFilterRegex().toString());
    Element secondJavaClass = javaClassList.get(1);
    javaClassCondition = parser.<JavaClass> processElement(secondJavaClass);

    Assert.assertEquals(Iteration.DEFAULT_VARIABLE_LIST_STRING, javaClassCondition.getVarname());
    Assert.assertEquals(3, javaClassCondition.getLocations().size());
    locations = javaClassCondition.getLocations();
    Assert.assertEquals("IMPORT", locations.get(0).name());
    Assert.assertEquals("METHOD_CALL", locations.get(1).name());
    Assert.assertEquals("INHERITANCE", locations.get(2).name());
    Assert.assertEquals("org.apache.commons.{*}", javaClassCondition.getReferences().toString());
    Assert.assertEquals(null, javaClassCondition.getTypeFilterRegex());
    Assert.assertEquals("source-match", javaClassCondition.getMatchesSource().toString());
}
 
Example 30
Source Project: rya   Source File: MergeConfigurationCLI.java    License: Apache License 2.0 5 votes vote down vote up
public static MergeToolConfiguration createConfigurationFromFile(final File configFile) throws MergeConfigurationException {
    try {
        final JAXBContext context = JAXBContext.newInstance(DBType.class, MergeToolConfiguration.class, AccumuloMergeToolConfiguration.class, TimestampMergePolicyConfiguration.class, MergePolicy.class, InstanceType.class);
        final Unmarshaller unmarshaller = context.createUnmarshaller();
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        XmlFactoryConfiguration.harden(dbf);
        final DocumentBuilder db = dbf.newDocumentBuilder();
        return unmarshaller.unmarshal(db.parse(configFile), MergeToolConfiguration.class).getValue();
    } catch (final JAXBException | IllegalArgumentException | ParserConfigurationException | SAXException | IOException JAXBe) {
        throw new MergeConfigurationException("Failed to create a config based on the provided configuration.", JAXBe);
    }
}