List of usage examples for javax.xml.stream XMLEventReader close
public void close() throws XMLStreamException;
From source file:com.msopentech.odatajclient.testservice.utils.AbstractUtilities.java
private Map.Entry<String, Boolean> getTargetInfo(final StartElement element, final String linkName) throws Exception { final InputStream metadata = fsManager.readFile(Constants.METADATA, Accept.XML); XMLEventReader reader = XMLUtilities.getEventReader(metadata); final String associationName = element.getAttributeByName(new QName("Relationship")).getValue(); final Map.Entry<Integer, XmlElement> association = XMLUtilities.getAtomElement(reader, null, "Association", Collections.<Map.Entry<String, String>>singleton(new SimpleEntry<String, String>("Name", associationName.substring(associationName.lastIndexOf(".") + 1))), 0, 4, 4, false);/*from w w w . j ava2 s . c o m*/ final InputStream associationContent = association.getValue().toStream(); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(associationContent, bos); IOUtils.closeQuietly(associationContent); reader.close(); reader = XMLUtilities.getEventReader(new ByteArrayInputStream(bos.toByteArray())); final Map.Entry<Integer, XmlElement> associationEnd = XMLUtilities.getAtomElement(reader, null, "End", Collections.<Map.Entry<String, String>>singleton(new SimpleEntry<String, String>("Role", linkName)), 0, -1, -1, false); final String target = associationEnd.getValue().getStart().getAttributeByName(new QName("Type")).getValue(); final boolean feed = associationEnd.getValue().getStart().getAttributeByName(new QName("Multiplicity")) .getValue().equals("*"); return new SimpleEntry<String, Boolean>(target, feed); }
From source file:sapience.injectors.stax.inject.StringBasedStaxStreamInjector.java
/** * If the reference is more then a simple attribute, we have to add new XML (subtree) to the stream. We transform * the reference into an InputStream and invoke another SAX parsing process for it. But the parsed events are added * to the main XMLEventWriter. // w ww . j a va2s .c om * * @param w * @param string * @throws XMLStreamException * @throws XMLStreamException */ private void createEventsForElement(XMLEventWriter w, Reference ref) throws XMLStreamException { XMLEventReader r = null; try { StringBuilder target = new StringBuilder(ref.getTarget().toString()); NamespaceContext c = w.getNamespaceContext(); // process namespaces //processNamespace(target, w.getNamespaceContext()); ByteArrayInputStream bais = new ByteArrayInputStream(target.toString().getBytes()); this.inFac.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); r = this.inFac.createXMLEventReader(bais); // start a new line while (r.hasNext()) { XMLEvent e = r.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_DOCUMENT: break; case XMLEvent.END_DOCUMENT: break; default: w.add(e); break; } } } finally { ; if (r != null) r.close(); } }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
private int countFeedElements(final InputStream is, final String elementName) throws XMLStreamException { final XMLEventReader reader = getEventReader(is); int count = 0; while (reader.hasNext()) { final XMLEvent event = reader.nextEvent(); if (event.getEventType() == XMLStreamConstants.START_ELEMENT && elementName.equals(event.asStartElement().getName().getLocalPart())) { count++;/* ww w .j ava 2 s .com*/ } } reader.close(); return count; }
From source file:edu.unc.lib.dl.services.TripleStoreManagerMulgaraImpl.java
/** * @param query/*from w ww .j a v a 2s. co 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:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
/** * {@inheritDoc }/*from w w w. j a v a 2 s .com*/ */ @Override protected NavigationLinks retrieveNavigationInfo(final String entitySetName, final InputStream is) throws Exception { final NavigationLinks links = new NavigationLinks(); final XMLEventReader reader = getEventReader(is); try { final List<Map.Entry<String, String>> filter = new ArrayList<Map.Entry<String, String>>(); filter.add(new AbstractMap.SimpleEntry<String, String>("type", "application/atom+xml;type=entry")); filter.add(new AbstractMap.SimpleEntry<String, String>("type", "application/atom+xml;type=feed")); int startDepth = 0; while (true) { // a. search for link with type attribute equals to "application/atom+xml;type=entry/feed" final Map.Entry<Integer, XmlElement> linkInfo = getAtomElement(reader, null, LINK, filter, startDepth, 2, 2, true); final XmlElement link = linkInfo.getValue(); startDepth = linkInfo.getKey(); final String title = link.getStart().getAttributeByName(new QName("title")).getValue(); final String href = link.getStart().getAttributeByName(new QName("href")).getValue(); try { final XmlElement inlineElement = getAtomElement(link.getContentReader(), null, INLINE); final XMLEventReader inlineReader = inlineElement.getContentReader(); try { while (true) { final XmlElement entry = getAtomElement(inlineReader, null, "entry"); links.addInlines(title, entry.toStream()); } } catch (Exception e) { // Reached the end of document } inlineReader.close(); } catch (Exception ignore) { // inline element not found (inlines are not mondatory). if (entityUriPattern.matcher(href).matches()) { links.addLinks(title, href.substring(href.lastIndexOf('/') + 1)); } } } } catch (Exception ignore) { // ignore } finally { reader.close(); } return links; }
From source file:com.amazonaws.client.handler.response.StaxResponseHandler.java
/** * @see com.amazonaws.client.handler.response.HttpResponseHandler#handle(com.amazonaws.network.response.HttpResponse) *//*from w w w .j a v a2s . com*/ public AmazonWebServiceResponse<T> handle(HttpResponse response) throws Exception { log.trace("Parsing service response XML"); InputStream content = response.getContent(); if (content == null) content = new ByteArrayInputStream("<eof/>".getBytes()); XMLEventReader eventReader; synchronized (xmlInputFactory) { eventReader = xmlInputFactory.createXMLEventReader(content); } try { AmazonWebServiceResponse<T> awsResponse = new AmazonWebServiceResponse<T>(); StaxUnmarshallerContext unmarshallerContext = new StaxUnmarshallerContext(eventReader, response.getHeaders()); unmarshallerContext.registerMetadataExpression("ResponseMetadata/RequestId", 2, ResponseMetadata.AWS_REQUEST_ID); unmarshallerContext.registerMetadataExpression("requestId", 2, ResponseMetadata.AWS_REQUEST_ID); registerAdditionalMetadataExpressions(unmarshallerContext); T result = responseUnmarshaller.unmarshall(unmarshallerContext); awsResponse.setResult(result); Map<String, String> metadata = unmarshallerContext.getMetadata(); Map<String, String> responseHeaders = response.getHeaders(); if (responseHeaders != null) { if (responseHeaders.get("x-amzn-RequestId") != null) { metadata.put(ResponseMetadata.AWS_REQUEST_ID, responseHeaders.get("x-amzn-RequestId")); } } awsResponse.setResponseMetadata(new ResponseMetadata(metadata)); log.trace("Done parsing service response"); return awsResponse; } finally { try { eventReader.close(); } catch (XMLStreamException e) { log.warn("Error closing xml parser", e); } } }
From source file:com.ksc.http.StaxResponseHandler.java
/** * @see com.ksc.http.HttpResponseHandler#handle(com.ksc.http.HttpResponse) *//* www . j a v a 2 s . co m*/ public KscWebServiceResponse<T> handle(HttpResponse response) throws Exception { log.trace("Parsing service response XML"); InputStream content = response.getContent(); if (content == null) { content = new ByteArrayInputStream("<eof/>".getBytes(StringUtils.UTF8)); } XMLEventReader eventReader; synchronized (xmlInputFactory) { eventReader = xmlInputFactory.createXMLEventReader(content); } try { KscWebServiceResponse<T> kscResponse = new KscWebServiceResponse<T>(); StaxUnmarshallerContext unmarshallerContext = new StaxUnmarshallerContext(eventReader, response.getHeaders()); unmarshallerContext.registerMetadataExpression("ResponseMetadata/RequestId", 2, ResponseMetadata.KSC_REQUEST_ID); unmarshallerContext.registerMetadataExpression("requestId", 2, ResponseMetadata.KSC_REQUEST_ID); registerAdditionalMetadataExpressions(unmarshallerContext); T result = responseUnmarshaller.unmarshall(unmarshallerContext); kscResponse.setResult(result); Map<String, String> metadata = unmarshallerContext.getMetadata(); Map<String, String> responseHeaders = response.getHeaders(); if (responseHeaders != null) { if (responseHeaders.get(X_KSC_REQUEST_ID_HEADER) != null) { metadata.put(ResponseMetadata.KSC_REQUEST_ID, responseHeaders.get(X_KSC_REQUEST_ID_HEADER)); } } kscResponse.setResponseMetadata(new ResponseMetadata(metadata)); log.trace("Done parsing service response"); return kscResponse; } finally { try { eventReader.close(); } catch (XMLStreamException e) { log.warn("Error closing xml parser", e); } } }
From source file:fr.openwide.talendalfresco.rest.client.AlfrescoRestClient.java
public void execute(ClientCommand clientCommand) throws RestClientException { int statusCode = -1; HttpMethodBase method = null;//w w w .j a va 2 s . co m try { // building method (and body entity if any) method = clientCommand.createMethod(); // setting server URL method.setURI(new URI(restCommandUrlPrefix + clientCommand.getName(), false)); method.getParams().setContentCharset(this.restEncoding); // building params (adding ticket) List<NameValuePair> params = clientCommand.getParams(); params.add(new NameValuePair(TICKET_PARAM, ticket)); method.setQueryString(params.toArray(EMPTY_NAME_VALUE_PAIR)); // Execute the method. statusCode = client.executeMethod(method); // checking HTTP status if (statusCode != HttpStatus.SC_OK) { throw new RestClientException("Bad HTTP Status : " + statusCode); } // parsing response XMLEventReader xmlReader = null; try { xmlReader = XmlHelper.createXMLEventReader(method.getResponseBodyAsStream(), this.restEncoding); clientCommand.handleResponse(xmlReader); if (!RestConstants.CODE_OK.equals(clientCommand.getResultCode())) { //String msg = "Business error in command " + clientCommand.toString(); //logger.error(msg, e); throw new RestClientException(clientCommand.getResultMessage(), new RestClientException(clientCommand.getResultError())); } } catch (XMLStreamException e) { String msg = "XML parsing error on response body : "; try { msg += new String(method.getResponseBody()); } catch (IOException ioex) { msg += "[unreadable]"; } ; //logger.error(msg, e); throw new RestClientException(msg, e); } catch (IOException e) { String msg = "IO Error when parsing XML response body : "; //logger.error(msg, e); throw new RestClientException(msg, e); } finally { if (xmlReader != null) { try { xmlReader.close(); } catch (Throwable t) { } } } } catch (RestClientException rcex) { throw rcex; } catch (URIException e) { throw new RestClientException("URI error while executing command " + clientCommand, e); } catch (HttpException e) { throw new RestClientException("HTTP error while executing command " + clientCommand, e); } catch (IOException e) { throw new RestClientException("IO error while executing command " + clientCommand, e); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
/** * {@inheritDoc }//from w ww. j a v a2 s . co m */ @Override protected Set<String> retrieveAllLinkNames(final InputStream is) throws Exception { final Set<String> links = new HashSet<String>(); final XMLEventReader reader = getEventReader(is); try { int startDepth = 0; while (true) { final Map.Entry<Integer, XmlElement> linkInfo = getAtomElement(reader, null, LINK, null, startDepth, 2, 2, true); startDepth = linkInfo.getKey(); links.add(linkInfo.getValue().getStart().getAttributeByName(new QName("title")).getValue()); } } catch (Exception ignore) { // ignore } finally { reader.close(); IOUtils.closeQuietly(is); } return links; }
From source file:com.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java
@Override protected Collection<Throwable> call(String inputName) throws Exception { final CompiledScript compiledScript; Unmarshaller unmarshaller;//from www .j a v a2 s . c om Marshaller marshaller; try { compiledScript = super.compileJavascript(); JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast"); unmarshaller = jc.createUnmarshaller(); marshaller = jc.createMarshaller(); XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory(); xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE); xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); PrintWriter pw = openFileOrStdoutAsPrintWriter(); XMLOutputFactory xof = XMLOutputFactory.newFactory(); xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE); XMLEventWriter w = xof.createXMLEventWriter(pw); StreamSource src = null; if (inputName == null) { LOG.info("Reading stdin"); src = new StreamSource(stdin()); } else { LOG.info("Reading file " + inputName); src = new StreamSource(new File(inputName)); } XMLEventReader r = xmlInputFactory.createXMLEventReader(src); XMLEventFactory eventFactory = XMLEventFactory.newFactory(); SimpleBindings bindings = new SimpleBindings(); while (r.hasNext()) { XMLEvent evt = r.peek(); switch (evt.getEventType()) { case XMLEvent.START_ELEMENT: { StartElement sE = evt.asStartElement(); Hit hit = null; JAXBElement<Hit> jaxbElement = null; if (sE.getName().getLocalPart().equals("Hit")) { jaxbElement = unmarshaller.unmarshal(r, Hit.class); hit = jaxbElement.getValue(); } else { w.add(r.nextEvent()); break; } if (hit != null) { bindings.put("hit", hit); boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings); if (accept) { marshaller.marshal(jaxbElement, w); w.add(eventFactory.createCharacters("\n")); } } break; } case XMLEvent.SPACE: break; default: { w.add(r.nextEvent()); break; } } r.close(); } w.flush(); w.close(); pw.flush(); pw.close(); return RETURN_OK; } catch (Exception err) { return wrapException(err); } finally { } }