List of usage examples for org.xml.sax.helpers AttributesImpl addAttribute
public void addAttribute(String uri, String localName, String qName, String type, String value)
From source file:org.dhatim.csv.CSVReader.java
public void parse(InputSource csvInputSource) throws IOException, SAXException { if (contentHandler == null) { throw new IllegalStateException("'contentHandler' not set. Cannot parse CSV stream."); }//from w w w . j a v a2s. com if (execContext == null) { throw new IllegalStateException("'execContext' not set. Cannot parse CSV stream."); } try { Reader csvStreamReader; au.com.bytecode.opencsv.CSVReader csvLineReader; String[] csvRecord; // Get a reader for the CSV source... csvStreamReader = csvInputSource.getCharacterStream(); if (csvStreamReader == null) { csvStreamReader = new InputStreamReader(csvInputSource.getByteStream(), encoding); } // Create the CSV line reader... csvLineReader = new au.com.bytecode.opencsv.CSVReader(csvStreamReader, separator, quoteChar, escapeChar, skipLines); if (validateHeader) { validateHeader(csvLineReader); } // Start the document and add the root "csv-set" element... contentHandler.startDocument(); contentHandler.startElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY, EMPTY_ATTRIBS); // Output each of the CVS line entries... int lineNumber = 0; int expectedCount = getExpectedColumnsCount(); while ((csvRecord = csvLineReader.readNext()) != null) { lineNumber++; // First line is line "1" if (csvRecord.length < expectedCount && strict) { logger.debug("[CORRUPT-CSV] CSV line #" + lineNumber + " invalid [" + Arrays.asList(csvRecord) + "]. The line should contain number of items at least as in CSV config file " + csvFields.length + " fields [" + csvFields + "], but contains " + csvRecord.length + " fields. Ignoring!!"); continue; } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENT_1, 0, 1); } AttributesImpl attrs = new AttributesImpl(); // If we reached here it means that this line has to be in the sax stream // hence we first add the record number attribute on the csv-record element attrs.addAttribute(XMLConstants.NULL_NS_URI, RECORD_NUMBER_ATTR, RECORD_NUMBER_ATTR, "xs:int", Integer.toString(lineNumber)); // if this line is truncated, we add the truncated attribute onto the csv-record element if (csvRecord.length < expectedCount) attrs.addAttribute(XMLConstants.NULL_NS_URI, RECORD_TRUNCATED_ATTR, RECORD_TRUNCATED_ATTR, "xs:boolean", Boolean.TRUE.toString()); contentHandler.startElement(XMLConstants.NULL_NS_URI, recordElementName, StringUtils.EMPTY, attrs); int recordIt = 0; for (Field field : fields) { String fieldName = field.getName(); if (field.ignore()) { int toSkip = parseIgnoreFieldDirective(fieldName); if (toSkip == Integer.MAX_VALUE) { break; } recordIt += toSkip; continue; } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENT_2, 0, 2); } // Don't insert the element if the csv record does not contain it!! if (recordIt < csvRecord.length) { String value = csvRecord[recordIt]; contentHandler.startElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY, EMPTY_ATTRIBS); StringFunctionExecutor stringFunctionExecutor = field.getStringFunctionExecutor(); if (stringFunctionExecutor != null) { value = stringFunctionExecutor.execute(value); } contentHandler.characters(value.toCharArray(), 0, value.length()); contentHandler.endElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY); } if (indent) { } recordIt++; } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENT_1, 0, 1); } contentHandler.endElement(null, recordElementName, StringUtils.EMPTY); } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); } // Close out the "csv-set" root element and end the document.. contentHandler.endElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY); contentHandler.endDocument(); } finally { // These properties need to be reset for every execution (e.g. when reader is pooled). contentHandler = null; execContext = null; } }
From source file:org.dhatim.fixedlength.FixedLengthReader.java
public void parse(InputSource flInputSource) throws IOException, SAXException { if (contentHandler == null) { throw new IllegalStateException("'contentHandler' not set. Cannot parse Fixed Length stream."); }// ww w. j a v a 2 s . c o m if (execContext == null) { throw new IllegalStateException("'execContext' not set. Cannot parse Fixed Length stream."); } try { Reader flStreamReader; BufferedReader flLineReader; String flRecord; int lineNumber = 0; // Get a reader for the Fixed Length source... flStreamReader = flInputSource.getCharacterStream(); if (flStreamReader == null) { flStreamReader = new InputStreamReader(flInputSource.getByteStream(), encoding); } // Create the Fixed Length line reader... flLineReader = new BufferedReader(flStreamReader); // Start the document and add the root element... contentHandler.startDocument(); contentHandler.startElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY, EMPTY_ATTRIBS); // Output each of the Fixed Length line entries... while ((flRecord = flLineReader.readLine()) != null) { lineNumber++; // First line is line "1" if (lineNumber <= this.skipLines) { continue; } boolean invalidLength = flRecord.length() < totalFieldLenght; if (invalidLength && strict) { if (logger.isWarnEnabled()) { logger.debug("[WARNING-FIXEDLENGTH] Fixed Length line #" + lineNumber + " is invalid. The line doesn't contain enough characters to fill all the fields. This line is skipped."); } continue; } char[] recordChars = flRecord.toCharArray(); if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENT_1, 0, 1); } AttributesImpl attrs = EMPTY_ATTRIBS; // Add a lineNumber ID if (this.lineNumber || invalidLength) { attrs = new AttributesImpl(); if (this.lineNumber) { attrs.addAttribute(XMLConstants.NULL_NS_URI, lineNumberAttributeName, lineNumberAttributeName, "xs:int", Integer.toString(lineNumber)); } if (invalidLength) { attrs.addAttribute(XMLConstants.NULL_NS_URI, truncatedAttributeName, truncatedAttributeName, "xs:boolean", Boolean.TRUE.toString()); } } contentHandler.startElement(XMLConstants.NULL_NS_URI, recordElementName, StringUtils.EMPTY, attrs); // Loops through fields int fieldLengthTotal = 0; for (int i = 0; i < flFields.length; i++) { // Field name local to the loop String fieldName = fields[i].getName(); // Field length local to the loop int fieldLength = fields[i].getLength(); StringFunctionExecutor stringFunctionExecutor = fields[i].getStringFunctionExecutor(); if (!fields[i].ignore()) { if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENT_2, 0, 2); } // Check that there are enough characters in the string boolean truncated = fieldLengthTotal + fieldLength > flRecord.length(); AttributesImpl recordAttrs = EMPTY_ATTRIBS; //If truncated then set the truncated attribute if (truncated) { recordAttrs = new AttributesImpl(); recordAttrs.addAttribute(XMLConstants.NULL_NS_URI, truncatedAttributeName, truncatedAttributeName, "xs:boolean", Boolean.TRUE.toString()); } contentHandler.startElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY, recordAttrs); // If not truncated then set the element data if (!truncated) { if (stringFunctionExecutor == null) { contentHandler.characters(recordChars, fieldLengthTotal, fieldLength); } else { String value = flRecord.substring(fieldLengthTotal, fieldLengthTotal + fieldLength); value = stringFunctionExecutor.execute(value); contentHandler.characters(value.toCharArray(), 0, value.length()); } } contentHandler.endElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY); } fieldLengthTotal += fieldLength; } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENT_1, 0, 1); } contentHandler.endElement(null, recordElementName, StringUtils.EMPTY); } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); } // Close out the "fixedlength-set" root element and end the document.. contentHandler.endElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY); contentHandler.endDocument(); } finally { // These properties need to be reset for every execution (e.g. when reader is pooled). contentHandler = null; execContext = null; } }
From source file:org.dhatim.flatfile.FlatFileReader.java
public void parse(InputSource inputSource) throws IOException, SAXException { if (contentHandler == null) { throw new IllegalStateException("'contentHandler' not set. Cannot parse Record stream."); }//from w w w . j a va2 s .co m if (execContext == null) { throw new IllegalStateException("'execContext' not set. Cannot parse Record stream."); } try { Reader recordReader; // Create the record parser.... RecordParser recordParser = parserFactory.newRecordParser(); recordParser.setRecordParserFactory(parserFactory); recordParser.setDataSource(inputSource); try { recordParser.initialize(); // Start the document and add the root "record-set" element... contentHandler.startDocument(); contentHandler.startElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY, EMPTY_ATTRIBS); // Output each of the CVS line entries... int lineNumber = 0; Record record = recordParser.nextRecord(); while (record != null) { lineNumber++; // First line is line "1" if (record != null) { List<Field> recordFields = record.getFields(); if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENTCHARS, 0, 1); } AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute(XMLConstants.NULL_NS_URI, RECORD_NUMBER_ATTR, RECORD_NUMBER_ATTR, "xs:int", Integer.toString(lineNumber)); RecordMetaData recordMetaData = record.getRecordMetaData(); if (recordFields.size() < recordMetaData.getUnignoredFieldCount()) { attrs.addAttribute(XMLConstants.NULL_NS_URI, RECORD_TRUNCATED_ATTR, RECORD_TRUNCATED_ATTR, "xs:boolean", Boolean.TRUE.toString()); } contentHandler.startElement(XMLConstants.NULL_NS_URI, record.getName(), StringUtils.EMPTY, attrs); for (Field recordField : recordFields) { String fieldName = recordField.getName(); if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENTCHARS, 0, 2); } contentHandler.startElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY, EMPTY_ATTRIBS); String value = recordField.getValue(); contentHandler.characters(value.toCharArray(), 0, value.length()); contentHandler.endElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY); } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENTCHARS, 0, 1); } contentHandler.endElement(XMLConstants.NULL_NS_URI, record.getName(), StringUtils.EMPTY); } record = recordParser.nextRecord(); } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); } // Close out the "csv-set" root element and end the document.. contentHandler.endElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY); contentHandler.endDocument(); } finally { recordParser.uninitialize(); } } finally { // These properties need to be reset for every execution (e.g. when reader is pooled). contentHandler = null; execContext = null; } }
From source file:org.dhatim.yaml.handler.YamlToSaxHandler.java
private void startElement(String name, String anchorName, boolean addAnchorAttribute) throws SAXException { AttributesImpl attributes; if (anchorName == null) { attributes = EMPTY_ATTRIBS;//from w w w . j a v a 2 s . co m } else { attributes = new AttributesImpl(); String attributeName = addAnchorAttribute ? anchorAttributeName : aliasAttributeName; String attributeType = addAnchorAttribute ? ATTRIBUTE_ID : ATTRIBUTE_IDREF; if (addAnchorAttribute) { } attributes.addAttribute(XMLConstants.NULL_NS_URI, attributeName, attributeName, attributeType, anchorName); } contentHandler.startElement(XMLConstants.NULL_NS_URI, name, StringUtils.EMPTY, attributes); }
From source file:org.dita.dost.util.XMLUtils.java
/** * Add or set attribute./* ww w . j av a 2 s . c o m*/ * * @param atts attributes * @param uri namespace URI * @param localName local name * @param qName qualified name * @param type attribute type * @param value attribute value */ public static void addOrSetAttribute(final AttributesImpl atts, final String uri, final String localName, final String qName, final String type, final String value) { final int i = atts.getIndex(qName); if (i != -1) { atts.setAttribute(i, uri, localName, qName, type, value); } else { atts.addAttribute(uri, localName, qName, type, value); } }
From source file:org.enhydra.shark.asap.util.BeanSerializerShark.java
private void setAttributeProperty(Object propValue, QName qname, QName xmlType, AttributesImpl attrs, SerializationContext context) throws Exception { String namespace = qname.getNamespaceURI(); String localName = qname.getLocalPart(); // org.xml.sax.helpers.AttributesImpl JavaDoc says: "For the // sake of speed, this method does no checking to see if the // attribute is already in the list: that is the // responsibility of the application." check for the existence // of the attribute to avoid adding it more than once. if (attrs.getIndex(namespace, localName) != -1) { return;/*from w w w . java2 s . co m*/ } String propString = context.getValueAsString(propValue, xmlType); attrs.addAttribute(namespace, localName, context.attributeQName2String(qname), "CDATA", propString); }
From source file:org.exist.cocoon.XMLDBSource.java
private void collectionToSAX(ContentHandler handler) throws SAXException, XMLDBException { AttributesImpl attributes = new AttributesImpl(); if (query != null) { // Query collection if (getLogger().isDebugEnabled()) { getLogger().debug("Querying collection " + url + "; query= " + this.query); }//from w w w . ja va 2 s . c o m queryToSAX(handler, collection, null); } else { // List collection if (getLogger().isDebugEnabled()) { getLogger().debug("Listing collection " + url); } final String nresources = Integer.toString(collection.getResourceCount()); attributes.addAttribute("", RESOURCE_COUNT_ATTR, RESOURCE_COUNT_ATTR, "CDATA", nresources); final String ncollections = Integer.toString(collection.getChildCollectionCount()); attributes.addAttribute("", COLLECTION_COUNT_ATTR, COLLECTION_COUNT_ATTR, "CDATA", ncollections); attributes.addAttribute("", COLLECTION_BASE_ATTR, COLLECTION_BASE_ATTR, "CDATA", url); handler.startDocument(); handler.startPrefixMapping(PREFIX, URI); handler.startElement(URI, COLLECTIONS, QCOLLECTIONS, attributes); // Print child collections String[] collections = collection.listChildCollections(); for (int i = 0; i < collections.length; i++) { attributes.clear(); attributes.addAttribute("", NAME_ATTR, NAME_ATTR, CDATA, collections[i]); handler.startElement(URI, COLLECTION, QCOLLECTION, attributes); handler.endElement(URI, COLLECTION, QCOLLECTION); } // Print child resources String[] resources = collection.listResources(); for (int i = 0; i < resources.length; i++) { attributes.clear(); attributes.addAttribute("", NAME_ATTR, NAME_ATTR, CDATA, resources[i]); handler.startElement(URI, RESOURCE, QRESOURCE, attributes); handler.endElement(URI, RESOURCE, QRESOURCE); } handler.endElement(URI, COLLECTIONS, QCOLLECTIONS); handler.endPrefixMapping(PREFIX); handler.endDocument(); } }
From source file:org.exist.cocoon.XMLDBSource.java
private void queryToSAX(ContentHandler handler, Collection collection, String resource) throws SAXException, XMLDBException { AttributesImpl attributes = new AttributesImpl(); XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); ResourceSet resultSet = (resource == null) ? service.query(query) : service.queryResource(resource, query); attributes.addAttribute("", QUERY_ATTR, QUERY_ATTR, "CDATA", query); attributes.addAttribute("", RESULTS_COUNT_ATTR, RESULTS_COUNT_ATTR, "CDATA", Long.toString(resultSet.getSize())); handler.startDocument();//from ww w . ja va 2 s .c om handler.startPrefixMapping(PREFIX, URI); handler.startElement(URI, RESULTSET, QRESULTSET, attributes); IncludeXMLConsumer includeHandler = new IncludeXMLConsumer(handler); // Print search results ResourceIterator results = resultSet.getIterator(); while (results.hasMoreResources()) { XMLResource result = (XMLResource) results.nextResource(); final String id = result.getId(); final String documentId = result.getDocumentId(); attributes.clear(); if (id != null) { attributes.addAttribute("", RESULT_ID_ATTR, RESULT_ID_ATTR, CDATA, id); } if (documentId != null) { attributes.addAttribute("", RESULT_DOCID_ATTR, RESULT_DOCID_ATTR, CDATA, documentId); } handler.startElement(URI, RESULT, QRESULT, attributes); try { result.getContentAsSAX(includeHandler); } catch (XMLDBException xde) { // That may be a text-only result Object content = result.getContent(); if (content instanceof String) { String text = (String) content; handler.characters(text.toCharArray(), 0, text.length()); } else { // Cannot do better throw xde; } } handler.endElement(URI, RESULT, QRESULT); } handler.endElement(URI, RESULTSET, QRESULTSET); handler.endPrefixMapping(PREFIX); handler.endDocument(); }
From source file:org.freecine.filmscan.ScanStrip.java
public void writeXml(TransformerHandler hd) throws SAXException { if (perforations == null) { findPerforations();//w w w . j a v a 2 s .c om } AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "", "orientation", "CDATA", "0"); atts.addAttribute("", "", "gamma", "CDATA", "1.0"); hd.startElement("", "", "scan", atts); atts.clear(); hd.startElement("", "", "perforations", atts); for (Perforation p : perforations) { atts.addAttribute("", "", "x", "CDATA", Integer.toString(p.x)); atts.addAttribute("", "", "y", "CDATA", Integer.toString(p.y)); hd.startElement("", "", "perforation", atts); hd.endElement("", "", "perforation"); } hd.endElement("", "", "perforations"); hd.endElement("", "", "scan"); hd.endDocument(); }
From source file:org.geoserver.qos.util.AttributesBuilder.java
public Attributes getAttributes() { AttributesImpl atts = new AttributesImpl(); attributes.forEach(a -> atts.addAttribute("", "", a.getName(), "string", a.getValue())); return atts;/*from w w w. j a v a 2s .co m*/ }