List of usage examples for javax.xml.parsers DocumentBuilderFactory newInstance
public static DocumentBuilderFactory newInstance()
From source file:com.betfair.testing.utils.cougar.assertions.AssertionUtils.java
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException { Document expected = new XMLHelpers().createAsDocument( DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream( ("<a><b><c>1</c><c>2</c><c>3</c></b><b><c>1</c><c>2</c><c>3</c></b></a>").getBytes()))); Document actual = new XMLHelpers().createAsDocument( DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream( ("<a><b><c>2</c><c>1</c><c>3</c></b><b><c>3</c><c>2</c><c>1</c></b></a>").getBytes()))); try {/*from w w w .j a v a 2 s . com*/ multiAssertEquals(expected, actual); System.out.println("Failed: should have been different"); } catch (AssertionError e) { System.out.println("Passed: were different"); } try { multiAssertEquals(expected, actual, "/a/b"); System.out.println("Passed: weren't different"); } catch (AssertionError e) { System.out.println("Failed: shouldn't have been different"); } }
From source file:DOM2DOM.java
public static void main(String[] args) throws TransformerException, TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, SAXException, IOException { TransformerFactory tFactory = TransformerFactory.newInstance(); if (tFactory.getFeature(DOMSource.FEATURE) && tFactory.getFeature(DOMResult.FEATURE)) { //Instantiate a DocumentBuilderFactory. DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); // And setNamespaceAware, which is required when parsing xsl files dFactory.setNamespaceAware(true); //Use the DocumentBuilderFactory to create a DocumentBuilder. DocumentBuilder dBuilder = dFactory.newDocumentBuilder(); //Use the DocumentBuilder to parse the XSL stylesheet. Document xslDoc = dBuilder.parse("birds.xsl"); // Use the DOM Document to define a DOMSource object. DOMSource xslDomSource = new DOMSource(xslDoc); // Set the systemId: note this is actually a URL, not a local filename xslDomSource.setSystemId("birds.xsl"); // Process the stylesheet DOMSource and generate a Transformer. Transformer transformer = tFactory.newTransformer(xslDomSource); //Use the DocumentBuilder to parse the XML input. Document xmlDoc = dBuilder.parse("birds.xml"); // Use the DOM Document to define a DOMSource object. DOMSource xmlDomSource = new DOMSource(xmlDoc); // Set the base URI for the DOMSource so any relative URIs it contains can // be resolved. xmlDomSource.setSystemId("birds.xml"); // Create an empty DOMResult for the Result. DOMResult domResult = new DOMResult(); // Perform the transformation, placing the output in the DOMResult. transformer.transform(xmlDomSource, domResult); //Instantiate an Xalan XML serializer and use it to serialize the output DOM to System.out // using the default output format, except for indent="yes" java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml"); xmlProps.setProperty("indent", "yes"); xmlProps.setProperty("standalone", "no"); Serializer serializer = SerializerFactory.getSerializer(xmlProps); serializer.setOutputStream(System.out); serializer.asDOMSerializer().serialize(domResult.getNode()); } else {// w w w . j av a2 s. c o m throw new org.xml.sax.SAXNotSupportedException("DOM node processing not supported!"); } }
From source file:edu.ucsb.cs.eager.sa.cerebro.ProfessorX.java
public static void main(String[] args) { Options options = new Options(); options.addOption("i", "input-file", true, "Path to input xml file"); options.addOption("r", "root-path", true, "Root path of all Git repositories"); CommandLine cmd;// www .jav a 2 s.c o m try { CommandLineParser parser = new BasicParser(); cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Error: " + e.getMessage() + "\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Cerebro", options); return; } String inputFileName = cmd.getOptionValue("i"); if (inputFileName == null) { System.err.println("input file path is required"); return; } String rootPath = cmd.getOptionValue("r"); if (rootPath == null) { System.err.println("root path is required"); return; } File inputFile = new File(inputFileName); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); Document doc; try { DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); doc = dBuilder.parse(inputFile); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } NodeList repoList = doc.getElementsByTagName("repo"); for (int i = 0; i < repoList.getLength(); i++) { Element repo = (Element) repoList.item(i); String name = repo.getElementsByTagName("name").item(0).getTextContent(); String classPath = repo.getElementsByTagName("classpath").item(0).getTextContent(); Set<String> classes = new LinkedHashSet<String>(); NodeList classesList = repo.getElementsByTagName("classes").item(0).getChildNodes(); for (int j = 0; j < classesList.getLength(); j++) { if (!(classesList.item(j) instanceof Element)) { continue; } classes.add(classesList.item(j).getTextContent()); } analyzeRepo(rootPath, name, classPath, classes); } }
From source file:com.github.fritaly.svngraph.SvnGraph.java
public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println(String.format("%s <input-file> <output-file>", SvnGraph.class.getSimpleName())); System.exit(1);/*from ww w . j av a 2s.co m*/ } final File input = new File(args[0]); if (!input.exists()) { throw new IllegalArgumentException( String.format("The given file '%s' doesn't exist", input.getAbsolutePath())); } final File output = new File(args[1]); final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input); final History history = new History(document); final Set<String> rootPaths = history.getRootPaths(); System.out.println(rootPaths); for (String path : rootPaths) { System.out.println(path); System.out.println(history.getHistory(path).getRevisions()); System.out.println(); } int count = 0; FileWriter fileWriter = null; GraphMLWriter graphWriter = null; try { fileWriter = new FileWriter(output); graphWriter = new GraphMLWriter(fileWriter); final NodeStyle tagStyle = graphWriter.getNodeStyle(); tagStyle.setFillColor(Color.WHITE); graphWriter.graph(); // map associating node labels to their corresponding node id in the graph final Map<String, String> nodeIdsPerLabel = new TreeMap<>(); // the node style associated to each branch final Map<String, NodeStyle> nodeStyles = new TreeMap<>(); for (Revision revision : history.getSignificantRevisions()) { System.out.println(revision.getNumber() + " - " + revision.getMessage()); // TODO Render also the deletion of branches // there should be only 1 significant update per revision (the one with action ADD) for (Update update : revision.getSignificantUpdates()) { if (update.isCopy()) { // a merge is also considered a copy final RevisionPath source = update.getCopySource(); System.out.println(String.format(" > %s %s from %s@%d", update.getAction(), update.getPath(), source.getPath(), source.getRevision())); final String sourceRoot = Utils.getRootName(source.getPath()); if (sourceRoot == null) { // skip the revisions whose associated root is // null (happens whether a branch was created // outside the 'branches' directory for // instance) System.err.println(String.format("Skipped revision %d because of a null root", source.getRevision())); continue; } final String sourceLabel = computeNodeLabel(sourceRoot, source.getRevision()); // create a node for the source (path, revision) final String sourceId; if (nodeIdsPerLabel.containsKey(sourceLabel)) { // retrieve the id of the existing node sourceId = nodeIdsPerLabel.get(sourceLabel); } else { // create the new node if (Utils.isTagPath(source.getPath())) { graphWriter.setNodeStyle(tagStyle); } else { if (!nodeStyles.containsKey(sourceRoot)) { final NodeStyle style = new NodeStyle(); style.setFillColor(randomColor()); nodeStyles.put(sourceRoot, style); } graphWriter.setNodeStyle(nodeStyles.get(sourceRoot)); } sourceId = graphWriter.node(sourceLabel); nodeIdsPerLabel.put(sourceLabel, sourceId); } // and another for the newly created directory final String targetRoot = Utils.getRootName(update.getPath()); if (targetRoot == null) { System.err.println(String.format("Skipped revision %d because of a null root", revision.getNumber())); continue; } final String targetLabel = computeNodeLabel(targetRoot, revision.getNumber()); if (Utils.isTagPath(update.getPath())) { graphWriter.setNodeStyle(tagStyle); } else { if (!nodeStyles.containsKey(targetRoot)) { final NodeStyle style = new NodeStyle(); style.setFillColor(randomColor()); nodeStyles.put(targetRoot, style); } graphWriter.setNodeStyle(nodeStyles.get(targetRoot)); } final String targetId; if (nodeIdsPerLabel.containsKey(targetLabel)) { // retrieve the id of the existing node targetId = nodeIdsPerLabel.get(targetLabel); } else { // create the new node if (Utils.isTagPath(update.getPath())) { graphWriter.setNodeStyle(tagStyle); } else { if (!nodeStyles.containsKey(targetRoot)) { final NodeStyle style = new NodeStyle(); style.setFillColor(randomColor()); nodeStyles.put(targetRoot, style); } graphWriter.setNodeStyle(nodeStyles.get(targetRoot)); } targetId = graphWriter.node(targetLabel); nodeIdsPerLabel.put(targetLabel, targetId); } // create an edge between the 2 nodes graphWriter.edge(sourceId, targetId); } else { System.out.println(String.format(" > %s %s", update.getAction(), update.getPath())); } } System.out.println(); count++; } // Dispatch the revisions per corresponding branch final Map<String, Set<Long>> revisionsPerBranch = new TreeMap<>(); for (String nodeLabel : nodeIdsPerLabel.keySet()) { if (nodeLabel.contains("@")) { final String branchName = StringUtils.substringBefore(nodeLabel, "@"); final long revision = Long.parseLong(StringUtils.substringAfter(nodeLabel, "@")); if (!revisionsPerBranch.containsKey(branchName)) { revisionsPerBranch.put(branchName, new TreeSet<Long>()); } revisionsPerBranch.get(branchName).add(revision); } else { throw new IllegalStateException(nodeLabel); } } // Recreate the missing edges between revisions from a same branch for (String branchName : revisionsPerBranch.keySet()) { final List<Long> branchRevisions = new ArrayList<>(revisionsPerBranch.get(branchName)); for (int i = 0; i < branchRevisions.size() - 1; i++) { final String nodeLabel1 = String.format("%s@%d", branchName, branchRevisions.get(i)); final String nodeLabel2 = String.format("%s@%d", branchName, branchRevisions.get(i + 1)); graphWriter.edge(nodeIdsPerLabel.get(nodeLabel1), nodeIdsPerLabel.get(nodeLabel2)); } } graphWriter.closeGraph(); System.out.println(String.format("Found %d significant revisions", count)); } finally { if (graphWriter != null) { graphWriter.close(); } if (fileWriter != null) { fileWriter.close(); } } System.out.println("Done"); }
From source file:OldExtractor.java
/** * @param args the command line arguments */// www . j ava 2 s . c o m public static void main(String[] args) { // TODO code application logic here String bingUrl = "https://api.datamarket.azure.com/Bing/Search/Web?$top=10&$format=Atom&Query=%27gates%27"; //Provide your account key here. String accountKey = "ghTYY7wD6LpyxUO9VRR7e1f98WFhHWYERMcw87aQTqQ"; // String accountKey = "xqbCjT87/MQz25JWdRzgMHdPkGYnOz77IYmP5FUIgC8"; byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes()); String accountKeyEnc = new String(accountKeyBytes); try { URL url = new URL(bingUrl); URLConnection urlConnection = url.openConnection(); urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc); InputStream inputStream = (InputStream) urlConnection.getContent(); byte[] contentRaw = new byte[urlConnection.getContentLength()]; inputStream.read(contentRaw); String content = new String(contentRaw); //System.out.println(content); try { File file = new File("Results.xml"); FileWriter fileWriter = new FileWriter(file); fileWriter.write(content); //fileWriter.write("a test"); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { System.out.println(e); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { //System.out.println("here"); //Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); //parse using builder to get DOM representation of the XML file Document dom = db.parse("Results.xml"); Element docEle = (Element) dom.getDocumentElement(); //get a nodelist of elements NodeList nl = docEle.getElementsByTagName("d:Url"); if (nl != null && nl.getLength() > 0) { for (int i = 0; i < nl.getLength(); i++) { //get the employee element Element el = (Element) nl.item(i); // System.out.println("here"); System.out.println(el.getTextContent()); //get the Employee object //Employee e = getEmployee(el); //add it to list //myEmpls.add(e); } } NodeList n2 = docEle.getElementsByTagName("d:Title"); if (n2 != null && n2.getLength() > 0) { for (int i = 0; i < n2.getLength(); i++) { //get the employee element Element e2 = (Element) n2.item(i); // System.out.println("here"); System.out.println(e2.getTextContent()); //get the Employee object //Employee e = getEmployee(el); //add it to list //myEmpls.add(e); } } NodeList n3 = docEle.getElementsByTagName("d:Description"); if (n3 != null && n3.getLength() > 0) { for (int i = 0; i < n3.getLength(); i++) { //get the employee element Element e3 = (Element) n3.item(i); // System.out.println("here"); System.out.println(e3.getTextContent()); //get the Employee object //Employee e = getEmployee(el); //add it to list //myEmpls.add(e); } } } catch (SAXException se) { se.printStackTrace(); } catch (ParserConfigurationException pe) { pe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } catch (IOException e) { System.out.println(e); } //The content string is the xml/json output from Bing. }
From source file:interoperabilite.webservice.fluent.FluentResponseHandling.java
public static void main(String[] args) throws Exception { Document result = Request.Get("http://somehost/content").execute() .handleResponse(new ResponseHandler<Document>() { @Override/*from w w w .ja v a 2 s .co m*/ public Document handleResponse(final HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response contains no content"); } DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); try { DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); ContentType contentType = ContentType.getOrDefault(entity); if (!contentType.equals(ContentType.APPLICATION_XML)) { throw new ClientProtocolException("Unexpected content type:" + contentType); } Charset charset = contentType.getCharset(); if (charset == null) { charset = Consts.ISO_8859_1; } return docBuilder.parse(entity.getContent(), charset.name()); } catch (ParserConfigurationException ex) { throw new IllegalStateException(ex); } catch (SAXException ex) { throw new ClientProtocolException("Malformed XML document", ex); } } }); // Do something useful with the result System.out.println(result); }
From source file:ebay.Ebay.java
/** * @param args the command line arguments *///from w w w .jav a2 s . co m public static void main(String[] args) { HttpClient client = null; HttpResponse response = null; BufferedReader rd = null; Document doc = null; String xml = ""; EbayDAO<Producto> db = new EbayDAO<>(Producto.class); String busqueda; while (true) { busqueda = JOptionPane.showInputDialog(null, "ingresa una busqueda"); if (busqueda != null) { busqueda = busqueda.replaceAll(" ", "%20"); try { client = new DefaultHttpClient(); /* peticion GET */ HttpGet request = new HttpGet("http://open.api.ebay.com/shopping?" + "callname=FindPopularItems" + "&appid=student11-6428-4bd4-ac0d-6ed9d84e345" + "&version=517&QueryKeywords=" + busqueda + "&siteid=0" + "&responseencoding=XML"); /* se ejecuta la peticion GET */ response = client.execute(request); rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); /* comienza la lectura de la respuesta a la peticion GET */ String line; while ((line = rd.readLine()) != null) { xml += line + "\n"; } } catch (IOException ex) { Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex); } /* creamos nuestro documentBulder(documento constructor) y obtenemos nuestro objeto documento apartir de documentBuilder */ try { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); doc = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); } catch (ParserConfigurationException | SAXException | IOException ex) { Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex); } Element raiz = doc.getDocumentElement(); if (raiz == null) { System.exit(0); } if (raiz.getElementsByTagName("Ack").item(0).getTextContent().equals("Success")) { NodeList array = raiz.getElementsByTagName("ItemArray").item(0).getChildNodes(); for (int i = 0; i < array.getLength(); ++i) { Node n = array.item(i); if (n.getNodeType() != Node.TEXT_NODE) { Producto p = new Producto(); if (((Element) n).getElementsByTagName("ItemID").item(0) != null) p.setId(new Long( ((Element) n).getElementsByTagName("ItemID").item(0).getTextContent())); if (((Element) n).getElementsByTagName("EndTime").item(0) != null) p.setEndtime( ((Element) n).getElementsByTagName("EndTime").item(0).getTextContent()); if (((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch").item(0) != null) p.setViewurl(((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch") .item(0).getTextContent()); if (((Element) n).getElementsByTagName("ListingType").item(0) != null) p.setListingtype( ((Element) n).getElementsByTagName("ListingType").item(0).getTextContent()); if (((Element) n).getElementsByTagName("GalleryURL").item(0) != null) p.setGalleryurl( ((Element) n).getElementsByTagName("GalleryURL").item(0).getTextContent()); if (((Element) n).getElementsByTagName("PrimaryCategoryID").item(0) != null) p.setPrimarycategoryid(new Integer(((Element) n) .getElementsByTagName("PrimaryCategoryID").item(0).getTextContent())); if (((Element) n).getElementsByTagName("PrimaryCategoryName").item(0) != null) p.setPrimarycategoryname(((Element) n).getElementsByTagName("PrimaryCategoryName") .item(0).getTextContent()); if (((Element) n).getElementsByTagName("BidCount").item(0) != null) p.setBidcount(new Integer( ((Element) n).getElementsByTagName("BidCount").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ConvertedCurrentPrice").item(0) != null) p.setConvertedcurrentprice(new Double(((Element) n) .getElementsByTagName("ConvertedCurrentPrice").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ListingStatus").item(0) != null) p.setListingstatus(((Element) n).getElementsByTagName("ListingStatus").item(0) .getTextContent()); if (((Element) n).getElementsByTagName("TimeLeft").item(0) != null) p.setTimeleft( ((Element) n).getElementsByTagName("TimeLeft").item(0).getTextContent()); if (((Element) n).getElementsByTagName("Title").item(0) != null) p.setTitle(((Element) n).getElementsByTagName("Title").item(0).getTextContent()); if (((Element) n).getElementsByTagName("ShippingServiceCost").item(0) != null) p.setShippingservicecost(new Double(((Element) n) .getElementsByTagName("ShippingServiceCost").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ShippingType").item(0) != null) p.setShippingtype(((Element) n).getElementsByTagName("ShippingType").item(0) .getTextContent()); if (((Element) n).getElementsByTagName("WatchCount").item(0) != null) p.setWatchcount(new Integer( ((Element) n).getElementsByTagName("WatchCount").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ListedShippingServiceCost").item(0) != null) p.setListedshippingservicecost( new Double(((Element) n).getElementsByTagName("ListedShippingServiceCost") .item(0).getTextContent())); try { db.insert(p); } catch (Exception e) { db.update(p); } } } } Ventana.crear(xml); } else System.exit(0); } }
From source file:Signing.java
public static void main(String[] args) throws Exception { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12")); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addAttribute(/* ww w . j a v a 2s.co m*/ soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body"); Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com"); SOAPBodyElement gltp = soapBody.addBodyElement(bodyName); Source source = soapPart.getContent(); Node root = null; if (source instanceof DOMSource) { root = ((DOMSource) source).getNode(); } else if (source instanceof SAXSource) { InputSource inSource = ((SAXSource) source).getInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); Document doc = db.parse(inSource); root = (Node) doc.getDocumentElement(); } dumpDocument(root); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(1024, new SecureRandom()); KeyPair keypair = kpg.generateKeyPair(); XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance(); Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null)); SignedInfo signedInfo = sigFactory.newSignedInfo( sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = sigFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo); System.out.println("Signing the message..."); PrivateKey privateKey = keypair.getPrivate(); Element envelope = getFirstChildElement(root); Element header = getFirstChildElement(envelope); DOMSignContext sigContext = new DOMSignContext(privateKey, header); sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); sigContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); sig.sign(sigContext); dumpDocument(root); System.out.println("Validate the signature..."); Element sigElement = getFirstChildElement(header); DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement); valContext.setIdAttributeNS(getNextSiblingElement(header), "http://schemas.xmlsoap.org/soap/security/2000-12", "id"); boolean valid = sig.validate(valContext); System.out.println("Signature valid? " + valid); }
From source file:io.aos.protocol.http.httpcommon.FluentResponseHandling.java
public static void main(String... args) throws Exception { Document result = Request.Get("http://somehost/content").execute() .handleResponse(new ResponseHandler<Document>() { public Document handleResponse(final HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); }//from w ww.j a v a2 s .c om if (entity == null) { throw new ClientProtocolException("Response contains no content"); } DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); try { DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); ContentType contentType = ContentType.getOrDefault(entity); if (!contentType.equals(ContentType.APPLICATION_XML)) { throw new ClientProtocolException("Unexpected content type:" + contentType); } Charset charset = contentType.getCharset(); if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } return docBuilder.parse(entity.getContent(), charset.name()); } catch (ParserConfigurationException ex) { throw new IllegalStateException(ex); } catch (SAXException ex) { throw new ClientProtocolException("Malformed XML document", ex); } } }); // Do something useful with the result System.out.println(result); }
From source file:com.adobe.aem.demomachine.gui.AemDemo.java
public static void main(String[] args) { String demoMachineRootFolder = null; // Command line options for this tool Options options = new Options(); options.addOption("f", true, "Path to Demo Machine root folder"); CommandLineParser parser = new BasicParser(); try {//from w ww .j ava 2 s . com CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("f")) { demoMachineRootFolder = cmd.getOptionValue("f"); } } catch (ParseException ex) { logger.error(ex.getMessage()); } // Let's grab the version number for the core Maven file String mavenFilePath = (demoMachineRootFolder != null ? demoMachineRootFolder : System.getProperty("user.dir")) + File.separator + "java" + File.separator + "core" + File.separator + "pom.xml"; File mavenFile = new File(mavenFilePath); if (mavenFile.exists() && !mavenFile.isDirectory()) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document; document = builder.parse(mavenFile); NodeList list = document.getElementsByTagName("version"); if (list != null && list.getLength() > 0) { aemDemoMachineVersion = list.item(0).getFirstChild().getNodeValue(); } } catch (Exception e) { logger.error("Can't parse Maven pom.xml file"); } } // Let's check if we have a valid build.xml file to work with... String buildFilePath = (demoMachineRootFolder != null ? demoMachineRootFolder : System.getProperty("user.dir")) + File.separator + "build.xml"; logger.debug("Trying to load build file from " + buildFilePath); buildFile = new File(buildFilePath); if (buildFile.exists() && !buildFile.isDirectory()) { // Launching the main window EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.getLookAndFeelDefaults().put("defaultFont", new Font("Arial", Font.BOLD, 14)); AemDemo window = new AemDemo(); window.frameMain.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } else { logger.error("No valid build.xml file to work with"); System.exit(-1); } }