List of usage examples for javax.xml.stream.events Attribute getValue
public String getValue();
From source file:org.sakaiproject.nakamura.docproxy.url.UrlRepositoryProcessor.java
/** * Parse the attributes of an XML 'document' element into a {@link UrlDocumentResult}. * // w w w .j a va 2 s .c o m * @param startEl * The 'document' element to process. * @param doc * The document to set attributes into. If null, a new * {@link UrlDocumentResult} is created. * @return A {@link UrlDocumentResult} containing values found in {@link startEl}. This * will be the provided doc, if it is not null, or a newly created one. * @throws XMLStreamException * If there is a problem processing the element. */ private UrlDocumentResult parseDocument(StartElement startEl, UrlDocumentResult doc) throws XMLStreamException { UrlDocumentResult _doc = null; if (doc != null) { _doc = doc; } else { _doc = new UrlDocumentResult(); } @SuppressWarnings("unchecked") Iterator<Attribute> attrs = startEl.getAttributes(); while (attrs.hasNext()) { Attribute attr = attrs.next(); QName attrName = attr.getName(); String attrLocalName = attrName.getLocalPart(); // collect the uri if ("uri".equalsIgnoreCase(attrLocalName)) { _doc.setUri(attr.getValue()); continue; } // collect the content length if ("contentLength".equalsIgnoreCase(attrLocalName)) { _doc.setContentLength(Long.parseLong(attr.getValue())); continue; } // collect the content length if ("contentType".equalsIgnoreCase(attrLocalName)) { _doc.setContentType(attr.getValue()); continue; } } return _doc; }
From source file:org.sakaiproject.nakamura.proxy.RSSProxyPostProcessor.java
public void process(Map<String, Object> templateParams, SlingHttpServletResponse response, ProxyResponse proxyResponse) throws IOException { if (proxyResponse.getResultCode() == HttpServletResponse.SC_PRECONDITION_FAILED) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This RSS feed is too big "); return;/*from www. j av a 2s. co m*/ } Map<String, String[]> headers = proxyResponse.getResponseHeaders(); // Check if the content-length is smaller than the maximum (if any). String[] contentLengthHeader = headers.get("Content-Length"); if (contentLengthHeader != null) { int length = Integer.parseInt(contentLengthHeader[0]); if (length > maxLength) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This RSS feed is too big. The maximum for a feed is: " + maxLength); return; } } // Check if the Content-Type we get is valid (if any). String[] contentTypeHeader = headers.get("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader[0]; if (contentType.contains(";")) { contentType = contentType.substring(0, contentType.indexOf(';')); } if (!contentTypes.contains(contentType)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This URL doesn't send a proper Content-Type back"); return; } } boolean isValid = false; InputStream in = proxyResponse.getResponseBodyAsInputStream(); InputStreamReader reader = new InputStreamReader(in); // XMLStreamWriter writer = null; XMLEventWriter writer = null; ByteArrayOutputStream out = null; int i = 0; try { XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(reader); // Create a temporary outputstream where we can write to. out = new ByteArrayOutputStream(); Set<String> checkedElements = null; XMLOutputFactory outputFactory = new WstxOutputFactory(); writer = outputFactory.createXMLEventWriter(out); while (eventReader.hasNext()) { XMLEvent e = eventReader.nextEvent(); // Stream it to an output stream. writer.add(e); if (!isValid) { if (e.getEventType() == XMLEvent.START_ELEMENT) { StartElement el = e.asStartElement(); String name = el.getName().getLocalPart().toLowerCase(); if (checkedElements == null) { // get the right format to validate against String formatKey = name; Attribute attr = el.getAttributeByName(new QName("version")); if (attr != null) { formatKey += "-" + attr.getValue(); } Set<String> format = formats.get(formatKey); if (format != null) { checkedElements = new HashSet<String>(format); } } else { checkedElements.remove(name); if (checkedElements.isEmpty()) { isValid = true; } } } if (i > eventsThreshold) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This file is too complex."); return; } i++; } } if (!isValid) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid RSS file."); return; } // Check if we are not streaming a gigantic file.. if (out.size() > maxLength) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This file is too big."); return; } for (Entry<String, String[]> h : proxyResponse.getResponseHeaders().entrySet()) { for (String v : h.getValue()) { response.setHeader(h.getKey(), v); } } // We always return 200 when we get to this point. response.setStatus(200); response.setHeader("Content-Length", Integer.toString(out.size())); // Write the cached stream to the output. out.writeTo(response.getOutputStream()); } catch (XMLStreamException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This is not a valid XML file."); } catch (Exception e) { logger.warn("Exception reading RSS feed.", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "General exception caught."); } finally { if (out != null) { out.close(); } reader.close(); try { if (writer != null) writer.close(); } catch (XMLStreamException e) { // Not much we can do? e.printStackTrace(); } } }
From source file:org.slc.sli.ingestion.parser.impl.EdfiRecordParserImpl.java
@SuppressWarnings("unchecked") private void parseEventAttributes(StartElement startElement) { Iterator<Attribute> it = startElement.getAttributes(); while (it.hasNext()) { Attribute a = it.next(); complexTypeStack.peek().getRight().put("@" + a.getName().getLocalPart(), a.getValue()); }/*from w w w .j a v a 2 s . c om*/ }
From source file:org.talend.dataprep.schema.xls.streaming.StreamingSheetReader.java
/** * Handles a Stream event.//from w w w .j av a 2 s . c o m * * @param event * @throws SAXException */ private void handleEvent(XMLEvent event) throws SAXException { if (event.getEventType() == XMLStreamConstants.CHARACTERS) { Characters c = event.asCharacters(); lastContents += c.getData(); } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT) { StartElement startElement = event.asStartElement(); String tagLocalName = startElement.getName().getLocalPart(); if ("row".equals(tagLocalName)) { Attribute rowIndex = startElement.getAttributeByName(new QName("r")); if (firstRowIndex == -1) { firstRowIndex = Integer.parseInt(rowIndex.getValue()); } currentRow = new StreamingRow(Integer.parseInt(rowIndex.getValue()) - 1); } else if ("cols".equals(tagLocalName)) { parsingCols = true; } else if ("col".equals(tagLocalName) && parsingCols) { colNumber = colNumber + 1; } else if ("c".equals(tagLocalName)) { Attribute ref = startElement.getAttributeByName(new QName("r")); String[] coord = ref.getValue().split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); currentCell = new StreamingCell(CellReference.convertColStringToIndex(coord[0]), Integer.parseInt(coord[1]) - 1); setFormatString(startElement, currentCell); Attribute type = startElement.getAttributeByName(new QName("t")); if (type != null) { currentCell.setType(type.getValue()); } else { currentCell.setType("n"); } Attribute style = startElement.getAttributeByName(new QName("s")); if (style != null) { String indexStr = style.getValue(); try { int index = Integer.parseInt(indexStr); currentCell.setCellStyle(stylesTable.getStyleAt(index)); } catch (NumberFormatException nfe) { LOGGER.warn("Ignoring invalid style index {}", indexStr); } } // we store the dimension as well to revert with this method when cols not found // can happen see xlsx attached here https://jira.talendforge.org/browse/TDP-1957 // <dimension ref="A1:B60"/> } else if ("dimension".equals(tagLocalName)) { Attribute attribute = startElement.getAttributeByName(new QName("ref")); if (attribute != null) { this.dimension = attribute.getValue(); } } // Clear contents cache lastContents = ""; } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) { EndElement endElement = event.asEndElement(); String tagLocalName = endElement.getName().getLocalPart(); if ("v".equals(tagLocalName) || "t".equals(tagLocalName)) { currentCell.setRawContents(unformattedContents()); currentCell.setContents(formattedContents()); } else if ("row".equals(tagLocalName) && currentRow != null) { rowCache.add(currentRow); } else if ("c".equals(tagLocalName)) { currentRow.getCellMap().put(currentCell.getColumnIndex(), currentCell); } else if ("cols".equals(tagLocalName)) { parsingCols = false; } } }
From source file:org.talend.dataprep.schema.xls.streaming.StreamingSheetReader.java
/** * Read the numeric format string out of the styles table for this cell. Stores the result in the Cell. * * @param startElement//from w ww . j a va2s. co m * @param cell */ void setFormatString(StartElement startElement, StreamingCell cell) { Attribute cellStyle = startElement.getAttributeByName(new QName("s")); String cellStyleString = (cellStyle != null) ? cellStyle.getValue() : null; XSSFCellStyle style = null; if (cellStyleString != null) { style = stylesTable.getStyleAt(Integer.parseInt(cellStyleString)); } else if (stylesTable.getNumCellStyles() > 0) { style = stylesTable.getStyleAt(0); } if (style != null) { cell.setNumericFormatIndex(style.getDataFormat()); String formatString = style.getDataFormatString(); if (formatString != null) { cell.setNumericFormat(formatString); } else { cell.setNumericFormat(BuiltinFormats.getBuiltinFormat(cell.getNumericFormatIndex())); } } else { cell.setNumericFormatIndex(null); cell.setNumericFormat(null); } }
From source file:org.xmlsh.commands.internal.xml2json.java
private boolean writeFile(StartElement start, XMLEventReader reader, PrintWriter writer) throws UnsupportedEncodingException, IOException, XMLStreamException, CoreException, TransformException, SaxonApiException {/*from www . j ava 2s .co m*/ Attribute aname = start.getAttributeByName(kATTR_NAME); if (aname == null) throw new InvalidArgumentException("Element FILE requries attribute name"); String name = aname.getValue(); //Attribute aencoding = start.getAttributeByName(new QName("encoding")); //String encoding = (aencoding == null ? "UTF-8" : aencoding.getValue()); PrintWriter w = getShell().getEnv().getOutput(getShell().getFile(name), false) .asPrintWriter(mSerializeOpts); boolean ret = parse(reader, w, false); w.close(); return ret; }
From source file:org.xmlsh.commands.internal.xml2json.java
private String getAttr(StartElement start, QName attr) { Attribute a = start.getAttributeByName(attr); if (a == null) return null; return a.getValue(); }
From source file:org.xmlsh.commands.internal.xml2json.java
private void writeNumber(StartElement start, XMLEventReader reader, PrintWriter writer) throws XMLStreamException { String chars;/*from w ww . j a v a 2 s . c o m*/ Attribute v = start.getAttributeByName(kATTR_VALUE); if (v != null) chars = v.getValue(); else chars = readChars(reader); chars = chars.trim(); writer.print(chars); readToEnd(reader); }
From source file:org.zuinnote.hadoop.office.format.common.parser.msexcel.internal.XSSFPullParser.java
public boolean hasNext() throws XMLStreamException { this.nextBeingCalled = true; if (this.finalized) { // we finished already - no more to read return false; }/*from www. j a v a 2s .co m*/ if ((this.currentRow > 1) && (this.currentRow <= this.nextRow)) { // we still have to process an empty row return true; } // search for the next row while (this.xer.hasNext()) { XMLEvent xe = xer.nextEvent(); if (xe.isStartElement() && xe.asStartElement().getName().getLocalPart().equalsIgnoreCase("row")) { // we // found // a row // get row number. Attribute at = xe.asStartElement().getAttributeByName(new QName("r")); String atValue = at.getValue(); this.nextRow = Integer.valueOf(atValue); return true; } } this.finalized = true; return false; }
From source file:org.zuinnote.hadoop.office.format.common.parser.msexcel.internal.XSSFPullParser.java
public Object[] getNext() throws XMLStreamException, FormatNotUnderstoodException { Object[] result = null;//from www . java2 s. c om if (!this.nextBeingCalled) { // skip to the next tag if (this.hasNext() == false) { return null; } } if (this.finalized) { // no more to read return null; } // check ArrayList<SpreadSheetCellDAO> cells = new ArrayList<>(); if (this.currentRow == this.nextRow) { // only if we have a row to report // read through row, cf. // http://download.microsoft.com/download/3/E/3/3E3435BD-AA68-4B32-B84D-B633F0D0F90D/SpreadsheetMLBasics.ppt int currentCellCount = 0; while (this.xer.hasNext()) { XMLEvent xe = xer.nextEvent(); // read+ if (xe.isEndElement()) { if (xe.asEndElement().getName().getLocalPart().equalsIgnoreCase("row")) { break; // end of row } } else if (xe.isStartElement()) { if (xe.asStartElement().getName().getLocalPart().equalsIgnoreCase("c")) { Attribute cellAddressAT = xe.asStartElement().getAttributeByName(new QName("r")); // check if cell is a subsequent cell and add null, if needed CellAddress currentCellAddress = new CellAddress(cellAddressAT.getValue()); for (int i = currentCellCount; i < currentCellAddress.getColumn(); i++) { cells.add(null); currentCellCount++; } currentCellCount++; // current cell Attribute cellTypeTAT = xe.asStartElement().getAttributeByName(new QName("t")); Attribute cellTypeSAT = xe.asStartElement().getAttributeByName(new QName("s")); String cellFormattedValue = ""; String cellFormula = ""; String cellAddress = cellAddressAT.getValue(); String cellComment = ""; String cellSheetName = this.sheetName; while ((!xe.isEndElement()) || !((xe.isEndElement()) && (xe.asEndElement().getName().getLocalPart().equalsIgnoreCase("c")))) { xe = xer.nextEvent(); if ((xe.isStartElement()) && (xe.asStartElement().getName().getLocalPart().equalsIgnoreCase("v"))) { // if a cell data type is set (e.g. b boolean (covered?), d date in ISO8601 format, e // error, inlineStr (covered), n number (covered), s shared string (covered), str formula string (covered) // we return as string if (cellTypeTAT != null) { XMLEvent xeSubCharacters = xer.nextEvent(); if (!xeSubCharacters.isCharacters()) { LOG.error( "Error parsing excel file. Value attribute (v) of cell does not contains characters"); } else { cellFormattedValue = xeSubCharacters.asCharacters().getData(); if (XSSFPullParser.CELLTYPE_STRING.equals(cellTypeTAT.getValue())) { // need to // read // from // Shared // String // Table int strIdx = Integer.valueOf(cellFormattedValue); if ((this.sst != null) && (this.sst.getCount() > strIdx)) { cellFormattedValue = this.sst.getItemAt(strIdx).getString(); } else { cellFormattedValue = ""; } } else if (XSSFPullParser.CELLTYPE_NUMBER.equals(cellTypeTAT.getValue())) { // need to read number and format it (e.g. if it is a date etc.) according // to style int strStyleIdx = Integer.valueOf(cellTypeSAT.getValue()); XSSFCellStyle cellStyle = this.styles.getStyleAt(strStyleIdx); cellFormattedValue = this.dataFormatter.formatRawCellContents( Double.valueOf(cellFormattedValue), cellStyle.getDataFormat(), cellStyle.getDataFormatString(), this.isDate1904); } } } else { LOG.error("Cannot read celltype"); } } else if ((xe.isStartElement()) && (xe.asStartElement().getName().getLocalPart().equalsIgnoreCase("f"))) { // read formula XMLEvent xeSubCharacters = xer.nextEvent(); if (!xeSubCharacters.isCharacters()) { LOG.error( "Error parsing excel file. Formula attribute (f) of cell does not contains characters"); } else { cellFormula = xeSubCharacters.asCharacters().getData(); } } else if ((xe.isStartElement()) && (xe.asStartElement().getName().getLocalPart().equalsIgnoreCase("is"))) { // read inline string cellFormattedValue = this.parseCellInlineStringText(xer); } } cells.add(new SpreadSheetCellDAO(cellFormattedValue, cellComment, cellFormula, cellAddress, cellSheetName)); } } // else ignore (e.g. col) } } // convert to array result = new SpreadSheetCellDAO[cells.size()]; result = cells.toArray(result); // read all cells in row and create SpreadSheetCellDAOs this.nextBeingCalled = false; this.currentRow++; return result; }