List of usage examples for javax.xml.xpath XPathConstants NODESET
QName NODESET
To view the source code for javax.xml.xpath XPathConstants NODESET.
Click Source Link
The XPath 1.0 NodeSet data type.
Maps to Java org.w3c.dom.NodeList .
From source file:AwsConsoleApp.java
public static void main(String[] args) throws Exception { System.out.println("==========================================="); System.out.println("Welcome to the AWS VPN connection creator"); System.out.println("==========================================="); init();//w ww. j av a2 s . c o m List<String> CIDRblocks = new ArrayList<String>(); String vpnType = null; String vpnGatewayId = null; String customerGatewayId = null; String customerGatewayInfoPath = null; String routes = null; options.addOption("h", "help", false, "show help."); options.addOption("vt", "vpntype", true, "Set vpn tunnel type e.g. (ipec.1)"); options.addOption("vgw", "vpnGatewayId", true, "Set AWS VPN Gateway ID e.g. (vgw-eca54d85)"); options.addOption("cgw", "customerGatewayId", true, "Set AWS Customer Gateway ID e.g. (cgw-c16e87a8)"); options.addOption("r", "staticroutes", true, "Set static routes e.g. cutomer subnet 10.77.77.0/24"); options.addOption("vi", "vpninfo", true, "path to vpn info file c:\\temp\\customerGatewayInfo.xml"); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; // Parse command line options try { cmd = parser.parse(options, args); if (cmd.hasOption("h")) help(); if (cmd.hasOption("vt")) { log.log(Level.INFO, "Using cli argument -vt=" + cmd.getOptionValue("vt")); vpnType = cmd.getOptionValue("vt"); // Whatever you want to do with the setting goes here } else { log.log(Level.SEVERE, "Missing vt option"); help(); } if (cmd.hasOption("vgw")) { log.log(Level.INFO, "Using cli argument -vgw=" + cmd.getOptionValue("vgw")); vpnGatewayId = cmd.getOptionValue("vgw"); } else { log.log(Level.SEVERE, "Missing vgw option"); help(); } if (cmd.hasOption("cgw")) { log.log(Level.INFO, "Using cli argument -cgw=" + cmd.getOptionValue("cgw")); customerGatewayId = cmd.getOptionValue("cgw"); } else { log.log(Level.SEVERE, "Missing cgw option"); help(); } if (cmd.hasOption("r")) { log.log(Level.INFO, "Using cli argument -r=" + cmd.getOptionValue("r")); routes = cmd.getOptionValue("r"); String[] routeItems = routes.split(","); CIDRblocks = Arrays.asList(routeItems); } else { log.log(Level.SEVERE, "Missing r option"); help(); } if (cmd.hasOption("vi")) { log.log(Level.INFO, "Using cli argument -vi=" + cmd.getOptionValue("vi")); customerGatewayInfoPath = cmd.getOptionValue("vi"); } else { log.log(Level.SEVERE, "Missing vi option"); help(); } } catch (ParseException e) { log.log(Level.SEVERE, "Failed to parse comand line properties", e); help(); } /* * Amazon VPC * Create and delete VPN tunnel to customer VPN hardware */ try { //String vpnType = "ipsec.1"; //String vpnGatewayId = "vgw-eca54d85"; //String customerGatewayId = "cgw-c16e87a8"; //List<String> CIDRblocks = new ArrayList<String>(); //CIDRblocks.add("10.77.77.0/24"); //CIDRblocks.add("172.16.1.0/24"); //CIDRblocks.add("172.18.1.0/24"); //CIDRblocks.add("10.66.66.0/24"); //CIDRblocks.add("10.8.1.0/24"); //String customerGatewayInfoPath = "c:\\temp\\customerGatewayInfo.xml"; Boolean staticRoutesOnly = true; List<String> connectionIds = new ArrayList<String>(); List<String> connectionIdList = new ArrayList<String>(); connectionIdList = vpnExists(connectionIds); if (connectionIdList.size() == 0) { CreateVpnConnectionRequest vpnReq = new CreateVpnConnectionRequest(vpnType, customerGatewayId, vpnGatewayId); CreateVpnConnectionResult vpnRes = new CreateVpnConnectionResult(); VpnConnectionOptionsSpecification vpnspec = new VpnConnectionOptionsSpecification(); vpnspec.setStaticRoutesOnly(staticRoutesOnly); vpnReq.setOptions(vpnspec); System.out.println("Creating VPN connection"); vpnRes = ec2.createVpnConnection(vpnReq); String vpnConnId = vpnRes.getVpnConnection().getVpnConnectionId(); String customerGatewayInfo = vpnRes.getVpnConnection().getCustomerGatewayConfiguration(); //System.out.println("Customer Gateway Info:" + customerGatewayInfo); // Write Customer Gateway Info to file System.out.println("Writing Customer Gateway Info to file:" + customerGatewayInfoPath); try (PrintStream out = new PrintStream(new FileOutputStream(customerGatewayInfoPath))) { out.print(customerGatewayInfo); } System.out.println("Creating VPN routes"); for (String destCIDR : CIDRblocks) { CreateVpnConnectionRouteRequest routeReq = new CreateVpnConnectionRouteRequest(); CreateVpnConnectionRouteResult routeRes = new CreateVpnConnectionRouteResult(); routeReq.setDestinationCidrBlock(destCIDR); routeReq.setVpnConnectionId(vpnConnId); routeRes = ec2.createVpnConnectionRoute(routeReq); } // Parse XML file File file = new File(customerGatewayInfoPath); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(customerGatewayInfoPath); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression exprGetipAddress = xpath .compile("/vpn_connection/ipsec_tunnel/vpn_gateway/tunnel_outside_address/ip_address"); NodeList vpnGateway = (NodeList) exprGetipAddress.evaluate(document, XPathConstants.NODESET); if (vpnGateway != null) { for (int i = 0; i < vpnGateway.getLength(); i++) { String vpnGatewayIP = vpnGateway.item(i).getTextContent(); System.out .println("AWS vpnGatewayIP for tunnel " + Integer.toString(i) + " " + vpnGatewayIP); } } System.out.println("=============================================="); XPathExpression exprGetKey = xpath.compile("/vpn_connection/ipsec_tunnel/ike/pre_shared_key"); NodeList presharedKeyList = (NodeList) exprGetKey.evaluate(document, XPathConstants.NODESET); if (presharedKeyList != null) { for (int i = 0; i < presharedKeyList.getLength(); i++) { String pre_shared_key = presharedKeyList.item(i).getTextContent(); System.out.println( "AWS pre_shared_key for tunnel " + Integer.toString(i) + " " + pre_shared_key); } } System.out.println("Creating VPN creation completed!"); } else { boolean yn; Scanner scan = new Scanner(System.in); System.out.println("Enter yes or no to delete VPN connection: "); String input = scan.next(); String answer = input.trim().toLowerCase(); while (true) { if (answer.equals("yes")) { yn = true; break; } else if (answer.equals("no")) { yn = false; System.exit(0); } else { System.out.println("Sorry, I didn't catch that. Please answer yes/no"); } } // Delete all existing VPN connections System.out.println("Deleting AWS VPN connection(s)"); for (String vpnConID : connectionIdList) { DeleteVpnConnectionResult delVPNres = new DeleteVpnConnectionResult(); DeleteVpnConnectionRequest delVPNreq = new DeleteVpnConnectionRequest(); delVPNreq.setVpnConnectionId(vpnConID); delVPNres = ec2.deleteVpnConnection(delVPNreq); System.out.println("Successfully deleted AWS VPN conntion: " + vpnConID); } } } catch (AmazonServiceException ase) { System.out.println("Caught Exception: " + ase.getMessage()); System.out.println("Reponse Status Code: " + ase.getStatusCode()); System.out.println("Error Code: " + ase.getErrorCode()); System.out.println("Request ID: " + ase.getRequestId()); } }
From source file:Main.java
public static Node findNodeByXPath(String xPathString, Object source) throws XPathExpressionException { NodeList list = (NodeList) getXPathExpression(xPathString).evaluate(source, XPathConstants.NODESET); int len = list.getLength(); return len == 0 ? null : list.item(0); }
From source file:Main.java
public static String toPrettyString(String xml) { int indent = 4; try {/* w ww . java 2 s .com*/ // Turn xml string into a document Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); // Remove whitespaces outside tags XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); } // Setup pretty print options TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // Return pretty print xml string StringWriter stringWriter = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(stringWriter)); return stringWriter.toString(); } catch (Exception e) { System.out.println(xml); throw new RuntimeException( "Problems prettyfing xml content [" + Splitter.fixedLength(100).split(xml) + "]", e); } }
From source file:Main.java
/** * Performs a xpath query on a document and returns the matching nodelist. * * @param context the Context where to start with the query * @param query the XPath-Query//from w ww . j a v a 2 s .co m * @return nodelist of matches * @throws Exception on error */ public static NodeList query(Node context, String query) throws Exception { NodeList result = null; XPath xpath = XPathFactory.newInstance().newXPath(); try { result = (NodeList) xpath.evaluate(query, context, XPathConstants.NODESET); } catch (XPathExpressionException xpx) { throw new Exception("Error evaluating XPath: " + xpx.getMessage(), xpx); } return result; }
From source file:Main.java
public static NodeList xpathNodeList(String expr, Document doc) { try {//www . ja v a 2s. c o m return (NodeList) xpath.evaluate(expr, doc, XPathConstants.NODESET); } catch (Exception e) { throw new RuntimeException("Cannot evaluate XPath:", e); } }
From source file:Main.java
/** * Counts the elements which results from the xpath expression. * //from www . j av a 2 s. c om * @param document the xml document. * @param xpath the expression * @param message The assert message. * @return Returns -1 if no element was found. */ public static int count(String message, Document document, String xpath) throws XPathExpressionException { XPathExpression expression = EXPRESSIONS.get(xpath); NodeList list = null; if (expression == null) { expression = XPathFactory.newInstance().newXPath().compile(xpath); EXPRESSIONS.put(xpath, expression); } if ((list = (NodeList) expression.evaluate(document.getDocumentElement(), XPathConstants.NODESET)) != null) { return list.getLength(); } return -1; }
From source file:Main.java
public static boolean updateDBConfig(String userName, String password, String name, String driver, String url, String dbConfigPath) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException, TransformerException { Document document = loadXML(dbConfigPath); XPath path = XPathFactory.newInstance().newXPath(); XPathExpression express = path.compile( "//Configure/New[@class='org.eclipse.jetty.plus.jndi.Resource']/Arg/New[@class='bitronix.tm.resource.jdbc.PoolingDataSource']/Set[@name='className']"); NodeList nodes = (NodeList) express.evaluate(document, XPathConstants.NODESET); Node node = nodes.item(0);/*from www . j a v a 2 s . c o m*/ node.setTextContent(driver); path.reset(); express = path.compile( "//Configure/New[@class='org.eclipse.jetty.plus.jndi.Resource']/Arg/New[@class='bitronix.tm.resource.jdbc.PoolingDataSource']/Get['@name=driverProperties']/Put"); nodes = (NodeList) express.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { node = nodes.item(i); if ("user".equals(node.getAttributes().item(0).getTextContent())) { node.setTextContent(userName); } else if ("password".equals(node.getAttributes().item(0).getTextContent())) { node.setTextContent(password); } else if ("URL".equals(node.getAttributes().item(0).getTextContent())) { // String url = node.getTextContent(); // System.out.println("basic url ---> " + url + "; name -->" + name); // url = replaceDBName("examples", name, url); // System.out.println("dist url ---> " + url); node.setTextContent(url); } } path.reset(); return updateXML(document, dbConfigPath); }
From source file:Main.java
/** * // w w w.java 2 s . c o m * <B>Purpose:</B> Evaluates an XPath and returns the Node list associated * witht the XPath * * @param element * @param xpathstring * @return * @throws XPathExpressionException */ public static NodeList evaluateXPath(Element element, String xpathstring) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(xpathstring); NodeList result = (NodeList) expr.evaluate(element, XPathConstants.NODESET); return result; }
From source file:Main.java
public static void writeTo(Document document, File output) { try {//from w ww. j a v a2s .c o m TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); FileOutputStream outputstream = new FileOutputStream(output); StreamResult result = new StreamResult(outputstream); // Manually add xml declaration, to force a newline after it. String xmlDeclaration = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; outputstream.write(xmlDeclaration.getBytes()); // Remove whitespaces outside tags. // Essential to make sure the nodes are properly indented. XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); } // Pretty-print options. transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(source, result); outputstream.close(); } catch (TransformerException | IOException | XPathExpressionException e) { System.out.println("Failed to write document file" + output.getPath() + ": " + e.toString()); } }
From source file:Main.java
/** * Extract the parameters specified in the XML document for the Element * specified by parent.//from www.j a va 2 s. co m * * @param parent * - Parent Node. * @return * @throws Exception */ public static HashMap<String, Object> parseParams(Element parent) throws Exception { XPath xpath = XPathFactory.newInstance().newXPath(); // XPath Query for showing all nodes value XPathExpression expr = xpath.compile(_PARAM_NODE_PARAMS_); NodeList nodes = (NodeList) expr.evaluate(parent, XPathConstants.NODESET); if (nodes != null && nodes.getLength() > 0) { HashMap<String, Object> params = new HashMap<String, Object>(); for (int ii = 0; ii < nodes.getLength(); ii++) { Element elm = (Element) nodes.item(ii); String name = elm.getAttribute(_PARAM_ATTR_NAME_); String value = elm.getAttribute(_PARAM_ATTR_VALUE_); if (name != null && !name.isEmpty()) { params.put(name, value); } } return params; } return null; }