Oracle® Containers for J2EE Services Guide
10g Release 3 (10.1.3) B14427-01 |
|
![]() Previous |
![]() Next |
This chapter describes how to use XML Query Service (XQS), a new service in the OC4J 10.1.3 implementation that provides a convenient user model for the retrieval, analysis, integration, and transformation of enterprise data. The following topics are covered:
This section introduces the XML Query Service, providing a brief overview of XQS and related technologies that it is built upon. This discussion includes the following:
XQS is an OC4J service built upon XQuery (the XML query language) to provide a simplified, declarative mechanism for creating integrated views of enterprise data.
Generally, without a service such as XQS, XQuery is limited to accessing XML documents. With XQS, you can also retrieve data from non-XML documents, relational databases, and other possibly non-XML enterprise information systems, through access mechanisms such as SOAP or SQL.
XQS simplifies your programming task. In the planning stages, you need only focus on the design of your XQuery expressions (queries, built-in function calls, or user-defined function calls) and the structure of the data. The details of accessing data sources are determined later, through configuration settings—this is where a binding occurs between your XQuery expressions and the data to be accessed. XQS then does the work of creating external XQuery functions, referred to as XQS functions, used in retrieving the data from the desired sources.
XQS supports ad-hoc queries, which are XQuery expressions passed in at runtime, or XQS views, which are queries you created and saved previously. A view becomes an XQuery function that you can access later by name. (XQuery itself does not yet support the concept of views.) Views allow you to reuse XQuery expressions in building hierarchical queries that are powerful and yet easily maintainable.
XQS offers a variety of client interfaces, allowing you to execute your XQuery expressions through an EJB, a JSP tag library, a Java class, or a Web service.
This section offers a glance at technologies that XQS is built upon:
Note: For introductory tutorials for these and related technologies, you can try the following site (among many others):
|
XQuery is a declarative language for querying and transforming XML data. You can intelligently query an XML source, using desired criteria, and retrieve and interpret elements and attributes and the data they contain. It is a standard and flexible technology that applies broadly across many and varied kinds of XML sources, including XML databases as well as XML documents. Its role is comparable to the role SQL plays in querying a relational database, with similar functionality.
In addition to querying data, XQuery can transform XML data. In this way, it can be used as a complement or an alternative to XSLT.
In XQuery, the basic construct is an expression, with the data model for expressions being based on XPath 2.0. Each XQuery result is returned as an XML sequence. This is a sequence of zero or more data items, where each item is a scalar value, XML node, or XML document. Type definitions for items are based on the XML Schema standard.
A query may consist of one or more fragments called modules, and a module may consist of a prolog followed by a query body. A prolog is a series of declarations and imports that define the processing environment for the module.
The general model for a query in XQuery is the "for-let-where-order-return" (FLWOR) expression. Here is pseudocode showing an example of what a FLWOR expression could accomplish:
For each department in depts.xml Let [variable] represent each employee in each department Where the headcount of employees in a department is at least 10 Order by average salary of department Return headcount and average salary of each department
XQuery also allows the definition and use of predefined functions to perform queries. For more complex queries, external functions may be provided separately, then declared and invoked from your XQuery definition. External functions may be implemented in a variety of languages, including Java and SQL.
The use of external functions is a critical part of XQS functionality. XQS creates external functions, according to your XQS configuration, to execute the desired queries on your data.
Notes:
|
The Oracle XQuery implementation in Java is an underlying engine for XQS and is provided as part of the XML Query Service. Do not confuse this with the Oracle XQuery implementation that is part of Oracle XML DB in the Oracle Database product, although the two have common origins and common features.
Oracle's XQuery implementation uses the type oracle.xml.xqxp.datamodel.XMLItem
to represent an individual item in the result XML sequence of a query.
Predefined Namespaces and Prefixes
The following table lists predefined namespaces and prefixes for use with XQuery and XQS.
Table 8-1 Predefined Namespaces and Prefixes
Prefix | Namespace | Description |
---|---|---|
ora |
http://xmlns.oracle.com/xdb |
Oracle XML DB namespace |
local |
http://www.w3.org/2003/11/xpath-local-functions |
XPath local function declaration namespace |
fn |
http://www.w3.org/2003/11/xpath-functions |
XPath function namespace |
xdt |
http://www.w3.org/2003/11/xpath-datatypes |
XPath datatype namespace |
xml |
http://www.w3.org/XML/1998/namespace |
XML namespace |
xs |
http://www.w3.org/2001/XMLSchema |
XML Schema namespace |
xsi |
http://www.w3.org/2001/XMLSchema-instance |
XML Schema instance namespace |
You can use these prefixes in XQuery expressions without first declaring them in the XQuery-expression prolog. You can redefine any of them except xml
in the prolog. All of these prefixes except ora
are predefined in the XQuery standard.
Oracle XQuery Extension Functions
The Java version of Oracle XQuery includes support for ora
extension functions first introduced in the database version, including the following:
ora:contains
lets you restrict a structural search with a full-text predicate.
ora:matches
lets you use a regular expression to match text in a string.
ora:replace
lets you use a regular expression to replace text in a string.
ora:sqrt
lets you return the square root of a number.
ora:view
lets you query existing database tables or views inside an XQuery expression, as if they were XML documents. In effect, this function creates XML views over the relational data.
For more information about these functions, refer to the XQuery chapter of the Oracle XML DB Developer's Guide.
Note: At the time of this release, the W3C XQuery working group had not yet published the XQuery recommendation. Oracle will continue to track the evolution of the XQuery standard, until such time as it becomes a recommendation. During this period, in order to follow the evolution of the XQuery standard, Oracle may be forced to release updates to the XQuery implementation which are not backwards compatible with previous releases or patch sets. During this period Oracle does not guarantee any backward compatibility between database releases or patch sets with respect to our XQuery implementation. After the XQuery standard becomes a recommendation, Oracle will produce a release or patch set that includes an implementation of the XQuery recommendation. From that point on, standard Oracle policies with respect to backwards compatibility will apply to the Oracle XQuery implementation. Seehttp://www.w3.org for the latest information on the status of XQuery.
|
Implementation Choices Specified in the XQuery Standard
Implicit time zone support: In XQuery in XQS, the implicit time zone is always assumed to be Z
.
Implementation Departures from the XQuery Standard
Boundary condition differences, for +0 and -0: The XQuery standard distinguishes positive zero from negative zero, but XQuery in XQS does not. Both are presented as 0, and they are treated equally.
XQuery Optional Features
There is currently no support for the following optional XQuery features defined by the W3C:
Schema Import Feature
Schema Validation Feature
Module Feature
In addition to these defined optional features, the W3C specification allows an implementation to provide implementation-defined pragmas and extensions. These include the following:
Pragmas
Must-understand extensions
Static-typing extensions
The Oracle implementation does not require any such pragmas or extensions.
Support for XQuery Functions and Operators
XQS supports all of the XQuery functions and operators included in the latest specification with the following exceptions, for which there is no support:
XQuery regular-expression functions.
Use the Oracle extensions for regular-expression operations, instead
Functions fn: trace
, fn:id
, fn:idref
, fn:codepoint-equal
, fn:prefix-from-QName
, fn:doc-available
, and fn:collection()
(fn:collection()
without any argument)
XQuery Functions doc and collection
XQuery built-in functions fn:doc
and fn:collection
are essentially implementation-defined. XQS supports these functions. Function doc
retrieves a file from the local file system that is targeted by its URI argument; it must be a file of well-formed XML data. Function collection
is similar, but works on a folder (each file in the folder must contain well-formed XML data).
The XQuery API for Java (XQJ) is an evolving standard for executing XQuery expressions from Java applications. (Refer to JSR-225.) It is a low-level programmatic interface comparable to JDBC. Because it is not yet a standard, however, XQJ is not yet supported in the 10.1.3 implementation of the Oracle Application Server.
XQS supplies a higher-level API for similar underlying functionality. You can execute XQuery expressions from Java without having to write code to connect to the data source, create XQuery expression objects, and so on.
XQS is versatile. It is useful for Web services as well as Java applications, and for accessing non-XML data as well as XML data.
XQS also relieves you of coding steps such as using the low-level XQJ interface to execute an XQuery expression. The XQS model of data source access through non-programmatic configuration allows faster and more convenient development. Also, registration of the library for the external functions that XQS creates is handled automatically, and namespace assignment is flexible and within your control.
As well as being used to retrieve data, XQS can serve as a convenient mechanism for transforming XML data or joining data from multiple sources.
In addition, XQS offers the following advantages and conveniences:
The XQS configuration model allows you to create queries that are independent of the particular data source or XML document you access, making your application more portable. You need only alter your XQS configuration for a different source or document location.
Use of the "XQS views" feature allows more convenient hierarchical queries, as well as allowing queries to be shared, reused, and centrally maintained.
Through the use of performance optimizations in cooperation with other Oracle Application Server and Oracle Database components, a query executed through XQS is expected to perform at least as well as, and typically better than, the hand-coded XQJ equivalent. XQS itself offers additional performance enhancements, including configurable caching for source data and results, and efficiencies in handling large data sets.
XQS simplifies migration between the middle tier and database tier. If a data source outgrows middle-tier capacity, you can typically migrate data to Oracle XDB without modifying or redeploying your middle-tier application. Move your data to the database and update your configuration for that data source as appropriate. Other middle-tier data sources can remain on the middle tier.
Also see "Introduction to XQS Performance and Optimization Features".
Be aware of the following for the XQS 10.1.3 implementation:
XQS uses the OC4J Java Object Cache for its caching. It requires that the cache be running (automatically starting it if necessary), and requires the presence of the Java Object Cache configuration file. See "Configuring XQS Caching" for additional information about caching.
Due primarily to limitations of the current XQuery specification, XQS reads from data sources but cannot write to data sources. You can query data, but not update, insert, or delete data.
Within the set of nodes (as defined by the XML data model) returned by a function call, each node has a unique identity. But if a function is called more than once in a query, XQS does not guarantee the uniqueness of node identities across the different result sets. Because of this, some queries based on node identity may produce nondeterministic results. As an example, consider the following queries, Q1 and Q2:
(: Q1 :) declare namespace xqs="http://xmlns.oracle.com/ias/xqs"; declare function xqs:a() external; let $x := xqs:a() return $x/b is $x/b
Q1 will always return true
, given that the node identity test is on nodes from the same function call.
(: Q2 :) declare namespace xqs="http://xmlns.oracle.com/ias/xqs"; declare function xqs:a() external; xqs:a()/b is xqs:a()/b
Q2 may return true
or false
, depending on certain performance optimization settings.
This section introduces important XQS features. Further details are provided later in the chapter.
As noted previously, XQS supports several different kinds of data sources. This section covers the following related topics:
In XQS, data sources requiring a variety of access protocols can be described through WSDL documents because of XQS support for the popular Apache Web Services Invocation Framework (WSIF), an extension of the Web service mechanism behind SOAP and HTTP to include any custom invocation protocols. Because of this mechanism, XQS supports WSDL-based sources other than SOAP-based Web services.
In all, XQS supports the following categories of data sources, with special features to access various kinds of sources through a WSDL document.
Document: Access files or, more generally, any URL-based input streams that contain XML documents. This is similar to the functionality of the built-in XQuery function fn:doc()
. XQS supports the Oracle Data Definition Description Language (D3L) translator plug-ins to convert non-XML data to XML, so non-XML files are supported as well.
XQS view: Run a previously stored query (similar in concept to database stored procedures). XQS locates the query, binds any external variables, and executes the query.
WSDL source with SOAP binding: Access a resource through a Web service. You must provide a WSDL document, with a SOAP binding, to describe the Web service operations and the data source.
WSDL source with SQL binding: Access tables, views, PL/SQL stored procedures, or Java stored procedures in a relational database. This is accomplished through the XQS WSIF provider for SQL, a binding that is defined by Oracle. See "Preparing to Use a Database Source (WSDL Source with SQL Binding)" for information. You must provide a WSDL document with a SQL binding. XQS converts a relational result set to an XML sequence by invoking the Oracle XML-SQL Utility. XQS gets connection information for the appropriate data source, as specified in the WSDL, from the OC4J data-sources.xml
configuration file.
The XQS fetchSize
attribute for WSDL sources with SQL binding recommends a number of rows for JDBC to fetch from the database in one round trip. This attribute is translated into a call to the setFetchSize
method of java.sql.PreparedStatement
. The setFetchSize
parameter in JDBC (and, therefore, the fetchSize
attribute in XQS) is only a hint: it is not binding.
WSDL source with Java or EJB binding: Access a resource through any custom Java class or EJB that returns XML data. This is accomplished through the WSIF provider for Java or WSIF provider for EJB. You must implement the class or EJB and provide a WSDL document with a Java or EJB binding, specifying the class name or EJB name and any argument types.
A WSDL document that you provide for any of the WSDL sources will describe a set of callable operations and provide specifics for connecting to the source, using the appropriate binding. Your XQS configuration will reference a name for each operation, and point to the WSDL for the description of the operation. The WSDL must have a working URL, which you specify in your XQS configuration. XQS will go to that URL to fetch the WSDL. Also note that XQS allows you to use a WSDL URL as an XQuery namespace, and to treat individual operations of a WSDL port as local names in that namespace.
Access of your data sources and execution of your operations are accomplished through external XQuery functions, referred to as "XQS functions" (introduced earlier), that XQS automatically creates and invokes for you based on your XQS configuration. You specify the desired name and namespace of the function in your configuration, along with other relevant items (input parameters, for example). When you use a data source in a query, you must declare the associated XQS function as an external function in your XQuery prolog.
A namespace corresponds to a function library containing function objects. Each function object corresponds to an operation. For a WSDL source with SOAP binding, for example, there is a function object for each operation in the WSDL document. For a WSDL source with SQL binding, each SQL query or stored procedure call maps to a function.
Each function object created by XQS is instantiated according to your XQS configuration, and performs the following basic tasks:
Accepts input arguments passed from the XQuery engine. Permissible input types are according to what is allowable in an XML sequence; namely, primitive Java types and XML nodes. XQS cannot perform Java object-to-XML mapping, but you can perform mapping prior to the query, such as through Oracle TopLink.
Invokes the query against the underlying data source. XQS maps the function name to the corresponding XQS configuration element, then finds the connection information for the data source and creates the connection.
Receives and packages results. XQS synchronously receives results from the data source, in XML form, then packages the results into an XML sequence.
Processes any errors (such as problems accessing a data source, for example, or type incompatibilities) and returns error information according to your error-handling configuration.
For most data sources you can use with XQS, there are necessary preparation steps. For example:
To use a non-XML document source, you must prepare to use the conversion tool, Oracle D3L, that XQS supplies. Preparation includes providing a D3L schema file with instructions about the data format.
To use an XQS view, you must consider the data input and return types, design the query, save it as an .xq
file, and decide where to place it.
To use a WSDL source with any of the supported bindings, you must provide (in some cases, create) an appropriate WSDL document.
See "How to Prepare to Use Your Data Sources" for details.
As is true with OC4J and its other components as well, XQS has the concept of global configuration versus application-specific configuration. Global configuration is for XQS functions and data sources that are to be available to all applications running in the OC4J instance, as opposed to being available only to a particular application.
The application-specific XQS configuration file is xqs-config.xml
, which XQS looks for in the xqs-resources.jar
file (created by the OC4J packaging utility) at the top level of the application EAR file. Use it to specify information about XQS functions and data sources specific to your application.
The global XQS configuration file is global-xqs-config.xml
, in the ORACLE_HOME
/j2ee/home/config
directory, which you can use to specify sources available to all applications.
When XQS looks for configuration for an XQS function, it first looks in the application-level file. If (and only if) it does not find it there, it will look in the global file. (In other words, if a function is configured in both files, it is ignored in the global file.)
The top-level elements are as follows:
<document-source>
to access data from a document, including either XML or non-XML files
<xqsview-source>
to use an XQS view
<wsdl-source>
for any data source involving a user-provided WSDL document
XQS reads information from the configuration file and uses that information to populate the XQS function objects that access the data sources.
You do not have to restart OC4J when you update configuration, but you must redeploy the application. (See the Oracle Containers for J2EE Deployment Guide for information.)
See "How to Configure Your XQS Functions" for additional information.
Note: In the 10.1.3 implementation of the Oracle Application Server, there are not yet any pages for XQS configuration in the Oracle Enterprise Manager 10g Application Server Control Console. Although MBeans are available (summarized for reference in "Summary of XQS MBeans and Administration"), we recommend for the current release that you manage your XQS configuration directly in thexqs-config.xml file.
|
XQS supports the following client interfaces for implementing your XQuery functionality. See "How to Develop Your Application Code: Using the XQS Client Interfaces" for usage information and examples for each of these interfaces.
Note: When you use any of the XQS client APIs for a query, the query execution defines the results, but does not necessarily put all the results into memory immediately. A set of results that is immediately and fully stored into memory is said to be materialized, whereas a set of results accessed one at a time (or several at a time, with batching) through an implicit cursor, using some sort of "next item" functionality, is said to be nonmaterialized. With nonmaterialized results, there is no guarantee as to when results are retrieved and written to memory. Any "next item" call may trigger the evaluation of the XQuery expression to produce the next result item.As noted in the descriptions that follow, XQS client APIs allow you the choice of using stateless client objects, with materialized results, or using stateful client objects, with nonmaterialized results. These concepts are discussed in further detail, and with strategic considerations, in "Stateful Versus Stateless Clients". |
Java class client API: XQS provides a general-purpose Java class, XQSFacade
, that you can use for a Java implementation of desired XQuery functionality. This class is based on the "facade" design pattern, shielding you from details and complexities of the underlying XQS functionality. Use the appropriate "execute" method to pass in an ad-hoc query or XQS view name and any bind parameters. In either case, use the "get next item" method to process the results. An XQSFacade
instance returns an XML result sequence directly to the client, meaning it is up to the client whether to retrieve and process items from the sequence incrementally (a stateful approach), or to retrieve and process all items from the sequence at once (a stateless approach).
Note: TheXQSFacade class is also used behind the scenes for the EJB client API and JSP tag library.
|
EJB client API: The EJB client API provides a way to access your application through session beans, either remotely (through RMI) or locally. XQS supports the use of either stateful or stateless session beans. Stateless beans minimize calls to the EJB, while stateful beans are preferable if memory usage is a concern. In either case, you provide the ad-hoc query or XQS view name, along with any bind parameters, in the appropriate "execute" method. For a stateful session bean, you use the "get next item" method to process the results. For a stateless session bean, the sequence is always materialized and is returned by the "execute" method.
JSP tag library: The JSP tag library provides a way to access your application through HTTP. XQS provides JSP tags for either stateful or stateless access. You provide the ad-hoc query or XQS view name using an "execute" or "executeCursor" tag. Which tag to use depends on whether you want stateful or stateless access. There is a nested "parameter" tag for specifying bind parameters. For stateful access, you use the "next" tag associated with the "executeCursor" tag to process the results. For stateless access, the sequence is always materialized and is returned by the "execute" tag. Results can be returned as a JSP output stream, a DOM document, or an array of Java Object
instances (according to attribute settings of the "execute" or "executeCursor" tag).
XQS view Web service: When you use an XQS view, you can optionally have XQS add an operation to a WSDL document that it creates, to expose the view as a Web service operation. (This is accomplished as part of the configuration for an XQS view.) You can then implement a client for this as you would for any other Web service.
Note: Also be aware of the XQSQueryParameter class. To use queries with external binds for the Java client API or EJB client API, you must create an array of QueryParameter objects for the bind values. See "XQS QueryParameter Class Reference" for reference information. (This class is also used behind the scenes for the JSP client interface.)
|
OC4JPackager, provided with XQS, is a command-line Java tool that packages XQS-related files with a J2EE or Web application to allow the application to use XQS functionality.
In a typical scenario, you would write a Web application that calls XQS through one of the XQS client APIs (the XQSFacade
class, EJB client API, or JSP tag library). You would also create an XQS configuration file, xqs-config.xml
, that points to the relevant data sources and XQS views, and choose an XQS repository—the directory where your views are located. Then you would bundle your application, XQS configuration file, and XQS repository into an EAR file, which you then deploy.
Given instructions through its command-line parameters, OC4JPackager will complete the step of bundling everything for you. Specifically, it does the following:
Bundles xqs-config.xml
and all XQS repository files into a file called xqs-resources.jar
.
Opens each archive associated with your application (such as WAR files and EJB JAR files) and modifies the Class-Path
attribute in the manifest (MANIFEST.MF
) to include xqs-resources.jar
.
Bundles an EAR archive that consists of all your application archive files plus xqs-resources.jar
.
Creates or modifies (as applicable) the orion-application.xml
file in the EAR archive to add xqs-resources.jar
to the list of libraries accessible by all components of the EAR.
When you run OC4JPackager, you specify a directory that contains one of the following:
An existing EAR file, which OC4JPackager will unbundle and rebuild
An existing set of J2EE modules such as WAR and EJB JAR files, which OC4JPackager will bundle into a new EAR.
For an XQS view that you want to expose as a Web service operation, OC4JPackager performs additional tasks, delegating invocation of the Web service operation to the XQS view. The operation is added to a WSDL document that is automatically generated. For more information see "OC4JPackager Additional Output to Expose XQS Views as Web Service Operations".
For more information about OC4JPackager in general, see "How to Use OC4JPackager to Package Your XQS Application" and "OC4JPackager Reference".
XQS itself does not add any layers of security. In this way, it is essentially like any J2EE application. Security is provided by OC4J through standard Web and J2EE security features that you must use, as appropriate for the type of XQS client you are using and the type of data source you are accessing.
For example, if you are using a WSDL source with a SQL binding, use data source security features. If you are using the XQS EJB client interface, use standard EJB security. If you are using the XQS JSP tag library, use standard authentication for an HTTP connection. And so on.
XQS offers the following features to improve performance:
Caching: XQS can cache the results of XQS view execution, or cache XML data from data sources for use in future queries. This improves performance, particularly for situations where data sources, such as external Web services, may require significant time to access. Caching is also important when accessing asynchronous sources. You can specify expiration and invalidation settings for cached data, or optionally disable caching entirely, through your XQS configuration.
Handling of large data sets: XQS has features to minimize the chance of running out of system memory when you access very large data sets, such as dozens of megabytes or more. In such situations, XQS will materialize the results partially, as the data is needed, staying within a fixed amount of memory usage (a "working unit" approach). You have the option of returning data items one by one.
Scalability: XQS efficiently streams inputs to the XQuery engine, allows sharing and reuse of cached resources (such as parsed WSDL documents), and can use non-materialized result sequences as appropriate for scalability. You can control these behaviors through your XQS configuration.
See "Using XQS Performance Features" for more information.
Note: While XQS works in close conjunction with the Oracle XQuery engine and XDK to optimize data flow, XQS does not optimize the queries. |
An XQS application may encounter problems related to XQS external functions and the underlying data sources during execution, such as problems converting input parameters to types expected by the data source, or problems converting data returned by the data source to XML. In addition, the data source may be unavailable or may return an error. The default behavior of XQS is to raise an XQuery dynamic error in these situations, which stops execution of a query, with no results being returned.
Alternatively, an XQS configuration attribute (onError
) allows you to choose less severe behaviors, allowing XQS to continue so you can obtain additional information about any errors that occurred. Three error-handling modes are available:
dynamicError
(default)
emptySequence
errorMessage
With emptySequence
or errorMessage
mode, if an error is encountered during execution of an XQS external function for which this mode has been set, the error does not terminate query execution, and will be retained by XQS for later retrieval if desired. XQS returns an empty XML sequence (for emptySequence
mode) or a one-item XML sequence consisting of an error message (for errorMessage
mode). In errorMessage
mode, you can preconfigure a fixed error message in your XQS configuration, or you can have the message be whatever is returned by the data source.
Information about "suppressed" errors from XQS external functions is returned by XQS in an iterator of XQSError
objects.
XQS applies special handling only to errors inside an XQS function. A regular XQuery error, such as a syntax error or type mismatch, terminates query execution regardless of the XQS error mode.
You configure the XQS error mode for each XQS function individually. The error mode for one function does not have any affect on the behavior of other XQS functions in the same query.
See "Using XQS Error Handling Modes and APIs" for more information.
The following are the key steps in using XQS. Links are provided to the sections that cover each step in detail.
Enable XQS as an OC4J extension.
For an instance of OC4J that Oracle Process Management and Notification (OPMN) manages, you can enable XQS by adding the following Java system property to the ORACLE_HOME
/opmn/conf/opmn.xml
configuration:
-Doracle.hooks=oracle.xds.XDSExtension
After configuring opmn.xml
, you can use Oracle Enterprise Manager (OEM) or the OPMN tool to start or stop XQS with the OC4J instance. See "How to Enable XQS As an OC4J Extension".
For a standalone instance of OC4J, pass following Java system property to the OC4J container:
-Doracle.hooks=oracle.xds.XDSExtension
You can pass this property on the command line, as follows:
java –jar oc4j.jar -Doracle.hooks=oracle.xds.XDSExtension
Or you can pass it by using the Ant task startoc4j.
See the Oracle Application Server Installation Guide for more details regarding various OC4J starting options. XQS users need to pass the additional Doracle.hooks parameter, as the preceding text describes.
Prepare your data sources as necessary. For a document source, for example, this would include any setup to convert from non-XML to XML. For XQS views, this includes defining and saving the queries. Some access of WSDL-based sources, such as databases, also requires special setup. See "How to Prepare to Use Your Data Sources".
Configure XQS. Use the xqs-config.xml
(or global-xqs-config.xml
) file to specify and configure data sources to be accessed and queries to be executed, and to create mappings to the XQS functions that represent the data sources for the queries. See "How to Configure Your XQS Functions".
Design your queries. See "How to Design Your Queries".
Develop your application. This primarily involves using one of the APIs that XQS provides to execute your XQuery expressions, and processing the XML results that are returned. See "How to Develop Your Application Code: Using the XQS Client Interfaces".
Package and deploy your application. Use the packager supplied with XQS. See "How to Use OC4JPackager to Package Your XQS Application".
Note: This is a simplification. Typically, you cannot actually go through the steps in a modular, sequential manner, especially with multiple sources that may include XQS views. The process is iterative. For example, you could start by preparing a database source and then design a query for it. Then you may want to persist the query as an XQS view—in other words, prepare an XQS view source. Then you may design another query that uses the view. |
For an OPMN-managed instance of OC4J, you can edit the ORACLE_HOME
/opmn/conf/opmn.xml
configuration to enable XQS as an OC4J extension. Add the following Java system property to the start-parameters
category in the OC4J
module of the IAS component:
-Doracle.hooks=oracle.xds.XDSExtension
For example:
<ias-component id="OC4J">
<process-type id="home" module-id="OC4J" status="enabled">
<module-data>
<category id="start-parameters">
<data id="java-options" value="-server -Djava.security.policy=$ORACLE_HOME/j2ee/home/config/java2.policy -Djava.awt.headless=true -Dhttp.webdir.enable=false -Doracle.hooks=oracle.xds.XDSExtension/>
</category>
<category id="stop-parameters">
<data id="java-options" value="-Djava.security.policy=$ORACLE_HOME/j2ee/home/config/java2.policy -Djava.awt.headless=true -Dhttp.webdir.enable=false"/>
</category>
</module-data>
<start timeout="600" retry="2"/>
<stop timeout="120"/>
<restart timeout="720" retry="2"/>
<port id="default-web-site" range="12501-12600" protocol="ajp"/>
<port id="rmi" range="12401-12500"/>
<port id="jms" range="12601-12700"/>
<process-set id="default_group" numprocs="1"/>
</process-type>
</ias-component>
After you configure opmn.xml
, you can start or stop an OC4J instance, including XQS, with EM or the OPMN tool.
For a standalone instance of OC4J, pass following Java system property to the OC4J container:
-Doracle.hooks=oracle.xds.XDSExtension
You can pass this property on the command line, as follows:
java –jar oc4j.jar -Doracle.hooks=oracle.xds.XDSExtension
Or you can pass it by using the Ant task startoc4j.
For most data sources you want to use with XQS, there are necessary preparation steps. This section covers the following topics:
Preparing to Use a Database Source (WSDL Source with SQL Binding)
Preparing to Use a Custom Class or EJB (WSDL Source with Java or EJB Binding)
Some documents do not use XML as their native message format, instead using native formats such as structured records of bytes and characters. Examples of this are Excel comma-separated-values (CSV) files. For non-XML data to be understandable for use with XQS and XQuery, it must follow a predefined, structured set of rules so that XQS can use an appropriate conversion tool. Data in such a structured format can be processed so that it can be retrieved and transformed into an XML format for your application.
For use of non-XML documents, the XQS 10.1.3 implementation supports the Oracle Data Definition Description Language (D3L). Prepare to use a non-XML document source with XQS by taking the following steps:
Ensure that the non-XML data is compatible with the D3L conversion mechanism.
Provide a schema file that gives instructions to D3L about the data format, so D3L can parse and convert the data.
Configure XQS to use D3L, specifying the name and location of the schema file.
The following sections provide an overview of D3L and its usage:
Note: See the Oracle Application Server Integration InterConnect User's Guide for details about D3L features. |
D3L describes the structure that must be followed by the native, non-XML format of a document to allow processing by certain Oracle middle-tier components—in general, by OracleAS Integration InterConnect; for purposes of this document, by XQS.
D3L supplies the following:
An XML-based data description language that describes the format of native files, such as the record layout of binary, string, structured, and sequence data
A translation engine that uses the instructions from a D3L schema file to translate the native format file contents
D3L schema files must comply with the syntax defined by the D3L document type definition (DTD). You specify the D3L schema file to use through your XQS configuration.
Important: To use D3L, the number of fields in the underlying native format data must be fixed and known. D3L is not suitable for arbitrarily structured data (such as regular XML), name-value pair data, or conditional data structures that require token look-aheads to parse. |
A D3L schema file describes data types, formats, and delimiters so that the D3L translation engine can parse the data and convert it to XML. The schema file must conform to the specifications of d3l.dtd
.
Refer to the Oracle Application Server Integration InterConnect User's Guide for details about D3L schema files and how to create them, but here is a fragment to give you a general idea of their appearance:
<?xml version="1.0" encoding="US-ASCII"?> <!DOCTYPE message SYSTEM "d3l.dtd"> <message name="replyFlight" type="BookingReplyType" object="Booking" header="D3L-Header" value="replyOptions"> <unsigned4 id="u4" /> <unsigned2 id="u2" /> <struct id="DateTimeRecord"> <field name="DateInfo"> <date format="MMDDYY"> <pfxstring id="datstr" length="u4" /> </date> </field> <field name="TimeHour"><limstring delimiter="*" /></field> <field name="TimeMinute"><limstring delimiter="*" /></field> </struct> ... </message>
To have XQS use the D3L conversion mechanism for a non-XML document source:
Use the <XMLTranslate>
subelement of <document-source>
to direct XQS to use D3L. (In the future, other tools may be supported as well, and specified in the same way.)
Use the <schema-file>
subelement of <XMLTranslate>
to specify the schema file for D3L to use in parsing the data.
Here is the XQS configuration to use a D3L schema file named PersonalInfoD3L.xml
:
<document-source ... > ... <XMLTranslate method="D3L"> <schema-file>http://host:port/xqs/PersonalInfoD3L.xml</schema-file> </XMLTranslate> ... </document-source>
Notes:
|
As noted earlier, an XQS view is a query that is stored for future use. XQS treats the view itself as a source, and you configure it through an <xqsview-source>
element. To prepare to use a query as an XQS view, do the following:
Consider any input parameters that the query will require. You can specify a parameter for an XQS view by declaring it as an external variable in the XQuery prolog.
Design the query, including external variable declarations for any input parameters, and save it as an .xq
file. (Also see "How to Design Your Queries".)
Consider where you will place the .xq
file. Your location for .xq
files is referred to as the XQS repository. You can specify a location through your XQS configuration (using the <repository>
element), or you can use a location you specify through the -repository
option when you run OC4JPackager.
Consider whether to expose the XQS view as a Web service operation. Do this through the WSDLvisibility
attribute of the <xqsview-source>
element in your XQS configuration. This results in the view being included as an operation in a Web service that XQS adds to your application. If you do expose the view as a Web service operation, be aware of the XML output type—we advise that you reflect that type in the <output-element>
subelement of <xqsview-source>
in your configuration. (Also see "Using an XQS View Exposed as a Web Service Operation" for additional information.)
Following is an XQuery expression that we will use for an XQS view. It accepts the external variable loc
and passes it through to a function readFile
that reads purchase order data from a file. You can use any desired .xq
file name to save it, and specify that name in your XQS configuration. You will also have to specify a desired name for the XQS function that XQS will implement to execute the view. The file name and function name are distinct, but you can use the function name as the base name of the file by default if you want.
declare variable $loc external; declare namespace xqs = "http://xmlns.oracle.com/ias/xqs"; declare function xqs:readFile($l as xs:string) external; for $po in xqs:readFile($loc)//po return $po//total
In your XQS configuration, under the <xqsview-source>
element, you will typically use at least the following:
The WSDLvisibility
attribute if you want to expose the view as a Web service operation, and then the <output-element>
subelement if you do expose the view
The <function-name>
subelement to specify the desired name of the XQS function for the view
The <input-parameters>
subelement and its subelements to specify external variables that correspond to input parameters of the XQS function (loc
in the preceding example)
The <queryName>
subelement to specify the name of the .xq
file containing the view (unless you use a base file name that matches the XQS function name)
The <repository>
subelement to specify the location of the .xq
file (not necessary if the file is in the location specified through the -repository
option when you run OC4JPackager)
Notes:
|
To access a data source through a Web service operation, you must provide a WSDL document for the Web service and specify the location of the WSDL in your XQS configuration. One XQS view function corresponds to one Web service operation that XQS will implement.
Examine the WSDL. You will use a <wsdl-source>
element and its subelements in the XQS configuration file to configure the XQS function, with configuration settings (some optional) corresponding to WSDL entries as follows:
The WSDL operation corresponds to an <operation>
element in the XQS configuration.
For WSDL input messages, each input message part corresponds to a <part>
subelement of <input-parameters>
.
The applicable WSDL service corresponds to a <service>
element.
The applicable WSDL port corresponds to a <port>
element.
The applicable WSDL port type corresponds to a <portType>
element.
In addition, consider how the WSDL document may be accessed by XQS, and specify this location using the <wsdlURL>
element.
Notes:
|
The XQS WSIF provider for SQL allows you to use XQuery on data fetched from a relational database that is accessed through SQL. To use this feature, you must provide a WSDL document that specifies SQL binding and contains complete information about any SQL operations (queries or stored procedure calls) to perform.
As an initial summary, be aware of the following for the WSDL document:
For connection information, the WSDL refers to a JNDI name, and XQS looks in the OC4J data-sources.xml
configuration file for the data source associated with that JNDI name.
The WSDL specifies the SQL statement for each operation. Each WSDL operation is for a single SQL statement (and corresponds to a single XQS function, as noted earlier).
The XQS fetchSize
attribute for WSDL sources with SQL binding recommends a number of rows for JDBC to fetch from the database in one round trip. This attribute is translated into a call to the setFetchSize
method of java.sql.PreparedStatement
. The setFetchSize
parameter in JDBC (and, therefore, the fetchSize
attribute in XQS) is only a hint, not a binding.
Each WSDL operation must use a predefined message type, SQLOutputMessage
, for the output message. This is defined in the Oracle xqs.wsdl
document, which you can import into your WSDL as discussed below. The output message contains one part, named result
, corresponding to the root of the XML document containing the query results. The result
type is defined in the XQS types namespace:
http://xmlns.oracle.com/ias/xqs/types/
Each WSDL operation must use a predefined message type, SQLFaultMessage
, for fault messages. This is also defined in xqs.wsdl
. The fault message contains two parts: code
for the error code and message
for the error message. These are also defined in the XQS types namespace.
Each operation can specify an XML transform to use for non-XML data. Currently only the Oracle XML-SQL Utility (XSU) is supported.
Specifically, you must use the XQS SQL extensions in your WSDL as follows (and as shown in the example afterward).
WSDL Definitions and Imports
Declare the namespaces and associated prefixes for XQS, XQS types, and the XQS SQL extensions. (By convention, in discussion that follows, we use the "sql:" prefix for XQS SQL extensions.)
Import xqs.wsdl
to define SqlOutputMessage
and SqlFaultMessage
. The xqs.wsdl
document is available with the XQSDemo
application, so that you can place it in the same directory as your WSDL document. Alternatively, you can import it from the following location:
<import namespace="http://xmlns.oracle.com/ias/xqs/" location="http://www.oracle.com/technology/tech/xml/xqs/xqs.wsdl" />
Input Message Declarations
If your SQL query uses bind variables, you must specify an input message with a part for each bind variable, where the part types match the required bind variable types.
WSDL Port Type Declarations
For each operation:
Use message="xqs:SqlOutputMessage"
for the <output>
element.
Use message="xqs:SqlFaultMessage"
for the <fault>
element.
WSDL Binding Declarations
In the <binding>
element:
Use an empty <sql:binding/>
subelement.
For each operation, use a <sql:operation>
subelement with XMLtransform="XSU-Client"
and element contents specifying the SQL statement to execute.
For each operation input, use a <sql:input>
subelement to specify the names of the bind parameters. This is a comma-separated list of previously defined message part names, in the order in which they are to be bound to the SQL statement.
WSDL Service Declarations
Use a <sql:address>
element, setting the data-source-location
attribute to indicate the JNDI location of the data source, as configured in the OC4J data-sources.xml
file.
Sample WSDL with SQL Binding
<?xml version="1.0" ?> <definitions targetNamespace="http://xqstest.sql.scott/" xmlns:scott="http://xqstest.sql.scott/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xqs="http://xmlns.oracle.com/ias/xqs/" xmlns:xqstypes="http://xmlns.oracle.com/ias/xqs/types/" xmlns:sql="http://xmlns.oracle.com/ias/xqs/sql/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <!-- import definitions of XQS SqlOutputMessage and SqlFaultMessage--> <import namespace="http://xmlns.oracle.com/ias/xqs/" location="xqs.wsdl" /> <!-- input messages --> <message name="EmpByNameAndDeptInput"> <part name="ename" type="xs:string"/> <part name="deptno" type="xs:int"/> </message> <message name="EmpByNameInput"> <part name="ename" type="xs:string"/> </message> <!-- port type declarations --> <portType name="ScottSqlSource"> <operation name="SelectEmpByName"> <input name="SqlInput" message="scott:EmpByNameInput"/> <output name="SqlResult" message="xqs:SqlOutputMessage"/> <fault name="SqlFault" message="xqs:SqlFaultMessage"/> </operation> <operation name="SelectEmpByNameAndDept"> <input name="SqlInput" message="scott:EmpByNameAndDeptInput"/> <output name="SqlResult" message="xqs:SqlOutputMessage"/> <fault name="SqlFault" message="xqs:SqlFaultMessage"/> </operation> </portType> <!-- binding declarations --> <binding name="SQLBinding" type="scott:ScottSqlSource"> <sql:binding/> <operation name="SelectEmpByName"> <sql:operation XMLtransform="XSU-client"> select * from emp where ename=:1 </sql:operation> <input name="SqlInput"> <sql:input> ename </sql:input> </input> <output name="SqlResult"/> <fault name="SqlFault"/> </operation> <operation name="SelectEmpByNameAndDept"> <sql:operation XMLtransform="XSU-client"> select * from emp where ename=:1 and deptno=:2 </sql:operation> <input name="SqlInput"> <sql:input> ename,deptno </sql:input> </input> <output name="SqlResult"/> <fault name="SqlFault"/> </operation> </binding> <!-- service declaration --> <service name="ScottSQLService"> <port name="ScottSQLPort" binding="scott:SQLBinding"> <sql:address data-source-location="jdbc/OracleCoreDS" /> </port> </service> </definitions>
xqs.wsdl
For reference, here is the Oracle xqs.wsdl
document, imported by the preceding sample WSDL.
<?xml version="1.0" ?> <definitions targetNamespace="http://xmlns.oracle.com/ias/xqs/" xmlns:xqstypes="http://xmlns.oracle.com/ias/xqs/types/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/"> <!-- XQS type defs --> <types> <xs:schema targetNamespace="http://xmlns.oracle.com/ias/xqs/types/" xmlns:xs="http://www.w3.org/1999/XMLSchema"> <!-- Result of all SQL functions is an XML Node representing document root, with optional XML type for elements-rows --> <xs:complexType name="SQLXMLDocument"> <xs:attribute name="rowType" type="xs:QName" /> <xs:sequence> <xs:element name="root" type="xs:anyType" minOccurs="0" maxOccurs="1"/> </xs:sequence> </xs:complexType> </xs:schema> </types> <!-- all XQS sql functions should use this message type for output --> <message name="SqlOutputMessage"> <part name="result" type="xqstypes:SQLXMLDocument"/> </message> <!-- all XQS sql functions should use this message type for error (fault) --> <message name="SqlFaultMessage"> <part name="code" type="xs:int"/> <part name="message" type="xs:string"/> </message> </definitions>
Considerations for the XQS Configuration
For general configuration considerations for a WSDL source, see "Preparing to Use a WSDL Source with SOAP Binding".
In particular, each <port>
element in your XQS configuration for a WSDL source must refer to the appropriate SQL binding. For example, consider the following XQS configuration:
<port namespace="http://xqstest.sql.scott/">
ScottSQLPort
</port>
Corresponding to the following WSDL port definition:
<service name="ScottSQLService">
<port name="ScottSQLPort" binding="scott:SQLBinding">
<sql:address data-source-location="jdbc/OracleCoreDS" />
</port>
</service>
Each XQS function name in your XQS configuration is bound to a single SQL statement in the WSDL.
You must specify a <port>
element that refers to the correct SQL binding.
Notes:
|
You can access a data source through a custom Java class or EJB by using the WSIF provider for Java or the WSIF provider for EJB. XQS does nothing special in this area; this is open technology from the Apache Foundation. You must do the following:
Implement a custom Java class or EJB that returns XML data that you can then query.
Create a WSDL document with Java or EJB binding (as appropriate) to define the desired operations.
Consider any XML-Java type mapping you will require.
See "Preparing to Use a WSDL Source with SOAP Binding" for general WSDL considerations for your XQS configuration.
Refer to the Oracle Application Server Web Services Developer's Guide for information about how to implement the class or bean and the Oracle Application Server Advanced Web Services Developer's Guide for information on the WSIF providers for Java and EJB.
Here is a sample fragment from a WSDL document with Java binding. With this, you can invoke the Java method readEntry()
, for example, by its operation name. Note that a WSDL <format:typeMapping>
specification corresponds to a <typeMap>
element in the XQS configuration.
< definitions> ... <binding name="JavaBinding" type="tns:AddressBook"> <java:binding /> <format:typeMapping encoding="Java" style="Java"> <format:typeMap typeName="typens:address" formatType = "localjava.client.stub.addressbook.wsiftypes.Address" /> <format:typeMap typeName="xsd:string" formatType="java.lang.String" /> </format:typeMapping> <operation name="readEntry"> <java:operation methodName="readEntry" parameterOrder = "name" methodType = "instance" /> <input name="ReadEntryWholeNameRequest" /> <operation name="readAllMatchingEntries"> ... </operation> </binding> <service name="AddressBookService"> <port name="JavaPort" binding="tns:JavaBinding"> <java:address className = "localjava.service.AddressBookImpl" /> </port> </service> ... </definitions>
There must be an entry in the XQS configuration for each XQuery external function used in any XQuery expression in your application—in other words, for each XQS function that XQS will implement—that specifies details including the desired name of the XQS function that will be used in the query, the data source to access, and any input parameters. There are three basic configuration categories: for a document source, an XQS view, or a WSDL source. And there are three corresponding high-level configuration elements: <document-source>
, <xqsview-source>
, and <wsdl-source>
.
Your configuration for any given XQS function can be either in the application-specific xqs-config.xml
file, or, for the configuration to be available to any application running in the OC4J instance, in the global-xqs-config.xml
file. In case of any duplication, the application-specific configuration file takes precedence. Duplicate or conflicting configuration in the global file would be ignored.
This section covers the following topics:
See "Introduction to XQS Configuration and Configuration Files" for related overview, including discussion of the local versus global XQS configuration file.
See "XQS Configuration File Reference" for reference information about the configuration elements discussed here.
This section discusses how to configure an XQS function that accesses a document source, concluding with examples. Elements mentioned here are subelements of the <document-source>
element. For additional information, see the reference section "<document-source>", which includes links to information about all the subelements.
Always Required
At a minimum, you must configure the following element for a document source:
<function-name>
: Through this element, specify the qualified name you want to use for the XQS function that XQS implements to access the document source. The element value is the local name, and there are attributes for the namespace (either namespace
or prefix
, as discussed in "<function-name>"). Your XQuery prolog must use the same name when declaring the XQS function as an XQuery external function.
Here is a sample configuration:
<document-source ... > <function-name namespace="http://xmlns.oracle.com/ias/xqs"> myFileSource </function-name> ... </document-source>
And here is a corresponding XQuery declaration and usage:
declare namespace xqs = "http://xmlns.oracle.com/ias/xqs"; declare function xqs:myFileSource() external; for $po in xqs:myFileSource()//po return $po
Optional or Sometimes Required
The following elements are sometimes necessary or appropriate for a document source:
<documentURL>
: Use this element to specify the URL of the document source. Here is an example:
<document-source ... > ... <documentURL> http://host:port/xqsdemos/Repository/pos-2KB.xml </documentURL> ... </document-source>
Important: For your specification of the document URL, be aware that if the document is on the local file system, then usingfile:// protocol to specify the absolute path to the file, instead of using http:// protocol, will give you faster data retrieval.
|
If you provide a <documentURL>
element, then you implicitly specify that your XQS function takes no arguments. Alternatively, you can omit <documentURL>
, in which case you must pass the URL in to the XQS function at runtime, as in the following example. In this case, the function must be declared in XQuery to have one parameter for the URL.
declare namespace xqs = "http://xmlns.oracle.com/ias/xqs"; declare function xqs:myFileSource($bind as xs:string) external; for $po in xqs:myFileSource ("http://host:port/xqsdemos/Repository/pos-2KB.xml")//po return $po
<output-element>
: You can use this subelement to specify the qualified name of the XML element or output type (either a simple type or a complex type) for data that is returned. This is not always required, but XQS can use the information for type checking. Here is an example:
<document-source ... > ... <output-element namespace="http://xmlns.oracle.com/ias/xqs/CustomerDemo" location="http://host:port/xqsdemos/Customers.xsd"> type=Customers </output-element> ... </document-source>
For an <xqsview-source> element that defines <output-element>, the <output-element> subelement is required in every XQS function that defines an "errorMessage" error-handling option in the underlying query, or in a query that is nested via use of another <xqsview-source> function. For more information about this requirement, see "Using XQS Error Handling Modes and APIs".
<XMLTranslate>
: For a non-XML document source, use this element to specify the conversion tool to use and to provide any information the tool needs. Currently only D3L is supported, which requires a D3L schema file to be specified through the <schema-file>
subelement. See "Preparing to Use a Non-XML Document Source" for information about D3L.
Here is an example:
<document-source ... > ... <XMLTranslate method="D3L"> <schema-file> http://host:port/xqsdemos/paymentInfoD3L.xml </schema-file> </XMLTranslate> ... </document-source>
Performance and Error-Handling
You can set up error-handling and specify the use of performance features such as caching or special processing of large data sets. This would involve the <document-source>
attributes isCached
, largeData
, and onError
, and subelements <cache-properties>
and <error-message>
. Configuring these features is not discussed here. Refer to "Using XQS Error Handling Modes and APIs" and "Using XQS Performance Features".
Examples
These examples use default settings for caching, large data, and error handling, which is equivalent to <document-source>
attribute settings of isCached="false"
, largeData="false"
, and onError="dynamicError"
.
The following example is for an XML document source that resides in a fixed location:
<document-source> <function-name namespace="http://xmlns.oracle.com/ias/xqs"> myFileSource </function-name> <documentURL> http://host:port/xqsdemos/Repository/pos-2KB.xml </documentURL> </document-source>
The following example is for a document source in non-XML format, using the D3L conversion tool and paymentInfoD3L.xml
D3L schema file:
<document-source> <function-name prefix="xqs"> paymentStatusInfo </function-name> <documentURL>http://host:port/xqsdemos/paymentInfo.csv</documentURL> <XMLTranslate method="D3L"> <schema-file> http://host:port/xqsdemos/paymentInfoD3L.xml </schema-file> </XMLTranslate> </document-source>
This section discusses how to configure an XQS function that uses an XQS view, concluding with an example. Elements mentioned here are subelements of the <xqsview-source>
element. For additional information, see the reference section "<xqsview-source>", which includes links to information about all the subelements.
For preliminary steps, such as creating the XQS view that you will use, see "Preparing to Use an XQS View".
WSDLvisibility Setting
You can use the <xqsview-source>
attribute setting WSDLvisibility="true"
to expose an XQS view as a Web service operation. XQS will add the operation to the WSDL that it generates. If the configuration is in the application-specific configuration file, xqs-config.xml
, then the Web service operation is made part of the Web service of that application. A view that is configured in the global configuration file, global-xqs-config.xml
, is potentially available to any application running in the OC4J instance. (To add an operation based on a global XQS view to the Web service of your application, you must point to the global configuration file when you run OC4JPackager. See "OC4JPackager Parameters" for information about the -globalXqsConfig
option.)
For more information about exposing an XQS view as a Web service, see "OC4JPackager Additional Output to Expose XQS Views as Web Service Operations".
Always Required
For ensuing discussion, assume the following example has been saved as an XQS view in mytotals.xq
. It uses a function that reads from a file, taking the input parameter loc
(a string variable indicating a file location) and passing it through to the function, then returns an integer total:
declare variable $loc external; declare namespace xqs = "http://xmlns.oracle.com/ias/xqs"; declare function xqs:readFile($l as xs:string) as xs:int external; for $po in xqs:readFile($loc)//po return $po//total
At a minimum, you must configure the following elements to use an XQS view:
<function-name>
: Through this element, specify the qualified name you want to use for the XQS function that XQS implements to execute the view. The element value is the local name, and there are attributes for the namespace (either namespace
or prefix
, as discussed in "<function-name>"). If you use this function in a query (as opposed to using the view directly in an executeView()
call), then you must declare the XQS function as an XQuery external function, using the function name specified in the <function-name>
element.
Here is a sample configuration:
<xqsview-source ... > <function-name namespace="http://xmlns.oracle.com/ias/xqs"> totals </function-name> ... </xqsview-source>
<input-parameters>
: If an XQS view takes external variables, then the function implemented by XQS must take an input parameter for each external variable in the view. XQS will assign function argument values to external variables before executing the query. Use the <input-parameters>
element to configure input parameters, with a <part>
subelement for each parameter. Note that this element is always required for an XQS view; use an empty element if there are no input parameters:
<xqsview-source ... > ... <input-parameters/> ... </xqsview-source>
Following is an example with one input parameter being bound to an external string variable named loc
. Type information, through a <schema-type>
or <xquery-sequence>
element, is required for any input parameter for an XQS view. Assume for the following example that the "xs
" prefix has been set to correspond to the XMLSchema namespace. (See reference documentation later in this chapter for information about the <input-parameters>
, <part>
, <schema-type>
, and <xquery-sequence>
elements.)
<xqsview-source ... > ... <input-parameters type-match="none" > <part position="1" name="loc"> <schema-type prefix="xs">string</schema-type> </part> </input-parameters> ... </xqsview-source>
And here is an example of using the XQS view in a query, with the XQuery declaration and usage corresponding to the preceding <function-name>
and <input-parameters>
discussion:
declare namespace xqs = "http://xmlns.oracle.com/ias/xqs"; declare function totals($loc as xs:string) as xs:int external; for $t in xqs:totals("C:\MyPurchaseOrders.xml") return <outstanding_balance> fn:sum($t) </outstanding_balance>
Optional or Sometimes Required
The following elements are sometimes necessary or appropriate for an XQS view:
<output-element>
: Use this to specify the qualified name of the XML element or output type (either a simple type or a complex type) for data that is returned. For an XQS view with WSDLvisibility="true"
, the <output-element>
element is particularly advisable and its location
attribute must point to the XML schema file containing the element or type definition. Here is an example:
<xqsview-source WSDLvisibility="true"> ... <output-element namespace="http://xmlns.oracle.com/ias/xqs/CustomerDemo" location="http://host:port/xqsdemos/Customers.xsd"> </output-element> ... </xqsview-source>
For an XQS view with WSDLvisibility="false"
, the <output-element>
element is still useful for type-checking. Assume the prefix "xs
" has been set to correspond to the XMLSchema namespace:
<xqsview-source WSDLvisibility="false"> ... <output-element prefix="xs">integer</output-element> ... </xqsview-source>
<query-name>
: Use this to specify the name of the .xq
file where you have saved the XQS view, with or without specifying the .xq
extension (which XQS will append if necessary). The <query-name>
element is optional. If you omit it, XQS will assume that the base name of the .xq
file is the same as the XQS function name specified in the <function-name>
element. Here is an example for an XQS view saved in mytotals.xq
:
<xqsview-source ... > ... <queryName>mytotals</queryName> ... </xqsview-source>
Given the earlier example for the <function-name>
element, if <queryName>
were omitted, then XQS would look for a file named totals.xq
.
<repository>
: Use this to specify where your XQS view repository is—the location of your .xq
file. If you omit this element, XQS assumes the repository is as specified through the optional -repository
option when you run OC4JPackager.
Here is an example:
<xqsview-source ... > ... <repository>META-INF/xqs/mydir</repository> ... </xqsview-source>
Considerations for Using <output-element >
When the WSDLvisibility
attribute is set to true
, XQS generates a Web service operation for the view and includes the definition of this operation in the WSDL document. The contents of <output-element>
in <xqsview-source>
determine the type of the output message for the WSDL operation, as follows:
If <output-element> is omitted, the type of result in the WSDL operation output message will be declared as follows:
<sequence> <any/> </sequence>
If <output-element> is present, it should provide a namespace for the output element in the form of namespace or prefix attribute. The namespace results in the <import> element in the WSDL. For example:
<output-element namespace="urn:PurchaseOrders" location="http://myhost:80/myapp/PurchaseOrders.xsd" />
This code generates the following import element in the WSDL:
<types>
<schema...>
<import namespace="urn:PurchaseOrders" schemaLocation="http://myhost:80/myapp/PurchaseOrders.xsd" />
...
</schema>
</types>
Whenever possible, provide the location attribute because it allows a more complete <import>
element in the WSDL.
If <output-element>
specifies a type attribute, it will be used in conjunction with a namespace
or prefix
attribute to create a qualified name for the type of the result element. The text value of <output-element>
will be used as the name for the result element itself.
For example:
<output-element namespace="urn:PurchaseOrders" location="http://myhost:80/myapp/PurchaseOrders.xsd" type="POType" > po </output-element>
This code results in an <import>
element, as discussed in the preceding text, plus the following definition of the result type for the WSDL operation:
<complexType name="POswithRetTypeResultType">
...
<element name="result" nillable="true">
<complexType >
<sequence>
<element name="po" xnlns:_ns1="urn:PurchaseOrders" type="_ns1:POType" minOccurs="0" maxOccurs="unbounded" />
</sequence>
...
If <output-element>
does not specify the type
attribute, then the result element in the WSDL operation output message will be declared as a reference to an element in the imported schema. For example, consider the following configuration element:
<output-element namespace="urn:PurchaseOrders" location="http://myhost:80/myapp/PurchaseOrders.xsd"> polist </output-element>
Such an element generates a result definition in the WSDL like this:
<complexType name="POListResultType">
...
<element name="result" nillable="true">
<complexType >
<sequence>
<element ref="_ns1:polist" minOccurs="0" maxOccurs="unbounded" />
</sequence>
...
If <output-element>
specifies the type
attribute but is empty (has no text
element value), XQS will use a fixed name for the result element, item
, but use the type name provided. For example, consider the following configuration:
<output-element namespace="urn:PurchaseOrders" location="http://myhost:80/myapp/PurchaseOrders.xsd" type="POType" />
Such a configuration will generate a definition of the result element like this:
<complexType name="POsResultType">
...
<element name="result" nillable="true">
<complexType >
<sequence>
<element name="item" xnlns:_ns1="urn:PurchaseOrders" type="_ns1:POType" minOccurs="0" maxOccurs="unbounded" />
</sequence>
Important: The type that defines the result element (through thetype attribute in WSDL), or the element that defines the result element by reference (through the ref attribute in WSDL) must refer to a top-level type or element definition in the imported schema. In the previous examples, POType must be a top-level type definition in the imported schema for the namespace urn:PurchaseOrders ; alternatively, polist (used to define an element by reference) must be defined at the top level of the imported schema at this location:
http://myhost:80/myapp/PurchaseOrders.xsd |
Performance and Error-Handling
You can set up error-handling and specify the use of performance features such as caching or special processing of large data sets. This would involve the <xqsview-source>
attributes isCached
, largeData
, and onError
, and subelements <cache-properties>
and <error-message>
. Configuring these features is not discussed here. Refer to "Using XQS Error Handling Modes and APIs" and "Using XQS Performance Features".
Example
The example that follows puts together previous fragments to configure the XQS function totals
, which takes a string variable loc
(for a file location) and outputs an integer result. For convenience, here once again is the XQS view, mytotals.xq
:
declare variable $loc external; declare namespace xqs = "http://xmlns.oracle.com/ias/xqs"; declare function xqs:readFile($l as xs:string) external; for $po in xqs:readFile($loc)//po return $po//total
This example uses default settings for caching, large data, and error handling, which is equivalent to <xqsview-source>
attribute settings of isCached="false"
, largeData="false"
, and onError="dynamicError"
. It does not expose the XQS view as a Web service.
<xqsview-source WSDLvisibility="false"> <function-name namespace="http://xmlns.oracle.com/ias/xqs"> totals </function-name> <input-parameters type-match="none" > <part position="1" name="loc"> <schema-type prefix="xs">string</schema-type> </part> </input-parameters> <repository>META-INF/xqs/mydir</repository> <queryName>mytotals</queryName> <output-element prefix="xs">int</output-element> </xqsview-source>
This section discusses how to configure an XQS function that accesses a WSDL-based source, concluding with a partial sample WSDL document and corresponding configuration. Elements mentioned here are subelements of the <wsdl-source>
element. For additional information, see the reference section "<wsdl-source>", which includes links to information about all the subelements.
Depending on the type of WSDL source you are using, also see "Preparing to Use a WSDL Source with SOAP Binding", "Preparing to Use a Database Source (WSDL Source with SQL Binding)", or "Preparing to Use a Custom Class or EJB (WSDL Source with Java or EJB Binding)".
Always Required
At a minimum, you must configure the following elements for a WSDL source:
<function-name>
: Through this element, specify the qualified name you want to use for the XQS function that XQS implements to access the WSDL source. The element value is the local name, and there are attributes for the namespace (either namespace
or prefix
, as discussed in "<function-name>"). Your XQuery prolog must use the same name when declaring the XQS function as an XQuery external function.
Here is a sample configuration:
<wsdl-source ... > <function-name namespace="http://xmlns.oracle.com/ias/xqs"> getmySearchCachedPage </function-name> ... </wsdl-source>
<input-parameters>
: For every WSDL source, the function implemented by XQS must take an input parameter for each input part specified in the WSDL. Use the <input-parameters>
element to configure input parameters, with a <part>
subelement for each parameter. Note that this element is always required for a WSDL source; use an empty element if there is no input:
<wsdl-source ... > ... <input-parameters/> ... </wsdl-source>
Following is an example with two input parameters, external string variables named key
and url
. Type information, through a <schema-type>
element, is optional for input parameters for a WSDL source; however, it is useful so that XQS can perform type-checking during invocation of the Web service. In the example, assume the "xs
" prefix has been set to correspond to the XMLSchema namespace. (See reference documentation later in this chapter for information about the <input-parameters>
, <part>
, and <schema-type>
elements.)
<wsdl-source ... > ... <input-parameters> <part position="1" name="key" > <schema-type prefix="xs">string</schema-type> </part> <part position="2" name="url" > <schema-type prefix="xs">string</schema-type> </part> </input-parameters> ... </wsdl-source>
<wsdlURL>
: Specify a URL that instructs XQS where to find the WSDL document. For example:
<wsdl-source ... > ... <wsdlURL>http://api.mySearch.com/mySearch.wsdl</wsdlURL> ... </wsdl-source>
<operation>
: Specify the Web service operation to execute, corresponding to an operation name in the WSDL. For example:
<wsdl-source ... > ... <operation>doGetCachedPage</operation> ... </wsdl-source>
<port>
: Specify the applicable Web service port, corresponding to a port name in the WSDL. For example:
<wsdl-source ... > ... <port namespace="urn:mySearch">mySearchPort</port> ... </wsdl-source>
Here is a sample function declaration corresponding to the <function-name>
and <input-parameters>
examples above:
declare namespace xqs = "http://xmlns.oracle.com/ias/xqs"; declare function xqs:getmySearchCachedPage ($key as xs:string, $url as xs:string) as xs:base64Binary external;
Optional or Sometimes Required
The following elements are sometimes necessary or appropriate for a WSDL source.
<service>
: Use this to specify the applicable service, corresponding to a service name in the WSDL. This is not required, however, if the WSDL defines only one service. Here is a sample service configuration:
<wsdl-source ... > ... <service namespace="urn:mySearch">mySearchService</service> ... </wsdl-source>
<portType>
: Use this to specify the applicable port type, corresponding to a port type name in the WSDL. This is not required, however, if the port in the WSDL supports only one binding (and, therefore, only one port type). Here is a sample port type configuration:
<wsdl-source ... > ... <portType namespace="urn:mySearch">mySearchPort</portType> ... </wsdl-source>
<output-element>
: You can optionally use this to specify the qualified name of the XML output element or type (either a simple type or a complex type) for data that is returned. This is not required, but XQS can use the information for type-checking. Here is an example:
<wsdl-source ... > ... <output-element namespace="http://xmlns.oracle.com/ias/xqs/CustomerDemo" location="http://host:port/xqsdemos/Customers.xsd"> type="Customers> </output-element> ... </wsdl-source>
<typeMap>
: For a WSDL source with Java or EJB binding, you can use this element to map XML types to Java types, using the <mapping>
subelement and its <xmlType>
subelement as shown. (See the reference documentation later in this chapter for more information about the <typeMap>
, <mapping>
, and <xmlType>
elements.)
<wsdl-source ... > ... <typeMap> <mapping typeClass="org.w3c.dom.Node"> <xmlType prefix="myeis">Customer</xmlType> </mapping> ... </typeMap> ... </wsdl-source>
(A <typeMap>
element would be ignored for a WSDL source with a SQL or SOAP binding.)
Performance and Error-Handling
You can set up error-handling and specify the use of caching. This would involve the <wsdl-source>
attributes isCached
and onError
, and subelements <cache-properties>
and <error-message>
. Configuring these features is not discussed here. Refer to "Using XQS Error Handling Modes and APIs" and "Configuring XQS Caching".
Example
This example puts together some of the previous fragments to configure an XQS function for a Web service operation defined in mySearch.wsdl
, a portion of which follows.
The example uses default settings for caching and error handling, which is equivalent to <wsdl-source>
attribute settings of isCached="false"
and onError="dynamicError"
.
<wsdl-source> <function-name namespace="http://xmlns.oracle.com/ias/xqs"> getmySearchCachedPage </function-name> <wsdlURL>http://api.mySearch.com/mySearch.wsdl</wsdlURL> <operation>doGetCachedPage</operation> <service namespace="urn:mySearch">mySearchService</service> <port namespace="urn:mySearch">mySearchPort</port> <input-parameters> <part position="1" name="key" > <schema-type prefix="xs">string</schema-type> </part> <part position="2" name="url" > <schema-type prefix="xs">string</schema-type> </part> </input-parameters> </wsdl-source>
mySearch.wsdl
Here are relevant fragments of mySearch.wsdl
, relating to the preceding configuration. Highlighted WSDL portions correspond to configuration elements.
<?xml version="1.0" ?> <definitions name="mySearch" targetNamespace="urn:mySearch" xmlns:typens="urn:mySearch" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/"> ... <message name="doGetCachedPage"> <part name="key" type="xs:string" /> <part name="url" type="xs:string" /> </message> <message name="doGetCachedPageResponse"> <part name="return" type="xs:base64Binary" /> </message> ... <portType name="mySearchPort"> <operation name="doGetCachedPage"> <input message="typens:doGetCachedPage" /> <output message="typens:doGetCachedPageResponse" /> </operation> ... </portType> ... <binding name="mySearchBinding" type="typens:mySearchPort"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" /> <operation name="doGetCachedPage"> <soap:operation soapAction="urn:mySearchAction" /> <input> <soap:body use="encoded" namespace="urn:mySearch" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" /> </input> <output> <soap:body use="encoded" namespace="urn:mySearch" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" /> </output> </operation> ... </binding> ... <service name="mySearchService"> <port name="mySearchPort" binding="typens:mySearchBinding"> <soap:address location="http://api.mySearch.com/search/beta2" /> </port> </service> </definitions>
This chapter assumes developers are already familiar with the XQuery language and the basics of how to design an effective and efficient query, but this section will summarize key points to consider, including special considerations for working with XQS, and includes query examples. The following topics are covered:
Notes:
|
As a first step, of course, you must consider your data source, including how to access it and the types of data it contains. "How to Prepare to Use Your Data Sources" already discussed any preliminary steps you must take for certain kinds of data sources.
Then you must consider aspects of the query itself, including the following:
Will your query require input parameters? If so, do you want type-checking? (See "Type-Checking for Input Parameters".)
What are the data types of any input parameters and the query return value?
Will you want to transform the data, outputting it into another XML structure?
Will you want to use an ad-hoc query, or save the query as an XQS view (.xq
file)?
Are there tuning and performance considerations, and will you want to use XQS performance features? XQS can cache source data, and also has a special mode for processing large volumes of data. (See "Using XQS Performance Features" for details.)
As discussed previously, XQS implements an external XQuery function to access the data source. Your XQuery prolog must include a declaration for the function that XQS creates, using a function name you choose, and must reference the appropriate namespace. The function name you declare must match the name you specify in the <function-name>
element when you configure the data source (as described under "How to Configure Your XQS Functions").
Here is a simple query that retrieves data from an XML document, the location of which is passed in to the XQS function at runtime:
declare namespace xqs = "http://xmlns.oracle.com/ias/xqs"; declare function xqs:get_poSQ($bind as xs:string) external; for $po in xqs:get_poSQ("http://host:port/xqsdemos/Repository/pos-2KB.xml") return $po
XQS implements the function according to your XQS configuration. The function name (get_poSQ
in this example) is of your choosing. The function takes as input a string with the name and location of the document source, pos-2KB.xml
, and returns purchase order data from the file.
Now here is an example that passes in parameter values through the XQuery code. The XQS function is example
, implemented by XQS according to your configuration.
declare namespace xqs = "http://xmlns.oracle.com/ias/xqs"; declare function xqs:example($i as xs:int, $d as xs:duration, $h as xs:hexBinary, $bin as xs:base64Binary, $t as xs:boolean) external; for $result in xqs:example(xs:int(1), xs:duration("P1Y2MT2H"), xs:hexBinary("0FB7"), xs:base64Binary("vYrfOJ39673//-BDiIIGHSPM=+"), xs:boolean("true")) return $result;
Following is a more complicated example for a query that, given the name of a customer, searches a payment record for orders by that customer. It returns information about the customer and the customer's orders. There are two data sources involved: 1) customer information is in a data source accessed through a custom WSIF extension "myeis"; and 2) payment information is in an Excel spreadsheet (non-XML document source). To access the data source for customer information, the XQS function customerInfo
is used, taking a string with the customer name as input. That function accesses the customer information data source and yields information for the specified customer, including a customer key. Then the payment information Excel file is accessed, using the XQS function paymentStatusInfo
, and order information is returned for the customer whose key matches the key from the customer information data source. Note the XQuery code includes an XML transformation of the results.
declare namespace xqs = "http://xmlns.oracle.com/ias/xqs"; (: returns payment info for all customers:) declare function xqs:paymentStatusInfo() external; (: returns customer info given customer name :) declare function xqs:customerInfo ($name as xs:string) external; (: customer name passed in to query :) declare variable $custName external; let $custInfo := xqs:customerInfo($custName) for $custOrderInfo in xqs:paymentStatusInfo()/excel/Row[CustomerKey eq $custInfo/key] return <result> <MYEIS_RESULT> <Row> <Name> { $custInfo/name } </Name> <Company> { $custInfo/company} </Company> <Address> { $custInfo/address} </Address> <City> { $custInfo/city} </City> <State> { $custInfo/state} </State> <Zip> { $custInfo/zip} </Zip> </Row> </MYEIS_RESULT> <EXCEL_RESULT> <Row> <OrderID>{$custOrderInfo/OrderId}</OrderID> <Amount>{$custOrderInfo/Amount}</Amount> <PaymentStatus>{$custOrderInfo/PaymentStatus}</PaymentStatus> </Row> </EXCEL_RESULT> </result>
For a WSDL source or XQS view, if you want XQuery to perform additional type-checking steps before sending input arguments to the underlying data source, then take the following steps:
For each input parameter, which is specified in your configuration for the applicable XQS function through a <part>
subelement under the <input-parameters>
element, specify the parameter type. For XQS view sources, this would be through one of the following, as appropriate:
A <schema-type>
subelement of <part>
For an input sequence, an <xquery-sequence>
subelement of <part>
, with the <itemType>
subelement of <xquery-sequence>
For WSDL sources, which do not support a sequence as input, only <schema-type>
is relevant.
(See the reference documentation later in this chapter for details about all these elements.)
Include the parameter types with the function declaration in the XQuery prolog.
If input parameters are of user-defined types, import the schema or files containing the type definitions.
Here is an example. First, the XQS configuration:
<wsdl-source isCached="false"> <function-name namespace="http://xmlns.oracle.com/ias/xqs"> SplitRatio </function-name> ... <input-parameters> <part position="1" name="parameters"> <schema-type namespace="http://www.xignite.com/services/"> GetSplitRatio </schema-type> </part> </input-parameters> </wsdl-source>
Then, the corresponding XQuery expression:
import schema namespace xignite="http://www.xignite.com/services/" at "http://www.xignite.com/xSecurity.asmx?wsdl" declare namespace xqs="http://xmlns.oracle.com/ias/xqs"; declare function xqs:SplitRatio($params as xignite:GetSplitRatio) as xignite:GetSplitRatioResponse external; let $in := <xignite:GetSplitRatio> .....</xignite:GetSplitRatio> let $y := xqs:SplitRatio($in) return <split>$y//xignite:Ratio</split>
At execution time, XQuery will ensure that the argument passed into xqs:SplitRatio
is of the type xignite:GetSplitRatio
from the imported schema.
This section discusses the steps involved in using the client APIs that XQS provides (first discussed in "Introduction to XQS Client Interfaces"), and offers some examples. The focus is on the Java class client API, the EJB client API, and the JSP tag library. For Web service clients, the particulars of what XQS does to expose an XQS view as a Web service operation are left to the packaging discussion—see "OC4JPackager Additional Output to Expose XQS Views as Web Service Operations". Otherwise, XQS generates a regular WSDL with SOAP 1.1 binding, and we assume readers are knowledgeable about creating Web service clients.
Note: XQS does not generate Java code for a Web service client. It is a responsibility of the user to invoke the Web service dynamically or generate the client invocation code based on the WSDL. |
The following topics are covered here:
Notes:
|
The XQS oracle.xds.client.QueryParameter
class is for use with the XQS Java client API and EJB client API for arrays of bind parameters for queries. It is also used behind the scenes with the XQS JSP tag library. (See "XQS QueryParameter Class Reference" for additional information.) Table 8-2 shows the correspondence between XML types that XQS supports, and Java types that you use to pass input values through instances of the QueryParameter
class.
Table 8-2 XQS Type Support for Bind Parameters
Supported XML Type | Corresponding Java Type for QueryParameter Class |
---|---|
boolean |
boolean |
string |
java.lang.String |
int |
int |
integer |
int, long, java.math.BigInteger |
long |
long |
float |
float |
double |
double |
decimal |
java.math.BigDecimal |
base64Binary |
java.lang.String |
hexBinary |
java.lang.String |
anyURI |
java.net.URI |
dateTime |
boolean, java.util.GregorianCalendar |
duration |
java.lang.String (lexical representation of duration) |
anyType, user-defined XML types |
org.w3c.dom.Node |
There are several basic coding steps in using the XQS client APIs:
Create your query. To use an ad-hoc query, this may consist of hard-coding a query or writing code to accept a query from user input. To use an XQS view, this consists of saving the query in an .xq
file. Also see "How to Design Your Queries".
Obtain an XQS client object, such as by creating the local interface to use the XQS EJB client API, by creating an XQSFacade
instance to use the Java class client API, or by including the XQS JSP tag library in a JSP page.
Specify any input parameters. For the Java class API or EJB API, create an array of type oracle.xds.client.QueryParameter
. (See "XQS QueryParameter Class Reference".) For the JSP tag library, use the param
subtag of execute
or executeCursor
. (See "XQS param Tag".) Also see the preceding section, "Supported Types for Query Parameters".
Execute the query.
Read and process the results. For a stateless client, XQS either returns the results all at once in a java.util.Vector
instance or, if you are using the JSP tags, returns a java.util.ArrayList
instance and an XML document. For a stateful client, you retrieve the results item by item, either using the Oracle XQuery type oracle.xml.xqxp.datamodel.XMLItem
, or, if you employ the JSP tags, using java.lang.Object
instances and nodes of an XML document. For the XQS EJB API and JSP tag library, you have the option of using either a stateless or stateful access pattern.
The Java class API (XQSFacade
) uses a stateful access pattern. See "Using the Java Class Client API" for information about using the XQSFacade
class.
Optionally retrieve and process errors. If you configure XQS to continue even if errors are encountered during execution of the XQS function for the query, you can retrieve information about the errors. See "Using XQS Error Handling Modes and APIs".
When using a stateful client, close the client object to free all resources associated with the query.
Note: This discussion does not include security or performance considerations. See "Security for XQS Applications" and "Using XQS Performance Features" for information on those topics. |
The XQS client APIs return query results as an XML sequence—one or more XML items, where each item may be an XML document, XML node, or primitive value. It is important to realize that the query execution defines the result, but does not necessarily materialize all result items into process memory immediately. An XML sequence, like a result set from a relational query, implicitly maintains a "cursor" that is initially positioned in front of the first item in the sequence and may be advanced by a "next" operation. If an XML sequence is accessed through the implicit cursor, through repeated calls to a "next" operation, then any of the "next" calls may trigger the actual evaluation of the XQuery expression in order to produce the next item requested. The exact moment when XQuery evaluates the expression and whether XQuery evaluates it incrementally or all at once depend on the specific XQuery expression and the level of optimization of the XQuery implementation. As an alternative to using this sort of cursor access, though, the XQS client APIs also offer reading all query results immediately into process memory in a single step.
Each of the single-step and cursor modes of execution has advantages and disadvantages. For most situations, single-step execution is preferable, because associated resources (such as connections to the underlying data sources, and internal XQuery resources dedicated to the expression) are freed immediately after the evaluation is completed. You also do not have the potential performance impact of repeated trips to the data source. However, single-step execution is not feasible when the total size of items in the result sequence may be too large, such that materializing the whole sequence at one time would run out of process memory. In this case, cursor mode is the only option, as long as there is nothing (such as aggregate expressions, for example) preventing the query from providing the results item-by-item.
To allow the choice between the single-step and cursor modes, XQS provides two types of client APIs: stateless for single-step mode, or stateful for cursor mode. (In this discussion, "state" refers to the internal state of the XQuery engine.) These work as follows:
When an XQuery expression is executed through a stateless API, the entire result sequence is materialized at once, and all internal state and resources are freed immediately afterward. The only requirement for stateless execution is that the entire result sequence must fit into process memory.
By contrast, executing an XQuery expression through a stateful API results in placement of the "current" position in front of the first item in the result sequence. To obtain each item, starting with the first item, the client must invoke a "next" operation. The current position and all the internal resources necessary to evaluate the next item constitute the state of the query. This state is freed only after the last item in the sequence is returned, or if the query is explicitly closed. It is important to note, however, that to take advantage of the reduced memory requirements of stateful execution, the client code must release each result item once it has been processed.
The XQS EJB client API and JSP client API each has features for stateless execution and features for stateful execution. The XQS Java class (XQSFacade
) client API provides stateful access. Users can simulate stateless access by immediately getting all result items and freeing the client object.
Refer to the "General Coding Steps in Using XQS Client APIs". Do as follows to apply these steps using the XQS Java class client API (after creating your query):
Create an XQSFacade
instance. Method calls in the following steps are called from this instance.
Create a QueryParameter
array for any input parameters.
Use the execute()
method to execute an ad-hoc query, or the executeView()
method to execute an XQS view, passing in the query and QueryParameter
array (or null
if there are no input parameters). For executeView()
, also pass in the namespace of the XQS function for the view.
If you configured any data sources used in the query with the emptySequence
or errorMessage
error mode, optionally use the getErrors()
method to retrieve any errors encountered during execution of the query. This returns an iterator over a collection of XQSError
objects. See "Using XQS Error Handling Modes and APIs" for information about error configuration and processing.
Repeatedly use the getNextItem()
method to get the results back item by item. Each item is returned in an XMLItem
instance. Process these items as desired.
Use the close()
method to free all resources associated with the query.
These steps are shown in examples that follow. Also see "XQSFacade Class Reference" for reference information.
This example shows general use of the XQSFacade
API. The query returns bind parameters in a sequence, showing how to bind and how to retrieve data. No configuration is necessary, because the query does not use any functions.
For processing query results, the code uses the XMLItem
class (in package oracle.xml.xqxp.datamodel
).
import oracle.xml.xqxp.datamodel.XMLItem; import oracle.xml.parser.v2.XMLDocument; import oracle.xml.parser.v2.XMLElement; import oracle.xds.client.XQSFacade; import oracle.xds.client.QueryParameter; import oracle.xds.client.XQSError; import oracle.xml.xqxp.functions.builtIns.FNUtil; import java.util.Vector; public class XQSFacadeTest { public static void main(String[] args) throws Exception { try{ //get XQSFacade XQSFacade facade = new XQSFacade(); String xquery = "declare variable $bind1 external;\n"+ "declare variable $bind2 external;\n"+ "declare variable $bind3 external;\n"+ "declare variable $bind4 external;\n"+ "declare variable $bind5 external;\n"+ "declare variable $bind6 external;\n"+ "declare variable $bind7 external;\n"+ "declare variable $bind8 external;\n"+ "declare variable $bind9 external;\n"+ "declare variable $bind10 external;\n"+ "declare variable $bind11 external;\n"+ "declare variable $bind12 external;\n"+ "declare variable $bind13 external;\n"+ "declare variable $bind14 external;\n"+ "declare variable $bind15 external;\n"+ "declare variable $bind16 external;\n"+ " ("+ "$bind1,$bind2,$bind3,$bind4,$bind5,$bind6,$bind7,\n"+ "$bind8,$bind9,$bind10,$bind11,$bind12,$bind13,$bind14,$bind15,$b ind16)"; QueryParameter params[] = new QueryParameter[16]; params[0] = new QueryParameter("bind1"); params[0].setString("test"); params[1] = new QueryParameter("bind2"); params[1].setInteger(new BigInteger("100")); params[2] = new QueryParameter("bind3"); params[2].setBoolean(true); params[3] = new QueryParameter("bind4"); params[3].setFloat(-1); params[4] = new QueryParameter("bind5"); params[4].setDuration("P1Y2M3DT10H30M"); params[5] = new QueryParameter("bind6"); params[5].setDouble(-11.0); TimeZone LAtz = new SimpleTimeZone(-28800000, "America/Los_Angeles", Calendar.APRIL, 1, -Calendar.SUNDAY, 7200000, Calendar.OCTOBER, -1, Calendar.SUNDAY, 7200000, 3600000); GregorianCalendar cal = new GregorianCalendar(LAtz); params[6] = new QueryParameter("bind7"); params[6].setDateTime(cal,true); URI uri = new URI("http://www.test.com"); params[7] = new QueryParameter("bind8"); params[7].setAnyURI(uri); params[8] = new QueryParameter("bind9"); params[8].setInt(-7); params[9] = new QueryParameter("bind10"); params[9].setLong(50l); params[10] = new QueryParameter("bind11"); params[10].setDecimal(new BigDecimal(999999)); params[11] = new QueryParameter("bind12"); XMLDocument document = new XMLDocument(); Element elem = document.createElementNS("http://client.xqs.oracle/", "tns:result"); document.appendChild(elem); params[11].setNode(elem); params[12] = new QueryParameter("bind13"); params[12].setBase64Binary("vYrfOJ39673//-BDiIIGHSPM=+"); params[13] = new QueryParameter("bind14"); params[13].setHexBinary("0FB7"); params[14] = new QueryParameter("bind15"); params[14].setDayTimeDuration(60.5); params[15] = new QueryParameter("bind16"); params[15].setYearMonthDuration(13); facade.execute(xquery, params); // lookup functions XMLItem item = facade.getNextItem(); while(item != null) { if (item.instanceOfType(XMLItem.XMLITEM_STRING)) { System.out.println("string item value: expected: \Ótest\Ó, actual:", item.getString()); } else if (item.instanceOfType(XMLItem.XMLITEM_INT)) { System.out.println("int item value: expected: \Ó-7\Ó, actual: ", item.getInt()); } else if (item.instanceOfType(XMLItem.XMLITEM_LONG)) { System.out.println("long item value: expected: \Ó501\Ó, actual: ", item.getInt()); } else if(item.instanceOfType(XMLItem.XMLITEM_INTEGER)) { if(item.intFormat()) System.out.println("integer item value: expected: \Ó100\Ó, actual: " , item.getInt()); else System.out.println("integer item value: expected: \Ó100\Ó, actual: ", item.getDecimal().intValue()); } else if(item.instanceOfType(XMLItem.XMLITEM_BOOLEAN)) { System.out.println("boolean item value: expected: \Ótrue\Ó, actual: ", item.getBoolean()); } else if(item.instanceOfType(XMLItem.XMLITEM_FLOAT)) { System.out.println("float item value: expected: \Ó-1\Ó, actual: ",(float)item.getDouble()); } else if (item.instanceOfType(XMLItem.XMLITEM_XDT_DAYTIMEDURATION)) { System.out.println("dayTimeDuration item value: expected: \Ó60.5 seconds\Ó, actual: ", item.getDayTimeDuration()); } else if (item.instanceOfType(XMLItem.XMLITEM_XDT_YEARMONTHDURATION)) { System.out.println("yearMonthDuration item value: expected: \Ó13 months\Ó, actual: ", item.getYearMonthDuration()); } else if (item.instanceOfType(XMLItem.XMLITEM_DURATION)) { System.out.println("duration item value: expected: \Ó P1Y2M3DT10H30M \Ó, actual: ", item.getLexicalValue()); } else if(item.instanceOfType(XMLItem.XMLITEM_DOUBLE)) { System.out.println("double item value: expected: \Ó –11.0\Ó, actual: ", item.getDouble()); } else if(item.instanceOfType(XMLItem.XMLITEM_DATETIME)) { System.out.println("dateTime item value: expected Timezone: \ÓPacific (Latz) \Ó, actual: ", item.getCalendar().getTimeZone()); } else if (item.instanceOfType(XMLItem.XMLITEM_ANYURI)) { System.out.println("anyURI item value: expected: \"http://www.test.com\", actual: ", item.getString()); } else if (item.instanceOfType(XMLItem.XMLITEM_DECIMAL)) { System.out.println("decimal item value: expected: \Ó999999 \Ó, actual: ", item.getDecimal().intValue()); } else if(item.instanceOfType(XMLItem.XMLITEM_NODE)) { XMLElement node = (XMLElement)item.getNode(); //when obtained from document function, it returns XMLDocument if(node instanceof XMLDocument) node = (XMLElement)node.getFirstChild(); System.out.println("node item value: expected namespace: \Ó http://client.xqs.oracle \Ó, actual: ",node.getNamespaceURI()); System.out.println("node item value: expected local name: \Óresult\Ó, actual: ",node.getLocalName()); } else if (item.instanceOfType(XMLItem.XMLITEM_HEXBINARY)) { System.out.println("hexBinary item value: expected: \Ó0FB7\Ó, actual: ", item.getString()); } else if (item.instanceOfType(XMLItem.XMLITEM_BASE64BINARY)) { System.out.println("base64Binary item value: expected: \Ó vYrfOJ39673//-BDiIIGHSPM=+ \Ó, actual: ", item.getString()); } else { System.out.println("item type not supported: "+item.getLexicalValue()); } item = facade.getNextItem(); } }catch(Exception ex){ ex.printStackTrace(); fail(ex.getMessage()); assertTrue("xquery execution failed", false); } facade.close(); } }
This section has a Java class to show the steps of using the XQSFacade
API in your client code, along with related XQS configuration. The example has an ad-hoc query that uses an XQS view source, which in turn uses a document source.
Query This example uses the following ad-hoc query:
declare namespace xqs="http://xmlns.oracle.com/ias/xqs"; declare function xqs:get_poSQ($bind as xs:string) external; for $po in xqs:get_poSQ("http://localhost:8888/myrepository/pos-2KB.xml") return $po
Configuration The query in turn uses the XQS function get_poSQ
, which corresponds to an XQS view source that is configured as shown immediately below. By default, if the .xq
file name and location are not specified in the configuration (through the <queryName>
and <repository>
elements), the file name is assumed to match the function name, and the location is assumed to be as specified through the -repository
option when you run OC4JPackager.
<xqsview-source> <function-name prefix="xqs">get_poSQ</function-name> <input-parameters> <part position="1" name="bind" > <schema-type prefix="xs">string</schema-type> </part> </input-parameters> </xqsview-source>
The XQS view get_poSQ
, defined in the file get_poSQ.xq
, uses a document source and is defined as follows:
declare namespace xqs = "http://xmlns.oracle.com/ias/xqs"; declare variable $bind external; declare function xqs:genericFile($bind as xs:string) external; for $po in xqs:genericFile($bind)//po return $po
And the document source genericFile
is configured as follows:
<document-source> <function-name namespace="http://xmlns.oracle.com/ias/xqs"> genericFile </function-name> </document-source>
The genericFile
function takes the document URL as input, so there is no <documentURL>
element.
Java Code The code follows—a complete class that does the following:
An XQSFacade
instance is created.
The ad-hoc query, which uses the XQS view get_poSQ
, is defined. The query is stored in the string xqueryStr
after being pieced together in a string buffer xqueryBuf
. The URL for the backend document source is taken by the get_poSQ
function as input.
The query is executed. There are no input parameters for the query, so null
is passed in to the execute()
method where the QueryParameter
array would go. (The next example, "Example 3: XQSFacade API with an XQS View", shows an input parameter.)
No error processing is shown here, but if you have appropriate configuration of the source (error mode errorMessage
or emptySequence
), you could retrieve and process error objects. (The next example also shows error processing. Or see "Using XQS Error Handling Modes and APIs" for additional information.)
A while
loop goes through the cursor item by item. Each item is a node, so is placed into an XML document, doc
. From there, results can be displayed or further processed as desired (from that point, the processing is not XQS-specific).
A close()
call closes the cursor and frees associated resources.
import oracle.xml.xqxp.datamodel.XMLItem; import oracle.xml.parser.v2.XMLDocument; import oracle.xml.parser.v2.XMLElement; import oracle.xml.parser.v2.XMLNode; import oracle.xds.client.XQSFacade; public class XQSFacadeTest { public static void main(String[] args) throws Exception{ XQSFacade bean = new XQSFacade(); StringBuffer xqueryBuf = new StringBuffer(); xqueryBuf.append ("declare namespace xqs=\"http://xmlns.oracle.com/ias/xqs\";\n"); xqueryBuf.append ("declare function xqs:get_poSQ($bind as xs:string) external;\n"); xqueryBuf.append("for $po in xqs:get_poSQ (\"http://localhost:8888/myrepository/pos-2KB.xml\") \n"); xqueryBuf.append("return $po\n"); String xqueryStr = xqueryBuf.toString(); //no parameters to be bound, so pass null bean.execute(xqueryStr, null); XMLItem item = bean.getNextItem(); XMLDocument doc = new XMLDocument(); XMLElement rootElem = (XMLElement)doc.createElement("QueryResult"); doc.appendChild(rootElem); while(item != null) { /* the test is actually superfluous - all items are expected to nodes for Purchase Order, here we show a standard treatment of items that are XML nodes, including entire documents (where node type is DOCUMENT_NODE) */ if(item.getItemType().isNode()) { rootElem.appendChild(doc.importNode( item.getNode().getNodeType()== XMLNode.DOCUMENT_NODE?(XMLNode) ((XMLDocument)item.getNode()).getDocumentElement(): (XMLNode)item.getNode(), true)); } item = bean.getNextItem(); } bean.close(); } }
This section has an example using the XQSFacade
API to execute an XQS view directly through an executeView()
call.
Configuration Here is the configuration for an XQS view named BasicFileWS
:
<xqsview-source WSDLvisibility="true" isCached="false" onError="errorMessage"> <function-name prefix="xqs">BasicFileWS</function-name> <input-parameters type-match="none" > <part position="1" name="custName"> <schema-type prefix="xs">string</schema-type> </part> </input-parameters> <output-element namespace="http://xmlns.oracle.com/ias/xqs/CustomerDemo" location="http://host:port/xqsdemos/MyTypes.xsd" type="CustomerOrdersType"> </output-element> </xqsview-source>
There is no <queryName>
element, so the .xq
file name is assumed to be BasicFileWS.xq
(matching the specified function name). The view takes a string parameter, custName
, as input.
Here is the definition of the view BasicFileWS.xq
(a query discussed earlier, in "Query Examples"), including the variable to take the customer name as input. This view uses two XQS functions, for data sources whose configurations are shown immediately following.
declare namespace xqs = "http://xmlns.oracle.com/ias/xqs" ; (: returns payment info for all customers:) declare function xqs:paymentStatusInfo () external; (: returns customer info given customer name :) declare function xqs:customerInfo ($name as xs:string) external; (: customer name passed in to query :) declare variable $custName external; let $custInfo := xqs:customerInfo($custName) for $custOrderInfo in xqs:paymentStatusInfo()/excel/Row[CustomerKey eq $custInfo/key] return <result> <MYEIS_RESULT> <Row> <Name> { $custInfo/name } </Name> <Company> { $custInfo/company} </Company> <Address> { $custInfo/address} </Address> <City> { $custInfo/city} </City> <State> { $custInfo/state} </State> <Zip> { $custInfo/zip} </Zip> </Row> </MYEIS_RESULT> <EXCEL_RESULT> <Row> <OrderID>{$custOrderInfo/OrderId}</OrderID> <Amount>{$custOrderInfo/Amount}</Amount> <PaymentStatus>{$custOrderInfo/PaymentStatus}</PaymentStatus> </Row> </EXCEL_RESULT> </result>
Here is the configuration for the document source associated with the function paymentStatusInfo
. This is a non-XML document, so D3L is used for conversion. (See "Preparing to Use a Non-XML Document Source".)
<document-source isCached="false"> <function-name prefix="xqs">paymentStatusInfo</function-name> <documentURL>http://host:port/xqsdemos/paymentInfo.csv</documentURL> <XMLTranslate method="D3L"> <schema-file> http://host:port/xqsdemos/paymentInfoD3L.xml </schema-file> </XMLTranslate> </document-source>
And here is the configuration for the WSDL source associated with the function customerInfo
. This includes some information for Java-to-XML type mapping.
<wsdl-source isCached="false"> <function-name namespace="http://xmlns.oracle.com/ias/xqs"> customerInfo </function-name> <wsdlURL>http://host:port/xqsdemos/CustomerInfo.wsdl</wsdlURL> <operation>getCustomer</operation> <service prefix="myeis">CustomerInfoMYEISService</service> <port prefix="myeis">CustomerInfo</port> <input-parameters> <part position="1" name="name"> <schema-type prefix="xs">string</schema-type> </part> </input-parameters> <typeMap> <mapping typeClass="org.w3c.dom.Node"> <xmlType prefix="myeis"> Customer </xmlType> </mapping> </typeMap> </wsdl-source>
Java Code This section shows a complete class with Java code for executing the view BasicFileWS
, accomplishing the following:
Obtain an XQSFacade
instance.
Set up the QueryParameter
array to input the customer name.
Execute the view. The view name passed to the executeView()
method must match the function name associated with the view in your configuration. Note this method also takes the namespace of the function (also indicated in your configuration). In this example, the view is declared in the XQS namespace.
Process errors. Methods of the XQSError
class are used to print out information about any errors encountered during the query. This assumes appropriate XQS error configuration to use the emptySequence
or errorMessage
mode; otherwise, an error will terminate the query and there will be no useful information in the errors iterator. In this example, as shown earlier in the BasicFileWS
configuration, errorMessage
mode is used. (See "Using XQS Error Handling Modes and APIs" and "XQSError Class Reference" for additional information.)
Process results. Query results are obtained as instances of class XMLItem
(in package oracle.xml.xqxp.datamodel
). Type constants and type-specific accessors of the XMLItem
class are used to retrieve values.
Close the cursor to free resources associated with the query
Note: There is no need to declare the XQS function,BasicFileWS , when it is executed directly in an executeView() call.
|
import oracle.xml.xqxp.datamodel.XMLItem; import oracle.xml.parser.v2.XMLDocument; import oracle.xml.parser.v2.XMLElement; import oracle.xml.parser.v2.XMLNode; import oracle.xds.client.XQSFacade; import oracle.xds.client.XQSError; import oracle.xds.client.QueryParameter; public class XQSFacadeViewTest { public static void main(String[] args) throws Exception{ XQSFacade facade = new XQSFacade(); String xqueryView = "BasicFileWS"; QueryParameter param = new QueryParameter(null, "custName"); param.setString("John Ford"); QueryParameter[] params = new QueryParameter[1]; params[0] = param; facade.executeView(xqueryView, "http://xmlns.oracle.com/ias/xqs", params); java.util.ListIterator errors = facade.getErrors(); while(errors.hasNext()) { XQSError error = (XQSError)errors.next(); System.out.println ("The function which gives error is: " + error.getFunctionQName()); System.out.println("The error type is: "+error.getErrorType()+ " which is - "+XQSError.typeNames(error.getErrorType())); System.out.println("The error code is:" + error.getErrorCode()); System.out.println("The error message is:" + error.getErrorMessage()); } XMLItem item = facade.getNextItem(); StringBuffer resultBuf = new StringBuffer(); XMLDocument doc = new XMLDocument(); XMLElement rootElem = (XMLElement)doc.createElement("QueryResult"); doc.appendChild(rootElem); while(item != null) { if(item.instanceOfType(XMLItem.XMLITEM_STRING)) { resultBuf.append(item.getString()); } else if(item.instanceOfType(XMLItem.XMLITEM_INT)) { resultBuf.append(item.getInt()); } else if(item.instanceOfType(XMLItem.XMLITEM_LONG)) { resultBuf.append(item.getInt()); } else if(item.instanceOfType(XMLItem.XMLITEM INTEGER)) { if(item.intFormat()) resultBuf.append(item.getInt()); else resultBuf.append(item.getDecimal().intValue()); } else if(item.instanceOfType(XMLItem.XMLITEM_BOOLEAN)) { resultBuf.append(item.getBoolean()); } else if(item.instanceOfType(XMLItem.XMLITEM_FLOAT)) { resultBuf.append((float)item.getDouble()); } else if(item.instanceOfType(XMLItem.XMLITEM_DOUBLE)) { resultBuf.append(item.getDouble()); } else if(item.instanceOfType(XMLItem.XMLITEM_XDT_DAYTIMEDURATION)) { resultBuf.append(item.getDayTimeDuration()); } else if(item.instanceOfType(XMLItem.XMLITEM_YEARMONTHDURATION)) { resultBuf.append(item.getYearMonthDuration()); } else if(item.instanceOfType(XMLItem.XMLITEM_DURATION)) { resultBuf.append(item.getLexicalValue()); } else if(item.instanceOfType(XMLItem.XMLITEM_DATETIME)) { resultBuf.append(item.getCalendar().getTime()); } else if(item.instanceOfType(XMLItem.XMLITEM_ANYURI)) { resultBuf.append(item.getString()); } else if(item.instanceOfType(XMLItem.XMLITEM_DECIMAL)) { resultBuf.append(item.getDecimal().intValue()); } else if(item.instanceOfType(XMLItem.XMLITEM_NODE)) { resultBuf.append(item.getNode().getNodeName()); } else if(item.instanceOfType(XMLItem.XMLITEM_HEXBINARY)) { resultBuf.append(item.getString()); } else if(item.instanceOfType(XMLItem.XMLITEM_BASE64BINARY)) { resultBuf.append(item.getString()); } item = facade.getNextItem(); } facade.close(); } }
Refer to the "General Coding Steps in Using XQS Client APIs". For the XQS EJB client API, there are differences in the details of these steps depending on whether you choose a stateful session or a stateless session, as follows (after creating your query):
Complete appropriate steps to create a bean instance, such as by executing the lookup, obtaining the EJB local home interface, and creating the local interface. Method calls in the following steps are called from this instance. See "EJB Clients for Stateful Versus Stateless Sessions" immediately below for how to create a stateful bean versus a stateless bean.
Create a QueryParameter
array for any input parameters.
Use the execute()
method to execute an ad-hoc query, or the executeView()
method to execute an XQS view, passing in the query and QueryParameter
array (or null
if there are no input parameters). For executeView()
, also pass in the namespace of the XQS function for the view.
For a stateful bean, repeatedly use the getNextItem()
method to get the results back item by item. Each item is returned in an XMLItem
instance. Process these items as desired.
For a stateless bean, the query results are fully materialized as a vector, java.util.Vector
, containing XMLItem
instances. Process this vector of items as desired.
If you configured any of the data sources used in the query with the emptySequence
or errorMessage
error mode, optionally use the getErrors()
method to retrieve any errors encountered within those data sources during execution of the query. This returns an iterator over a collection of XQSError
objects. See "Using XQS Error Handling Modes and APIs" for information about error configuration and processing.
For a stateful bean, use the close()
method to free all resources associated with the query. This is not applicable for a stateless bean.
These steps are shown in examples that follow. Also see "XQS EJB Client API Reference" for reference information.
See "Stateful Versus Stateless Clients" for information about when to use a stateful session and when to use a stateless one.
Obtaining a stateful EJB versus a stateless EJB is determined by your JNDI lookup and which XQS package you use. The following example will obtain a stateful bean:
//Look up and create the EJB to execute the query. InitialContext ic = new InitialContext(); //Use Local client. oracle.xds.client.ejb.stateful.XQSClientLocalHome home = (oracle.xds.client.ejb.stateful.XQSClientLocalHome)ic.lookup ("java:comp/env/XQSClientStatefulLocal"); oracle.xds.client.ejb.stateful.XQSClientLocal bean = home.create();
And this example will obtain a stateless bean:
//Look up and create the EJB to execute the query. InitialContext ic = new InitialContext(); //Use Local client. oracle.xds.client.ejb.stateless.XQSClientLocalHome home = (oracle.xds.client.ejb.stateless.XQSClientLocalHome)ic.lookup ("java:comp/env/XQSClientStatelessLocal"); oracle.xds.client.ejb.stateless.XQSClientLocal bean = home.create();
As noted earlier, when you execute a query (ad-hoc or view) in a stateless EJB session, results are fully materialized in a vector containing XMLItem
instances, which you then process as desired. For a stateful session, after executing the query, you retrieve items one by one using the getNextItem()
method, which returns items of type XMLItem
.
The XQS EJB stateful client API is the same as the XQSFacade
API. Beyond the code shown in the preceding section to create the bean, code examples for a stateful EJB client would look like what is shown for XQSFacade
in "Example 2: XQSFacade API with an Ad-Hoc Query" and "Example 3: XQSFacade API with an XQS View". You loop to repeatedly use the getNextItem()
method to retrieve and process items one by one, as XMLItem
instances.
This stateless EJB example reuses the BasicFileWS
XQS view used in "Example 3: XQSFacade API with an XQS View", and repeats some of that code. Refer to that section to see the view and its configuration.
In addition to the JNDI lookup and creation of the stateless bean, the key difference between this stateless EJB example and an XQSFacade
example is in the result processing. Results for a stateless session are fully materialized into a vector containing XMLItem
instances. You then retrieve items one by one from there, casting them as XMLItem
, as opposed to there being a getNextItem()
method in the bean to retrieve XMLItem
instances. The basic nature of the processing remains the same, however.
... //lookup and create the EJB to execute the xquery InitialContext ic = new InitialContext(); oracle.xds.client.ejb.stateless.XQSClientLocalHome home = (oracle.xds.client.ejb.stateless.XQSClientLocalHome) ic.lookup("java:comp/env/XQSClientStatelessLocal"); oracle.xds.client.ejb.stateless.XQSClientLocal bean = home.create(); String xqueryView = "BasicFileWS"; QueryParameter param = new QueryParameter("custName"); param.setString("John Ford"); QueryParameter[] params = new QueryParameter[1]; params[0] = param; java.util.Vector result = bean.executeView(xqueryView,"http://xmlns.oracle.com/ias/xqs",params); java.util.Enumeration resultEnum = result.elements(); while(resultEnum!=null && resultEnum.hasMoreElements()) { XMLItem item = (XMLItem)resultEnum.nextElement(); if(item.instanceOfType(XMLItem.XMLITEM_STRING)) { resultBuf.append(item.getString()); } else if(item.instanceOfType(XMLItem.XMLITEM_INT)) { resultBuf.append(item.getInt()); } else if(item.instanceOfType(XMLItem.XMLITEM_LONG)) { resultBuf.append(item.getInt()); } else if(item.instanceOfType(XMLItem.XMLITEM_INTEGER)) { if(item.intFormat()) resultBuf.append(item.getInt()); else resultBuf.append(item.getDecimal().intValue()); } else if(item.instanceOfType(XMLItem.XMLITEM_BOOLEAN)) { resultBuf.append(item.getBoolean()); } else if(item.instanceOfType(XMLItem.XMLITEM_FLOAT)) { resultBuf.append((float)item.getDouble()); } else if(item.instanceOfType(XMLItem.XMLITEM_DOUBLE)) { resultBuf.append(item.getDouble()); } else if(item.instanceOfType(XMLItem.XMLITEM_XDT_DAYTIMEDURATION)) { resultBuf.append(item.getDayTimeDuration()); } else if(item.instanceOfType(XMLItem.XMLITEM_YEARMONTHDURATION)) { resultBuf.append(item.getYearMonthDuration()); } else if(item.instanceOfType(XMLItem.XMLITEM_DURATION)) { resultBuf.append(item.getLexicalValue()); } else if(item.instanceOfType(XMLItem.XMLITEM_DATETIME)) { resultBuf.append(item.getCalendar().getTime()); } else if(item.instanceOfType(XMLItem.XMLITEM_ANYURI)) { resultBuf.append(item.getString()); } else if(item.instanceOfType(XMLItem.XMLITEM_DECIMAL)) { resultBuf.append(item.getDecimal().intValue()); } else if(item.instanceOfType(XMLItem.XMLITEM_NODE)) { resultBuf.append(item.getNode().getNodeName()); } else if(item.instanceOfType(XMLItem.XMLITEM_HEXBINARY)) { resultBuf.append(item.getString()); } else if(item.instanceOfType(XMLItem.XMLITEM_BASE64BINARY)) { resultBuf.append(item.getString()); } // Here is where you might use a bean.getErrors() call and process errors. // (Assuming appropriate configuration.) } ...
Refer to the "General Coding Steps in Using XQS Client APIs". For the XQS JSP tag library, there are differences in the details of these steps depending on whether you choose a stateful or stateless access mode, as follows (after creating your query):
Import the XQS JSP tag library through a taglib
statement, specifying the TLD URI and desired prefix.
Use an executeCursor
tag to execute a query in a stateful mode, or an execute
tag to execute a query in a stateless mode. With either an executeCursor
or execute
tag:
Use the xqueryString
attribute to specify an ad-hoc query, or the xqsViewName
and namespace
attributes to specify an XQS view.
Define output variables for results of the query: to an XML document (by using the toXMLDoc
attribute) and to a java.util.ArrayList
instance of results (by using the resultItems
attribute). Also, you can optionally output to the JSP output stream (by using the toWriter
attribute). Results will be represented by Java object types according to Table 8-2, "XQS Type Support for Bind Parameters".
If you configured any of the data sources used in the query with the emptySequence
or errorMessage
error mode, optionally use the errors
attribute to process any errors encountered within those data sources during execution of the query. This will give you an iterator over a collection of XQSError
objects. See "Using XQS Error Handling Modes and APIs" for information about error configuration and processing.
In either an executeCursor
or execute
tag, use a param
subtag for each input parameter. Use the param
tag localName
, namespace
, value
, and type
attributes as appropriate.
With the executeCursor
tag, use the related next
tag to retrieve results item by item or in batches and place them into the output vehicles.
With the execute
tag, results are fully materialized into the output vehicles.
Loop through one or more output vehicles to process the results. This is not XQS-specific, as the available output vehicles—JSP output stream, XML document, and list of Java objects—are standard. Be aware that results of each execution of next
must be processed before next
is executed again, because results are overwritten.
With the executeCursor
tag, use the close
tag to free all resources associated with the query. This is not applicable for the execute
tag.
These steps are shown in examples that follow. Also see "XQS JSP Tag Library Reference" for reference information.
Note: You can also use standard JSTL tags in a JSP page to transform results as desired. |
See "Stateful Versus Stateless Clients" for information about when to use stateful access and when to use stateless access.
In a JSP page employing XQS, whether you use stateful access or stateless access is determined by which query tag you use. The executeCursor
tag uses stateful access, while the execute
tag uses stateless access.
As noted earlier, when you execute a query (ad-hoc or view) in a stateless JSP access pattern, results are fully materialized into the output vehicles you choose through your attribute settings—an XML DOM document and an Object[]
array, and optionally the JSP output stream—and then you process those results as desired. For a stateful access pattern, after executing the query, you retrieve and process items one by one using the next
tag.
This stateful JSP example reuses the BasicFileWS
XQS view used in "Example 3: XQSFacade API with an XQS View". Refer to that section to see the view and its configuration.
The code shown below does the following:
The page
directives import required classes.
A taglib
directive specifies the TLD URI of the tag library, and the desired tag prefix to use.
The executeCursor
tag executes the view, resulting in an open cursor ready for fetching. The namespace
attribute specifies the namespace where the underlying XQSView function is defined.
The param
subtag of executeCursor
specifies the input parameter (customer name).
The next
tag, associated with the executeCursor
tag through the cursorId
setting, loops through the results to populate the output vehicles (XML document and result items ArrayList
instance), using the itemsFetched
attribute each time through as a test of whether any data remains to be processed. The next
tag must reference the cursor ID (mycursor
) specified in the executeCursor
tag.
The close
tag closes the cursor and frees resources associated with it. This tag must also reference the cursor ID (mycursor
) specified in the executeCursor
tag.
Notes:
|
<%@ page import="oracle.xml.parser.v2.XMLElement" %> <%@ page import="oracle.xml.parser.v2.XMLDocument" %> <%@ taglib uri="http://xmlns.oracle.com/j2ee/jsp/tld/ojsp/xquerytag.tld" prefix="xq"%> <% String xqueryView = "BasicFileWS"; int items; %> <xq:executeCursor xqsViewName="<%=xqueryView%>" namespace="http://xmlns.oracle.com/ias/xqs" resultItems="myresults" toXMLDoc="mydoc" cursorId="mycursor" errors="myerrors" > <xq:param localName="custName" value="John Ford" type="String"/> </xq:executeCursor> <% do{ // Populate the XML document and result items array. %> <xq:next cursorId="mycursor" itemsFetched="fetched" /> <% items=fetched.intValue(); }while(items>0) // Here is where you might process the "myerrors" error iterator. // (Assuming appropriate configuration.) // Retrieve results from XML document mydoc and/or result items array myresults. // (This processing is not XQS-specific.) %> <xq:close cursorId="mycursor" />
This example uses the XQS JSP execute
tag to execute an ad-hoc query, and a stateless access pattern is used. The intent is primarily to compare and contrast the following, compared to the preceding example using stateful access:
Use an ad-hoc query instead of a view. See "Example 2: XQSFacade API with an Ad-Hoc Query", which uses the same query, for relevant configuration. The query is pieced together in a string buffer, then written from there to a string.
Use the execute
tag, for stateless access, instead of the executeCursor
tag, for stateful access. Note that there is no next
subtag for an execute
tag, and the close
tag is not required.
<%@ page import="oracle.xml.xqxp.datamodel.XMLItem" %> <%@ page import="oracle.xml.parser.v2.XMLElement" %> <%@ page import="oracle.xml.parser.v2.XMLDocument" %> <%@ taglib uri="http://xmlns.oracle.com/j2ee/jsp/tld/ojsp/xquerytag.tld" prefix="xq"%> <% StringBuffer xqueryBuf = new StringBuffer(); xqueryBuf.append("declare namespace xqs=\"http://xmlns.oracle.com/ias/xqs\";\n"); xqueryBuf.append("declare function xqs:get_poSQ($bind as xs:string) external;\n"); xqueryBuf.append("for $po in xqs:get_poSQ(\"http://localhost:8888/myrepository/pos-2KB.xml\") \n"); xqueryBuf.append("return $po\n"); String xqueryStr = xqueryBuf.toString(); %> <xq:execute xqueryString="<%=xqueryStr%>" toXMLDoc="mydoc" resultItems="myresults" errors="myerrors" /> <% // Here is where you might process the "myerrors" error iterator. // (Assuming appropriate configuration.) %> <% // Retrieve the results from either the XML document mydoc or result items array // myresults. (This processing is not XQS-specific.) %>
XQS can expose an XQS view as a Web service operation, with the Web service being implemented through a servlet that is generated automatically. This and related details are described in "OC4JPackager Additional Output to Expose XQS Views as Web Service Operations".
Note that you must provide the Web service client yourself.
This section describes how to use OC4JPackager to bundle XQS-related files with your application. See "Introduction to OC4JPackager" for an overview.
OC4JPackager produces an EAR file which you can deploy to OC4J as you would any other EAR file. See the Oracle Containers for J2EE Deployment Guide for general information.
The following topics are covered here:
This section covers the basic preparatory and execution steps when you have a J2EE application and want to run OC4JPackager to enable it to use XQS features. See "OC4JPackager Reference" for general information about the OC4JPackager parameters and Java properties mentioned here.
Note: OC4JPackager does not support directory or file names with spaces. |
Complete these steps to prepare to run OC4JPackager:
Create JAR files for your application components as usual—WAR files for Web modules, EJB JAR files for EJB modules, and so on, all with the applicable standard J2EE configuration files (such as web.xml
and ejb-jar.xml
). You then have the option of bundling them into an EAR file for OC4JPackager to access, or leaving them and any other relevant files (such as application.xml
) in a directory structure reflecting the structure and contents of an EAR file.
Choose a desired directory for your application, and place the EAR file or structured EAR contents (as applicable) in that directory.
You will specify that directory to OC4JPackager through the -appArchives
parameter (required).
Choose a desired directory as your XQS repository, where any XQS view (.xq
) files are located, and place the XQS view (.xq
) files there.
You can specify that directory to OC4J Packager through the -repository
parameter.
Assuming you have completed your XQS configuration (see "How to Configure Your XQS Functions"), choose a desired directory for the xqs-config.xml
file and place the file in that directory.
You will specify that directory to OC4JPackager through the -xqsConfig
parameter (required).
If you would like to expose XQS view sources in the global configuration as Web services through your application, choose a desired directory for the global-xqs-config.xml
file and place the file in that directory.
You will specify that directory to OC4JPackager through the -globalXqsConfig
parameter.
Specify the following, as applicable, when you run OC4JPackager. See the next section, "Running OC4JPackager on the Command Line", for examples.
Program Parameters
Use the required -appArchives
parameter to specify the directory where your application is located (where the EAR file is, or the top-level directory of an EAR structure).
Use the optional -repository
parameter to specify the directory for your XQS repository.
Use the required -xqsConfig
parameter to specify the full path of your application xqs-config.xml
file, including the file name.
If the global XQS configuration file includes configuration for XQS views and you would like to expose XQS view sources in the global configuration as Web services through your application, use the -globalXqsConfig
parameter to specify the full path of the global-xqs-config.xml
file, including the file name.
Use the required -name
and -output
parameters to specify the desired name and output directory of the EAR file that OC4JPackager will produce.
Use applicable flags to have OC4JPackager include files for XQS features that your application uses:
Use the -jsp
flag if you use the XQS JSP tag library.
Use the -sf
flag if you use the XQS stateful EJB client API.
Use the -sl
flag if you use the XQS stateless EJB client API.
(The XQSFacade
class is always included.)
Java VM Properties
Use the required Java property java.home
to specify your Java home directory, from which OC4JPackager will run the java
command for its tasks.
Use the optional Java property xds.packager.work.dir
if you want to have OC4JPackager use a particular working directory (where it unbundles and bundles EAR files as needed). The default is the directory specified by the user.home
Java property,.
Use the optional Java property java.util.logging.properties.file
to specify a logging properties file where you can specify Java logging settings, including the OC4JPackager logging level. Logging properties are defined by standard J2SE logging, as described in the following guide:
http://java.sun.com/j2se/1.4.2/docs/guide/util/logging/
Use the optional Java property oracle.home
if you want to indicate your Oracle home directory. You must do this to use OC4JPackager flags -jsp
, -sf
, and -sl
(described in "OC4JPackager Parameters") and related JAR files.
You can run OC4JPackager from a command line by using the java
command to execute OC4JPackager.jar
(where %
is the command prompt):
% java -jar OC4JPackager.jar ...
OC4JPackager.jar
is in the xds/tools
directory of your XQS distribution.
Here is an example (where $ORACLE_HOME
has been set as the home directory of your Oracle installation, and "\
" indicates line wrap). This is for an application that uses the XQS JSP tag library and stateful EJB client API, and has no relevant configuration in the XQS global configuration file. Note that you can specify paths that are either relative to your current directory, or absolute.
% java -jar OC4JPackager.jar \ -Djava.home=/home/myjavainstall \ -Dxds.packager.work.dir=$ORACLE_HOME/temp \ -Doracle.home=$ORACLE_HOME \ -Djava.util.logging.properties.file=myfile.properties \ -appArchives $ORACLE_HOME/myapp \ -xqsConfig $ORACLE_HOME/xds/myconfig/xqs-config.xml \ -repository $ORACLE_HOME/xds/repository \ -output $ORACLE_HOME/xds/mystaging -name myxqsapp.ear \ -jsp -sf
Alternatively, you can run OC4JPackager through Ant, as described in the next section.
Also see "OC4JPackager Basic Output".
As an alternative to running OC4JPackager from a command line, as described in the preceding section, you can run it as part of a build process using Ant, through the standard Ant java
task. Refer to the Apache Web site http://ant.apache.org/manual/
for general information about Ant. (In addition, if you are interested, see the Oracle Containers for J2EE Deployment Guide for information about OC4J-specific Ant tasks.)
The following example from an Ant build file executes OC4JPackager, and corresponds to the command-line example shown in the preceding section:
<java jar="OC4JPackager.jar" fork="true" failonerror="true"> <jvmarg value="-Doracle.home=${ORACLE_HOME}"/> <jvmarg value="-Djava.home=/home/myjavainstall"/> <jvmarg value="-Dxds.packager.work.dir=${ORACLE_HOME}/temp"/> <jvmarg value="-Djava.util.logging.properties.file=myfile.properties"/> <arg line="-appArchives ${ORACLE_HOME}/myapp"/> <arg line="-xqsConfig ${ORACLE_HOME}/xds/myconfig/xqs-config.xml"/> <arg line="-repository ${ORACLE_HOME}/xds/repository"/> <arg line="-output ${ORACLE_HOME}/xds/mystaging" /> <arg line="-name myxqsapp.ear"/> <arg line="-jsp"/> <arg line="-sf"/> </java>
Important: In the<arg> elements to set OC4JPackager parameters, use the line attribute, as shown, as opposed to the value attribute.
|
The EAR file produced by OC4JPackager has the standard structure, with at least one additional component—a file named xqs-resources.jar
that contains the XQS configuration file and a directory with the XQS repository files (.xq
files for XQS views).
Note: The EAR file will contain additional components if you have XQS views that you are exposing as Web service operations. See the next section, "OC4JPackager Additional Output to Expose XQS Views as Web Service Operations". |
For an application consisting of a Web module mywebapp
and EJB module myejb
, here are the contents of the EAR file that OC4JPackager would produce:
META-INF/ application.xml orion-application.xml data-sources.xml mywebapp.war myejb.jar xqs-resources.jar
Aside from xqs-resources.jar
, your application must already include the application.xml
file, plus optional orion-application.xml
and data-sources.xml
files, if needed, WAR files for any Web modules, EJB JAR files for any EJB modules, and so on.
The structure of xqs-resources.jar
is as follows:
APP-REPOSITORY/ filename.xq filename.xq filename.xq ... xqs-config.xml xds-application.properties
The file xds-application.properties
is for internal use by XQS.
For any XQS view with a setting of WSDLvisibility="true"
in the XQS configuration, XQS exposes the view as a Web service operation. (You must have a Web service client to invoke the operation, as for any Web service.)
OC4JPackager creates an implementation of the Web service and a WSDL document that defines an operation for each XQS view to be exposed. OC4JPackager then produces a WAR file with contents including the following:
The WSDL document
Web module configuration file web.xml
, to configure the Web service servlet
Web services configuration file oracle-webservices.xml
OC4JPackager also updates the application.xml
file for your application, to make an entry for the additional Web module.
The name of the additional Web module, representing the XQS View Web service, as well as the context root and the WAR file correspond to the name of your application, such as the following for an application myapp
:
/myapp-WS
—the context root of the Web services module
myapp-WS-web.war
The generated WSDL file is always names xqsview-WS.wsdl
.
The URL pattern for the servlet representing the Web service (and leading to the Oracle Web service test page) is always /xqs-ws
.
Thus, the URL for the WSDL of the XQS view Web service is http://
host
:
port
/myapp-WS/xqs-ws?WSDL
.
Note: The additional WAR file does not contain client invocation code for Web services. It is intended to be part of your application deployment on the server. |
In the WSDL document, the wsdl:operation
will have the same name as the corresponding XQS function name defined in the XQS configuration (in the <function-name>
subelement of <xqsview-source>
). Each wsdl:input
message type maps to the XML types corresponding to the input parameter types defined in the XQS configuration (under the <input-parameters>
subelement of <xqsview-source>
). The wsdl:output
message type maps to the XML element or type corresponding to the output element defined in the XQS configuration (in the <output-element>
subelement of <xqsview-source>
). These can be either simple types such as string
or int
, or complex types defined by users. The bindings will be SOAP doc/wrapped bindings.
The following sections together provide an example:
Example: Configuration to Expose a View as a Web Service Operation
Example: EAR File for a View Exposed as a Web Service Operation
Example: WAR File for a View Exposed as a Web Service Operation
Example: WSDL document for a View Exposed as a Web Service Operation
The following configuration, seen earlier in this chapter, exposes the view BasicFileWS
as a Web service operation, through the setting WSDLvisibility="true"
.
<xqsview-source WSDLvisibility="true" isCached="false"> <function-name prefix="xqs">BasicFileWS</function-name> <input-parameters type-match="none" > <part position="1" name="custName"> <schema-type prefix="xs">string</schema-type> </part> </input-parameters> <output-element namespace="http://xmlns.oracle.com/ias/xqs/CustomerDemo" location="http://host:port/xqsdemos/MyTypes.xsd" type=CustomerOrdersType>customerOrders </output-element> </xqsview-source>
Assume, for ensuing discussion, that this is part of an application called myapp
.
Assume an application, myapp
, comprises mywebapp.war
and myejb.jar
and exposes one or more XQS views as Web service operations. Here are the relevant contents of the application EAR file after we run OC4JPackager:
META-INF/ application.xml mywebapp.war myejb.jar myapp-WS-web.war xqs-resources.jar
The WAR file myapp-WS-web.war
is for the automatically created servlet implementation of the Web service operations for any exposed views. See the next section for its contents.
Here are the contents of myapp-WS-web.war
, created for a servlet implementation of the Web service operations for any exposed views:
WEB-INF/ web.xml oracle-webservices.xml wsdl/ xqsview-WS.wsdl
In particular, note the WSDL document. Sample fragments of the WSDL are shown in the next section, "Example: WSDL document for a View Exposed as a Web Service Operation".
This section shows fragments of a WSDL document generated through use of OC4JPackager for an XQS view being exposed as a Web service. This example focuses on fragments relating to a view named BasicFileWS
.
... <definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:__xqscws="xqs-client-ws" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xqs0="http://xmlns.oracle.com/ias/xqs" xmlns:tns="xqs- client-ws_myapp-WS" name="myapp-WS" targetNamespace="xqs- client-ws_myapp-WS"> ... <types> ... <schema targetNamespace="http://xmlns.oracle.com/ias/xqs" xmlns:xqs1="http://xmlns.oracle.com/ias/xqs/CustomerDemo" xmlns:tns="http://xmlns.oracle.com/ias/xqs" ... > <import namespace=Óhttp://xmlns.oracle.com/ias/xqs/CustomerDemoÓ schemaLocation=Óhttp://host:port/xqsdemos/MyTypes.xsdÓ/> <complexType name="BasicFileWSType"> <sequence> <element name="custName" type="string" nillable="true" /> </sequence> </complexType> <complexType name="BasicFileWSResultType"> <sequence> <element name="return" nillable="true"> <complexType> <sequence> <element name="result" nillable="true"> <complexType> <sequence> <element name="customerOrders" type="xqs1:CustomerOrdersType" minOccurs="0" maxOccurs="unbounded" /> </sequence> </complexType> </element> <element name="errors" nillable="true" minOccurs="0"> <complexType> <sequence> <element name="xqserror" type="__xqscws:XQSErrorType" maxOccurs="unbounded" /> </sequence> </complexType> </element> </sequence> </complexType> </element> </sequence> </complexType> <element name="BasicFileWS" type="tns:BasicFileWSType" /> <element name="BasicFileWSResult" type="tns:BasicFileWSResultType" /> … </schema> … </types> … <message name="BasicFileWSRequest"> <part name="parameters" element="xqs0:BasicFileWS" /> </message> <message name="BasicFileWSResponse"> <part name="return" element="xqs0:BasicFileWSResult" /> </message> … <portType name="XQSViewWebServices"> <operation name="BasicFileWS"> <input message="tns:BasicFileWSRequest" /> <output message="tns:BasicFileWSResponse" /> </operation> … </portType> <binding name="HttpSoap11Binding" type="tns:XQSViewWebServices"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" /> <operation name="BasicFileWS"> <soap:operation /> <input> <soap:body use="literal" parts="parameters" /> </input> <output> <soap:body use="literal" parts="return" /> </output> </operation> … </binding> <service name="XQSView-WS"> <port name="HttpSoap11" binding="tns:HttpSoap11Binding"> <soap:address xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" location="http://host:port/myapp-WS/xqs-ws" /> </port> </service> </definitions>
This section discusses performance features that XQS offers. The following topics are covered:
As noted previously, the XQS client APIs give you the choice of stateless query execution, where results are fully materialized into process memory, or stateful query execution, where results are accessed incrementally through a cursor. Each approach has advantages and disadvantages. For most situations, stateless execution is preferable because associated resource are freed immediately after the evaluation is completed. However, stateless execution is not feasible when the total size of items in the result sequence may be too large, such that materializing the whole sequence at one time would run out of process memory. In this case, cursor mode is the only option, as long as there is nothing (such as aggregate expressions, for example) preventing the query from providing the results item-by-item.
See "Stateful Versus Stateless Clients" for additional information.
This section covers the details of how to configure the cache when using XQS, and discusses related considerations:
Important: The XQS 10.1.3 implementation uses the OC4J Java Object Cache for its caching. The Java Object Cache must be running (and will be started automatically if necessary), and its configuration file,ORACLE_HOME /j2ee/home/config/javacache.xml , must be present. There is generally no need for you to update this file directly, but you have that option. See Chapter 7, "Java Object Cache," for more information.
QQ Alfred: Please change "Chapter 7, "Java Object Cache," " (above) to live cross-reference. Be aware that any configuration of the Java Object Cache applies across the OC4J instance, not just to your XQS application. |
XQS caching is configured individually for each XQS function (essentially, for each data source that you access). Use the steps that follow to employ caching for any particular XQS function.
Strategies to consider are discussed in the next section, "XQS Caching Strategies". Complete documentation for all the elements and attributes mentioned here is under "XQS Configuration File Reference".
Enable caching through the isCached
attribute of the <document-source>
, <xqsview-source>
, or <wsdl-source>
element. For example:
<document-source isCached="true"> ... </document-source>
Important: IfisCached has a value of "false " (the default), all other cache settings for the XQS function are ignored.
|
Use the <cache-properties>
subelement of <document-source>
, <xqsview-source>
, or <wsdl-source>
. The time-to-live
attribute takes an integer value to determine how long, in seconds, cache entries are maintained before expiring. For example:
<cache-properties time-to-live="600"> ... </cache-properties>
Use the <in-memory>
subelement of <cache-properties>
to specify which cache mode to use, through the useSpool
and useDiskCache
attributes. For plain memory-based caching, set useSpool
and useDiskCache
both to "false
". For memory-based caching with the capability of spooling cached data to disk as necessary in case of any memory shortage, set useSpool
to "true
" and useDiskCache
to "false
". For disk-based caching, set useDiskCache
to "true
" and useSpool
to "false
". (See "XQS Caching Strategies", immediately below, for related considerations.) The following example uses memory-based caching, but with spooling if necessary:
<in-memory useSpool="true" useDiskCache="false"/>
Here is the complete cache configuration example:
<document-source isCached="true"> ... <cache-properties time-to-live="600"> <in-memory useSpool="true" useDiskCache="false"/> </cache-properties> ... </document-source>
Note the following considerations for XQS caching:
In situations where data is expensive in any way (in time, in terms of any other possible access costs, or in terms of application overhead), you should probably cache your sources. You should also consider the possible impact of caching on the OC4J instance system memory, but memory effects can be alleviated through disk-based caching, or memory-based caching with spooling. (These are discussed immediately below.)
In order to cache query results, define a query as an XQS view. A view, being a type of XQS source, can be cached (meaning its results are cached).
Expiration, or time-to-live, of cached objects is at your discretion. The nature of the data, and how old it can be without losing its usefulness, determines how long it should be cached before expiring.
In defining your <in-memory>
settings, consider whether to use plain memory-based caching (useSpool="false"
and useDiskCache="false"
); memory-based caching with spooling to disk, in case that is necessary due to memory shortage (useSpool="true"
and useDiskCache="false"
); or disk-based caching (useSpool="false"
and useDiskCache="true"
). See "<in-memory>" for additional information. Note the following:
Plain memory-based caching has the fastest performance but the greatest risk of loss of cached data, due either to memory shortage or server failure.
Memory-based caching with spooling is faster than disk-based caching (unless memory issues result in cached data always being spooled), but risks the loss of cached data in case of server failure.
Disk-based caching has the slowest performance, but the greatest safety for cached data. There are no memory concerns, and cached data is recovered in the event of server failure.
Balance the criticality of cached data versus the importance of execution speed.
Be aware that the issue of XQS functions and node identity, described in "Requirements, Limitations, and Special Notes for the Current Release", may be relevant in some unusual or atypical situations, resulting in differing query results depending on whether caching is used. Generally this is not an issue, however, as the great majority of queries depend on equality between values, not between nodes.
There are situations where data sets are so large that memory limitations are encountered regardless of system capacity or the use of typical memory conservation. A solution for this is to use a "working unit" approach behind the scenes, where a constant amount of memory is used regardless of the total amount of data being retrieved. XQS is cooperating with dependent technologies in the Oracle XDK and middle-tier XQuery to provide such a scalable solution whenever you are running XQS.
There are also situations, however, where data sets are large enough that even the "working unit" approach is insufficient. In these circumstances, for document sources and XQS view sources, you can provide a hint to XQS that the data source may take up sizable memory resources, and that XQS should use memory-saving internal optimizations. Use the largeData
flag—an attribute of the <document-source>
and <xqsview-source>
elements—as in the following example:
<document-source largeData="true"> ... </document-source>
If you have trouble loading a large document source or XQS view source into memory, enabling this flag may allow you to proceed.
Important:
|
For WSDL sources with SQL binding, XQS has special functionality to analyze each XQuery expression and try to choose the most efficient way to execute it. In particular, if you have expressions that apply an XPath path to the results of the function call, it is best to apply the path directly at the point of the function call.
For example, assume mySQLData()
is for a WSDL source with SQL binding, executing a relational query and returning results as XML. First consider the following XQuery expression:
... for $i in mySQLData(param) return <c> $i/a/b/c </c>
By comparison, now consider this XQuery expression:
... for $i in mySQLData(param)/a/b/c return <c> $i </c>
The second XQuery expression is equivalent to the first, but may execute faster and bring in less data from the database to the OC4J server space, if the XPath expression selects only a small subtree of the XML result returned by mySQLData()
. This is because in the second case, the XPath expression "/a/b/c
" would be executed by the XQuery engine in the database, and therefore only the "c
" sub-tree would be brought into the XQS application running on OC4J. XQS applies this optimization to a certain subset of XPath expressions, such that the correctness of the result is assured.
Note: This optimization is supported only with Oracle Database and a version of 10.2 or higher. |
As noted in "Introduction to XQS Error Handling", you can configure XQS functions to continue even if they encounter errors (such as data source unavailability or data conversion problems). If you do configure XQS functions to continue, you can then retrieve the errors, which are returned as an iterator over oracle.xds.client.XQSError
objects, and obtain information about the errors.
XQS applies special handling only to errors inside an XQS function. A regular XQuery error, such as a syntax error or type mismatch, terminates query execution regardless of the XQS error mode.
You configure the XQS error mode for each XQS function individually. The error mode for one function does not have any effect on the behavior of other XQS functions in the same query.
The following sections discuss how to configure XQS functions to continue and return error information, and what methods are available to retrieve that information:
For each data source you configure in xqs-config.xml
(or global-xqs-config.xml
), you can specify XQS error-handling through the onError
attribute of the source element—<document-source>
, <xqsview-source>
, or <wsdl-source>
. The following settings are supported.
dynamicError
(default): With this setting, XQS raises an XQuery dynamic error and the query is terminated if any problem is encountered during evaluation of the XQS function. In this circumstance, no error objects are returned; you cannot retrieve any information beyond the exception message itself.
emptySequence
: With this setting, in the event of an error generated by the XQS function, the function returns an empty XML sequence as its result, and the query execution can continue. You can retrieve error objects and obtain information from them as discussed in the sections that follow.
errorMessage
: With this setting, in the event of an error generated by the XQS function, the function returns a one-item XML sequence for the function result. The item in the sequence represents an error message—either a preconfigured message or whatever message the data source returns, depending on your configuration. You can also retrieve error objects and obtain information from them as discussed in the sections that follow.
So there are possibly two steps in configuring your XQS error-handling for a particular data source:
Specify the desired setting of the onError
attribute in the <document-source>
, <xqsview-source>
, or <wsdl-source>
element.
If you are using errorMessage
mode, optionally use the <error-message>
subelement of <document-source>
, <xqsview-source>
, or <wsdl-source>
. This will preconfigure an error message for XQS to place in the one-item XML sequence that is returned for the query result.
Here is an example for a source that uses emptySequence
mode:
<document-source onError="emptySequence"> ... </document-source>
And here is an example that uses errorMessage
mode with a preconfigured message:
<wsdl-source onError="errorMessage"> ... <error-message>No information available</error-message> ... </wsdl-source>
In errorMessage
mode, if you do not specify a preconfigured message (in other words, if you do not use an <error-message>
element), then XQS will take whatever message is returned by the data source, and put that message in the one-item XML sequence that is returned as the function result. Occasionally it will be impossible to obtain any meaningful error message from a data source with poor error-reporting facilities. In that case, if you did not provide a preconfigured message, the error message returned will be empty.
The single item in the sequence returned can be of one of two types: xs:string
or xs:node.
If the item is a string, the string is simply the error message, either preconfigured or taken from the actual error that occurred.
If the item is an XML node, it will be called xqserror
and its text value will be the error message. In addition, the error node will have three attributes: functionName
, type
and code
. The XQS error node looks like this:
<xqserror functionName="XQS function name" type="XQSERR_XXX" code="XQS 0NNN" > error message </xqserror>
XQS chooses a more appropriate type for the error item based on the type information it has about the function:
If the XQS function is a Document function, the error item will be of type xs:node
. This is because a Document function is always expected to return an XML node.
If the XQS function is configured with <output-element>
, and the type or element name is not a primitive XML Schema type, XQS assumes that the function is an XML element type and creates the error item as an XML node.
If <output-element>
specifies a primitive XML Schema type (even if it is not xs:string
), or if <output-element>
is not provided, then XQS creates the error item as a string.
Notes:
|
Assuming an XQS function is configured to use the emptySequence
or errorMessage
error-handling mode, you can use features of the XQS client APIs to retrieve an iterator of error objects, from which you can obtain information about any problems that occurred during the query. Here is a quick summary:
If you use the XQSFacade
class or either of the XQS EJB APIs (stateful or stateless), use the following method to retrieve an iterator containing error objects:
java.util.ListIterator getErrors()
If you use the XQS JSP tag library (stateful or stateless), specify the desired variable name as the value of the errors
attribute of the execute
or executeCursor
tag. The JSP tag implementation creates the ListIterator
variable and populates it with an iterator containing error objects.
In either case, you will have an iterator containing oracle.xds.client.XQSError
objects. Here is an example:
... XQSFacade bean = new XQSFacade(); ... bean.executeView(viewname, namespace, queryparams); ... ListIterator errorIt = bean.getErrors(); XQSError error = null; while(errorIt.hasNext()) { error = (XQSError)errorIt.next(); (Process errors) } ... bean.close(); ...
And here is a JSP example:
XQSError error=null;
...
<xq:executeCursor ... errors="errorIt" ... >
...
</xq:executeCursor>
...
<xq:next ... />
while(errorIt.hasNext()) {
error = (XQSError)errorIt.next();
(Process errors)
}
See the next sections, "Obtaining Information from XQS Error Objects" and "Example: Error Retrieval and Processing", for information and examples for obtaining error information.
The preceding section, "Retrieving XQS Error Objects", describes how to obtain a java.util.ListIterator
instance consisting of oracle.xds.client.XQSError
objects.
You can process the iterator instance to obtain the individual XQSError
objects. The ListIterator
type includes the following methods:
Object next()
: This returns the next element in the iterator. You can cast each element to the XQSError
type.
boolean hasNext()
: This returns true
if there are elements remaining.
You can then use the individual XQSError
instances to obtain information about each error that occurred during a query.
Notes:
|
This section summarizes the XQSError
methods for obtaining error information, and also summarizes XQS error types. For complete information, see "XQSError Class Reference".
With each XQSError
instance, you can do the following. Assume an XQSError
instance, xqserr
, for these examples:
Obtain the qualified name of the XQS function that returned the error:
String funcname = xqserr.getFunctionQName();
Obtain the error type (see immediately below for types):
int errortype = xqserr.getErrorType();
Obtain string representation of the error type:
String typeStr= XQSError.typeNames(xqserr.getErrorType()
Obtain the error message:
String errormessage = xqserr.getErrorMessage();
For data sources that provide error codes separately from error messages (such as ORA-xxxxx
codes from an Oracle database), obtain the error code:
String errorcode = xqserr.getErrorCode();
Optionally use utility methods to combine the function name, error type, error message, and error code into a single string, an XML string (a string that includes appropriate XML markup), or an XML node:
String errorstring = xqserr.toString(); ... String errorxmlstring = xqserr.toXMLString(); ... org.w3c.dom.node errornode = xqserr.toXMLNode();
Here is a summary of the integer constants for error types:
XQSERR_MISSING_SRC
: Data source not found.
XQSERR_SRC_ACCESS
: Data source found but returns an access error (such as invalid login).
XQSERR_SRC_ERROR
: Data source found and accessed but returns some other error.
XQSERR_PARAM
: Problems encountered in passing bind parameters to the source, or receiving output parameters from the source.
XQSERR_SRC_CONFIG
: Problems encountered in processing XQS configuration.
XQSERR_INTERNAL:XQS encountered unexpected internal error.
See "XQSError Class Reference" for additional information about these constants.
This section shows a simple error-processing example with corresponding configuration.
Configuration To use XQSError
objects in an XQS application (as discussed earlier, in "Configuring XQS Function Error Handling"), the data source must be configured for error mode emptySequence
or errorMessage
. The following example uses errorMessage
mode:
<xqsview-source ... onError="errorMessage"> <function-name prefix="xqs">BasicFileWS</function-name> <output-element namespace="myNS">myElement</output-element> ... </xqsview-source>
Because no <error-message>
element is used, the one-item XML result sequence that is returned will forward whatever message comes from the data source, rather than containing a predefined message. If the XQS view function, in fact, encounters an error, XQS will construct an <xqserror>
XML node and return it as the function result. The error message will be the text value of the <xqserror>
node. XQS will choose the XML node representation because the XQS view configuration specifies a user-defined element in its <output-element>
configuration.
Java Code Following is a sample code fragment that executes a view and then does the following error processing:
Calls the getErrors()
method of the XQSFacade
class to retrieve a java.util.ListIterator
instance of XQSError
objects.
Uses the ListIterator
class hasNext()
method to determine how many error objects to iterate through.
For each error, prints the qualified name of the XQS function that produced the error, then prints the error type, error message, and error code.
... XQSFacade bean = new XQSFacade(); String xqueryView = "BasicFileWS"; QueryParameter param = new QueryParameter("custName"); param.setString("John Ford"); QueryParameter[] params = new QueryParameter[1]; params[0] = param; bean.executeView(xqueryView, null, params); while(bean.getNextItem() !=null) { } ListIterator errors = bean.getErrors(); while(errors.hasNext()) { XQSError error = (XQSError)errors.next(); System.out.println("The function which gives error is: " + error.getFunctionQName()); System.out.println("The error type is:" + error.getErrorType()) + ", which means " +XQSError.typeNames(error.getErrorType())); System.out.println("The error message is:" + error.getErrorMessage()); System.out.println("The error code is:" + error.getErrorCode()); } ...
This section provides reference documentation for XQS public classes and user interfaces:
This section documents the constructor and methods of the oracle.xds.client.QueryParameter
class. A QueryParameter
array is used for binding external variables for a query when using the XQS general-purpose Java API or the EJB API.
"Example 3: XQSFacade API with an XQS View" includes an example of using QueryParameter
for an input parameter.
The QueryParameter
class supplies the following constructors:
QueryParameter(String namespace, String localName)
QueryParameter(String localName)
When you construct a QueryParameter
instance, you specify the name of the external XQuery variable to be bound, and this must match the name from the corresponding external variable declaration in the XQuery prolog. XQuery variables use XML names, so the QueryParameter
constructor can take two string values—one for the namespace and one for the local name. If you do not specify a namespace, then null
is assigned to the namespace in the qualified name.
The QueryParameter
class supplies the following methods, each to set a value of an external XQuery variable. These methods reflect XML types supported by XQS, and their Java equivalents; also see "Supported Types for Query Parameters".
void setBase64Binary(String value)
Use this to bind a base 64 binary value, represented by a Java string (for example, "vYrfOJ39673//-BDiIIGHSPM=+"), and corresponding to the XML base64Binary
type.
void setBoolean(boolean value)
Use this to bind a boolean
value, corresponding to the XML boolean
type.
void setDateTime(java.util.GregorianCalendar value boolean isTimeZoneSet)
Use this to bind a GregorianCalendar
value representing a particular point in time, corresponding to the XML dateTime
type. Set isTimeZone
to true
if the calendar object TimeZone
property has been set. (See http://java.sun.com/j2se/1.4.2/docs/api/
for information about using GregorianCalendar
objects.)
void setDecimal(java.math.BigDecimal value)
Use this to bind a BigDecimal
value, corresponding to the XML decimal
type.
void setDouble(double value)
Use this to bind a double
value, corresponding to the XML double
type.
void setDuration(String value)
Use this to bind a String
value representing a duration, corresponding to the XML duration
type. See http://www.w3.org/TR/xmlschema-2/#duration
for information about lexical (string) representations of durations.
void setFloat(float value)
Use this to bind a floating point value, corresponding to the XML float
type.
void setHexBinary(String value)
Use this to bind a hexadecimal binary value, represented by a Java string (for example, "0FB7"), and corresponding to the XML hexBinary
type.
void setInt(int value)
Use this to bind an integer value, corresponding to the XML int
type.
void setInteger(int value)
void setInteger(long value)
void setInteger(java.math.BigInteger value)
Use one of the setInteger()
methods to bind an integer value, corresponding to the XML integer
type. Choose the appropriate signature based on the value representation or magnitude.
void setLong(long value)
Use this to bind a long integer value, corresponding to the XML long
type.
void setString(String value)
Use this to bind a Java string value, corresponding to the XML string
type.
void setAnyURI(java.net.URI value)
Use this to bind a URI
value, corresponding to the XML anyURI
type.
void setNode(org.w3c.dom.Node value)
Use this to bind an XML node, corresponding to the XML anyType
type or to any user-defined XML type.
Note: TheQueryParameter class has no getter methods corresponding to these setter methods.
|
This section documents the constructor and methods of the oracle.xds.client.XQSFacade
class, a general-purpose Java client API that XQS supplies. See "Using the Java Class Client API" for usage instructions and an example.
The XQSFacade
class supplies the following methods:
void execute(String xquery, QueryParameter[] params)
Use this method to execute an ad-hoc query. Pass in a string containing the query, and a QueryParameter
array for any bind parameters. (See "XQS QueryParameter Class Reference".) The array can be null if there are no parameters to pass.
void executeView(String viewName, String namespace, QueryParameter[] params)
Use this method to execute an XQS view directly. Pass in a view name by specifying the local name and namespace (as strings), and pass in a QueryParameter
array for any bind parameters (or null). The view name and namespace together define a qualified name and must match the corresponding function name and namespace in your configuration, according to the <function-name>
subelement of <xqsview-source>
, and its namespace
or prefix
attribute.
oracle.xml.xqxp.datamodel.XMLItem getNextItem()
After using execute()
or executeView()
, use getNextItem()
to obtain the next item in the result sequence, as an Oracle XMLItem
instance. The first getNextItem()
call returns the first item in the sequence. If you call this method after you have already retrieved the last item, it returns null
.
Important: A call to thegetNextItem() method triggers the evaluation of the item by XQuery. Any resources required when executing the query (such as a database connection or file handle) are not freed until after the last getNextItem() call.
|
java.util.ListIterator getErrors()
If you configure any of the XQS functions used in your query to continue even if errors are encountered (as discussed in "Configuring XQS Function Error Handling"), you can use getErrors()
to retrieve information about any errors that may have been encountered during execution of XQS functions. This method returns an iterator over a collection of XQSError
objects, from which you can retrieve the specifics of each error. (See "XQSError Class Reference".) If there were no errors, the iterator will point to an empty collection.
void close()
Use this to free all resources associated with the query. It is good practice to call close()
after retrieving all query results.
This section documents EJB client methods supported by XQS, through the XQSClientRemote
and XQSClientHome
interfaces for remote EJBs, and the XQSClientLocal
and XQSClientLocalHome
interfaces for local EJBs. There are versions of these interfaces for either stateful or stateless session beans.
See "Using the EJB Client API" for usage instructions and examples.
The following Oracle-specific methods are available through EJB interfaces in package oracle.xds.client.ejb.stateful
, for stateful session beans, and have the same functionality as the methods of the same name discussed in "XQSFacade Class Reference":
void execute(String xquery, QueryParameter[] params) throws EJBException
void executeView(String viewName, String namespace, QueryParameter[] params) throws EJBException
oracle.xml.xqxp.datamodel.XMLItem getNextItem() throws EJBException
java.util.ListIterator getErrors()
void close()
The following Oracle-specific methods are available through EJB interfaces in package oracle.xds.client.ejb.stateless
, for stateless session beans:
java.util.Vector execute(String xquery, QueryParameter[] params) throws EJBException
Use this method to execute an ad-hoc query. Pass in a string containing the query, and a QueryParameter
array for any bind parameters. (See "XQS QueryParameter Class Reference".) The array can be null if there are no parameters to pass. Results are fully materialized, returned in a Vector
instance.
java.util.Vector executeView(String viewName, String namespace, QueryParameter[] params) throws EJBException
Use this method to execute an XQS view. Pass in a view name by specifying the local name and namespace (as strings), and pass in a QueryParameter
array for any bind parameters (or null). The view name and namespace together define a qualified name and must match the corresponding function name and namespace in your configuration, according to the <function-name>
subelement of <xqsview-source>
, and its namespace
or prefix
attribute. Results are fully materialized, returned in a Vector
instance.
java.util.ListIterator getErrors()
This method has the same functionality as the method of the same name discussed in "XQSFacade Class Reference".
XQS supplies custom JSP tags for either stateful or stateless access to XQuery.
See "Using the JSP Tag Library" for usage instructions and examples.
See the Oracle Containers for J2EE Support for JavaServer Pages Developer's Guide for general information about using JSP tag libraries.
Notes: The prefix "xq:" is used in the tag syntax here. This is by convention but is not required. You can specify any desired prefix in yourtaglib directive.
For tag syntax, note the following:
|
Use these tags when you want a stateful access to XQuery.
Use this tag to prepare and execute the query. It has the following syntax. (The param
subtag, used for any bind parameters, is described next.)
<xq:executeCursor [ xqueryString = "query" ] [ xqsViewName = "viewname" ] [ namespace = "namespace" ] cursorId = "cursorname" [ maxItems = "maxnumber" ] [ toWriter = "true" | "false" ] toXMLDoc = "docname" resultItems = "arrayname" errors = "errorvarname" > <xq:param ... /> <xq:param ... /> ... </xq:executeCursor>
Important:
|
Use attributes of the executeCursor
tag as follows:
xqueryString
: When using an ad-hoc query, use this attribute to specify the complete XQuery syntax of the query. It is usually easiest to define the query in a string variable and specify the name of the variable in a JSP expression:
String myquerystring = "..."; ... <xq:executeCursor ... xqueryString = "<%=myquerystring%>" ... > ... </xq:executeCursor>
xqsViewName
: When using an XQS view, use this attribute to specify the view. Specifically, this is the name of the corresponding XQS function name in your configuration.
namespace
: If you use xqsViewName
to specify a view, you must also use namespace
to specify the namespace of the XQS function for the view, according to your XQS configuration.
cursorId
(required): Use this tag to specify the name of a variable for the cursor, for later use. (The variable will be declared by the JSP container.) You will reference the specified variable name when you use a next
tag to retrieve results from the cursor, and when you use the close
tag to close the cursor. Here is an example:
<xq:executeCursor ... cursorId="mycursor" ... > ... </xq:executeCursor> ... <xq:next cursorId="mycursor" /> ... <xq:close cursorId="mycursor" />
maxItems
: Use this if you want to specify a maximum number of items to receive from the query, such as maxItems="10000"
. Items beyond that point will be discarded, and the next
tag will stop returning values after maxItem
items have been received.
toWriter
: Set this to "true
" to output query results to the JSP output stream. The writing occurs every time the next
tag is executed.
toXMLDoc
(required): Provide the name for a variable to be used by a related next
tag to output query results to an XML DOM document. The document can be used after the executeCursor
tag. A variable of type org.w3c.dom.Document
will be declared by the JSP container. Here is an example:
<xq:executeCursor cursorId="mycursor" toXMLDoc="mydoc" ... > ... </xq:executeCursor> <xq:next cursorId="mycursor" /> Element root = mydoc.getDocumentElement(); ...
After using the executeCursor
tag, each time you execute the next
tag you will receive a batch of result nodes collected in the document mydoc
.
Important:
|
Note: The specified name will also become the name of the root element of the document. |
resultItems
(required): Provide the name for a variable to be used by a related next
tag to output query results to an array list. A variable of type java.util.ArrayList
will be declared by the JSP container. The ArrayList
instance can be used after the executeCursor
tag. Here is an example:
<xq:executeCursor ... resultItems="myobjects" ... > ... </xq:executeCursor> Node node = (Node)myobjects.get(0); ...
After using the executeCursor
tag, each time you execute the next
tag you can access a result item from the myobjects
variable.
Important:
|
errors
(required): Provide the name of a variable to be used in retrieving errors that result from execution of the XQS query. A variable of type java.util.ListIterator
will be declared by the JSP container for an iterator over a collection of XQSError
objects (one object per error). The iterator can be used after the executeCursor
tag. Here is an example:
<xq:executeCursor cursorId="mycursor" errors="myerroriter" ... > ... </xq:executeCursor> <xq:next cursorId="mycursor" /> XQSError error = (XQSError)myerroriterator.next(); ...
See "XQSError Class Reference" for how to use XQSError
objects.
Important: You cannot use a runtime expression for theerrors attribute.
|
Use this subtag of executeCursor
and execute
to specify any external bind parameters for the query (one param
tag per parameter). It has the following syntax:
<xq:param localName = "localvarname" [ namespace = "namespace" ] value = "bindvalue" type = "bindparamtype" />
Use attributes of the param
tag as follows:
localName
(required): Use this to specify the local part of the external variable name.
namespace
: Use this to specify the namespace part of the external variable name. Because it is permissible to use a local variable name without a namespace, this attribute is optional.
value
(required): Use this for the value to be bound, which will presumably be a runtime value using a JSP runtime expression:
<xq:param ... value = "<%=jspExpression%>"... />
Note: The type of the bind value must be a match for thetype attribute setting, as noted in Table 8-3 below.
|
type
(required): Use this to specify the data type of the bind parameter, indicating an XML type for which the XQS QueryParameter
class supports a corresponding Java type. Supported settings, and the type or types for which they are appropriate, are shown in Table 8-3. (Also see "Supported Types for Query Parameters".)
Table 8-3 Correspondence of Java Types to type Attribute Settings
type Attribute Setting | Matching Java Type(s) |
---|---|
boolean |
java.lang.Boolean |
string |
java.lang.String |
int |
java.lang.Integer |
integer |
java.lang.Integer, java.lang.Long, java.math.BigInteger |
long |
java.lang.Long |
float |
java.lang.Float |
double |
java.lang.Double |
decimal |
java.math.BigDecimal |
base64Binary |
java.lang.String (Representation of the value.) |
hexBinary |
java.lang.String (Representation of the value.) |
anyURI |
java.net.URI |
dateTime |
java.util.GregorianCalendar (With the assumption that the time zone for the calendar value has been initialized appropriately.) |
duration |
java.lang.String (Lexical representation of the duration, discussed at |
node |
java.lang.String (Text representation of the node, to be parsed by an XML parser.) |
Use this tag to process results, item by item or batch by batch, from the executeCursor
tag, referencing the cursor ID name that you specified in that tag. The next
tag has the following syntax:
<xq:next cursorId = "cursorname" [ batchSize= "numitems" ] [ itemsFetched = "intvarname" ] />
Use attributes of the next
tag as follows:
cursorId
(required): Use this attribute to reference the cursor name for the query, as specified in the executeCursor
tag. The cursor must still be open (there has not yet been a close
tag specifying the same cursor name).
batchSize
: Use this attribute if you want XQS to use batch mode for the query. Specify an integer value for how many items you want fetched from the cursor each time the next
tag is executed. The default value is "1
" (no batching).
itemsFetched
: Specify the name of a java.lang.Integer
variable for a value that indicates how many items were fetched from the cursor in the current next
tag execution. The variable will be declared by the JSP container.
Here is an example:
... <xq:executeCursor cursorId="mycursor" resultItems="myresults" toXMLDoc="mydoc" errors="myerrors" ... > <xq:param ... /> ... </xq:executeCursor> <% int items; do { // Populate output vehicles (myresults array and mydoc document) %> <xq:next cursorId="mycursor" itemsFetched="fetched" /> <% items = fetched.intValue(); } while(items>0) // ... Here is where you would retrieve results from the output vehicles ... %> ...
For a stateful JSP (using the executeCursor
tag), use the close
tag to free resources associated with the query. It has the following syntax:
<xq:close
cursorId = "cursorname"
/>
Use attributes of the close
tag as follows:
cursorId
(required): Use this attribute to reference the cursor name, as specified in the executeCursor
tag, corresponding to the query you want to close.
Use the execute
tag when you want a stateless access to XQuery.
Use this tag to prepare and execute the query. It has the following syntax:
<xq:execute [ xqueryString = "query" ] [ xqsViewName = "viewname" ] [ namespace = "namespace" ] [ maxItems = "maxnumber" ] [ toWriter = "true" | "false" ] toXMLDoc = "docname" resultItems = "arrayname" errors = "errorvarname" > <xq:param ... /> <xq:param ... /> ... </xq:execute>
Important:
|
Aside from cursorId
, this tag uses the same attributes as the executeCursor
tag (for stateful access). It also uses the XQS param
subtag, as does executeCursor
, for bind parameters. See "XQS executeCursor Tag" and "XQS param Tag".
This section provides reference documentation for the class oracle.xds.client.XQSError
.
If you configure any of the XQS functions used in your query to continue even if errors are encountered, as discussed in "Configuring XQS Function Error Handling", you can retrieve information about any errors that may have occurred during execution of the XQS function for the query. Errors are returned in an iterator of XQSError
objects.
The XQSError
class provides a number of methods to return its key information—the name of the XQS function that encountered the error, the type of error (an XQS-specific designation), the error message, and the error code (if applicable)—in various formats. See "Obtaining Information from XQS Error Objects" for usage instructions and an example.
String getFunctionQName()
Use this to get the fully qualified name of the XQS function that encountered the error, as follows:
{namespace_URI}/local_name
int getErrorType()
Use this to get an integer constant that indicates the XQS error type designation:
XQSERR_MISSING_SRC
if the data source cannot be found—such as if an HTTP 404 error is returned, the file is not found for a document source, the source is down, or the desired table in a database source does not exist.
XQSERR_SRC_ACCESS
if the data source is found but returns an access error. This would include, for example, an ORA-xxxxx
error from an Oracle database, a Web site login error, or a parser error when reading a document source.
XQSERR_SRC_ERROR
if the data source is found but returns some kind of error besides an access error, such as a business method error, a Web service fault message, or a SQL error for a database source.
XQSERR_PARAM
if XQS encountered problems in passing bind parameters to the data source or receiving output parameters from the data source. For example, this is returned if XQS could not convert an input string to the corresponding data type required according to the WSDL document, or if XQS could not transform a non-XML file into an XML document with the particular transformer it is using.
XQSERR_SRC_CONFIG
if XQS encountered a problem while processing configuration of the XQS function.
XQSERR_INTERNAL if XQS encountered an unexpected internal error.
String getErrorMessage()
Use this to retrieve the error message, either from the data source or from XQS, as applicable. This method never returns null
. If a data source generates an error without returning a message, XQS returns the generic message "Function generated an error."
String getErrorCode()
For an error generated by a data source, use this to return the XQS error code string.
String toString()
Use this to combine the function name, error type, error code, and error message into a single string.
String toXMLString()
Use this to combine the function name, error type, error code, and error message into a string representation of an XML error element.
public static String[] typenames
Use this static array to store one of the following string representations of XQS error types in each element of the array:
XQSERR_MISSING_SRC
XQSERR_SRC_ACCESS
XQSERR_PARAM
XQSERR_SRC_ERROR
XQSERR_SRC_CONFIG
XQSERR_INTERNAL
Given a Java object error of type XQSError
, the expression XQSError.typNames[error.getErrorType()]
returns a string appropriate for the error type of the object.
org.w3c.dom.Node toXMLNode()
Use this to retrieve the function name, error type, error code, and error message in DOM node format.
This section has an alphabetical dictionary of elements of the XQS configuration files, xqs-config.xml
and global-xqs-config.xml
. The XML schema for XQS configuration files can be found at http://www.oracle.com/technology/tech/xml/xqs/xqs-config.xsd
. It is also available with the XLSDemo application in xds/samples/XQSDemo/XDS/xqs-config.xsd
, This XML schema applies to both the application-specific as well as global configurations Also see "How to Configure Your XQS Functions" for information about the use of key elements for each category of data source.
At the application level, XQS looks for xqs-config.xml
in the xqs-resources.jar
file at the top level of the application EAR file. The global version, global-xqs-config.xml
, is in the following location:
ORACLE_HOME/j2ee/home/config
For each external function declared for an XQuery expression, XQS will first look for configuration for the function in the application-specific xqs-config.xml
file; if the configuration is not found there, XQS will look in global-xqs-config.xml
, where you can configure data sources available to any application.
Following is a summary of the hierarchy of these files. For each XQS function you configure, you will use a <wsdl-source>
element, <xqsview-source>
element, or <wsdl-source>
element, depending on the kind of data source being accessed.
Parent element: <xqs-config>
Child elements: <use-prefix>
Required? Optional; zero or one
Use this element, with <use-prefix>
subelements, if you want to designate prefixes to represent certain XML namespaces in XQS configuration elements. Each <use-prefix>
subelement designates one prefix.
The <bind-prefix>
element has no attributes.
Parent element: <document-source>, <wsdl-source>, or <xqsview-source>
Child elements: <in-memory>
Required? Optional; zero or one inside each occurrence of a parent element
If you enable XQS caching through the isCached
attribute of <document-source>
, <wsdl-source>
, or <xqsview-source>
, use the <cache-properties>
element with its required <in-memory>
subelement to set caching properties for use by the particular XQS function. See "XQS Caching Strategies" for related considerations.
The <cache-properties>
element is ignored if isCached="false"
(the default).
Parent element: <xqs-sources>
Child elements: <cache-properties>, <documentURL>, <error-message>, <function-name>, <output-element>, <XMLTranslate>
Required? Optional; zero or more
Use a <document-source>
element and its subelements (as appropriate) for each XQS function you configure that uses a document source.
You can configure the use of a generic document source where the URL is taken at runtime, or you can use the <documentURL>
subelement to specify a fixed URL in the configuration. (For an example of taking a URL at runtime, see "Configuring an XQS Function That Accesses a Document Source".)
For a non-XML document, you can use the <XMLTranslate>
element to configure translation to XML, if the document conforms to formats supported by the D3L tool. (See "Preparing to Use a Non-XML Document Source" for information about D3L.)
Table 8-5 <document-source> Attributes
Name | Description |
---|---|
isCached |
Values: Boolean Default: false Set this to " |
largeData |
Values: Boolean Default: false Set this to " |
onError |
Values: dynamicError | emptySequence | errorMessage Default: dynamicError This determines which error-handling mode XQS uses. See "Configuring XQS Function Error Handling". |
Parent element: <document-source>
Child elements: None
Required? Optional; zero or one inside each occurrence of the parent element
Use the value of this element to specify the document to use as the data source, such as in the following example:
<documentURL>http://host:port/xqsdemos/Repository/pos-2KB.xml</documentURL>
If it is a non-XML document, use the <XMLTranslate>
subelement of <document-source>
to specify the translation tool for XQS to use.
The <documentURL>
element has no attributes.
Notes:
|
Parent element: <document-source>, <wsdl-source>, or <xqsview-source>
Child elements: None
Required? Optional; zero or one inside each occurrence of a parent element
For the XQS errorMessage
error mode—determined by the onError
attribute of <document-source>
, <wsdl-source>
, or <xqsview-source>
—use the <error-message>
element if you want to predefine a fixed error message instead of forwarding whatever message comes from the data source. The element value constitutes the message, as in the following example:
<error-message>No information available</error-message>
Also see "Introduction to XQS Error Handling".
The <error-message>
element has no attributes.
Parent element: <document-source>, <wsdl-source>, or <xqsview-source>
Child elements: None
Required? Required inside each occurrence of a parent element; one only
Use this element to declare the desired name of the XQuery function that XQS will implement to access the data source. The element value is the function name, and attribute settings specify the function namespace. (Each XQuery function must belong to some namespace.) Be aware that you must reference the function namespace every time you invoke the function in an XQuery expression, unless you have declared that particular namespace as the default for the XQuery expression.
Use the namespace
attribute to specify the namespace directly; use the prefix
attribute as a shortcut if you have previously defined a namespace prefix through a <bind-prefix>
element. You must use one or the other, but do not use both namespace
and prefix
at the same time. For information about using the <output-element>
element, see "Considerations for Using <output-element >" on .
The function name you specify here is the function name you will declare in the XQuery external function declarations in your code, to access the corresponding data source.
Here is an example:
<function-name namespace="http://xmlns.oracle.com/ias/xqs"> customerInfo </function-name>
Or, alternatively, if xqs
has been defined as a prefix for the XQS namespace:
<function-name prefix="xqs">customerInfo</function-name>
Here is an example of an XQuery function declaration corresponding to the preceding configuration:
declare namespace xqs="http://xmlns.oracle.com/ias/xqs"; declare function xqs:customerInfo() external;
Parent element: <cache-properties>
Child elements: None
Required? Required if the parent element is used; one only
Use the <cache-properties>
element and its <in-memory>
subelement to set XQS cache properties. Attributes of the <in-memory>
element determine the caching mode. For simple memory-based caching, set useSpool
and useDiskCache
both to "false
". For memory-based caching with the capability of spooling cached data to disk as necessary, in case of any memory shortage, set useSpool
to "true
" and useDiskCache
to "false
". For disk-based caching, set useDiskCache
to "true
" and useSpool
to "false
". With disk-based caching, cached data will survive a server crash. See "XQS Caching Strategies" for related considerations.
For example, for memory-based caching that uses spooling if necessary:
<cache-properties time-to-live="600"> <in-memory useSpool="true" useDiskCache="false"/> </cache-properties>
See "Configuring XQS Caching" for additional information.
Table 8-7 <in-memory> Attributes
Name | Description |
---|---|
useSpool |
Values: Boolean Default: false Set |
useDiskCache |
Values: Boolean Default: false Set |
Parent element: <wsdl-source> or <xqsview-source>
Child elements: <part>
Required? Required inside each occurrence of a parent element; one only
Use this element to specify input parameters to the XQS function for the associated data source. Use a <part>
subelement for each parameter. Type-matching, for WSDL sources only, is according to the type-match
attribute.
This element is required even if there are no input parameters; use an empty element in that case.
Table 8-8 <input-parameter> Attributes
Name | Description |
---|---|
type-match |
Values: strict | none Default: strict For a WSDL source, this determines whether XQS performs type-matching for input parameters. With a setting of |
Parent element: <xquery-sequence>
Child elements: None
Required? Optional; zero or one inside each occurrence of the parent element
When you use the <xquery-sequence>
element to specify a sequence type as an input type for an XQS view, where each member of the sequence is of the same type, you can use the <itemType>
subelement to specify the type of the members. This is useful in allowing XQS to perform type-checking.
Use the namespace
attribute to directly specify a namespace that defines the type; use the prefix
attribute as a shortcut if you have previously defined a namespace prefix through a <bind-prefix>
element. You must use one or the other, but do not use both namespace
and prefix
at the same time.
Table 8-9 <itemType> Attributes
Name | Description |
---|---|
namespace |
Values: URI Default: None (required if Specifies the namespace directly. |
prefix |
Values: String Default: None (required if Specifies the namespace through a predefined prefix. |
location |
Values: URI Default: None For a user-defined type, you can specify a URI with the location where the schema that defines the type can be found. This is useful for type-checking by XQS, if a corresponding detailed declaration of the parameter exists in your XQuery prolog. |
Parent element: <typeMap>
Child elements: <xmlType>
Required? Required inside the parent element if that is used; one or more
For a WSDL source with Java or EJB binding, use this in conjunction with its <xmlType>
subelement to map between a Java type and an XML type. Use the typeClass
attribute to specify the Java type.
Parent element: <wsdl-source>
Child elements: None
Required? Required inside each occurrence of the parent element; one only
Use this to specify the Web service operation to execute. It would be an operation defined in the WSDL document that the <wsdlURL>
element points to, with the value of the XQS <operation>
element corresponding to the name
attribute of an <operation>
element in the WSDL. Here is an example:
<operation>getCustomerByKey</operation>
The <operation>
element has no attributes.
Parent element: <document-source>, <wsdl-source>, or <xqsview-source>
Child elements: None
Required? Optional; zero or one inside each occurrence of a parent element
The value of this element defines the item type of the sequence that is the result of the XQS function. This element is not required, but XQS can use the information for type-checking and optimizations. We especially advise you to use this element for an XQS view source with the setting WSDLvisibility="true"
. XQS would still generate a valid Web service operation without the type information, but it is not a good practice to define an untyped Web service in a production system.
You can define the result item in either of two ways: by its type or by a reference to an element previously defined in another schema. The name of such an imported element is given as the text value of the element <output-element>
. For example, if items in the result sequence will be <po>
elements from the schema urn:PurchaseOrders
namespace, <output-element>
might look like this:
<output-element namespace="urn:purchaseOrders" > po </output-element>
If items in the result sequence will be elements of type POType
defined in the schema urn:PurchaseOrders
namespace, found at http://myHost:/mySchemas/PurchaseOrders.xsd
, <output-element>
might look like this:
<output-element prefix="po_ns" location="http://myHost:/mySchemas/PurchaseOrders.xsd" type="POType"/>
Use the namespace
attribute to specify the namespace directly; or use the prefix
attribute as a shortcut if you have previously defined a namespace prefix through a <bind-prefix>
element. You must use one or the other, but do not use both namespace
and prefix
at the same time.
Here is an example for a complex type:
<output-element namespace="http://xmlns.oracle.com/ias/xqs/CustomerDemo" location="http://host:port/xqsdemos/Customers.xsd" type="CustomersType"> cstomers </output-element>
Here is an example for a simple type:
<output-element prefix="xs">float</output-element>
Table 8-11 <output-element> Attributes
Name | Description |
---|---|
namespace |
Values: URI Default: None (required if Specifies a namespace directly. |
prefix |
Values: String Default: None (required if Specifies a namespace through a predefined prefix. |
location |
Values: URI Default: None Specify a URI with the location where the schema that defines the element or type can be found. This attribute is required when you use the |
type |
Values: String Default: None Specify a local name for the XML type that will be the item type of the sequence that is the result of the XQS function. The namespace for the type name is determined from the |
Parent element: <input-parameters>
Child elements: <schema-type>, <xquery-sequence>
Required? Required unless parent element is empty; one for each input argument
Use a <part>
element for each input parameter for a WSDL source or XQS view. Specify the name and position (order) of the parameter through the attributes. Use a <schema-type>
subelement or an <xquery-sequence>
subelement (for XQS views only) to specify the type, as appropriate. Specifying the type is required for an XQS view that uses input parameters. For a WSDL source, specifying a type is not required, but is useful so that XQS can perform type-checking.
For a WSDL source, each <part>
element must correspond to a part in the input message of the WSDL operation that is used to access the source. For an XQS view, each <part>
element must correspond to an external bind variable of the XQuery that defines the view.
Table 8-12 <part> Attributes
Name | Description |
---|---|
name |
Values: String Default: n/a (required) This specifies the name of the input parameter. For a WSDL source, the name must be the same as in the WSDL document. For an XQS view, it must be the same as the name of the external XQuery variable. |
position |
Values: Positive integer Default: n/a (required) The position attributes for all the |
Parent element: <document-source>
Child elements: None
Required? Optional; zero or one
This element is reserved for future security enhancements.
The <password>
element has no attributes.
Parent element: <wsdl-source>
Child elements: None
Required? Required inside each occurrence of the parent element; one only
The value of this element specifies the name of a Web service port defined in the WSDL document that the <wsdlURL>
element points to, corresponding to the name
attribute of a <port>
element in the WSDL.
Attribute settings specify the namespace, but you are not required to specify a namespace if the applicable service has only one port.
Use the namespace
attribute to specify the namespace directly; use the prefix
attribute as a shortcut if you have previously defined a namespace prefix through a <bind-prefix>
element. Do not use both namespace
and prefix
at the same time.
For example:
<port namespace="http://customer.myeis.com/">CustomerInfo</port>
Alternatively:
<bind-prefix> <use-prefix prefix="myeis">http://customer.myeis.com/</use-prefix> </bind-prefix> ... <port prefix="myeis">CustomerInfo</port>
Parent element: <wsdl-source>
Child elements: None
Required? May be required; zero or one inside each occurrence of the parent element
The value of this element specifies the name of a Web service port type defined in the WSDL document that the <wsdlURL>
element points to, corresponding to the name
attribute of a <portType>
element in the WSDL. This element is required if the port used for the operation has multiple bindings in the WSDL.
Attribute settings specify the namespace, but you are not required to specify a namespace if all port types in the WSDL belong to the same namespace.
Use the namespace
attribute to specify the namespace directly; use the prefix
attribute as a shortcut if you have previously defined a namespace prefix through a <bind-prefix>
element. Do not use both namespace
and prefix
at the same time.
For example:
<portType namespace="http://customer.myeis.com/">CustomerInfoType</portType>
Parent element: <xqsview-source>
Child elements: None
Required? Optional; zero or one inside each occurrence of the parent element
The value of this element specifies the name of the XQuery expression text file (.xq
file) where the XQS view is defined, such as in the following example:
<queryName>UserByOrderNum.xq</queryName>
You can leave off the .xq
file name extension, as XQS assumes that automatically. The directory where XQS looks for the file is according to the <repository>
subelement of <xqsview-source>
(or else according to a default location).
If you do not use the <queryName>
element, XQS assumes the XQS view file to have the same name as the function you specify in the <function-name>
subelement of <xqsview-source>
.
The <queryName>
element has no attributes.
Parent element: <xqsview-source>
Child elements: None
Required? Optional; zero or one inside each occurrence of the parent element
The value of this element is the absolute path to the directory containing the XQuery expression text file (.xq
file) where the XQS view is defined. Specify the file name in the <queryName>
subelement of <xqsview-source>
.
If you do not use the <repository>
element, XQS looks in the directory you specified through the OC4JPackager -repository
option. Here is an example explicitly specifying what would be the default directory for the XQS demo application:
<repository>/META-INF/xqs/mydir/</repository>
The <repository>
element has no attributes.
Parent element: <XMLTranslate>
Child elements: None
Required? Required if the parent element is used; one only
If a document source is non-XML and conforms to formats supported by the D3L tool, use the <XMLTranslate>
element and <schema-file>
subelement to give information to XQS about how to translate the document to XML for you. (See "Preparing to Use a Non-XML Document Source" for information about D3L.)
The <XMLTranslate>
element specifies the translation tool to use (D3L), and the <schema-file>
element specifies the schema file to use in translation.
Here is an example:
<documentURL>http://host:port/xqsdemos/paymentInfo.csv</documentURL> <XMLTranslate method="D3L"> <schema-file>http://host:port/xqsdemos/paymentInfoD3L.xml</schema-file> </XMLTranslate>
The <schema-file>
element has no attributes.
Parent element: <part>
Child elements: None
Required? See description; one only
For each input parameter for an XQS view, either this element or the <xquery-sequence>
element (for an input sequence) is required to specify the parameter type.
For each input parameter for a WSDL source, this element is optional inside the <part>
parent element, but is useful for type-checking, or for organizational purposes—to have all your types listed in the XQS configuration file. (A WSDL source cannot have an input sequence.)
Note that to perform type-checking for WSDL sources, the <input-parameters>
element must have the attribute setting type-match="strict"
.
For <schema-type>
, the element value specifies the type, and attribute settings specify the namespace. Use the namespace
attribute to specify the namespace directly; use the prefix
attribute as a shortcut if you have previously defined a namespace prefix through a <bind-prefix>
element. You must use one or the other, but do not use both namespace
and prefix
at the same time.
Here is an example:
<input-parameters> <part position="1" name="empname"> <schema-type namespace="http://www.w3.org/2001/XMLSchema">string</schema-type> </part> </input-parameters>
Or, alternatively, defining xs
as a prefix for the XMLSchema namespace:
<bind-prefix> <use-prefix prefix="xs">http://www.w3.org/2001/XMLSchema</use-prefix> </bind-prefix> ... <input-parameters> <part position="1" name="empname"> <schema-type prefix="xs">string</schema-type> </part> </input-parameters>
Or, for a user-defined type:
<input-parameters> <part position="1" name="DBServiceSelect_cust_id_inparameters"> <schema-type namespace= "http://xmlns.oracle.com/pcbpel/adapter/db/top/TestDBAdapter"> DBServiceSelect_cust_id </schema-type> </part> </input-parameters>
In addition to any user-defined XML types, XQS currently supports the following subset of types defined in the XQuery 1.0 and XPath 2.0 data model: xs:boolean
, xs:string
, xs:int
, xs:long
, xs:float
, xs:double
, xs:decimal
, xs:base64Binary
, xs:hexBinary
, xs:anyURI
, xs:dateTime
, xs:duration
, and xs:anyType
. (Also see "Supported Types for Query Parameters".) If you have an XQuery/XPath input type that is not among these supported types, choose a supported type with the Java representation that best suits your data, and use a setting of type-match="none"
in the <input-parameters>
element. (For a WSDL source with a Java or EJB binding, this is a situation where you would also use the <typeMap>
subelement of <wsdl-source>
.)
Parent element: <wsdl-source>
Child elements: None
Required? May be required; zero or one inside each occurrence of the parent element
The value of this element specifies the name of a service. It would be a service defined in the WSDL document that the <wsdlURL>
element points to, with the value of the XQS <service>
element corresponding to the name
attribute of a <service>
element in the WSDL. The XQS <service>
element is required if the WSDL document defines multiple services.
Attribute settings specify the namespace, but you are not required to specify a namespace if all service elements in the WSDL belong to the same namespace.
Use the namespace
attribute to specify the namespace directly; use the prefix
attribute as a shortcut if you have previously defined a namespace prefix through a <bind-prefix>
element. Do not use both namespace
and prefix
at the same time.
For example:
<service namespace="http://customer.myeis.com/">CustomerInfoMYEISService</service>
Parent element: <wsdl-source>
Child elements: <mapping>
Required? Optional; zero or one within each occurrence of the parent element
For a WSDL source with a Java or EJB binding, you can use this element as necessary to map XML types to Java types. Specify the Java type through the <mapping>
subelement, and the XML type through the <xmlType>
subelement of <mapping>
.
The <typeMap>
element has no attributes.
Parent element: <bind-prefix>
Child elements: None
Required? Required if the parent element is used; one or more
Use a <bind-prefix>
element and <use-prefix>
subelements if you want to designate prefixes to represent certain XML namespaces. Each <use-prefix>
subelement designates one prefix, with the element value specifying a namespace and the prefix attribute specifying the prefix to represent that namespace. Here is an example:
<bind-prefix> <use-prefix prefix="xs">http://www.w3.org/2001/XMLSchema</use-prefix> <use-prefix prefix="xqs">http://xmlns.oracle.com/ias/xqs</use-prefix> <use-prefix prefix="myeis">http://customer.myeis.com/</use-prefix> </bind-prefix>
Given these settings, XQS configuration elements that must specify a namespace can use, for example, prefix="myeis"
instead of namespace="http://customer.myeis.com/"
.
Note: A<use-prefix> designation is valid only in the XQS configuration file in which it appears, not in XQuery expressions.
|
Parent element: <document-source>
Child elements: None
Required? Optional; zero or one
This element is reserved for future security enhancements.
The <username>
element has no attributes.
Parent element: <xqs-sources>
Child elements: <cache-properties>, <error-message>, <function-name>, <input-parameters>, <operation>, <output-element>, <port>, <portType>, <service>, <typeMap>, <wsdlURL>
Required? Optional; zero or more
Use a <wsdl-source>
element and its subelements (as appropriate) for each XQS function you configure that will access a WSDL-based source. (See "Supported Categories of Data Sources" for an overview of the kinds of WSDL-based sources you can use with XQS.)
Table 8-18 <wsdl-source> Attributes
Name | Description |
---|---|
fetchSize |
Values: Integer Default: 1 This attribute takes effect only for WSDL sources that use XQS SQL binding to connect to a relational database. The attribute is optional, and the default is 1 row.The |
isCached |
Values: Boolean Default: false Set this to " |
largeData |
Values: Boolean Default: false Set this to " |
onError |
Values: dynamicError | emptySequence | errorMessage Default: dynamicError This determines which error-handling mode XQS uses. See "Introduction to XQS Error Handling". |
Parent element: <wsdl-source>
Child elements: None
Required? Required inside each occurrence of the parent element; one only
Use this to point to the WSDL document that defines the operation to be executed. The WSDL will be accessed at runtime. Here is an example:
<wsdlURL>http://api.mySearch.com/mySearch.wsdl</wsdlURL>
The <wsdlURL>
element has no attributes.
Note: If you are behind a firewall and the specified URL requires external Internet access, be aware that you must also configure OC4J with appropriate proxy settings. |
Parent element: n/a (root)
Child elements: <bind-prefix>, <xqs-sources>
Required? Required; one only
This is the root element of xqs-config.xml
and global-xqs-config.xml
. At a minimum, you must have this element, its <xqs-sources>
subelement, and at least one subelement of <xqs-sources>
—<document-source>
, <wsdl-source>
, or <xqsview-source>
.
Parent element: <xqs-config>
Child elements: <document-source>, <wsdl-source>, <xqsview-source>
Required? Required; one only
This is the parent element for the source elements for all XQS functions being configured. It does not have any attributes.
Parent element: <xqs-sources>
Child elements: <cache-properties>, <error-message>, <function-name>, <input-parameters>, <output-element>, <queryName>, <repository>
Required? Optional; zero or more
Use an <xqsview-source>
element and its subelements (as appropriate) for each XQS function you configure that uses an XQS view.
Table 8-20 <xqsview-source> Attributes
Name | Description |
---|---|
isCached |
Values: Boolean Default: false Set this to " |
largeData |
Values: Boolean Default: false Set this to " |
onError |
Values: dynamicError | emptySequence | errorMessage Default: dynamicError This determines which error-handling mode XQS uses. See "Introduction to XQS Error Handling". |
WSDLvisibility |
Values: Boolean Default: false Set this to " |
Parent element: <document-source>
Child elements: <schema-file>
Required? Optional; zero or one inside each occurrence of the parent element
If a document source is non-XML and conforms to formats supported by the D3L tool, use the <XMLTranslate>
element and <schema-file>
subelement to give information to XQS about how to translate the document to XML for you. This is useful for translating formatted files, such as Excel comma-separated-values (CSV) files, to XML. See "Preparing to Use a Non-XML Document Source" for information about D3L.
The method
attribute of <XMLTranslate>
specifies the translation tool to use. XQS currently supports the D3L translation tool.
The <schema-file>
subelement is required, to specify the schema to use in translation.
Parent element: <mapping>
Child elements: None
Required? Required inside each occurrence of the parent element; one only
For a WSDL source with Java or EJB binding, use this in conjunction with its <mapping>
parent element to map between a Java type and an XML type. Use attribute settings to specify the namespace of the XML type: use the namespace
attribute to specify the namespace directly; use the prefix
attribute as a shortcut if you have previously defined a namespace prefix through a <bind-prefix>
element. You must use one or the other, but do not use both namespace
and prefix
at the same time.
The <mapping>
parent element specifies the Java type.
Here is an example:
<typeMap> <mapping typeClass="org.w3c.dom.Node"> <xmlType prefix="myeis">Customer</xmlType> </mapping> ... </typeMap>
Parent element: <part>
Child elements: <itemType>
Required? This or <schema-type> is required inside each occurrence of the parent element or an XQS view; one only
For each input parameter for an XQS view, where the parameter is an XQuery/XPath sequence type, you must use this element (as opposed to the <schema-type>
element for a non-sequence type) inside the <part>
parent element to specify the type.
For a WSDL source, input sequences are not supported so this element is not relevant.
The <xquery-sequence>
element can be used for a heterogeneous sequence consisting of items of multiple types, in which case it should be an empty element. Alternatively, it can include the <itemType>
subelement to specify the common type of each member of a homogeneous sequence.
The <xquery-sequence>
element has no attributes.
This section provides reference documentation for parameters and properties of the XQS packager utility, OC4JPackager. For an overview, see "Introduction to OC4JPackager". For usage instructions, see "How to Use OC4JPackager to Package Your XQS Application".
Note: For specifying paths in parameter or property settings, OC4JPackager supports paths that are either relative to the current directory (including the use of ". " and ".. " directory notation) or absolute.
|
This section documents OC4JPackager parameters in alphabetical order, with descriptions and usage examples. Run OC4JPackager as follows (where %
is the command prompt):
% java -jar OC4JPackager.jar -option1 value1 -option2 value2 ... -optionN valueN
Required. Specify a directory path.
Use this to specify where your application is located—either the directory containing an EAR file, or the top-level directory of an EAR structure.
-appArchives /dir1/myappdir
Optional. Specify a file path.
If any of the XQS views you want to expose as Web services are configured in the global-xqs-config.xml
file for global access, use this parameter to specify the path (including file name) of this file. This will bring those views into your local configuration.
-globalXqsConfig ORACLE_HOME/j2ee/home/config/global-xqs-config.xml
Optional. This is a toggle flag.
Use this without any other parameters to show OC4JPackager usage information and a parameter list.
-help
Optional (required if you use the XQS JSP tag library). This is a toggle flag.
Use this to include the XQS JSP tag library JAR file (xquerytaglib.jar
) in the output EAR file.
-jsp
Required. Specify an EAR file name.
Use this to specify the desired name of the output EAR file (with or without the .ear
extension). Its location will be determined by the -output
parameter.
-name myxqsapp.ear
Required. Specify a directory path.
Use this to specify where OC4JPackager should place the EAR file that it creates. The file name is according to the -name
parameter.
-output /dir1/mydeployments
Optional. Specify a directory path.
Use this to specify your XQS repository location, where your XQS views are stored.
-repository ORACLE_HOME/xds/samples/repository
Optional (required if you use the XQS stateful EJB client API). This is a toggle flag.
Use this to include the XQS stateful EJB client JAR file (xqsclient-stateful.jar
) in the output EAR file.
-sf
This also results in the following <module>
element being added to the application.xml
file:
<module> <ejb>xqsclient-stateful.jar</ejb> </module>
Optional (required if you use the XQS stateless EJB client API). This is a toggle flag.
Use this to include the XQS stateless EJB client JAR file (xqsclient-stateless.jar
) in the output EAR file.
-sl
This also results in the following <module>
element being added to the application.xml
file:
<module> <ejb>xqsclient-stateless.jar</ejb> </module>
This section documents Java properties supported by OC4JPackager, in alphabetical order, with descriptions and usage examples. Use the Java -D
option, as follows:
java -Dproperty1=value1 -Dproperty2=value2 -jar OC4JPackager.jar \ -option1 value1 -option2 value2 ... -optionN valueN
Optional. Specify a directory path.
OC4JPackager supports the oracle.home
property to specify your Oracle home directory. For example:
-Doracle.home=/myroot/myoraclehome
Specifying an Oracle home directory allows XQS to find any client JAR files requested through the -jsp
, -sf
, and -sl
flags and bundle them with your application. If you do not set oracle.home
, these flags are ignored.
Required. Specify a directory path.
Specify the path to your Java home directory, from which OC4JPackager will run the java
command for its work (such as unbundling and bundling JAR files).
-Djava.home=/dir1/myjavahome
OC4JPackager will exit if you do not specify this property.
Optional. Specify a file path.
Use this to indicate a path to the file, including the file name, where you specify Java logging properties, as in the following example (where myfile.properties
is in the current directory):
-Djava.util.logging.properties.file=myfile.properties
Without specifying a logging properties file, you will not see any Java error output.
OC4JPackager logs messages using the standard J2SE logging framework, as described at the following location:
http://java.sun.com/j2se/1.4.2/docs/guide/util/logging/
Within the properties file, OC4JPackager supports the property oracle.xds.tools.OC4JPackager.level
to specify any of the following logging levels for messages from the packager: SEVERE
, WARNING
, INFO
, or FINE
. For high-level progress messages use INFO
; for low-level debugging messages, use FINE
.
Here are sample entries for a logging properties file, to send messages to the console and use the INFO
level for messages from OC4JPackager:
# output to console handlers= java.util.logging.ConsoleHandler ... # set packager level to INFO oracle.xds.tools.OC4JPackager.level=INFO
Standards-compliant MBeans play a role in OC4J runtime configuration. The following sections provide an overview:
Note: This information is provided for reference, but for the current release we advise you to make your XQS configuration settings directly through the configuration files. See "How to Configure Your XQS Functions". |
OC4J support for the JMX specification (JSR-77) allows standard interfaces to be created for managing resources dynamically, including resources relating to XQS, in a J2EE environment. The OC4J implementation of JMX provides a JMX client, the System MBean Browser, that you can use to manage an OC4J instance through MBeans that are provided with OC4J.
An MBean is a Java object that represents a JMX manageable resource. Each manageable resource within OC4J, such as an application, is managed through an instance of the appropriate MBean. Each MBean provided with OC4J exposes a management interface that is accessible through the System MBean Browser in the Application Server Control Console. You can set MBean attributes, execute operations to call methods on an MBean, subscribe to notifications of errors or specific events, and display execution statistics.
To access the browser from the OC4J home page, select the Administration tab and then, under the list of tasks, go to the task "System MBean Browser". From the browser, you can do the following:
Select the MBean of interest in the left-hand frame.
Use the Attributes tab in the right-hand frame to view or change attributes. An attribute that can be set has a field where you can type in a new value. Then apply the change.
Use the Operations tab in the right-hand frame to invoke methods on the MBean. Select the operation of interest, and then specify to invoke it.
Use the Notifications tab (where applicable) in the right-hand frame to subscribe to notifications. You can select each item for which you want notification, and then apply the changes.
Use the Statistics tab (where applicable) in the right-hand frame to display execution statistics.
Be aware that MBeans and their attributes vary regarding when changes take effect. In the runtime model, changes take effect immediately. In the configuration model, some changes take effect when the resource is restarted, others when the application is restarted, and still others when OC4J is restarted. There is also variation in whether changes are persisted.
See the Oracle Containers for J2EE Configuration and Administration Guide for additional general information about OC4J MBeans. The System MBean Browser itself also provides information about the MBeans.
Table 8-23 summarizes the OC4J implementation of MBeans that relate to XQS. These implementations are in the oracle.xds.management
package.
Note that if you use these MBeans, XQS does the work of persisting values to the xqs-config.xml
(or global-xqs-config.xml
) configuration file, as soon as you make the updates.
Note: MBeans are self-documenting in the System MBean Browser, providing some documentation of MBean attributes, operations, and notifications (as applicable). |
Table 8-23 System MBeans for XQS
MBean | Description |
---|---|
XDSConfig |
The overall configuration MBean for XQS. |
XDSDocumentSourceConfig |
The configuration MBean for XQS document sources, corresponding to the XQS |
XDSWsdlSourceConfig |
The configuration MBean for XQS WSDL sources, corresponding to the XQS |
XDSViewSourceConfig |
The configuration MBean for XQS views, corresponding to the |
This section describes how to enable OC4J logging and offers an assortment of troubleshooting tips for your XQS application.
You can enable OC4J logging by using the Java property java.util.logging.properties.file
to specify a logging properties file. In this file you can specify Java logging settings, including the OC4JPackager logging level. Logging properties are defined by standard J2SE logging, as specified at the following location:
http://java.sun.com/j2se/1.4.2/docs/guide/util/logging/
For more information about logging, see "java.util.logging.properties.file" , the chapter on logging in OC4J in the Oracle Containers for J2EE Configuration and Administration Guide, and the logging implementation guidelines in the Oracle Containers for J2EE Developer's Guide.
This section discusses possible problems you may encounter with your XQS application, and their solutions.
Note: There are no Dynamic Monitoring Service (DMS) metrics for the XQS 10.1.3 implementation. |
Trouble with large volumes of data: If you have trouble loading large XML documents into memory, enabling the largeData
flag may allow you to proceed. See "Configuring XQS Document or View Sources for Large Data".
XQS function did not load properly: You may see an error message such as the following (where "arity" refers to the number of arguments the function takes, and "ns
" and "funcname
" are replaced by the namespace and name of your function):
XP0017: It is a static error if the expanded QName and number of arguments in a function call do not match the name and arity of an in-scope function in the static context. Detail: unknown function 'ns:funcname'
The key point is that XQuery did not recognize the function, which is an indication that the function could not be loaded properly by XQS, perhaps because it was not configured correctly. Examine your OC4J error log file (such as ORACLE_HOME
/j2ee/home/log/oc4j/log.xml
) and look for a detailed explanation of the particular problem with this function.
External function has inconsistent signatures: Consider an error such as the following:
external function "Foo" has inconsistent signatures: the one defined in function library framework is different from the one declared in function declaration prolog
Be aware that the term "function library framework" in the context of XQS refers to the signature defined within an <input-parameters>
element in the XQS configuration file. You must ensure that <part>
definitions under the <input-parameters>
element match function signatures in your XQuery prologs.
If you have trouble bringing your XQuery signatures into consistency with your configuration, you may be trying to use an unsupported XML type. (See "Supported Types for Query Parameters".) As a workaround, however, you can avoid prolog type declarations for XQuery parameters or XQuery return values altogether. For example, instead of a fully typed function declaration such as the following:
declare function xqs:Foo ($s as element()) as xs:positiveInteger external;
You can declare the function without types, as follows:
declare function xqs:Foo ($s) external;
However, you are always required to specify the number of input parameters, through your XQS configuration.
For an XQS sample, see the technology preview of Oracle XML Query Service on the Oracle Technology Network at the following location:
http://www.oracle.com/technology/sample_code/tech/java/oc4j/index.html