List of usage examples for javax.xml.stream XMLEventReader hasNext
@Override public boolean hasNext();
From source file:fr.openwide.talendalfresco.rest.client.RestAuthenticationTest.java
public void testRestLogin() { // create client and configure it HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); // instantiating a new method and configuring it GetMethod method = new GetMethod(restCommandUrlPrefix + "login"); method.setFollowRedirects(true); // ? // Provide custom retry handler is necessary (?) method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); NameValuePair[] params = new NameValuePair[] { new NameValuePair("username", "admin"), new NameValuePair("password", "admin") }; method.setQueryString(params);// ww w . j a v a 2 s. c o m try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); System.out.println(new String(responseBody)); // TODO rm HashSet<String> defaultElementSet = new HashSet<String>( Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE, RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE })); HashMap<String, String> elementValueMap = new HashMap<String, String>(6); try { XMLEventReader xmlReader = XmlHelper.getXMLInputFactory() .createXMLEventReader(new ByteArrayInputStream(responseBody)); StringBuffer singleLevelTextBuf = null; while (xmlReader.hasNext()) { XMLEvent event = xmlReader.nextEvent(); switch (event.getEventType()) { case XMLEvent.CHARACTERS: case XMLEvent.CDATA: if (singleLevelTextBuf != null) { singleLevelTextBuf.append(event.asCharacters().getData()); } // else element not meaningful break; case XMLEvent.START_ELEMENT: StartElement startElement = event.asStartElement(); String elementName = startElement.getName().getLocalPart(); if (defaultElementSet.contains(elementName) // TODO another command specific level || "ticket".equals(elementName)) { // reinit buffer at start of meaningful elements singleLevelTextBuf = new StringBuffer(); } else { singleLevelTextBuf = null; // not useful } break; case XMLEvent.END_ELEMENT: if (singleLevelTextBuf == null) { break; // element not meaningful } // TODO or merely put it in the map since the element has been tested at start EndElement endElement = event.asEndElement(); elementName = endElement.getName().getLocalPart(); if (defaultElementSet.contains(elementName)) { String value = singleLevelTextBuf.toString(); elementValueMap.put(elementName, value); // TODO test if it is code and it is not OK, break to error handling } // TODO another command specific level else if ("ticket".equals(elementName)) { ticket = singleLevelTextBuf.toString(); } // singleLevelTextBuf = new StringBuffer(); // no ! in start break; } } } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Throwable t) { // TODO Auto-generated catch block t.printStackTrace(); //throw t; } String code = elementValueMap.get(RestConstants.TAG_CODE); assertTrue(RestConstants.CODE_OK.equals(code)); System.out.println("got ticket " + ticket); } catch (HttpException e) { // TODO e.printStackTrace(); } catch (IOException e) { // TODO e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }
From source file:com.adobe.acs.commons.it.build.ScrMetadataIT.java
private Descriptor parseScr(InputStream is, String name, boolean checkNs) throws Exception { Descriptor result = new Descriptor(); XMLEventReader reader = xmlInputFactory.createXMLEventReader(is); while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { StartElement start = event.asStartElement(); String elementName = start.getName().getLocalPart(); if (elementName.equals("component")) { result.name = start.getAttributeByName(new QName("name")).getValue(); if (checkNs) { String scrUri = start.getName().getNamespaceURI(); if (!ALLOWED_SCR_NS_URIS.contains(scrUri)) { throw new Exception( String.format("Banned Namespace URI %s found for %s", scrUri, name)); }/*w w w .j a v a 2 s . com*/ } } else if (elementName.equals("property")) { String propName = start.getAttributeByName(new QName("name")).getValue(); Attribute value = start.getAttributeByName(new QName("value")); Attribute typeAttr = start.getAttributeByName(new QName("type")); String type = typeAttr == null ? "String" : typeAttr.getValue(); if (value != null) { result.properties.add(new Property(propName, value.getValue(), type)); } else { result.properties.add(new Property(propName, cleanText(reader.getElementText()), type)); } } } } return result; }
From source file:com.adobe.acs.commons.it.build.ScrMetadataIT.java
private Descriptor parseMetatype(InputStream is, String name) throws Exception { Descriptor result = new Descriptor(); XMLEventReader reader = xmlInputFactory.createXMLEventReader(is); while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { StartElement start = event.asStartElement(); String elementName = start.getName().getLocalPart(); if (elementName.equals("Designate")) { Attribute pidAttribute = start.getAttributeByName(new QName("pid")); if (pidAttribute != null) { result.name = pidAttribute.getValue(); } else { pidAttribute = start.getAttributeByName(new QName("factoryPid")); if (pidAttribute != null) { result.name = pidAttribute.getValue(); }/* ww w .j av a2s . com*/ result.factory = true; } } else if (elementName.equals("AD")) { String propName = start.getAttributeByName(new QName("id")).getValue(); Attribute value = start.getAttributeByName(new QName("default")); Attribute typeAttr = start.getAttributeByName(new QName("type")); String type = typeAttr == null ? "String" : typeAttr.getValue(); if (value == null) { result.properties.add(new Property(propName, "", type)); } else { result.properties.add(new Property(propName, value.getValue(), type)); } } } } if (result.name == null) { throw new Exception("Could not identify pid for " + name); } return result; }
From source file:jenkins.plugins.livingdoc.XmlReportReader.java
public XmlReportReader parse(FilePath fileReport) throws IOException { this.name = getFilenameWithoutExtension(fileReport); InputStreamReader fileReader = null; XMLEventReader xmlEventReader = null; try {/*from w w w . j a v a 2 s .co m*/ fileReader = new InputStreamReader(new FileInputStream(new File(fileReport.toURI())), Charset.forName("UTF-8")); xmlEventReader = XIF.createXMLEventReader(fileReader); while (xmlEventReader.hasNext()) { final XMLEvent event = xmlEventReader.nextEvent(); if (event.isStartElement()) { final String localPart = event.asStartElement().getName().getLocalPart(); if (localPart.equals("external-link")) { this.externalLink = readString(xmlEventReader.nextEvent()); continue; } if (localPart.equals("success")) { int success = readInteger(xmlEventReader.nextEvent()); this.statistics.setSuccess(success); continue; } if (localPart.equals("failure")) { int failure = readInteger(xmlEventReader.nextEvent()); this.statistics.setFailure(failure); continue; } if (localPart.equals("error")) { int error = readInteger(xmlEventReader.nextEvent()); this.statistics.setError(error); continue; } if (localPart.equals("ignored")) { int ignored = readInteger(xmlEventReader.nextEvent()); this.statistics.setIgnored(ignored); continue; } if (localPart.equals("total")) { int total = readInteger(xmlEventReader.nextEvent()); this.timeStatistics.setTotal(total); continue; } if (localPart.equals("execution")) { int execution = readInteger(xmlEventReader.nextEvent()); this.timeStatistics.setExecution(execution); continue; } if (localPart.equals("results")) { this.results = readString(xmlEventReader.nextEvent()); } if (localPart.equals("global-exception")) { this.globalException = readString(xmlEventReader.nextEvent()); } } } } catch (XMLStreamException | InterruptedException ex) { throw new IOException(String.format("Cannot read xml report file %s", fileReport), ex); } finally { IOUtils.closeQuietly(fileReader); closeQuietly(xmlEventReader); } return this; }
From source file:edu.unc.lib.dl.services.TripleStoreManagerMulgaraImpl.java
/** * @param query/*ww w .j a v a 2 s . c o m*/ * an ITQL command * @return the message returned by Mulgara * @throws RemoteException * for communication failure */ public String storeCommand(String query) { String result = null; String response = this.sendTQL(query); if (response != null) { StringReader sr = new StringReader(response); XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); XMLEventReader r = null; try { boolean inMessage = false; StringBuffer message = new StringBuffer(); r = factory.createXMLEventReader(sr); while (r.hasNext()) { XMLEvent e = r.nextEvent(); if (e.isStartElement()) { StartElement s = e.asStartElement(); if ("message".equals(s.getName().getLocalPart())) { inMessage = true; } } else if (e.isEndElement()) { EndElement end = e.asEndElement(); if ("message".equals(end.getName().getLocalPart())) { inMessage = false; } } else if (inMessage && e.isCharacters()) { message.append(e.asCharacters().getData()); } } result = message.toString(); } catch (XMLStreamException e) { e.printStackTrace(); } finally { if (r != null) { try { r.close(); } catch (Exception ignored) { log.error(ignored); } } } sr.close(); } return result; }
From source file:HTTPChunkLocator.java
/** * parses a chunk info part/* www. j av a 2 s . c o m*/ * <p/> * <pre> * <chunk_list> * <chunk offset="0" chunk_size="67108864"> * <map> * <copy ip_addr="10.10.2.200" name="vistasn1" snid="1" vid="1" /> * <copy ip_addr="10.10.2.201" name="vistasn2" snid="2" vid="3" /> * </map> * </chunk> * </chunk_list> * </pre> */ private List<ChunkLocation> parseChunks(final XMLEventReader reader, final long fileSizeInBytes) throws XMLStreamException, IOException { long offset = -1; long length = -1; final List<ChunkLocation> locations = new ArrayList<ChunkLocation>(5); final List<StorageNodeInfo> sninfo = new ArrayList<StorageNodeInfo>(); final List<Integer> volumeIds = new ArrayList<Integer>(); while (reader.hasNext()) { final XMLEvent nextEvent = reader.nextEvent(); if (!(nextEvent instanceof StartElement)) { continue; } final StartElement start = (StartElement) nextEvent; if (CHUNK_ID.equals(start.getName().getLocalPart())) { if (sninfo.size() > 0) { final ChunkInfo chunkInfo = new ChunkInfo(offset, length, volumeIds.toArray(new Integer[0])); locations.add( new ChunkLocation(sninfo.toArray(new StorageNodeInfo[0]), chunkInfo, fileSizeInBytes)); sninfo.clear(); volumeIds.clear(); } offset = Long.parseLong(get(start, Q_OFFSET)); length = Long.parseLong(get(start, Q_CHUNK_SIZE)); } else if (COPY_ID.equals(start.getName().getLocalPart())) { final InetAddress ip = InetAddress.getByName(get(start, Q_IP_ADDR)); final int vid = Integer.parseInt(get(start, Q_VID)); final String name = get(start, Q_NAME); sninfo.add(new StorageNodeInfo(name, ip.getHostAddress(), true, true)); volumeIds.add(Integer.valueOf(vid)); } } if (sninfo.size() > 0) { final ChunkInfo chunkInfo = new ChunkInfo(offset, length, volumeIds.toArray(new Integer[0])); locations.add(new ChunkLocation(sninfo.toArray(new StorageNodeInfo[0]), chunkInfo, fileSizeInBytes)); } return locations; }
From source file:fr.openwide.talendalfresco.rest.client.importer.RestImportFileTest.java
public void login() { // create client and configure it HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); // instantiating a new method and configuring it GetMethod method = new GetMethod(restCommandUrlPrefix + "login"); method.setFollowRedirects(true); // ? // Provide custom retry handler is necessary (?) method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); NameValuePair[] params = new NameValuePair[] { new NameValuePair("username", "admin"), new NameValuePair("password", "admin") }; method.setQueryString(params);//w ww .j a v a2s. c o m try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); System.out.println(new String(responseBody)); // TODO rm HashSet<String> defaultElementSet = new HashSet<String>( Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE, RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE })); HashMap<String, String> elementValueMap = new HashMap<String, String>(6); try { XMLEventReader xmlReader = XmlHelper.getXMLInputFactory() .createXMLEventReader(new ByteArrayInputStream(responseBody)); StringBuffer singleLevelTextBuf = null; while (xmlReader.hasNext()) { XMLEvent event = xmlReader.nextEvent(); switch (event.getEventType()) { case XMLEvent.CHARACTERS: case XMLEvent.CDATA: if (singleLevelTextBuf != null) { singleLevelTextBuf.append(event.asCharacters().getData()); } // else element not meaningful break; case XMLEvent.START_ELEMENT: StartElement startElement = event.asStartElement(); String elementName = startElement.getName().getLocalPart(); if (defaultElementSet.contains(elementName) // TODO another command specific level || "ticket".equals(elementName)) { // reinit buffer at start of meaningful elements singleLevelTextBuf = new StringBuffer(); } else { singleLevelTextBuf = null; // not useful } break; case XMLEvent.END_ELEMENT: if (singleLevelTextBuf == null) { break; // element not meaningful } // TODO or merely put it in the map since the element has been tested at start EndElement endElement = event.asEndElement(); elementName = endElement.getName().getLocalPart(); if (defaultElementSet.contains(elementName)) { String value = singleLevelTextBuf.toString(); elementValueMap.put(elementName, value); // TODO test if it is code and it is not OK, break to error handling } // TODO another command specific level else if ("ticket".equals(elementName)) { ticket = singleLevelTextBuf.toString(); } // singleLevelTextBuf = new StringBuffer(); // no ! in start break; } } } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Throwable t) { // TODO Auto-generated catch block t.printStackTrace(); //throw t; } String code = elementValueMap.get(RestConstants.TAG_CODE); assertTrue(RestConstants.CODE_OK.equals(code)); System.out.println("got ticket " + ticket); } catch (HttpException e) { // TODO e.printStackTrace(); } catch (IOException e) { // TODO e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }
From source file:fr.openwide.talendalfresco.rest.client.importer.RestImportFileTest.java
public void testSingleFileImport() { // create client and configure it HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); // instantiating a new method and configuring it PostMethod method = new PostMethod(restCommandUrlPrefix + "import"); // Provide custom retry handler is necessary (?) method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); NameValuePair[] params = new NameValuePair[] { new NameValuePair("path", "/app:company_home"), new NameValuePair("ticket", ticket) }; method.setQueryString(params);// w w w .ja v a 2s . co m try { //method.setRequestBody(new NameValuePair[] { // new NameValuePair("path", "/app:company_home") }); FileInputStream acpXmlIs = new FileInputStream(SAMPLE_SINGLE_FILE_PATH); InputStreamRequestEntity entity = new InputStreamRequestEntity(acpXmlIs); //InputStreamRequestEntity entity = new InputStreamRequestEntity(acpXmlIs, "text/xml; charset=ISO-8859-1"); method.setRequestEntity(entity); } catch (IOException ioex) { fail("ACP XML file not found " + ioex.getMessage()); } try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); System.out.println(new String(responseBody)); // TODO rm HashSet<String> defaultElementSet = new HashSet<String>( Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE, RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE })); HashMap<String, String> elementValueMap = new HashMap<String, String>(6); try { XMLEventReader xmlReader = XmlHelper.getXMLInputFactory() .createXMLEventReader(new ByteArrayInputStream(responseBody)); StringBuffer singleLevelTextBuf = null; while (xmlReader.hasNext()) { XMLEvent event = xmlReader.nextEvent(); switch (event.getEventType()) { case XMLEvent.CHARACTERS: case XMLEvent.CDATA: if (singleLevelTextBuf != null) { singleLevelTextBuf.append(event.asCharacters().getData()); } // else element not meaningful break; case XMLEvent.START_ELEMENT: StartElement startElement = event.asStartElement(); String elementName = startElement.getName().getLocalPart(); if (defaultElementSet.contains(elementName) // TODO another command specific level || "ticket".equals(elementName)) { // reinit buffer at start of meaningful elements singleLevelTextBuf = new StringBuffer(); } else { singleLevelTextBuf = null; // not useful } break; case XMLEvent.END_ELEMENT: if (singleLevelTextBuf == null) { break; // element not meaningful } // TODO or merely put it in the map since the element has been tested at start EndElement endElement = event.asEndElement(); elementName = endElement.getName().getLocalPart(); if (defaultElementSet.contains(elementName)) { String value = singleLevelTextBuf.toString(); elementValueMap.put(elementName, value); // TODO test if it is code and it is not OK, break to error handling } // TODO another command specific level else if ("ticket".equals(elementName)) { ticket = singleLevelTextBuf.toString(); } // singleLevelTextBuf = new StringBuffer(); // no ! in start break; } } } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Throwable t) { // TODO Auto-generated catch block t.printStackTrace(); //throw t; } String code = elementValueMap.get(RestConstants.TAG_CODE); assertTrue(RestConstants.CODE_OK.equals(code)); System.out.println("got ticket " + ticket); } catch (HttpException e) { // TODO e.printStackTrace(); } catch (IOException e) { // TODO e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }
From source file:sapience.injectors.stax.inject.ModelBasedStaxStreamInjector.java
/** * The actual injection procedure//from w w w . ja v a2 s. c o m * @param in the input stream where the XML is coming from (will be closed in the end) * @param out the output stream where we write the annotated XML into (remains open) * @param refs a list of references * @throws IOException */ public void inject(InputStream in, OutputStream out, List<Reference> refs) throws IOException { StringBuilder pb; XPathElement characters = null; int marked; interceptingElements = new ArrayList<Reference>(); try { XMLEventReader r = getXMLInputFactory().createXMLEventReader(in); XMLEventWriter w = getXMLOutputFactory().createXMLEventWriter(out); while (r.hasNext()) { XMLEvent e = r.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_ELEMENT: StartElement se = (StartElement) e; if (super.getNamespaceContext() == null) { super.updateNamespaceContext(se.getNamespaceContext()); } if (references == null) { // process the namespaces in the references references = this.prepareReferences(refs); } // store location col = e.getLocation().getColumnNumber(); // add to current xpath updateCurrentPath(getGenerator().asXPathElement((StartElement) e)); System.out.println(getCurrentPath()); // check if the current xpath is in our list of attribute references for (XPathPattern p : references.keySet()) { if (references.get(p) == null) continue; if (p.isAttribute()) { if (getMatcher().matches(p, getCurrentPath())) { se = this.handleAttribute(w, references.get(p), se); references.put(p, null); // removing it would lead to concurrentmodificationexcpetion } } } w.add(se); break; case XMLEvent.END_ELEMENT: updateCurrentPath(characters); // before removing from stack, we check if the current path with added characters is a match (which means we have to add a new element now) XPathStack currentPath = getCurrentPath(); for (XPathPattern p : references.keySet()) { if (references.get(p) == null) continue; if (getMatcher().matches(p, currentPath)) { if (p.isSiblingElement()) { // injection happens below this.interceptingElements.add(references.get(p)); } else if (p.isChildElement()) { // we can add it directly w.add(getXMLEventFactory().createSpace("\n")); writeElementIntoStream(w, references.get(p)); } else { throw new IOException("Invalid Reference: " + p); } references.put(p, null); // removing it would lead to concurrentmodificationexcpetion //references.remove(p); //break; //otherwise ConcurrentModificationException } } // clean up if (characters != null) { getCurrentPath().pop(); characters = null; } getCurrentPath().pop(); w.add(e); // do not change position // if the intercepting is not null, the preceding element was a match, hence we inject some xml before writing a new element if (this.interceptingElements.size() > 0) { // write all references into stream for (Reference ref : this.interceptingElements) { w.add(getXMLEventFactory().createSpace("\n")); writeElementIntoStream(w, ref); } // reset list this.interceptingElements.clear(); } break; case XMLEvent.CHARACTERS: characters = getGenerator().asXPathElement((Characters) e); w.add(e); break; default: w.add(e); break; } } } catch (XPathExpressionException e) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, "Not a valid XPath", e); } throw new IOException(e); } catch (XMLStreamException e) { if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, "Failed to inject. Reason: " + e.getLocalizedMessage(), e); } throw new IOException(e); } finally { in.close(); } }