Java Code Examples for javax.xml.parsers.DocumentBuilder#parse()

The following examples show how to use javax.xml.parsers.DocumentBuilder#parse() . 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 check out the related API usage on the sidebar.
Example 1
Source File: XmlHelper.java    From android-uiconductor with Apache License 2.0 6 votes vote down vote up
private static Node getNodeByXpath(String xml, String xPathString) throws Exception {
  DocumentBuilder builder;
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  Document doc = null;

  try {
    builder = factory.newDocumentBuilder();
    doc = builder.parse(new InputSource(new StringReader(xml)));
  } catch (Exception e) {
    logger.warning("Failed to parse xml." + e.getMessage());
  }
  XPath xpathCompiler = XPathFactory.newInstance().newXPath();

  NodeList nodes =
      (NodeList) xpathCompiler.compile(xPathString).evaluate(doc, XPathConstants.NODESET);
  if (nodes.getLength() == 0) {
    return null;
  }
  return nodes.item(0);
}
 
Example 2
Source File: XmlLoader.java    From aiml-java-interpreter with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Element load(File file) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    Document doc = null;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(file);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    if (doc == null) return null;

    Element rootElement = doc.getDocumentElement();
    rootElement.normalize();
    return rootElement;
}
 
Example 3
Source File: DMLConfig.java    From systemds with Apache License 2.0 6 votes vote down vote up
/**
 * Method to parse configuration
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
private void parseConfig () throws ParserConfigurationException, SAXException, IOException 
{
	DocumentBuilder builder = getDocumentBuilder();
	_document = null;
	if( _fileName.startsWith("hdfs:") || _fileName.startsWith("gpfs:")
		|| IOUtilFunctions.isObjectStoreFileScheme(new Path(_fileName)) )
	{
		Path configFilePath = new Path(_fileName);
		try( FileSystem DFS = IOUtilFunctions.getFileSystem(configFilePath) ) {
			_document = builder.parse(DFS.open(configFilePath));
		}
	}
	else  // config from local file system
	{
		_document = builder.parse(_fileName);
	}

	_xmlRoot = _document.getDocumentElement();
}
 
Example 4
Source File: ConQATOutputParser.java    From JDeodorant with MIT License 6 votes vote down vote up
public ConQATOutputParser(IJavaProject iJavaProject, String cloneOutputFilePath) throws InvalidInputFileException {
	super(iJavaProject, cloneOutputFilePath);
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setIgnoringElementContentWhitespace(true);
	try {
		DocumentBuilder builder = factory.newDocumentBuilder();
		File file = new File(this.getToolOutputFilePath());
		this.document = builder.parse(file);
		NodeList cloneClassesNodeList = document.getElementsByTagName("cloneClass");
		if (cloneClassesNodeList.getLength() != 0) {
			this.setCloneGroupCount(cloneClassesNodeList.getLength());
		} else {			
			this.document = null;
			throw new InvalidInputFileException();
		}
	} catch (IOException ioex) {
		ioex.printStackTrace();
	} catch (SAXException saxe) {
		saxe.printStackTrace();
	} catch (ParserConfigurationException e) {
		e.printStackTrace();
	}
}
 
Example 5
Source File: ProcessDiagramLayoutFactory.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected Document parseXml(InputStream bpmnXmlStream) {
  // Initiate DocumentBuilderFactory
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  // Get one that understands namespaces
  factory.setNamespaceAware(true);

  DocumentBuilder builder;
  Document bpmnModel;
  try {
    // Get DocumentBuilder
    builder = factory.newDocumentBuilder();
    // Parse and load the Document into memory
    bpmnModel = builder.parse(bpmnXmlStream);
  } catch (Exception e) {
    throw new ActivitiException("Error while parsing BPMN model.", e);
  }
  return bpmnModel;
}
 
Example 6
Source File: AcceptanceTestContext.java    From gatf with Apache License 2.0 6 votes vote down vote up
public AcceptanceTestContext(DistributedAcceptanceContext dContext, ClassLoader projectClassLoader)
{
       this.projectClassLoader = projectClassLoader;
	this.gatfExecutorConfig = dContext.getConfig();
	this.httpHeaders.putAll(dContext.getHttpHeaders());
	this.soapEndpoints.putAll(dContext.getSoapEndpoints());
	this.soapActions.putAll(dContext.getSoapActions());
	try {
		if(dContext.getSoapMessages()!=null) {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			for (Map.Entry<String, String> soapMsg : dContext.getSoapMessages().entrySet()) {
				Document soapMessage = db.parse(new ByteArrayInputStream(soapMsg.getValue().getBytes()));
				this.soapMessages.put(soapMsg.getKey(), soapMessage);
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
		// TODO: handle exception
	}
	getWorkflowContextHandler().init();
}
 
Example 7
Source File: XmlCombinerTest.java    From xml-combiner with Apache License 2.0 6 votes vote down vote up
private static String combineWithKeysAndFilter(List<String> keyAttributeNames, XmlCombiner.Filter filter,
		String... inputs) throws IOException, ParserConfigurationException, SAXException,
		TransformerConfigurationException, TransformerException {
	XmlCombiner combiner = new XmlCombiner(keyAttributeNames);
	combiner.setFilter(filter);
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	DocumentBuilder builder = factory.newDocumentBuilder();

	for (String input : inputs) {
		Document document = builder.parse(new ByteArrayInputStream(input.getBytes("UTF-8")));
		combiner.combine(document);
	}
	Document result = combiner.buildDocument();

	Transformer transformer = TransformerFactory.newInstance().newTransformer();
	StringWriter writer = new StringWriter();
	transformer.transform(new DOMSource(result), new StreamResult(writer));
	return writer.toString();
}
 
Example 8
Source File: XMLUtil.java    From sagacity-sqltoy with Apache License 2.0 5 votes vote down vote up
/**
 * 读取xml文件
 * 
 * @param xmlFile
 * @param charset
 * @param isValidator
 * @param handler
 * @throws Exception
 */
public static Object readXML(Object xmlFile, String charset, boolean isValidator, XMLCallbackHandler handler)
		throws Exception {
	if (StringUtil.isBlank(xmlFile))
		return null;
	InputStream fileIS = null;
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		if (!isValidator) {
			factory.setFeature(NO_VALIDATOR_FEATURE, false);
		}
		DocumentBuilder builder = factory.newDocumentBuilder();
		fileIS = FileUtil.getFileInputStream(xmlFile);
		if (fileIS != null) {
			Document doc = builder.parse(fileIS);
			if (null != doc) {
				return handler.process(doc, doc.getDocumentElement());
			}
		}
	} catch (Exception e) {
		logger.error("解析文件:{}错误:{}!", xmlFile, e.getMessage());
		throw e;
	} finally {
		if (fileIS != null) {
			fileIS.close();
		}
	}
	return null;
}
 
Example 9
Source File: Xml.java    From RADL with Apache License 2.0 5 votes vote down vote up
public static Document parse(InputStream stream, boolean validating) {
  DocumentBuilder documentBuilder = getDocumentBuilder(validating);
  try {
    return documentBuilder.parse(stream);
  } catch (Exception e) {
    throw new RuntimeException(e);
  } finally {
    documentBuilder.reset();
  }
}
 
Example 10
Source File: XMLUtils.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public static Document createDoc(final File XMLFile)
		throws ParserConfigurationException, SAXException, IOException {
	// Creation of the DOM source
	final DocumentBuilderFactory fabriqueD = DocumentBuilderFactory.newInstance();
	final DocumentBuilder builder = fabriqueD.newDocumentBuilder();
	final Document document = builder.parse(XMLFile);

	return document;
}
 
Example 11
Source File: EmployeeRepository.java    From JavaMainRepo with Apache License 2.0 5 votes vote down vote up
public ArrayList<Employee> load() throws ParserConfigurationException, SAXException, IOException {

		ArrayList<Employee> employees = new ArrayList<Employee>();

		File fXmlFile = new File(XML_FILENAME);
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();

		NodeList nodeList = doc.getElementsByTagName(Constants.XML_TAGS.EMPLOYEE);

		for (int i = 0; i < nodeList.getLength(); i++) {
			org.w3c.dom.Node node = nodeList.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				Element element = (Element) node;
				String discriminant = element.getElementsByTagName(Constants.XML_TAGS.DISCRIMINANT).item(0)
						.getTextContent();

				switch (discriminant) {
				case Constants.Employees.Caretaker:
					String name = element.getElementsByTagName("name").item(0).getTextContent();
					BigDecimal salary = BigDecimal
							.valueOf(Double.valueOf(element.getElementsByTagName("salary").item(0).getTextContent()));
					long id = Long.valueOf(element.getElementsByTagName("id").item(0).getTextContent());
					Employee caretaker = new Caretaker(name, id, salary);
					caretaker.decodeFromXml(element);
					employees.add(caretaker);
					break;
				default:
					break;
				}
			}
		}
		return employees;
	}
 
Example 12
Source File: ClassificationHandlerTest.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
public void testClassificationParsing(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> classificationList = $(doc).children("classification").get();
    Element firstClassification = classificationList.get(0);
    Classification classification = parser.<Classification> processElement(firstClassification);

    Assert.assertNull(classification.getIssueCategory());
    Assert.assertEquals("testVariable", classification.getVariableName());
    Assert.assertEquals(5, classification.getEffort());
    Assert.assertEquals("test message", classification.getClassificationPattern().toString());
    Assert.assertEquals("simple description", classification.getDescriptionPattern().toString());
    Assert.assertEquals(1, classification.getLinks().size());
    List<Link> links = classification.getLinks();
    Assert.assertEquals("someUrl", links.get(0).getLink());
    Assert.assertEquals("someDescription", links.get(0).getTitle());

    Element secondClassification = classificationList.get(1);
    classification = parser.<Classification> processElement(secondClassification);
    Assert.assertEquals(null, classification.getVariableName());
    Assert.assertEquals(IssueCategoryRegistry.OPTIONAL, classification.getIssueCategory().getCategoryID());
    Assert.assertEquals(0, classification.getEffort());
    Assert.assertEquals("test-message", classification.getClassificationPattern().toString());
    Assert.assertEquals(null, classification.getDescriptionPattern());
    Assert.assertEquals(3, classification.getLinks().size());
    links = classification.getLinks();
    Assert.assertEquals("url1", links.get(0).getLink());
    Assert.assertEquals("url2", links.get(1).getLink());
    Assert.assertEquals("url3", links.get(2).getLink());
    Assert.assertEquals("description1", links.get(0).getTitle());
    Assert.assertEquals("description2", links.get(1).getTitle());
    Assert.assertEquals("description3", links.get(2).getTitle());

}
 
Example 13
Source File: FileTEDBUpdater.java    From netphony-topology with Apache License 2.0 5 votes vote down vote up
public static Hashtable <Object,Object> getITSites(String fileName){
	Hashtable <Object,Object> it_site_id_domain_ed=new Hashtable <Object,Object>();

	File file2 = new File(fileName);
	try {
		DocumentBuilder builder2 =	DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc2 = builder2.parse(file2);

		NodeList nodes_domains = doc2.getElementsByTagName("domain");

		for (int j = 0; j < nodes_domains.getLength(); j++) {
			Element element_domain = (Element) nodes_domains.item(j);
			NodeList nodes_domain_id =  element_domain.getElementsByTagName("domain_id");
			Element domain_id_e = (Element) nodes_domain_id.item(0);
			String domain_id_str=getCharacterDataFromElement(domain_id_e);
			Inet4Address domain_id= (Inet4Address) Inet4Address.getByName(domain_id_str);

			NodeList ITsites = element_domain.getElementsByTagName("it_site");
			for (int i = 0; i < ITsites.getLength(); i++) {
				Element element = (Element) ITsites.item(i);
				NodeList it_site_id_node = element.getElementsByTagName("it_site_id");
				Element it_site_id_e = (Element) it_site_id_node.item(0);
				String it_site_id=getCharacterDataFromElement(it_site_id_e);
				Inet4Address it_site_id_addr= (Inet4Address) Inet4Address.getByName(it_site_id);

				NodeList domain_id_node = element.getElementsByTagName("domain_id");
				it_site_id_domain_ed.put(it_site_id_addr, domain_id);
				//graph.addVertex(router_id_addr);					
			}

		}

	}
	catch (Exception e) {
		e.printStackTrace();
	}		 

	return it_site_id_domain_ed;

}
 
Example 14
Source File: DocumentBuilderFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test the default functionality of newInstance method. To test
 * the isCoalescing method and setCoalescing This checks to see if the CDATA
 * and text nodes got combined In that case it will print "&lt;xml&gt;This
 * is not parsed&lt;/xml&gt; yet".
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckDocumentBuilderFactory02() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(true);
    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    Document doc = docBuilder.parse(new File(XML_DIR, "DocumentBuilderFactory01.xml"));
    Element e = (Element) doc.getElementsByTagName("html").item(0);
    NodeList nl = e.getChildNodes();
    assertEquals(nl.getLength(), 1);
}
 
Example 15
Source File: ConfigUtil.java    From db with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Parses the XML configuration file specified by {@code documentName} and returns the result of the query as a parsed map
 *
 * @param documentName XML document to be parsed
 * @param query {@link XPath} valid query to be used to parse the document for results
 * @return {@link Map} with the key value pair from the XML
 *
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 * @throws ParserConfigurationException
 */
private static Map<String, List<String>> getDataFromConfFile(final String documentName, final String query) throws SAXException, IOException, XPathExpressionException, ParserConfigurationException {
    logger.trace("Attempting to get config values from method \"" + documentName + "\" with query \"" + query + "\"");

    // Creating an XML parser
    final DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    // Setting the entity resolver so it finds the DTD correctly
    db.setEntityResolver((String publicId, String systemId) -> {
        if (systemId.contains(".dtd")) {
            final String[] fileParts = systemId.split(Pattern.quote(File.separator));
            return new InputSource(ClassLoader.getSystemResourceAsStream(fileParts[fileParts.length - 1]));
        }

        return null;
    });

    // Loading the document
    final Document doc = db.parse(ClassLoader.getSystemResourceAsStream(documentName));
    final XPath xPath = XPathFactory.newInstance().newXPath();

    // Executing the query
    final NodeList nodeList = (NodeList) xPath.compile(query).evaluate(doc, XPathConstants.NODESET);

    // Creating the result to be returned
    final Map<String, List<String>> elementDataMap = new HashMap<>();
    for (int i = 0; i < nodeList.getLength(); i++) {
        String key = "";
        final Node attributeNode = nodeList.item(i).getAttributes().getNamedItem("id");
        if (attributeNode != null) {
            key = attributeNode.getNodeValue();
        }

        List<String> dataList = elementDataMap.get(key);
        if (dataList == null) {
            dataList = new ArrayList<>();
        }

        final String value = nodeList.item(i).getFirstChild().getNodeValue();
        dataList.add(value);
        elementDataMap.put(key, dataList);
    }

    return elementDataMap;
}
 
Example 16
Source File: JDBCServices.java    From diirt with MIT License 4 votes vote down vote up
/**
 * Creates a JDBCService based on the description of an XML file.
 *
 * @param input a stream with an xml file; can't be null
 * @return the new service
 */
public static Service createFromXml(InputStream input) {
    if (input == null){
        throw new IllegalArgumentException("Input must not be null");
    }
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(input);

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xPath = xpathFactory.newXPath();

        String ver = xPath.evaluate("/jdbcService/@ver", document);
        String serviceName = xPath.evaluate("/jdbcService/@name", document);
        String serviceDesecription = xPath.evaluate("/jdbcService/@description", document);
        String jdbcUrl = xPath.evaluate("/jdbcService/jdbcUrl", document);
        if (!ver.equals("1")) {
            throw new IllegalArgumentException("Unsupported version " + ver);
        }

        JDBCServiceDescription service = new JDBCServiceDescription(serviceName, serviceDesecription);
        service.dataSource(new SimpleDataSource(jdbcUrl));
        service.executorService(defaultExecutor);

        NodeList methods = (NodeList) xPath.evaluate("/jdbcService/methods/method", document, XPathConstants.NODESET);
        for (int i = 0; i < methods.getLength(); i++) {
            Node method = methods.item(i);
            String methodName = xPath.evaluate("@name", method);
            String methodDescription = xPath.evaluate("@description", method);
            String query = xPath.evaluate("query", method);
            String resultName = xPath.evaluate("result/@name", method);
            String resultDescription = xPath.evaluate("result/@description", method);

            JDBCServiceMethodDescription jdbcMethod = new JDBCServiceMethodDescription(methodName, methodDescription);
            jdbcMethod.query(query);
            if (!resultName.trim().isEmpty()) {
                jdbcMethod.queryResult(resultName, resultDescription);
            }

            NodeList arguments = (NodeList) xPath.evaluate("argument", method, XPathConstants.NODESET);
            for (int nArg = 0; nArg < arguments.getLength(); nArg++) {
                Node argument = arguments.item(nArg);
                String argName = xPath.evaluate("@name", argument);
                String argDescription = xPath.evaluate("@description", argument);
                String argType = xPath.evaluate("@type", argument);
                Class<?> argClass = null;
                switch(argType) {
                    case "VNumber": argClass = VNumber.class;
                        break;
                    case "VString": argClass = VString.class;
                        break;
                    default: throw new IllegalArgumentException("Type " + argType + " not supported.");
                }
                if (!argName.trim().isEmpty()) {
                    jdbcMethod.addArgument(argName, argDescription, argClass);
                }
            }
            service.addServiceMethod(jdbcMethod);
        }

        return service.createService();
    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException ex) {
        Logger.getLogger(JDBCServices.class.getName()).log(Level.FINEST, "Couldn't create service", ex);
        throw new IllegalArgumentException("Couldn't create service", ex);
    }
}
 
Example 17
Source File: ModuleListParser.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Look for all possible modules in a NB build.
 * Checks modules/{,autoload/,eager/}*.jar as well as well-known core/*.jar and lib/boot.jar in each cluster.
 * XXX would be slightly more precise to check config/Modules/*.xml rather than scan for module JARs.
 */
private static void doScanBinaries(File cluster, Map<String,Entry> entries) throws IOException {
    File moduleAutoDepsDir = new File(new File(cluster, "config"), "ModuleAutoDeps");
        for (String moduleDir : MODULE_DIRS) {
            if (moduleDir.endsWith("lib") && !cluster.getName().contains("platform")) {
                continue;
            }
            File dir = new File(cluster, moduleDir.replace('/', File.separatorChar));
            if (!dir.isDirectory()) {
                continue;
            }
            File[] jars = dir.listFiles();
            if (jars == null) {
                throw new IOException("Cannot examine dir " + dir);
            }
            for (File m : jars) {
                scanOneBinary(m, cluster, entries, moduleAutoDepsDir);
            }
        }

        final File configDir = new File(new File(cluster, "config"), "Modules");
        File[] configs = configDir.listFiles();
        XPathExpression expr = null;
        DocumentBuilder b = null;
        if (configs != null) {
            for (File xml : configs) {
                // TODO, read location, scan
                final String fileName = xml.getName();
                if (!fileName.endsWith(".xml")) {
                    continue;
                }
                if (entries.containsKey(fileName.substring(0, fileName.length() - 4).replace('-', '.'))) {
                    continue;
                }
                try {
                    if (expr == null) {
                        expr = XPathFactory.newInstance().newXPath().compile("/module/param[@name='jar']");
                        b = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                        b.setEntityResolver(new EntityResolver() {
                            public InputSource resolveEntity(String publicId, String systemId)
                            throws SAXException, IOException {
                                return new InputSource(new ByteArrayInputStream(new byte[0]));
                            }
                        });
                    }
                    Document doc = b.parse(xml);
                    String res = expr.evaluate(doc);
                    File jar = new File(cluster, res.replace('/', File.separatorChar));
                    if (!jar.isFile()) {
                        if (cluster.getName().equals("ergonomics")) {
                            // this is normal
                            continue;
                        }
                        throw new BuildException("Cannot find module " + jar + " from " + xml);
                    }
                    scanOneBinary(jar, cluster, entries, moduleAutoDepsDir);
                } catch (Exception ex) {
                    throw new BuildException(ex);
                }
            }
        }
}
 
Example 18
Source File: CustomerResource.java    From resteasy-examples with Apache License 2.0 4 votes vote down vote up
protected Customer readCustomer(InputStream is)
{
   try
   {
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document doc = builder.parse(is);
      Element root = doc.getDocumentElement();
      Customer cust = new Customer();
      if (root.getAttribute("id") != null && !root.getAttribute("id").trim().equals(""))
         cust.setId(Integer.valueOf(root.getAttribute("id")));
      NodeList nodes = root.getChildNodes();
      for (int i = 0; i < nodes.getLength(); i++)
      {
         Element element = (Element) nodes.item(i);
         if (element.getTagName().equals("first-name"))
         {
            cust.setFirstName(element.getTextContent());
         }
         else if (element.getTagName().equals("last-name"))
         {
            cust.setLastName(element.getTextContent());
         }
         else if (element.getTagName().equals("street"))
         {
            cust.setStreet(element.getTextContent());
         }
         else if (element.getTagName().equals("city"))
         {
            cust.setCity(element.getTextContent());
         }
         else if (element.getTagName().equals("state"))
         {
            cust.setState(element.getTextContent());
         }
         else if (element.getTagName().equals("zip"))
         {
            cust.setZip(element.getTextContent());
         }
         else if (element.getTagName().equals("country"))
         {
            cust.setCountry(element.getTextContent());
         }
      }
      return cust;
   }
   catch (Exception e)
   {
      throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
   }
}
 
Example 19
Source File: LibertyServerConfigGeneratorTest.java    From boost with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Test that the server.xml and boostrap.properties are fully configured
 * with the MySQL datasource
 * 
 * @throws ParserConfigurationException
 * @throws TransformerException
 * @throws IOException
 */
@Test
public void testAddJdbcBoosterConfig_MySQL() throws Exception {

    LibertyServerConfigGenerator serverConfig = new LibertyServerConfigGenerator(
            outputDir.getRoot().getAbsolutePath(), null, logger);

    Map<String, String> jdbcDependency = BoosterUtil.getJDBCDependency();
    jdbcDependency.put(JDBCBoosterConfig.MYSQL_GROUP_ID + ":" + JDBCBoosterConfig.MYSQL_ARTIFACT_ID, "1.0");

    Properties boostProperties = new Properties();
    boostProperties.put(BoostProperties.DATASOURCE_URL, MYSQL_URL);

    BoosterConfigParams params = new BoosterConfigParams(jdbcDependency, boostProperties);
    LibertyJDBCBoosterConfig jdbcConfig = new LibertyJDBCBoosterConfig(params, logger);
    jdbcConfig.addServerConfig(serverConfig);
    serverConfig.writeToServer();

    File serverXml = new File(outputDir.getRoot().getAbsolutePath() + "/server.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(serverXml);

    Element serverRoot = doc.getDocumentElement();

    // Check that the <library> element is correctly configured
    List<Element> libraryList = getDirectChildrenByTag(serverRoot, LIBRARY);
    assertEquals("Didn't find one and only one library", 1, libraryList.size());

    Element library = libraryList.get(0);
    assertEquals("Library id is not correct", JDBC_LIBRARY_1, library.getAttribute("id"));

    Element fileset = getDirectChildrenByTag(library, FILESET).get(0);
    assertEquals("Fileset dir attribute is not correct", RESOURCES, fileset.getAttribute("dir"));

    String mysqlJar = JDBCBoosterConfig.MYSQL_ARTIFACT_ID + "-1.0.jar";
    assertEquals("Fileset includes attribute is not correct", mysqlJar, fileset.getAttribute("includes"));

    // Check that the <dataSource> element is correctly configured
    List<Element> dataSourceList = getDirectChildrenByTag(serverRoot, DATASOURCE);
    assertEquals("Didn't find one and only one dataSource", 1, dataSourceList.size());

    Element dataSource = dataSourceList.get(0);
    assertEquals("DataSource id is not correct", DEFAULT_DATASOURCE, dataSource.getAttribute("id"));
    assertEquals("DataSource jdbcDriverRef is not correct", JDBC_DRIVER_1,
            dataSource.getAttribute(JDBC_DRIVER_REF));

    List<Element> propertiesList = getDirectChildrenByTag(dataSource, PROPERTIES);
    assertEquals("Didn't find one and only one properties", 1, propertiesList.size());

    Element properties = propertiesList.get(0);
    assertEquals("The url attribute is not correct", BoostUtil.makeVariable(BoostProperties.DATASOURCE_URL),
            properties.getAttribute(URL));

    // Check that the <jdbcDriver> element is correctly configured
    List<Element> jdbcDriverList = getDirectChildrenByTag(serverRoot, JDBC_DRIVER);
    assertEquals("Didn't find one and only one jdbcDriver", 1, jdbcDriverList.size());

    Element jdbcDriver = jdbcDriverList.get(0);
    assertEquals("JdbcDriver id is not correct", JDBC_DRIVER_1, jdbcDriver.getAttribute("id"));
    assertEquals("JdbcDriver libraryRef is not correct", JDBC_LIBRARY_1, jdbcDriver.getAttribute(LIBRARY_REF));

    // Check variables.xml content
    String variablesXml = outputDir.getRoot().getAbsolutePath() + LibertyServerConfigGenerator.CONFIG_DROPINS_DIR
            + "/variables.xml";

    assertEquals("The variable set for " + BoostProperties.DATASOURCE_URL + " is not correct", MYSQL_URL,
            ConfigFileUtils.findVariableInXml(variablesXml, BoostProperties.DATASOURCE_URL));

    // No user set.
    assertEquals("The variable set for " + BoostProperties.DATASOURCE_USER + " is not correct", "",
            ConfigFileUtils.findVariableInXml(variablesXml, BoostProperties.DATASOURCE_USER));

    // No password set.
    assertEquals("The variable set for " + BoostProperties.DATASOURCE_PASSWORD + " is not correct", "",
            ConfigFileUtils.findVariableInXml(variablesXml, BoostProperties.DATASOURCE_PASSWORD));
}
 
Example 20
Source File: XmlParser.java    From xcurator with Apache License 2.0 4 votes vote down vote up
public Document parse(InputStream is, int maxElement) throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilder builder = XMLUtils.createNsAwareDocumentBuilder();
    Document doc = builder.parse(is);
    doc = pruneDocument(doc, maxElement);
    return doc;
}