List of usage examples for org.xml.sax ContentHandler endDocument
public void endDocument() throws SAXException;
From source file:edu.mayo.informatics.lexgrid.convert.directConversions.hl7.HL7MapToLexGrid.java
void loadMetaData(CodingScheme csclass, String connectionString, String driver) { messages_.info("Loading individual coding scheme metadata"); Connection c = null;/* w w w. java2 s .co m*/ // create the filename of the metadata file to be created String filename = loaderPrefs.getXMLMetadataFilePath() + "/" + PreferenceLoaderConstants.META_HL7_METADATA_FILE_NAME; FileOutputStream fos; try { fos = new FileOutputStream(filename); OutputFormat of = new OutputFormat("XML", "ISO-8859-1", true); of.setIndent(1); of.setIndenting(true); XMLSerializer serializer = new XMLSerializer(fos, of); // SAX2.0 ContentHandler. ContentHandler hd = serializer.asContentHandler(); hd.startDocument(); // Element attributes. AttributesImpl atts = new AttributesImpl(); // CODINGSCHEMES tag. hd.startElement("", "", "codingSchemes", atts); String defaultLanguage = "en"; String isNative = "0"; String codeSystemId; String codeSystemType; String codeSystemName; String fullName; String description; String releaseId; String copyrightNotice; Integer approximateNumberofConcepts; try { c = DBUtility.connectToDatabase(accessConnectionString, driver, null, null); PreparedStatement getCodingSchemeMetaData = c .prepareStatement("SELECT b.codeSystemid, b.codeSystemType, b.codeSystemName, " + "b.fullName, b.description, b.releaseId, b.copyrightNotice " + "FROM VCS_code_system AS b"); ResultSet codingSchemeMetaData = getCodingSchemeMetaData.executeQuery(); PreparedStatement getCodingSchemeConceptCount = c .prepareStatement("SELECT VCS_concept_code_xref.codeSystemId2, " + "COUNT (VCS_concept_code_xref.codeSystemId2) as conceptcount " + "FROM VCS_concept_code_xref " + "GROUP BY VCS_concept_code_xref.codeSystemId2;"); ResultSet codingSchemeConceptCount = getCodingSchemeConceptCount.executeQuery(); Hashtable<String, Integer> conceptCountList = new Hashtable<String, Integer>(); while (codingSchemeConceptCount.next()) { String codingSchemeId = codingSchemeConceptCount.getString("codeSystemId2"); String codingSchemeCount = codingSchemeConceptCount.getString("conceptcount"); conceptCountList.put(new String(codingSchemeId), new Integer(codingSchemeCount)); } codingSchemeConceptCount.close(); int codeSchemeCounter = 0; while (codingSchemeMetaData.next()) { codeSystemId = codingSchemeMetaData.getString("codeSystemid"); if (codeSystemId == null) { codeSystemId = SQLTableConstants.TBLCOLVAL_MISSING; } codeSystemType = codingSchemeMetaData.getString("codeSystemType"); if (codeSystemType == null) { codeSystemType = SQLTableConstants.TBLCOLVAL_MISSING; } codeSystemName = codingSchemeMetaData.getString("codeSystemName"); if (codeSystemName == null) { codeSystemName = SQLTableConstants.TBLCOLVAL_MISSING; } fullName = codingSchemeMetaData.getString("fullName"); if (fullName == null) { fullName = SQLTableConstants.TBLCOLVAL_MISSING; } description = codingSchemeMetaData.getString("description"); if (description == null) { description = SQLTableConstants.TBLCOLVAL_MISSING; } // The description contains HTML tags. We try to remove // them. else { int begin = description.lastIndexOf("<p>"); int end = description.lastIndexOf("</p>"); if (begin > -1) { if (begin + 3 < end) description = description.substring(begin + 3, end); } } releaseId = codingSchemeMetaData.getString("releaseId"); if (releaseId == null) { releaseId = SQLTableConstants.TBLCOLVAL_MISSING; } copyrightNotice = codingSchemeMetaData.getString("copyrightNotice"); if (copyrightNotice == null) { copyrightNotice = SQLTableConstants.TBLCOLVAL_MISSING; } approximateNumberofConcepts = ((Integer) conceptCountList.get(codeSystemId)); if (approximateNumberofConcepts == null) { approximateNumberofConcepts = new Integer(0); } // Begin codingScheme element atts.clear(); atts.addAttribute("", "", SQLTableConstants.TBLCOL_CODINGSCHEMENAME, "CDATA", codeSystemName); // May want to change to _fullName atts.addAttribute("", "", SQLTableConstants.TBLCOL_FORMALNAME, "CDATA", fullName); atts.addAttribute("", "", SQLTableConstants.TBLCOL_CODINGSCHEMEURI, "CDATA", codeSystemId); atts.addAttribute("", "", SQLTableConstants.TBLCOL_DEFAULTLANGUAGE, "CDATA", defaultLanguage); atts.addAttribute("", "", SQLTableConstants.TBLCOL_REPRESENTSVERSION, "CDATA", releaseId); atts.addAttribute("", "", SQLTableConstants.TBLCOL_ISNATIVE, "CDATA", isNative); atts.addAttribute("", "", SQLTableConstants.TBLCOL_APPROXNUMCONCEPTS, "CDATA", approximateNumberofConcepts.toString()); hd.startElement("", "", SQLTableConstants.TBLCOL_CODINGSCHEME, atts); // localname atts.clear(); hd.startElement("", "", "localName", atts); hd.characters(codeSystemName.toCharArray(), 0, codeSystemName.length()); hd.endElement("", "", SQLTableConstants.TBLCOLVAL_LOCALNAME); // entityDescription atts.clear(); hd.startElement("", "", SQLTableConstants.TBLCOL_ENTITYDESCRIPTION, atts); hd.characters(description.toCharArray(), 0, description.length()); hd.endElement("", "", SQLTableConstants.TBLCOL_ENTITYDESCRIPTION); // copyright atts.clear(); hd.startElement("", "", SQLTableConstants.TBLCOL_COPYRIGHT, atts); hd.characters(copyrightNotice.toCharArray(), 0, copyrightNotice.length()); hd.endElement("", "", SQLTableConstants.TBLCOL_COPYRIGHT); // May need to include as Property // // CodingScheme // atts.clear(); // hd.startElement("","","CodingScheme",atts); // hd.characters(_codeSystemType.toCharArray(),0,_codeSystemType.length()); // hd.endElement("","","CodingScheme"); // End codingScheme element hd.endElement("", "", SQLTableConstants.TBLCOL_CODINGSCHEME); codeSchemeCounter++; } // End while there are result rows to process getCodingSchemeConceptCount.close(); hd.endElement("", "", "codingSchemes"); hd.endDocument(); fos.close(); } catch (Exception e) { messages_.error("Failed while preparing HL7 Code System MetaData.", e); e.printStackTrace(); } finally { try { c.close(); } catch (SQLException e) { messages_.debug("An error occurred while closing the MS Access connection: " + e.getMessage()); e.printStackTrace(); } } } catch (FileNotFoundException fnfe) { messages_.debug("Loader Preferences file was not found, file: " + filename); fnfe.printStackTrace(); } catch (IOException ioe) { messages_.debug("IOException, file: " + filename); ioe.printStackTrace(); } catch (SAXException saxe) { messages_.debug("SAXException, file: " + filename); saxe.printStackTrace(); } }
From source file:nl.architolk.ldt.processors.HttpClientProcessor.java
public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException { try {//from w w w . ja va 2 s.c o m CloseableHttpClient httpclient = HttpClientProperties.createHttpClient(); try { // Read content of config pipe Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG); Node configNode = configDocument.selectSingleNode("//config"); URL theURL = new URL(configNode.valueOf("url")); if (configNode.valueOf("auth-method").equals("basic")) { HttpHost targetHost = new HttpHost(theURL.getHost(), theURL.getPort(), theURL.getProtocol()); //Authentication support CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( configNode.valueOf("username"), configNode.valueOf("password"))); // logger.info("Credentials: "+configNode.valueOf("username")+"/"+configNode.valueOf("password")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); // Add AuthCache to the execution context httpContext = HttpClientContext.create(); httpContext.setCredentialsProvider(credsProvider); httpContext.setAuthCache(authCache); } else if (configNode.valueOf("auth-method").equals("form")) { //Sign in. Cookie will be remembered bij httpclient HttpPost authpost = new HttpPost(configNode.valueOf("auth-url")); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("userName", configNode.valueOf("username"))); nameValuePairs.add(new BasicNameValuePair("password", configNode.valueOf("password"))); authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpResponse httpResponse = httpclient.execute(authpost); // logger.info("Signin response:"+Integer.toString(httpResponse.getStatusLine().getStatusCode())); } CloseableHttpResponse response; if (configNode.valueOf("method").equals("post")) { // POST HttpPost httpRequest = new HttpPost(configNode.valueOf("url")); setBody(httpRequest, context, configNode); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("put")) { // PUT HttpPut httpRequest = new HttpPut(configNode.valueOf("url")); setBody(httpRequest, context, configNode); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("delete")) { //DELETE HttpDelete httpRequest = new HttpDelete(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("head")) { //HEAD HttpHead httpRequest = new HttpHead(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("options")) { //OPTIONS HttpOptions httpRequest = new HttpOptions(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else { //Default = GET HttpGet httpRequest = new HttpGet(configNode.valueOf("url")); String acceptHeader = configNode.valueOf("accept"); if (!acceptHeader.isEmpty()) { httpRequest.addHeader("accept", configNode.valueOf("accept")); } //Add proxy route if needed HttpClientProperties.setProxy(httpRequest, theURL.getHost()); response = executeRequest(httpRequest, httpclient); } try { contentHandler.startDocument(); int status = response.getStatusLine().getStatusCode(); AttributesImpl statusAttr = new AttributesImpl(); statusAttr.addAttribute("", "status", "status", "CDATA", Integer.toString(status)); contentHandler.startElement("", "response", "response", statusAttr); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); Header contentType = response.getFirstHeader("Content-Type"); if (entity != null && contentType != null) { //logger.info("Contenttype: " + contentType.getValue()); //Read content into inputstream InputStream inStream = entity.getContent(); // output-type = json means: response is json, convert to xml if (configNode.valueOf("output-type").equals("json")) { //TODO: net.sf.json.JSONObject might nog be the correct JSONObject. javax.json.JsonObject might be better!!! //javax.json contains readers to read from an inputstream StringWriter writer = new StringWriter(); IOUtils.copy(inStream, writer, "UTF-8"); JSONObject json = JSONObject.fromObject(writer.toString()); parseJSONObject(contentHandler, json); // output-type = xml means: response is xml, keep it } else if (configNode.valueOf("output-type").equals("xml")) { try { XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inStream)); } catch (Exception e) { throw new OXFException(e); } // output-type = jsonld means: reponse is json-ld, (a) convert to nquads; (b) convert to xml } else if (configNode.valueOf("output-type").equals("jsonld")) { try { Object jsonObject = JsonUtils.fromInputStream(inStream, "UTF-8"); //TODO: UTF-8 should be read from response! Object nquads = JsonLdProcessor.toRDF(jsonObject, new NQuadTripleCallback()); Any23 runner = new Any23(); DocumentSource source = new StringDocumentSource((String) nquads, configNode.valueOf("url")); ByteArrayOutputStream out = new ByteArrayOutputStream(); TripleHandler handler = new RDFXMLWriter(out); try { runner.extract(source, handler); } finally { handler.close(); } ByteArrayInputStream inJsonStream = new ByteArrayInputStream(out.toByteArray()); XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inJsonStream)); } catch (Exception e) { throw new OXFException(e); } // output-type = rdf means: response is some kind of rdf (except json-ld...), convert to xml } else if (configNode.valueOf("output-type").equals("rdf")) { try { Any23 runner = new Any23(); DocumentSource source; //If contentType = text/html than convert from html to xhtml to handle non-xml style html! logger.info("Contenttype: " + contentType.getValue()); if (configNode.valueOf("tidy").equals("yes") && contentType.getValue().startsWith("text/html")) { org.jsoup.nodes.Document doc = Jsoup.parse(inStream, "UTF-8", configNode.valueOf("url")); //TODO UTF-8 should be read from response! RDFCleaner cleaner = new RDFCleaner(); org.jsoup.nodes.Document cleandoc = cleaner.clean(doc); cleandoc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); cleandoc.outputSettings() .syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml); cleandoc.outputSettings().charset("UTF-8"); source = new StringDocumentSource(cleandoc.html(), configNode.valueOf("url"), contentType.getValue()); } else { source = new ByteArrayDocumentSource(inStream, configNode.valueOf("url"), contentType.getValue()); } ByteArrayOutputStream out = new ByteArrayOutputStream(); TripleHandler handler = new RDFXMLWriter(out); try { runner.extract(source, handler); } finally { handler.close(); } ByteArrayInputStream inAnyStream = new ByteArrayInputStream(out.toByteArray()); XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inAnyStream)); } catch (Exception e) { throw new OXFException(e); } } else { CharArrayWriter writer = new CharArrayWriter(); IOUtils.copy(inStream, writer, "UTF-8"); contentHandler.characters(writer.toCharArray(), 0, writer.size()); } } } contentHandler.endElement("", "response", "response"); contentHandler.endDocument(); } finally { response.close(); } } finally { httpclient.close(); } } catch (Exception e) { throw new OXFException(e); } }
From source file:org.ajax4jsf.io.parser.FastHtmlParser.java
private void writeToHead(Writer out, boolean haveHtml, boolean haveHead) throws IOException { if (!haveHead && !haveHtml) { out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); }//from ww w .jav a2s.com if (!haveHead) { out.write("<head>"); } if (headEvents != null && headEvents.length > 0) { Serializer serializer = SerializerFactory .getSerializer(OutputPropertiesFactory.getDefaultMethodProperties(Method.XHTML)); serializer.setWriter(out); ContentHandler contentHandler = serializer.asContentHandler(); TreeWalker walker = new TreeWalker(contentHandler); try { contentHandler.startDocument(); for (Node node : headEvents) { walker.traverseFragment(node); } contentHandler.endDocument(); } catch (SAXException e) { throw new IOException(e.getMessage()); } } if (!haveHead) { out.write("</head>"); } }
From source file:org.apache.cocoon.components.notification.Notifier.java
/** * Generate notification information in XML format. *///from w w w.j a v a2 s. c o m public static void notify(Notifying n, ContentHandler ch, String mimetype) throws SAXException { final String PREFIX = Constants.ERROR_NAMESPACE_PREFIX; final String URI = Constants.ERROR_NAMESPACE_URI; // Start the document ch.startDocument(); ch.startPrefixMapping(PREFIX, URI); // Root element. AttributesImpl atts = new AttributesImpl(); atts.addAttribute(URI, "type", PREFIX + ":type", "CDATA", n.getType()); atts.addAttribute(URI, "sender", PREFIX + ":sender", "CDATA", n.getSender()); ch.startElement(URI, "notify", PREFIX + ":notify", atts); ch.startElement(URI, "title", PREFIX + ":title", new AttributesImpl()); ch.characters(n.getTitle().toCharArray(), 0, n.getTitle().length()); ch.endElement(URI, "title", PREFIX + ":title"); ch.startElement(URI, "source", PREFIX + ":source", new AttributesImpl()); ch.characters(n.getSource().toCharArray(), 0, n.getSource().length()); ch.endElement(URI, "source", PREFIX + ":source"); ch.startElement(URI, "message", PREFIX + ":message", new AttributesImpl()); if (n.getMessage() != null) { ch.characters(n.getMessage().toCharArray(), 0, n.getMessage().length()); } ch.endElement(URI, "message", PREFIX + ":message"); ch.startElement(URI, "description", PREFIX + ":description", XMLUtils.EMPTY_ATTRIBUTES); ch.characters(n.getDescription().toCharArray(), 0, n.getDescription().length()); ch.endElement(URI, "description", PREFIX + ":description"); Map extraDescriptions = n.getExtraDescriptions(); for (Iterator i = extraDescriptions.entrySet().iterator(); i.hasNext();) { final Map.Entry me = (Map.Entry) i.next(); String key = (String) me.getKey(); String value = String.valueOf(me.getValue()); atts = new AttributesImpl(); atts.addAttribute(URI, "description", PREFIX + ":description", "CDATA", key); ch.startElement(URI, "extra", PREFIX + ":extra", atts); ch.characters(value.toCharArray(), 0, value.length()); ch.endElement(URI, "extra", PREFIX + ":extra"); } // End root element. ch.endElement(URI, "notify", PREFIX + ":notify"); // End the document. ch.endPrefixMapping(PREFIX); ch.endDocument(); }
From source file:org.apache.cocoon.components.source.impl.QDoxSource.java
/** * @see XMLizable#toSAX(org.xml.sax.ContentHandler) * @throws SAXException if any error occurs during SAX outputting. *///w ww . ja v a 2s . c om public void toSAX(ContentHandler handler) throws SAXException { if (javadocClass == null) { logger.error("No classfile loaded! Cannot output SAX events."); return; } if (logger.isDebugEnabled()) { logger.debug("Outputting SAX events for class " + javadocClass.getFullyQualifiedName()); logger.debug(" #fields: " + javadocClass.getFields().length); logger.debug(" #methods and constructors: " + javadocClass.getMethods().length); } // Output SAX 'header': handler.startDocument(); handler.startPrefixMapping(NS_PREFIX, NS_URI); // Output class-level element: outputClassStartElement(handler, javadocClass); // Modifiers: outputModifiers(handler, javadocClass); // Imports: JavaSource parent = javadocClass.getParentSource(); // Add two implicit imports: parent.addImport("java.lang.*"); if (parent.getPackage() != null) { parent.addImport(parent.getPackage() + ".*"); } else { parent.addImport("*"); } String[] imports = parent.getImports(); saxStartElement(handler, IMPORTS_ELEMENT); for (int i = 0; i < imports.length; i++) { if (imports[i].endsWith("*")) { // package import: saxStartElement(handler, IMPORT_ELEMENT, new String[][] { { IMPORT_ATTRIBUTE, "package" } }); String imp = StringUtils.substringBeforeLast(imports[i], ".*"); saxCharacters(handler, imp); } else { saxStartElement(handler, IMPORT_ELEMENT, new String[][] { { IMPORT_ATTRIBUTE, "class" } }); saxCharacters(handler, imports[i]); } saxEndElement(handler, IMPORT_ELEMENT); } saxEndElement(handler, IMPORTS_ELEMENT); // Superclass: if (!javadocClass.isInterface()) { outputSuperClassInheritance(handler, javadocClass, CLASS_INHERITANCE); } // Implements: outputImplements(handler, javadocClass, true); // Containing class in case this is an inner class: if (containingJavadocClass != null) { saxStartElement(handler, NESTED_IN_ELEMENT); outputClassStartElement(handler, containingJavadocClass); outputModifiers(handler, containingJavadocClass); outputComment(handler, containingJavadocClass.getComment()); outputTags(handler, containingJavadocClass); outputClassEndElement(handler, containingJavadocClass); saxEndElement(handler, NESTED_IN_ELEMENT); } // Comment: outputComment(handler, javadocClass.getComment()); // Tags: outputTags(handler, javadocClass); // Inner classes: outputInnerClasses(handler, javadocClass, true); // Fields: outputFields(handler, javadocClass, true); // Constructors: outputMethods(handler, javadocClass, CONSTRUCTOR_MODE); // Methods: outputMethods(handler, javadocClass, METHOD_MODE); // Close class-level element: outputClassEndElement(handler, javadocClass); // Output SAX 'footer': handler.endPrefixMapping(NS_PREFIX); handler.endDocument(); }
From source file:org.apache.cocoon.components.source.impl.XModuleSource.java
/** * Implement this method to obtain SAX events. * *//*from w w w.jav a 2 s. c o m*/ public void toSAX(ContentHandler handler) throws SAXException { Object obj = getInputAttribute(this.attributeType, this.attributeName); if (obj == null) throw new SAXException(" The attribute: " + this.attributeName + " is empty"); if (!(this.xPath.length() == 0 || this.xPath.equals("/"))) { JXPathContext context = JXPathContext.newContext(obj); obj = context.getPointer(this.xPath).getNode(); if (obj == null) throw new SAXException("the xpath: " + this.xPath + " applied on the attribute: " + this.attributeName + " returns null"); } if (obj instanceof Document) { DOMStreamer domStreamer = new DOMStreamer(handler); domStreamer.stream((Document) obj); } else if (obj instanceof Node) { DOMStreamer domStreamer = new DOMStreamer(handler); handler.startDocument(); domStreamer.stream((Node) obj); handler.endDocument(); } else if (obj instanceof XMLizable) { ((XMLizable) obj).toSAX(handler); } else { throw new SAXException( "The object type: " + obj.getClass() + " could not be serialized to XML: " + obj); } }
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 ww. jav a2s . 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();//from ww w .ja v a 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.exist.xquery.modules.compression.AbstractExtractFunction.java
/** * Processes a compressed entry from an archive * * @param name The name of the entry/*from w ww . jav a 2 s . c o m*/ * @param isDirectory true if the entry is a directory, false otherwise * @param is an InputStream for reading the uncompressed data of the entry * @param filterParam is an additional param for entry filtering function * @param storeParam is an additional param for entry storing function * @throws XMLDBException */ protected Sequence processCompressedEntry(String name, boolean isDirectory, InputStream is, Sequence filterParam, Sequence storeParam) throws IOException, XPathException, XMLDBException { String dataType = isDirectory ? "folder" : "resource"; //call the entry-filter function Sequence filterParams[] = new Sequence[3]; filterParams[0] = new StringValue(name); filterParams[1] = new StringValue(dataType); filterParams[2] = filterParam; Sequence entryFilterFunctionResult = entryFilterFunction.evalFunction(contextSequence, null, filterParams); if (BooleanValue.FALSE == entryFilterFunctionResult.itemAt(0)) { return Sequence.EMPTY_SEQUENCE; } else { Sequence entryDataFunctionResult; Sequence uncompressedData = Sequence.EMPTY_SEQUENCE; //copy the input data ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int read = -1; while ((read = is.read(buf)) != -1) { baos.write(buf, 0, read); } byte[] entryData = baos.toByteArray(); if (entryDataFunction.getSignature().getArgumentCount() == 3) { Sequence dataParams[] = new Sequence[3]; System.arraycopy(filterParams, 0, dataParams, 0, 2); dataParams[2] = storeParam; entryDataFunctionResult = entryDataFunction.evalFunction(contextSequence, null, dataParams); String path = entryDataFunctionResult.itemAt(0).getStringValue(); Collection root = new LocalCollection(context.getUser(), context.getBroker().getBrokerPool(), new AnyURIValue("/db").toXmldbURI(), context.getAccessContext()); if (isDirectory) { XMLDBAbstractCollectionManipulator.createCollection(root, path); } else { Resource resource; File file = new File(path); name = file.getName(); path = file.getParent(); Collection target = (path == null) ? root : XMLDBAbstractCollectionManipulator.createCollection(root, path); MimeType mime = MimeTable.getInstance().getContentTypeFor(name); try { NodeValue content = ModuleUtils.streamToXML(context, new ByteArrayInputStream(baos.toByteArray())); resource = target.createResource(name, "XMLResource"); ContentHandler handler = ((XMLResource) resource).setContentAsSAX(); handler.startDocument(); content.toSAX(context.getBroker(), handler, null); handler.endDocument(); } catch (SAXException e) { resource = target.createResource(name, "BinaryResource"); resource.setContent(baos.toByteArray()); } if (resource != null) { if (mime != null) { ((EXistResource) resource).setMimeType(mime.getName()); } target.storeResource(resource); } } } else { //try and parse as xml, fall back to binary try { uncompressedData = ModuleUtils.streamToXML(context, new ByteArrayInputStream(entryData)); } catch (SAXException saxe) { if (entryData.length > 0) uncompressedData = BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), new ByteArrayInputStream(entryData)); } //call the entry-data function Sequence dataParams[] = new Sequence[4]; System.arraycopy(filterParams, 0, dataParams, 0, 2); dataParams[2] = uncompressedData; dataParams[3] = storeParam; entryDataFunctionResult = entryDataFunction.evalFunction(contextSequence, null, dataParams); } return entryDataFunctionResult; } }
From source file:org.exist.xquery.modules.xslfo.RenderFunction.java
@Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { // gather input XSL-FO document // if no input document (empty), return empty result as we need data to // process//from w w w . jav a2 s . co m if (args[0].isEmpty()) { return Sequence.EMPTY_SEQUENCE; } Item inputNode = args[0].itemAt(0); // get mime-type String mimeType = args[1].getStringValue(); // get parameters Properties parameters = new Properties(); if (!args[2].isEmpty()) { parameters = ModuleUtils.parseParameters(((NodeValue) args[2].itemAt(0)).getNode()); } ProcessorAdapter adapter = null; try { adapter = ((XSLFOModule) getParentModule()).getProcessorAdapter(); NodeValue configFile = args.length == 4 ? (NodeValue) args[3].itemAt(0) : null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ContentHandler contentHandler = adapter.getContentHandler(context.getBroker(), configFile, parameters, mimeType, baos); // process the XSL-FO contentHandler.startDocument(); inputNode.toSAX(context.getBroker(), contentHandler, new Properties()); contentHandler.endDocument(); // return the result return BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), new ByteArrayInputStream(baos.toByteArray())); } catch (SAXException se) { throw new XPathException(this, se.getMessage(), se); } finally { if (adapter != null) { adapter.cleanup(); } } }