List of usage examples for org.xml.sax.helpers AttributesImpl AttributesImpl
public AttributesImpl()
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 ww w . ja v a 2s.c o m 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."); }//from w ww. ja 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."); }//ww w. j ava 2 s . c o 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;/*from w w w. ja v a 2 s. c o m*/ if (anchorName == null) { attributes = EMPTY_ATTRIBS; } 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.enhydra.shark.asap.util.BeanSerializerShark.java
/** * Check for meta-data in the bean that will tell us if any of the * properties are actually attributes, add those to the element * attribute list//from ww w . ja va 2s. com * * @param value the object we are serializing * @return attributes for this element, null if none */ protected Attributes getObjectAttributes(Object value, Attributes attributes, SerializationContext context) { if (typeDesc == null || !typeDesc.hasAttributes()) return attributes; AttributesImpl attrs; if (attributes == null) { attrs = new AttributesImpl(); } else if (attributes instanceof AttributesImpl) { attrs = (AttributesImpl) attributes; } else { attrs = new AttributesImpl(attributes); } try { // Find each property that is an attribute // and add it to our attribute list for (int i = 0; i < propertyDescriptor.length; i++) { String propName = propertyDescriptor[i].getName(); if (propName.equals("class")) continue; FieldDesc field = typeDesc.getFieldByName(propName); // skip it if its not an attribute if (field == null || field.isElement()) continue; QName qname = field.getXmlName(); if (qname == null) { qname = new QName("", propName); } if (propertyDescriptor[i].isReadable() && !propertyDescriptor[i].isIndexed()) { // add to our attributes Object propValue = propertyDescriptor[i].get(value); // Convert true/false to 1/0 in case of soapenv:mustUnderstand if (qname.equals(new QName(Constants.URI_SOAP11_ENV, Constants.ATTR_MUST_UNDERSTAND))) { if (propValue.equals(Boolean.TRUE)) { propValue = "1"; } else if (propValue.equals(Boolean.FALSE)) { propValue = "0"; } } // If the property value does not exist, don't serialize // the attribute. In the future, the decision to serializer // the attribute may be more sophisticated. For example, don't // serialize if the attribute matches the default value. if (propValue != null) { setAttributeProperty(propValue, qname, field.getXmlType(), attrs, context); } } } } catch (Exception e) { // no attributes return attrs; } return attrs; }
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 .j av a 2s . co 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();// w ww . j a v a2 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.Project.java
public void writeXml(TransformerHandler hd) throws SAXException { AttributesImpl atts = new AttributesImpl(); hd.startElement("", "", "project", atts); hd.startElement("", "", "scenes", atts); scene.writeXml(hd);/*from w w w . j a va 2 s. c o m*/ hd.endElement("", "", "scenes"); hd.endElement("", "", "project"); }
From source file:org.freecine.filmscan.ScanStrip.java
public void writeXml(TransformerHandler hd) throws SAXException { if (perforations == null) { findPerforations();// w ww . j a v a 2s . c o m } 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 va2s .c o m*/ }