List of usage examples for javax.xml.stream XMLStreamConstants CHARACTERS
int CHARACTERS
To view the source code for javax.xml.stream XMLStreamConstants CHARACTERS.
Click Source Link
From source file:ar.com.zauber.commons.spring.test.impl.TamperdataHttpServletRequestFactory.java
/** hace el trabajo sucio * @throws UnsupportedEncodingException */ private HttpServletRequest parse(final XMLStreamReader reader) throws XMLStreamException, UnsupportedEncodingException { final MockHttpServletRequest ret = new MockHttpServletRequest(); ret.setMethod("POST"); String header = null;/*from www. ja v a 2 s .co m*/ String postHeader = null; int event; while ((event = reader.next()) != XMLStreamConstants.END_DOCUMENT) { if (event == XMLStreamConstants.START_ELEMENT) { final String name = reader.getLocalName(); if (name.equals("tdRequestHeader") || name.equals("tdPostHeader")) { header = reader.getAttributeValue(0); } else if (name.equals("tdPostElements")) { ret.setMethod("POST"); } else if (name.equals("tdPostElement")) { postHeader = reader.getAttributeValue(0); } } else if (event == XMLStreamConstants.CHARACTERS) { String text = reader.getText(); if (text.length() > 1 && Character.isWhitespace(text.charAt(0))) { text = text.substring(1); } if (text.length() > 1 && Character.isWhitespace(text.charAt(text.length() - 1))) { text = text.substring(0, text.length() - 1); } final String value = URLDecoder.decode(URLDecoder.decode(text, encoding), encoding); if (header != null) { ret.addHeader(header, value); } else if (postHeader != null) { ret.addParameter(postHeader, value); } header = null; postHeader = null; } else { header = null; postHeader = null; } } reader.close(); return ret; }
From source file:au.org.ala.bhl.DocumentPaginator.java
private void paginateImpl(XMLStreamReader parser, PageHandler handler) throws Exception { if (parser == null) { return;/*from w w w . j a va 2 s .c om*/ } StringBuilder buffer = new StringBuilder(); String currentPage = null; while (true) { int event = parser.next(); if (event == XMLStreamConstants.END_DOCUMENT) { parser.close(); break; } if (event == XMLStreamConstants.START_ELEMENT) { if (parser.getLocalName().equals("PARAM")) { String attrName = parser.getAttributeValue("", "name"); if (attrName.equals("PAGE")) { if (!StringUtils.isEmpty(currentPage)) { if (handler != null) { handler.handlePage(currentPage, buffer.toString()); } } buffer = new StringBuilder(); currentPage = parser.getAttributeValue("", "value"); } } } if (event == XMLStreamConstants.CHARACTERS) { String value = StringUtils.trim(parser.getText()); if (!StringUtils.isEmpty(value)) { buffer.append(value).append(" "); } } } }
From source file:StAXEventTreeViewer.java
public void buildTree(DefaultTreeModel treeModel, DefaultMutableTreeNode current, File file) throws XMLStreamException, FileNotFoundException { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader reader = inputFactory.createXMLEventReader(new FileInputStream(file)); while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); switch (event.getEventType()) { case XMLStreamConstants.START_DOCUMENT: StartDocument startDocument = (StartDocument) event; DefaultMutableTreeNode version = new DefaultMutableTreeNode(startDocument.getVersion()); current.add(version);/*from w ww .ja v a 2 s . c o m*/ current.add(new DefaultMutableTreeNode(startDocument.isStandalone())); current.add(new DefaultMutableTreeNode(startDocument.standaloneSet())); current.add(new DefaultMutableTreeNode(startDocument.encodingSet())); current.add(new DefaultMutableTreeNode(startDocument.getCharacterEncodingScheme())); break; case XMLStreamConstants.START_ELEMENT: StartElement startElement = (StartElement) event; QName elementName = startElement.getName(); DefaultMutableTreeNode element = new DefaultMutableTreeNode(elementName.getLocalPart()); current.add(element); current = element; if (!elementName.getNamespaceURI().equals("")) { String prefix = elementName.getPrefix(); if (prefix.equals("")) { prefix = "[None]"; } DefaultMutableTreeNode namespace = new DefaultMutableTreeNode( "prefix=" + prefix + ",URI=" + elementName.getNamespaceURI()); current.add(namespace); } for (Iterator it = startElement.getAttributes(); it.hasNext();) { Attribute attr = (Attribute) it.next(); DefaultMutableTreeNode attribute = new DefaultMutableTreeNode("Attribute (name=" + attr.getName().getLocalPart() + ",value=" + attr.getValue() + "')"); String attURI = attr.getName().getNamespaceURI(); if (!attURI.equals("")) { String attPrefix = attr.getName().getPrefix(); if (attPrefix.equals("")) { attPrefix = "[None]"; } attribute.add(new DefaultMutableTreeNode("prefix = " + attPrefix + ", URI = " + attURI)); } current.add(attribute); } break; case XMLStreamConstants.END_ELEMENT: current = (DefaultMutableTreeNode) current.getParent(); break; case XMLStreamConstants.CHARACTERS: Characters characters = (Characters) event; if (!characters.isIgnorableWhiteSpace() && !characters.isWhiteSpace()) { String data = characters.getData(); if (data.length() != 0) { current.add(new DefaultMutableTreeNode(characters.getData())); } } break; case XMLStreamConstants.DTD: DTD dtde = (DTD) event; current.add(new DefaultMutableTreeNode(dtde.getDocumentTypeDeclaration())); default: System.out.println(event.getClass().getName()); } } }
From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.java
/** * Reserved for internal use. Parses the operation response as an entity. Parses the result returned in the * specified stream in AtomPub format into a {@link TableResult} containing an entity of the specified class type * projected using the specified resolver. * //w w w . j a va 2 s . c o m * @param xmlr * An <code>XMLStreamReader</code> on the input stream. * @param clazzType * The class type <code>T</code> implementing {@link TableEntity} for the entity returned. Set to * <code>null</code> to ignore the returned entity and copy only response properties into the * {@link TableResult} object. * @param resolver * An {@link EntityResolver} instance to project the entity into an instance of type <code>R</code>. Set * to <code>null</code> to return the entity as an instance of the class type <code>T</code>. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * @return * A {@link TableResult} containing the parsed entity result of the operation. * * @throws XMLStreamException * if an error occurs while accessing the stream. * @throws ParseException * if an error occurs while parsing the stream. * @throws InstantiationException * if an error occurs while constructing the result. * @throws IllegalAccessException * if an error occurs in reflection while parsing the result. * @throws StorageException * if a storage service error occurs. */ protected static <T extends TableEntity, R> TableResult parseEntity(final XMLStreamReader xmlr, final Class<T> clazzType, final EntityResolver<R> resolver, final OperationContext opContext) throws XMLStreamException, ParseException, InstantiationException, IllegalAccessException, StorageException { int eventType = xmlr.getEventType(); final TableResult res = new TableResult(); xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.ENTRY); res.setEtag(StringEscapeUtils.unescapeHtml4( xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.ETAG))); while (xmlr.hasNext()) { eventType = xmlr.next(); if (eventType == XMLStreamConstants.CHARACTERS) { xmlr.getText(); continue; } final String name = xmlr.getName().toString(); if (eventType == XMLStreamConstants.START_ELEMENT) { if (name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.ID)) { res.setId(Utility.readElementFromXMLReader(xmlr, ODataConstants.ID)); } else if (name .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) { // Do read properties if (resolver == null && clazzType == null) { return res; } else { res.setProperties(readProperties(xmlr, opContext)); break; } } } } // Move to end Content eventType = xmlr.next(); if (eventType == XMLStreamConstants.CHARACTERS) { eventType = xmlr.next(); } xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.CONTENT); eventType = xmlr.next(); if (eventType == XMLStreamConstants.CHARACTERS) { eventType = xmlr.next(); } xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.ENTRY); String rowKey = null; String partitionKey = null; Date timestamp = null; // Remove core properties from map and set individually EntityProperty tempProp = res.getProperties().get(TableConstants.PARTITION_KEY); if (tempProp != null) { res.getProperties().remove(TableConstants.PARTITION_KEY); partitionKey = tempProp.getValueAsString(); } tempProp = res.getProperties().get(TableConstants.ROW_KEY); if (tempProp != null) { res.getProperties().remove(TableConstants.ROW_KEY); rowKey = tempProp.getValueAsString(); } tempProp = res.getProperties().get(TableConstants.TIMESTAMP); if (tempProp != null) { res.getProperties().remove(TableConstants.TIMESTAMP); timestamp = tempProp.getValueAsDate(); } if (resolver != null) { // Call resolver res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag())); } else if (clazzType != null) { // Generate new entity and return final T entity = clazzType.newInstance(); entity.setEtag(res.getEtag()); entity.setPartitionKey(partitionKey); entity.setRowKey(rowKey); entity.setTimestamp(timestamp); entity.readEntity(res.getProperties(), opContext); res.setResult(entity); } return res; }
From source file:StAXStreamTreeViewer.java
private void parseRestOfDocument(XMLStreamReader reader, DefaultMutableTreeNode current) throws XMLStreamException { while (reader.hasNext()) { int type = reader.next(); switch (type) { case XMLStreamConstants.START_ELEMENT: DefaultMutableTreeNode element = new DefaultMutableTreeNode(reader.getLocalName()); current.add(element);//from w w w. ja v a 2s. c om current = element; if (reader.getNamespaceURI() != null) { String prefix = reader.getPrefix(); if (prefix == null) { prefix = "[None]"; } DefaultMutableTreeNode namespace = new DefaultMutableTreeNode( "prefix = '" + prefix + "', URI = '" + reader.getNamespaceURI() + "'"); current.add(namespace); } if (reader.getAttributeCount() > 0) { for (int i = 0; i < reader.getAttributeCount(); i++) { DefaultMutableTreeNode attribute = new DefaultMutableTreeNode( "Attribute (name = '" + reader.getAttributeLocalName(i) + "', value = '" + reader.getAttributeValue(i) + "')"); String attURI = reader.getAttributeNamespace(i); if (attURI != null) { String attPrefix = reader.getAttributePrefix(i); if (attPrefix == null || attPrefix.equals("")) { attPrefix = "[None]"; } DefaultMutableTreeNode attNamespace = new DefaultMutableTreeNode( "prefix=" + attPrefix + ",URI=" + attURI); attribute.add(attNamespace); } current.add(attribute); } } break; case XMLStreamConstants.END_ELEMENT: current = (DefaultMutableTreeNode) current.getParent(); break; case XMLStreamConstants.CHARACTERS: if (!reader.isWhiteSpace()) { DefaultMutableTreeNode data = new DefaultMutableTreeNode("CD:" + reader.getText()); current.add(data); } break; case XMLStreamConstants.DTD: DefaultMutableTreeNode dtd = new DefaultMutableTreeNode("DTD:" + reader.getText()); current.add(dtd); break; case XMLStreamConstants.SPACE: break; case XMLStreamConstants.COMMENT: DefaultMutableTreeNode comment = new DefaultMutableTreeNode(reader.getText()); current.add(comment); break; default: System.out.println(type); } } }
From source file:at.lame.hellonzb.parser.NzbParser.java
/** * This is the constructor of the class. * It parses the given XML file./*from w w w. j ava2 s . c o m*/ * * @param mainApp The main application object * @param file The file name of the nzb file to parse * @throws XMLStreamException * @throws IOException */ public NzbParser(HelloNzbCradle mainApp, String file) throws XMLStreamException, IOException, ParseException { this.mainApp = mainApp; DownloadFile currentFile = null; DownloadFileSegment currentSegment = null; boolean groupFlag = false; boolean segmentFlag = false; this.name = file.trim(); this.name = file.substring(0, file.length() - 4); this.downloadFiles = new Vector<DownloadFile>(); this.origTotalSize = 0; this.downloadedBytes = 0; // create XML parser String string = reformatInputStream(file); InputStream in = new ByteArrayInputStream(string.getBytes()); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader parser = factory.createXMLStreamReader(in); // parse nzb file with a Java XML parser while (parser.hasNext()) { switch (parser.getEventType()) { // parser has reached the end of the xml file case XMLStreamConstants.END_DOCUMENT: parser.close(); break; // parser has found a new element case XMLStreamConstants.START_ELEMENT: String elemName = parser.getLocalName().toLowerCase(); if (elemName.equals("file")) { currentFile = newDownloadFile(parser); boolean found = false; for (DownloadFile dlf : downloadFiles) if (dlf.getFilename().equals(currentFile.getFilename())) { found = true; break; } if (!found) downloadFiles.add(currentFile); } else if (elemName.equals("group")) groupFlag = true; else if (elemName.equals("segment")) { currentSegment = newDownloadFileSegment(parser, currentFile); currentFile.addSegment(currentSegment); segmentFlag = true; } break; // end of element case XMLStreamConstants.END_ELEMENT: groupFlag = false; segmentFlag = false; break; // get the elements value(s) case XMLStreamConstants.CHARACTERS: if (!parser.isWhiteSpace()) { if (groupFlag && (currentFile != null)) currentFile.addGroup(parser.getText()); else if (segmentFlag && (currentSegment != null)) currentSegment.setArticleId(parser.getText()); } break; // any other parser event? default: break; } parser.next(); } checkFileSegments(); this.origTotalSize = getCurrTotalSize(); }
From source file:com.wavemaker.runtime.data.parser.BaseHbmParser.java
protected String nextInternal(String parentElementName, int numTries, String... elementNames) { int i = 1;/* ww w . j a va 2s.c om*/ try { for (int event = this.xmlReader.next(); event != XMLStreamConstants.END_DOCUMENT; event = this.xmlReader .next()) { switch (event) { case XMLStreamConstants.START_ELEMENT: this.currentText.delete(0, this.currentText.length()); this.currentElementName = this.xmlReader.getName().toString(); if (numTries > -1) { if (i == numTries) { return this.currentElementName; } else if (i > numTries) { return null; } } i++; if (elementNames != null) { for (String s : elementNames) { if (s.equals(this.currentElementName)) { return this.currentElementName; } } } break; case XMLStreamConstants.END_ELEMENT: String endElementName = this.xmlReader.getName().toString(); if (endElementName.equals(parentElementName)) { return null; } break; case XMLStreamConstants.CHARACTERS: this.currentText.append(this.xmlReader.getText()); break; case XMLStreamConstants.CDATA: break; } } } catch (XMLStreamException ex) { throw new WMRuntimeException(ex); } return null; }
From source file:gdv.xport.util.AbstractFormatterTest.java
/** * We use the XMLStreams to validate the XML. * * @param xmlString XML-String/*ww w . j a va2 s . co m*/ * @throws XMLStreamException * the given XML string is not a valid XML */ protected static void checkXML(final String xmlString) throws XMLStreamException { XMLStreamReader xmlr = xmlInputFactory.createXMLStreamReader(new StringReader(xmlString)); int n = 0; while (xmlr.hasNext()) { int eventType = xmlr.next(); if (eventType == XMLStreamConstants.CHARACTERS) { n += xmlr.getText().length(); } } log.info(n + " bytes text in " + xmlString.length() + " bytes XML"); }
From source file:com.microsoft.tfs.core.memento.XMLMemento.java
/** * Reads the current element from the given reader and returns the * {@link XMLMemento} read from its data. The {@link XMLStreamReader} must * be positioned at {@link XMLStreamConstants#START_ELEMENT}. * * @param reader// w ww . j av a 2s . com * the reader (must not be <code>null</code>) * @return the {@link XMLMemento} read from the stream * @throws XMLStreamException * if an error occurred reading from the reader */ private synchronized void readFromElement(final XMLStreamReader reader) throws XMLStreamException { Check.notNull(reader, "reader"); //$NON-NLS-1$ /* * Read all the attributes from the current element. */ final int attributeCount = reader.getAttributeCount(); for (int i = 0; i < attributeCount; i++) { putString(reader.getAttributeLocalName(i), reader.getAttributeValue(i)); } /* * Process child nodes (which may be text or child Mementos). */ String localName; int event; do { event = reader.next(); if (event == XMLStreamConstants.START_ELEMENT) { localName = reader.getLocalName(); final XMLMemento child = (XMLMemento) createChild(localName); child.readFromElement(reader); } else if (event == XMLStreamConstants.CHARACTERS) { putTextData(reader.getText()); } } while (event != XMLStreamConstants.END_ELEMENT); }
From source file:com.evolveum.polygon.connector.hcm.DocumentProcessing.java
public Map<String, Object> parseXMLData(HcmConnectorConfiguration conf, ResultsHandler handler, Map<String, Object> schemaAttributeMap, Filter query) { XMLInputFactory factory = XMLInputFactory.newInstance(); try {// w ww.j a va2 s . co m String uidAttributeName = conf.getUidAttribute(); String primariId = conf.getPrimaryId(); String startName = ""; String value = null; StringBuilder assignmentXMLBuilder = null; List<String> builderList = new ArrayList<String>(); Integer nOfIterations = 0; Boolean isSubjectToQuery = false; Boolean isAssigment = false; Boolean evaluateAttr = true; Boolean specificAttributeQuery = false; XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(conf.getFilePath())); List<String> dictionary = populateDictionary(FIRSTFLAG); if (!attrsToGet.isEmpty()) { attrsToGet.add(uidAttributeName); attrsToGet.add(primariId); specificAttributeQuery = true; evaluateAttr = false; LOGGER.ok("The uid and primary id were added to the queried attribute list"); schemaAttributeMap = modifySchemaAttributeMap(schemaAttributeMap); } while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); Integer code = event.getEventType(); if (code == XMLStreamConstants.START_ELEMENT) { StartElement startElement = event.asStartElement(); startName = startElement.getName().getLocalPart(); if (!evaluateAttr && attrsToGet.contains(startName)) { evaluateAttr = true; } if (!elementIsEmployeeData) { if (startName.equals(EMPLOYEES)) { if (dictionary.contains(nOfIterations.toString())) { LOGGER.ok("The defined number of iterations has been hit: {0}", nOfIterations.toString()); break; } else { startName = ""; elementIsEmployeeData = true; nOfIterations++; } } } else if (evaluateAttr) { if (!isAssigment) { if (!ASSIGNMENTTAG.equals(startName)) { } else { assignmentXMLBuilder = new StringBuilder(); isAssigment = true; } } else { builderList = processAssignment(startName, null, START, builderList); } if (multiValuedAttributesList.contains(startName)) { elementIsMultiValued = true; } } } else if (elementIsEmployeeData) { if (code == XMLStreamConstants.CHARACTERS && evaluateAttr) { Characters characters = event.asCharacters(); if (!characters.isWhiteSpace()) { StringBuilder valueBuilder; if (value != null) { valueBuilder = new StringBuilder(value).append("") .append(characters.getData().toString()); } else { valueBuilder = new StringBuilder(characters.getData().toString()); } value = valueBuilder.toString(); // value = StringEscapeUtils.escapeXml10(value); // LOGGER.info("The attribute value for: {0} is // {1}", startName, value); } } else if (code == XMLStreamConstants.END_ELEMENT) { EndElement endElement = event.asEndElement(); String endName = endElement.getName().getLocalPart(); isSubjectToQuery = checkFilter(endName, value, query, uidAttributeName); if (!isSubjectToQuery) { attributeMap.clear(); elementIsEmployeeData = false; value = null; endName = EMPLOYEES; } if (endName.equals(EMPLOYEES)) { attributeMap = handleEmployeeData(attributeMap, schemaAttributeMap, handler, uidAttributeName, primariId); elementIsEmployeeData = false; } else if (evaluateAttr) { if (endName.equals(startName)) { if (value != null) { if (!isAssigment) { if (!elementIsMultiValued) { attributeMap.put(startName, value); } else { multiValuedAttributeBuffer.put(startName, value); } } else { value = StringEscapeUtils.escapeXml10(value); builderList = processAssignment(endName, value, VALUE, builderList); builderList = processAssignment(endName, null, END, builderList); } // LOGGER.info("Attribute name: {0} and the // Attribute value: {1}", endName, value); value = null; } } else { if (endName.equals(ASSIGNMENTTAG)) { builderList = processAssignment(endName, null, CLOSE, builderList); // if (assigmentIsActive) { for (String records : builderList) { assignmentXMLBuilder.append(records); } attributeMap.put(ASSIGNMENTTAG, assignmentXMLBuilder.toString()); // } else { // } builderList = new ArrayList<String>(); // assigmentIsActive = false; isAssigment = false; } else if (multiValuedAttributesList.contains(endName)) { processMultiValuedAttributes(multiValuedAttributeBuffer); } } } if (specificAttributeQuery && evaluateAttr) { evaluateAttr = false; } } } else if (code == XMLStreamConstants.END_DOCUMENT) { handleBufferedData(uidAttributeName, primariId, handler); } } } catch (FileNotFoundException e) { StringBuilder errorBuilder = new StringBuilder("File not found at the specified path.") .append(e.getLocalizedMessage()); LOGGER.error("File not found at the specified path: {0}", e); throw new ConnectorIOException(errorBuilder.toString()); } catch (XMLStreamException e) { LOGGER.error("Unexpected processing error while parsing the .xml document : {0}", e); StringBuilder errorBuilder = new StringBuilder( "Unexpected processing error while parsing the .xml document. ") .append(e.getLocalizedMessage()); throw new ConnectorIOException(errorBuilder.toString()); } return attributeMap; }