List of usage examples for javax.xml.stream XMLStreamConstants START_ELEMENT
int START_ELEMENT
To view the source code for javax.xml.stream XMLStreamConstants START_ELEMENT.
Click Source Link
From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java
@Override public InputStream selectEntity(final InputStream entity, final String[] propertyNames) throws Exception { final XMLEventReader reader = getEventReader(entity); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLEventWriter writer = getEventWriter(bos); final List<String> found = new ArrayList<String>(Arrays.asList(propertyNames)); boolean inProperties = false; boolean writeCurrent = true; Boolean writeNext = null;/*ww w .j a v a 2 s . c o m*/ String currentName = null; final List<String> fieldToBeSaved = new ArrayList<String>(Arrays.asList(propertyNames)); while (reader.hasNext()) { final XMLEvent event = reader.nextEvent(); if (event.getEventType() == XMLStreamConstants.START_ELEMENT && LINK.equals(event.asStartElement().getName().getLocalPart()) && !fieldToBeSaved .contains(event.asStartElement().getAttributeByName(new QName("title")).getValue()) && !"edit".equals(event.asStartElement().getAttributeByName(new QName("rel")).getValue())) { writeCurrent = false; } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT && LINK.equals(event.asEndElement().getName().getLocalPart())) { writeNext = true; } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT && (PROPERTIES).equals(event.asStartElement().getName().getLocalPart())) { writeCurrent = true; writeNext = false; inProperties = true; } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT && (PROPERTIES).equals(event.asEndElement().getName().getLocalPart())) { writeCurrent = true; } else if (inProperties) { if (event.getEventType() == XMLStreamConstants.START_ELEMENT) { final String elementName = event.asStartElement().getName().getLocalPart(); for (String propertyName : propertyNames) { if ((ATOM_PROPERTY_PREFIX + propertyName.trim()).equals(elementName)) { writeCurrent = true; found.remove(propertyName); currentName = propertyName; } } } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT && StringUtils.isNotBlank(currentName) && (ATOM_PROPERTY_PREFIX + currentName.trim()) .equals(event.asEndElement().getName().getLocalPart())) { writeNext = false; currentName = null; } } if (writeCurrent) { writer.add(event); } if (writeNext != null) { writeCurrent = writeNext; writeNext = null; } } writer.flush(); writer.close(); reader.close(); IOUtils.closeQuietly(entity); // Do not raise any exception in order to support FC properties as well // if (!found.isEmpty()) { // throw new Exception(String.format("Could not find a properties '%s'", found)); // } return new ByteArrayInputStream(bos.toByteArray()); }
From source file:org.apache.olingo.fit.utils.XMLUtilities.java
public XMLElement getXmlElement(final StartElement start, final XMLEventReader reader) throws Exception { final XMLElement res = new XMLElement(); res.setStart(start);// www. j av a2 s. c om final Charset encoding = Charset.forName(org.apache.olingo.commons.api.Constants.UTF8); final ByteArrayOutputStream content = new ByteArrayOutputStream(); final OutputStreamWriter writer = new OutputStreamWriter(content, encoding); int depth = 1; while (reader.hasNext() && depth > 0) { final XMLEvent event = reader.nextEvent(); if (event.getEventType() == XMLStreamConstants.START_ELEMENT) { depth++; } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) { depth--; } if (depth == 0) { res.setEnd(event.asEndElement()); } else { event.writeAsEncodedUnicode(writer); } } writer.flush(); writer.close(); res.setContent(new ByteArrayInputStream(content.toByteArray())); return res; }
From source file:org.apache.olingo.fit.utils.XMLUtilities.java
public Map.Entry<Integer, XMLElement> extractElement(final XMLEventReader reader, final XMLEventWriter writer, final List<String> path, final Collection<Map.Entry<String, String>> filter, final boolean filterInOr, final int startPathPos, final int minPathPos, final int maxPathPos) throws Exception { StartElement start = null;//from w w w .j a v a 2 s . c om int searchFor = 0; int depth = startPathPos; // Current inspected element String current = null; // set defaults final List<String> pathElementNames = path == null ? Collections.<String>emptyList() : path; final Collection<Map.Entry<String, String>> filterAttrs = filter == null ? Collections.<Map.Entry<String, String>>emptySet() : filter; while (reader.hasNext() && start == null) { final XMLEvent event = reader.nextEvent(); if (event.getEventType() == XMLStreamConstants.START_ELEMENT) { depth++; if (current != null || ((minPathPos < 0 || minPathPos <= depth) && (maxPathPos < 0 || depth <= maxPathPos))) { if (pathElementNames.isEmpty() || pathElementNames.get(searchFor).trim() .equals(event.asStartElement().getName().getLocalPart())) { if (searchFor < pathElementNames.size() - 1) { // path exploring not completed writeEvent(event, writer); current = pathElementNames.get(searchFor).trim(); searchFor++; } else { // path exploring completed ... evaluate filter about path element name attribute boolean match = filterAttrs.isEmpty() || !filterInOr; for (Map.Entry<String, String> filterAttr : filterAttrs) { final Attribute attr = event.asStartElement() .getAttributeByName(new QName(filterAttr.getKey().trim())); if (attr == null || !filterAttr.getValue().trim().equals(attr.getValue())) { match = filterInOr ? match : false; } else { match = filterInOr ? true : match; } } if (match) { // found searched element start = event.asStartElement(); } else { skipElement(event.asStartElement(), reader, writer, false); depth--; } } } else if (current == null) { writeEvent(event, writer); } else { // skip element skipElement(event.asStartElement(), reader, writer, false); depth--; } } else { writeEvent(event, writer); } } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) { depth--; writeEvent(event, writer); if (event.asEndElement().getName().getLocalPart().equals(current)) { // back step .... searchFor--; current = searchFor > 0 ? pathElementNames.get(searchFor - 1).trim() : null; } } else { writeEvent(event, writer); } } if (start == null) { throw new NotFoundException(); } return new SimpleEntry<Integer, XMLElement>(Integer.valueOf(depth - 1), getXmlElement(start, reader)); }
From source file:org.apache.olingo.fit.utils.XMLUtilities.java
@Override public InputStream selectEntity(final InputStream entity, final String[] propertyNames) throws Exception { final XMLEventReader reader = getEventReader(entity); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLEventWriter writer = getEventWriter(bos); final List<String> found = new ArrayList<String>(Arrays.asList(propertyNames)); boolean inProperties = false; boolean writeCurrent = true; Boolean writeNext = null;/*from w w w . j ava 2s . c o m*/ String currentName = null; final List<String> fieldToBeSaved = new ArrayList<String>(Arrays.asList(propertyNames)); while (reader.hasNext()) { final XMLEvent event = reader.nextEvent(); if (event.getEventType() == XMLStreamConstants.START_ELEMENT && Constants.get(ConstantKey.LINK).equals(event.asStartElement().getName().getLocalPart()) && !fieldToBeSaved .contains(event.asStartElement().getAttributeByName(new QName("title")).getValue()) && !"edit".equals(event.asStartElement().getAttributeByName(new QName("rel")).getValue())) { writeCurrent = false; } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT && Constants.get(ConstantKey.LINK).equals(event.asEndElement().getName().getLocalPart())) { writeNext = true; } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT && (Constants.get(ConstantKey.PROPERTIES)) .equals(event.asStartElement().getName().getLocalPart())) { writeCurrent = true; writeNext = false; inProperties = true; } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT && (Constants.get(ConstantKey.PROPERTIES)) .equals(event.asEndElement().getName().getLocalPart())) { writeCurrent = true; } else if (inProperties) { if (event.getEventType() == XMLStreamConstants.START_ELEMENT) { final String elementName = event.asStartElement().getName().getLocalPart(); for (String propertyName : propertyNames) { if ((Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + propertyName.trim()) .equals(elementName)) { writeCurrent = true; found.remove(propertyName); currentName = propertyName; } } } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT && StringUtils.isNotBlank(currentName) && (Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + currentName.trim()) .equals(event.asEndElement().getName().getLocalPart())) { writeNext = false; currentName = null; } } if (writeCurrent) { writer.add(event); } if (writeNext != null) { writeCurrent = writeNext; writeNext = null; } } writer.flush(); writer.close(); reader.close(); IOUtils.closeQuietly(entity); // Do not raise any exception in order to support FC properties as well // if (!found.isEmpty()) { // throw new Exception(String.format("Could not find a properties '%s'", found)); // } return new ByteArrayInputStream(bos.toByteArray()); }
From source file:org.apache.solr.handler.AnalysisRequestHandler.java
NamedList<Object> processContent(XMLStreamReader parser, IndexSchema schema) throws XMLStreamException, IOException { NamedList<Object> result = new SimpleOrderedMap<Object>(); while (true) { int event = parser.next(); switch (event) { case XMLStreamConstants.END_DOCUMENT: { parser.close();//from ww w . ja v a 2 s . com return result; } case XMLStreamConstants.START_ELEMENT: { String currTag = parser.getLocalName(); if ("doc".equals(currTag)) { log.trace("Tokenizing doc..."); SolrInputDocument doc = readDoc(parser); SchemaField uniq = schema.getUniqueKeyField(); NamedList<NamedList<NamedList<Object>>> theTokens = new SimpleOrderedMap<NamedList<NamedList<Object>>>(); result.add(doc.getFieldValue(uniq.getName()).toString(), theTokens); for (String name : doc.getFieldNames()) { FieldType ft = schema.getFieldType(name); Analyzer analyzer = ft.getAnalyzer(); Collection<Object> vals = doc.getFieldValues(name); for (Object val : vals) { Reader reader = new StringReader(val.toString()); TokenStream tstream = analyzer.tokenStream(name, reader); NamedList<NamedList<Object>> tokens = getTokens(tstream); theTokens.add(name, tokens); } } } break; } } } }
From source file:org.apache.solr.handler.AnalysisRequestHandler.java
SolrInputDocument readDoc(XMLStreamReader parser) throws XMLStreamException { SolrInputDocument doc = new SolrInputDocument(); StringBuilder text = new StringBuilder(); String name = null;//w ww . j ava2 s. co m String attrName = ""; float boost = 1.0f; boolean isNull = false; while (true) { int event = parser.next(); switch (event) { // Add everything to the text case XMLStreamConstants.SPACE: case XMLStreamConstants.CDATA: case XMLStreamConstants.CHARACTERS: text.append(parser.getText()); break; case XMLStreamConstants.END_ELEMENT: if ("doc".equals(parser.getLocalName())) { return doc; } else if ("field".equals(parser.getLocalName())) { if (!isNull) { doc.addField(name, text.toString(), boost); boost = 1.0f; } } break; case XMLStreamConstants.START_ELEMENT: text.setLength(0); String localName = parser.getLocalName(); if (!"field".equals(localName)) { log.warn("unexpected XML tag doc/" + localName); throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "unexpected XML tag doc/" + localName); } String attrVal = ""; for (int i = 0; i < parser.getAttributeCount(); i++) { attrName = parser.getAttributeLocalName(i); attrVal = parser.getAttributeValue(i); if ("name".equals(attrName)) { name = attrVal; } } break; } } }
From source file:org.apache.solr.handler.DocumentAnalysisRequestHandler.java
/** * Resolves the {@link DocumentAnalysisRequest} from the given solr request. * * @param req The solr request./*from w ww . j a v a2 s . c om*/ * * @return The resolved document analysis request. * * @throws IOException Thrown when reading/parsing the content stream of the request fails. * @throws XMLStreamException Thrown when reading/parsing the content stream of the request fails. */ DocumentAnalysisRequest resolveAnalysisRequest(SolrQueryRequest req) throws IOException, XMLStreamException { DocumentAnalysisRequest request = new DocumentAnalysisRequest(); SolrParams params = req.getParams(); String query = params.get(AnalysisParams.QUERY, params.get(CommonParams.Q, null)); request.setQuery(query); boolean showMatch = params.getBool(AnalysisParams.SHOW_MATCH, false); request.setShowMatch(showMatch); ContentStream stream = extractSingleContentStream(req); InputStream is = null; XMLStreamReader parser = null; try { is = stream.getStream(); final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType()); parser = (charset == null) ? inputFactory.createXMLStreamReader(is) : inputFactory.createXMLStreamReader(is, charset); while (true) { int event = parser.next(); switch (event) { case XMLStreamConstants.END_DOCUMENT: { parser.close(); return request; } case XMLStreamConstants.START_ELEMENT: { String currTag = parser.getLocalName(); if ("doc".equals(currTag)) { log.trace("Reading doc..."); SolrInputDocument document = readDocument(parser, req.getSchema()); request.addDocument(document); } break; } } } } finally { if (parser != null) parser.close(); IOUtils.closeQuietly(is); } }
From source file:org.apache.solr.handler.DocumentAnalysisRequestHandler.java
/** * Reads the document from the given xml stream reader. The following document format is expected: * <p/>/*from w ww.j a v a 2 s .c o m*/ * <pre><code> * <doc> * <field name="id">1</field> * <field name="name">The Name</field> * <field name="text">The Text Value</field> * </doc> * </code></pre> * <p/> * <p/> * <em>NOTE: each read document is expected to have at least one field which serves as the unique key.</em> * * @param reader The {@link XMLStreamReader} from which the document will be read. * @param schema The index schema. The schema is used to validate that the read document has a unique key field. * * @return The read document. * * @throws XMLStreamException When reading of the document fails. */ SolrInputDocument readDocument(XMLStreamReader reader, IndexSchema schema) throws XMLStreamException { SolrInputDocument doc = new SolrInputDocument(); String uniqueKeyField = schema.getUniqueKeyField().getName(); StringBuilder text = new StringBuilder(); String fieldName = null; boolean hasId = false; while (true) { int event = reader.next(); switch (event) { // Add everything to the text case XMLStreamConstants.SPACE: case XMLStreamConstants.CDATA: case XMLStreamConstants.CHARACTERS: text.append(reader.getText()); break; case XMLStreamConstants.END_ELEMENT: if ("doc".equals(reader.getLocalName())) { if (!hasId) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "All documents must contain a unique key value: '" + doc.toString() + "'"); } return doc; } else if ("field".equals(reader.getLocalName())) { doc.addField(fieldName, text.toString(), DEFAULT_BOOST); if (uniqueKeyField.equals(fieldName)) { hasId = true; } } break; case XMLStreamConstants.START_ELEMENT: text.setLength(0); String localName = reader.getLocalName(); if (!"field".equals(localName)) { log.warn("unexpected XML tag doc/" + localName); throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "unexpected XML tag doc/" + localName); } for (int i = 0; i < reader.getAttributeCount(); i++) { String attrName = reader.getAttributeLocalName(i); if ("name".equals(attrName)) { fieldName = reader.getAttributeValue(i); } } break; } } }
From source file:org.apache.solr.handler.loader.XMLLoader.java
/** * @since solr 1.2// w ww .j a va 2 s .c o m */ void processUpdate(SolrQueryRequest req, UpdateRequestProcessor processor, XMLStreamReader parser) throws XMLStreamException, IOException, FactoryConfigurationError { AddUpdateCommand addCmd = null; SolrParams params = req.getParams(); while (true) { int event = parser.next(); switch (event) { case XMLStreamConstants.END_DOCUMENT: parser.close(); return; case XMLStreamConstants.START_ELEMENT: String currTag = parser.getLocalName(); if (currTag.equals(UpdateRequestHandler.ADD)) { log.trace("SolrCore.update(add)"); addCmd = new AddUpdateCommand(req); // First look for commitWithin parameter on the request, will be overwritten for individual <add>'s addCmd.commitWithin = params.getInt(UpdateParams.COMMIT_WITHIN, -1); addCmd.overwrite = params.getBool(UpdateParams.OVERWRITE, true); for (int i = 0; i < parser.getAttributeCount(); i++) { String attrName = parser.getAttributeLocalName(i); String attrVal = parser.getAttributeValue(i); if (UpdateRequestHandler.OVERWRITE.equals(attrName)) { addCmd.overwrite = StrUtils.parseBoolean(attrVal); } else if (UpdateRequestHandler.COMMIT_WITHIN.equals(attrName)) { addCmd.commitWithin = Integer.parseInt(attrVal); } else { log.warn("XML element <add> has invalid XML attr: " + attrName); } } } else if ("doc".equals(currTag)) { if (addCmd != null) { log.trace("adding doc..."); addCmd.clear(); addCmd.solrDoc = readDoc(parser); processor.processAdd(addCmd); } else { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unexpected <doc> tag without an <add> tag surrounding it."); } } else if (UpdateRequestHandler.COMMIT.equals(currTag) || UpdateRequestHandler.OPTIMIZE.equals(currTag)) { log.trace("parsing " + currTag); CommitUpdateCommand cmd = new CommitUpdateCommand(req, UpdateRequestHandler.OPTIMIZE.equals(currTag)); ModifiableSolrParams mp = new ModifiableSolrParams(); for (int i = 0; i < parser.getAttributeCount(); i++) { String attrName = parser.getAttributeLocalName(i); String attrVal = parser.getAttributeValue(i); mp.set(attrName, attrVal); } RequestHandlerUtils.validateCommitParams(mp); SolrParams p = SolrParams.wrapDefaults(mp, req.getParams()); // default to the normal request params for commit options RequestHandlerUtils.updateCommit(cmd, p); processor.processCommit(cmd); } // end commit else if (UpdateRequestHandler.ROLLBACK.equals(currTag)) { log.trace("parsing rollback"); RollbackUpdateCommand cmd = new RollbackUpdateCommand(req); processor.processRollback(cmd); } // end rollback else if (UpdateRequestHandler.DELETE.equals(currTag)) { log.trace("parsing delete"); processDelete(req, processor, parser); } // end delete break; } } }
From source file:org.apache.solr.handler.loader.XMLLoader.java
/** * @since solr 1.3//from w w w . ja v a 2s. c om */ void processDelete(SolrQueryRequest req, UpdateRequestProcessor processor, XMLStreamReader parser) throws XMLStreamException, IOException { // Parse the command DeleteUpdateCommand deleteCmd = new DeleteUpdateCommand(req); // First look for commitWithin parameter on the request, will be overwritten for individual <delete>'s SolrParams params = req.getParams(); deleteCmd.commitWithin = params.getInt(UpdateParams.COMMIT_WITHIN, -1); for (int i = 0; i < parser.getAttributeCount(); i++) { String attrName = parser.getAttributeLocalName(i); String attrVal = parser.getAttributeValue(i); if ("fromPending".equals(attrName)) { // deprecated } else if ("fromCommitted".equals(attrName)) { // deprecated } else if (UpdateRequestHandler.COMMIT_WITHIN.equals(attrName)) { deleteCmd.commitWithin = Integer.parseInt(attrVal); } else { log.warn("XML element <delete> has invalid XML attr: " + attrName); } } StringBuilder text = new StringBuilder(); while (true) { int event = parser.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: String mode = parser.getLocalName(); if (!("id".equals(mode) || "query".equals(mode))) { String msg = "XML element <delete> has invalid XML child element: " + mode; log.warn(msg); throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, msg); } text.setLength(0); if ("id".equals(mode)) { for (int i = 0; i < parser.getAttributeCount(); i++) { String attrName = parser.getAttributeLocalName(i); String attrVal = parser.getAttributeValue(i); if (UpdateRequestHandler.VERSION.equals(attrName)) { deleteCmd.setVersion(Long.parseLong(attrVal)); } if (UpdateRequest.ROUTE.equals(attrName)) { deleteCmd.setRoute(attrVal); } } } break; case XMLStreamConstants.END_ELEMENT: String currTag = parser.getLocalName(); if ("id".equals(currTag)) { deleteCmd.setId(text.toString()); } else if ("query".equals(currTag)) { deleteCmd.setQuery(text.toString()); } else if ("delete".equals(currTag)) { return; } else { String msg = "XML element <delete> has invalid XML (closing) child element: " + currTag; log.warn(msg); throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, msg); } processor.processDelete(deleteCmd); deleteCmd.clear(); break; // Add everything to the text case XMLStreamConstants.SPACE: case XMLStreamConstants.CDATA: case XMLStreamConstants.CHARACTERS: text.append(parser.getText()); break; } } }