List of usage examples for javax.xml.xpath XPathFactory newInstance
public static XPathFactory newInstance()
Get a new XPathFactory instance using the default object model, #DEFAULT_OBJECT_MODEL_URI , the W3C DOM.
This method is functionally equivalent to:
newInstance(DEFAULT_OBJECT_MODEL_URI)
Since the implementation for the W3C DOM is always available, this method will never fail.
From source file:Main.java
/** * Create an XPathExpression from the supplied xpath string. * * @param xpath The xpath string.//from w w w .ja v a2 s . c o m * @return An XPathExpression. */ public static XPathExpression createXPathExpression(String xpath) throws Exception { if (XPATH == null) { XPATH = XPathFactory.newInstance().newXPath(); } return XPATH.compile(xpath); }
From source file:Main.java
public static Map<String, String> readXmlToMap(String filename, String xpathExp, String arrtibute) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException { //to-do something Map<String, String> dataMap = new HashMap<String, String>(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setIgnoringElementContentWhitespace(true); DocumentBuilder db = dbf.newDocumentBuilder(); File file = new File(filename); if (file.exists()) { Document doc = db.parse(file); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); NodeList varList = (NodeList) xpath.evaluate(xpathExp, doc, XPathConstants.NODESET); for (int i = 0; i < varList.getLength(); i++) { dataMap.put(varList.item(i).getAttributes().getNamedItem(arrtibute).getNodeValue(), varList.item(i).getTextContent()); }// w w w. j a va2s . c om } return dataMap; }
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();//from w w w .java2 s . co 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 String valueForXPath(String xpath, InputStream inputStream) throws XPathExpressionException { /*//from ww w . j a v a 2s .co m * Report.systemProperty("javax.xml.parsers.DocumentBuilderFactory"); * Report.systemProperty("javax.xml.parsers.SAXParserFactory"); * Report.systemProperty("javax.xml.transform.TransformerFactory"); */ XPathFactory factory = XPathFactory.newInstance(); InputSource is = new InputSource(inputStream); XPath xp = factory.newXPath(); return xp.evaluate(xpath, is); }
From source file:Main.java
public static Object evaluateXpath(String expression, Object node, QName returnType, NamespaceContext nsContext) throws XPathExpressionException { XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); if (nsContext != null) { xpath.setNamespaceContext(nsContext); }//from w w w . ja va2 s . c o m return xpath.evaluate(expression, node, returnType); // XPathExpression xpathExpr = xpath.compile(expression); // return xpathExpr.evaluate(node, returnType); }
From source file:Main.java
public static NodeList getElementsByXpath(Document docInput, String xPath) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(xPath); return ((NodeList) expr.evaluate(docInput, XPathConstants.NODESET)); }
From source file:Main.java
/** * Select node list what matches given xpath query * * @param node xml node/*from w w w .j a v a 2s .c o m*/ * @param expression xpath query * @return nodes which confirms given xpath query. * @throws XPathExpressionException in case of any errors. */ public static NodeList query(final Node node, final String expression) throws XPathExpressionException { final XPath xpath = XPathFactory.newInstance().newXPath(); return (NodeList) xpath.evaluate(expression, node, XPathConstants.NODESET); }
From source file:Main.java
/** * Select only one node what matches given xpath query * * @param node xml node// w ww . ja va 2s. c o m * @param expression xpath query * @return first element which confirms given xpath query. * @throws XPathExpressionException in case of any errors. */ public static Element queryElement(final Node node, final String expression) throws XPathExpressionException { final XPath xpath = XPathFactory.newInstance().newXPath(); return (Element) xpath.evaluate(expression, node, XPathConstants.NODE); }
From source file:Main.java
/** * Locates the element defined by the XPath expression in the XML file and replaces the child text with the passed value. * @param fileName The XML file to update. * @param xPathExpression An XPath expression that locates the element to update. * @param value The value to update the attribute to. *///ww w .j a v a 2 s . c om public static void updateElementValueInXMLFile(String fileName, String xPathExpression, String value) { try { Document document = parseXML(new File(fileName)); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression xpathExpression = xpath.compile(xPathExpression); Element element = (Element) xpathExpression.evaluate(document, NODE); element.getFirstChild().setNodeValue(value); writeElement(document.getDocumentElement(), fileName); } catch (Exception e) { throw new RuntimeException("Failed to extract element from:" + fileName, e); } }
From source file:Main.java
public static String xPathSearch(String input, String expression) throws Exception { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression xPathExpression = xPath.compile(expression); Document document = documentBuilder.parse(new ByteArrayInputStream(input.getBytes("UTF-8"))); String output = (String) xPathExpression.evaluate(document, XPathConstants.STRING); return output == null ? "" : output.trim(); }