PL/SQL Function Result Cache?

Hi all,
As we know, there's a new feature in 11g, called 'result cache', this 'result cache' can be shared throughout the whole instance, but if I got it right, only sql query result and function return value are cached, right? how about the store procedure, I mean, procedure also has its 'return value'--the output parameter, could it benefit from this new feature?
Another question is, if my PL/SQL Function just retrieves the table and returns the result without any complicated calculation, is it necessary to enable the 'result cache' mechanism on this Function? because we already have 'db buffer cache' if the only thing we do is to query tables.
Many thanks.

Hi Morven,
As of now, PL/SQL Result cache feature is only enabled for stored functions and not for procedures. This is due to the objectives they achieve. Functions are usually computative and procedures are for logic implementation.
And for enabling result caching feature for a function, you are the better judge as u can test the performance in both the case. But, i would support enabling the cache because oracle 11g provides Cache as a different SGA component. db_buffer_cache will also be used for buffering other data blocks and not the result sets.
Hope my explanation is fine.

Similar Messages

  • DB buffer cache vs. SQL query & PL/SQL function result cache

    Hi all,
    Started preparing for OCA cert. just myself using McGraw Hill's exam guide. Have a question about memory structures.
    Actually, DB buffer cache is used to copy e.g. SELECT queries result data blocks, that can be reused by another session (server process).
    There is also additional otion - SQL query & PL/SQL function result cache (from 11g), where also stored the results of such queries.
    Do they do the same thing or nevertheless there is some difference, different purpose?
    thanks in advance...

    There is also additional otion - SQL query & PL/SQL function result cache (from 11g), where also stored the results of such queries.Result cache located in shared pool.So it is one component of shared pool.When server process execute query(and if you configured result cache) then result will store in shared pool.Then next execution time run time mechanism will detect and consider using result cache without executing this query(if data was not changed this is happen detection time)
    Do they do the same thing or nevertheless there is some difference, different purpose?.Buffer cache and result cache are different things and purpose also,but result cache introduced to improve response time of query in 11g(but such mechanism also implemented in 10g subquery execution,in complex query).In buffer cache holds data blocks but not such results.
    Edited by: Chinar on Nov 4, 2011 4:40 AM
    (Removing lots of "But" word from sentences :-) )

  • 11g Express Edition Wishlist - include PL/SQL Function Result Cache

    After this thread - Oracle Database 11g XE
    and referencing the Express Edition Licensing Information guide - http://download.oracle.com/docs/cd/B25329_01/doc/license.102/b25456/toc.htm
    if this one is also on your wish list, just send a reply and support this thread.
    Best regards.

    Tonguc,
    Look where it's listed in the Licencing Information manual:
    http://download.oracle.com/docs/cd/B28359_01/license.111/b28287/editions.htm#BABDJGGI
    It was one of my favorite features in the beta. I was disappointed when it was released as EE-only.
    Doug

  • Function result Cache in oracle 11G

    Hi,
    i am reading the following article and trying to reproduce same set of statements to learn about function result cache.
    http://www.oracle.com/technology/oramag/oracle/07-sep/o57asktom.html
    Details about my output:
    SQL> create or replace
    function not_cached
    ( p_owner in varchar2 )
    return number
    as
    l_cnt number;
    begin
    select count(*)
    into l_cnt
    from t
    where owner = p_owner;
    sys.dbms_lock.sleep(1);
    return l_cnt;
    end;
    Function created.
    Elapsed: 00:00:00.13
    SQL> create or replace
    function cached
    ( p_owner in varchar2 )
    return number
    result_cache
    relies_on(T)
    as
    l_cnt number;
    begin
    select count(*)
    into l_cnt
    from t
    where owner = p_owner;
    dbms_lock.sleep(1);
    return l_cnt;
    end;
    Function created.
    Elapsed: 00:00:00.08
    SQL> exec dbms_output.put_line( not_cached( 'SCOTT' ) );
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:01.06
    SQL> exec dbms_output.put_line( not_cached( 'SCOTT' ) );
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:01.01
    SQL> SQL> exec dbms_output.put_line( not_cached( 'SCOTT' ) );
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:01.02
    SQL> SQL> set serveroutput on
    SQL> exec dbms_output.put_line( not_cached( 'SCOTT' ) );
    0
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:01.02
    SQL> SQL> exec dbms_output.put_line( cached( 'SCOTT' ) );
    0
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:01.02
    SQL> SQL> exec dbms_output.put_line( cached( 'SCOTT' ) );
    0
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:01.02
    SQL> SQL> exec dbms_output.put_line( cached( 'SCOTT' ) );
    0
    PL/SQL procedure successfully completed.
    SQL> exec dbms_output.put_line( cached( 'SCOTT' ) );
    0
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:01.01
    I am supposed to get the results quickly for "cached" call. However, i still dont see any change in the response time. May i know what i am missing here?
    Thank you
    Giridhar

    Try to play with
    RESULT_CACHE_MAX_SIZE
    http://download.oracle.com/docs/cd/B28359_01/server.111/b28320/initparams206.htm#REFRN10272
    RESULT_CACHE_MAX_RESULT
    http://download.oracle.com/docs/cd/B28359_01/server.111/b28320/initparams205.htm#REFRN10298

  • Function result caching

    Hi All,
    Using Oracle 10g Database, I would like to cache the return value of a pl/sql function. Also, whenever the underlying value changes, the cache entry has to be invalidated. Do we have any supported functionality by Oracle.
    Regards

    Hi,
    Would it work for you to make the function DETERMINISTIC?
    Table dropped.
    SQL> set serveroutput on
    SQL> create table t (x number)
    Table created.
    SQL> insert into t (x) values (1)
    1 row created.
    SQL> create or replace package stats
    as
      cnt number;
    end;
    Package created.
    SQL> create or replace function f
    return number deterministic
    is
      the_x number;
    begin
      stats.cnt := stats.cnt + 1;
      select x into the_x from t;
      return the_x;
    end;
    Function created.
    SQL> exec stats.cnt := 0
    PL/SQL procedure successfully completed.
    SQL> select count(f), max(f) from all_objects
      COUNT(F)     MAX(F)
         42705          1
    1 row selected.
    SQL> exec dbms_output.put_line(stats.cnt)
    2
    PL/SQL procedure successfully completed.
    SQL> update t set x = 2
    1 row updated.
    SQL> commit
    Commit complete.
    SQL> exec stats.cnt := 0
    PL/SQL procedure successfully completed.
    SQL> select count(f), max(f) from all_objects
      COUNT(F)     MAX(F)
         42705          2
    1 row selected.
    SQL> exec dbms_output.put_line(stats.cnt)
    2
    PL/SQL procedure successfully completed.Regards
    Peter

  • Client Result Cache Question

    Hi,
    i am not sure, whether the new feature "Client Result Cache" for OCI - Connections is an enterprise only feature or not.
    The Licensing Information at http://docs.oracle.com/cd/E11882_01/license.112/e10594/editions.htm#CJACGHEB shows this three features are enterprise only:
    Client Side Query Cache
    Query Results Cache
    PL/SQL Function Result Cache
    Which of these are pointing to Client Result Cache? Is it the Query Results Cache? Or something else?
    As an Hint, i am unable to activate the feature on standard edition databases, but i am not sure, if this is the reason or if i am just making some mistakes in configuration/testing.
    Thanks in advance
    Joerg

    we stopped all tests, because it seems to be a enterprise edition only feature.

  • Result cache doubt

    what is the difference if i write relies_on clause or if i dont write it, technically please explain what exactly is the difference ??
    create or replace function tax (i in varchar2)
    return number
    result_cache
    is
    begin
    return i*0.08 ;
    end;
    create or replace function tax (i in varchar2)
    return number
    result_cache relies_on (emp)
    is
    begin
    return i*0.08 ;
    end;

    http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/function.htm#i34368
    RELIES_ON
    Specifies the data sources on which the results of a function depend. For more information, see Using the PL/SQL Function Result Cache. http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/subprograms.htm#BABFHACJ
    To enable result-caching for a function, use the RESULT_CACHE clause. When a result-cached function is invoked, the system checks the cache. If the cache contains the result from a previous call to the function with the same parameter values, the system returns the cached result to the invoker and does not reexecute the function body. If the cache does not contain the result, the system executes the function body and adds the result (for these parameter values) to the cache before returning control to the invoker.Not sure why are you talking about invalidated data, result_cache just invoked result from a previous call to the function if it exists, if not it executes the function body.
    The clause relies_on just specifies the data sources on which the results of a function depend.
    am i missing something??

  • Does Result Cache Really Work..

    Does Result Cache Really Work..
    We have upgraded to 11.2.0.2 Theere were some corruption issue we were facing cause of using result cache..
    Still the same error after upgrade...
    Is any one here familiar with using result cache..One good thing about result cahce i found it does improve performance.
    But the problem is the datbaase crashes..after it reaches some memory limit..Does any one have good expereince using it..?

    Probably following notes on Oracle Support site can help.
    11g New Feature PL/SQL Function Result Cache [ID 430887.1]
    11g New Feature : SQL Query Result Cache [ID 453567.1]
    PL/SQL Procedures Do Not Switch Result Cache Mode Within The Same Session [ID 556035.1]
    HTH

  • Using the client result cache without the query result cache

    I have constructed a client in C# using ODP.NET to connect to an Oracle database and want to perform client result caching for some of my queries.
    This is done using a result_cache hint in the query.
    select /*+ result_cache */ * from table
    As far as I can tell query result caching on the server is done using the same hint, so I was wondering if there was any way to differentiate between the two? I want the query results to be cached on the client, but not on the server.
    The only way I have found to do this is to disable all caching on the server, but I don't want to do this as I want to use the server cache for PL/SQL function results.
    Thanks.

    e3a934c9-c4c2-4c80-b032-d61d415efd4f wrote:
    I have constructed a client in C# using ODP.NET to connect to an Oracle database and want to perform client result caching for some of my queries.
    This is done using a result_cache hint in the query.
    select /*+ result_cache */ * from table 
    As far as I can tell query result caching on the server is done using the same hint, so I was wondering if there was any way to differentiate between the two? I want the query results to be cached on the client, but not on the server.
    The only way I have found to do this is to disable all caching on the server, but I don't want to do this as I want to use the server cache for PL/SQL function results.
    Thanks.
    You haven't provided ANY information about how you configured the result cache. Different parameters are used for configuring the client versus the server result cache so you need to post what, if anything, you configured.
    Post the code you executed when you set the 'client_result_cache_lag' and 'client_result_cache_size' parameters so we can see what values you used. Also post the results of querying those parameters after you set them that show that they really are set.
    You also need to post your app code that shows that you are using the OCI statements are used when you want to use client side result cacheing.
    See the OCI dev guide
    http://docs.oracle.com/cd/B28359_01/appdev.111/b28395/oci10new.htm#sthref1491
    Statement Caching in OCI
    Statement caching refers to the feature that provides and manages a cache of statements for each session. In the server, it means that cursors are ready to be used without the need to parse the statement again. Statement caching can be used with connection pooling and with session pooling, and will improve performance and scalability. It can be used without session pooling as well. The OCI calls that implement statement caching are:
      OCIStmtPrepare2()
      OCIStmtRelease()

  • Oracle result cache and functions

    Hi All,
    I am on 11.2 in Linux.
    I want to use Oracle's result cache to cache results of (user defined) functions, which we use in SELECT commands.
    My question is, does result caching work for deterministic and non-deterministic functions ?
    Just curious, how Oracle keeps track of changes being made which affect a function's return value?
    Thoughts please.
    Thanks in advance

    I want to ... cache results of (user defined) functions, which we use in SELECT commands.You have four choices:
    1. Subquery caching - (wrap function call in SELECT) useful for repeated function calls in a single SELECT
    2. Marking function as DETERMINISTIC - inconsistent results across versions, deterministic best reserved for function-based indexes only
    3. Result Cache
    4. Move function logic out of function and inline to the main SQL statement.
    The biggest downside of any function call that is inline to SQL is that it bypasses the read consistency mechanism, actually that's probably the second biggest downside. The biggest downside is normally that their misuse kills performance.
    If your function itself contains SQL then you should seriously reconsider whether you should be using a function.
    does result caching work for deterministic and non-deterministic functions ?Result cache knows nothing about determinism so yes it should be applied regardless.
    Oracle keeps track of changes being made which affect a function's return value?See v$result_cache_dependency.
    The mechanism is very blunt, there is no fine-grained tracking of data changes that may affect your result.
    It's as simple as function F1 relies on table T1. If the data in table T1 changes, invalidate the results in the result cache for F1.

  • SQL Result Cache  vs In-Memory Database Cache

    Hi,
    can anyone help me to understand the relations and differences between the 11 g new features of SQL Result Cache vs In-Memory Database Cache ?
    Thanks

    I highly recommend you read the 11g New Features Guide. Here is a sample from it:
    h4. 1.11.2.9 Query Result Cache
    A separate shared memory pool is now used for storing and retrieving
    cached results. Query retrieval from the query result cache is faster
    than rerunning the query. Frequently executed queries will see
    performance improvements when using the query result cache.
    The new query result cache enables explicit caching of results in
    database memory. Subsequent queries using the cached results will
    experience significant performance improvements.
    See Also:
    [Oracle Database Performance Tuning Guide|http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/memory.htm#PFGRF10121] for details
    [Results Cache Concepts|http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/memory.htm#PFGRF10121|Results Cache Concepts]
    HTH!

  • Refering alias of a function result in an sql statement

    Dear Sir,
    How to refer an alias of a function result in sql statement?
    eg.(new_name is the alias)
    select myfunction(name) new_name
    from mytable
    where new_name = '#vincent#';
    I can't refer new_name in the above statement coz it gives an error "invalid column name".
    But I don't want to put the myfunction(name) again in the where clause which will double the job. So, how should I refer to it?
    Please advise.
    Thanks.
    null

    You can not refer to the alias like you are talking. You will have to use myfunction(name) as you have said. Or you can try creating a view with query:
    select myfunction(name) new_name
    from mytable
    and then refer to "new_name".
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by guest2000:
    Dear Sir,
    How to refer an alias of a function result in sql statement?
    eg.(new_name is the alias)
    select myfunction(name) new_name
    from mytable
    where new_name = '#vincent#';
    I can't refer new_name in the above statement coz it gives an error "invalid column name".
    But I don't want to put the myfunction(name) again in the where clause which will double the job. So, how should I refer to it?
    Please advise.
    Thanks.<HR></BLOCKQUOTE>
    null

  • Query result cache with functions

    Hi all,
    one of my colleagues has found a little bit weird behavior of a query result cache. He has set result_cache_mode = 'FORCE' (but it can be reproduced with a result_cache hint too) and suddenly functions called from the query get executed twice (for the first time) .
    An easy example:
    alter session set result_cache_mode = 'FORCE';
    create sequence test_seq;
    create or replace function test_f(i number)
    return number
    is                  
    begin
      dbms_output.put_line('TEST_F executed');
      --autonomous transaction or package variable can be used too
      return test_seq.nextval;
    end;
    prompt First call
    select test_f(1) from dual;
    prompt Second call
    select test_f(1) from dual;
    drop sequence test_seq;
    drop function test_f;
    First call
    TEST_F(1)
             2
    TEST_F executed
    TEST_F executed
    Second call
    TEST_F(1)
             1
    As you can see - for the first time the function is executed twice and return the value from the second execution. When I execute the query again it returns the value from the first execution... but it doesn't matter, problem is in the double execution. Our developers used to send emails via select (it's easier for them):
    select send_mail(...) from dual;
    ... and now the customers complains that they get emails twice
    And now the question - is there any way, hot to get rid of this behavior (without changing the parameter back or rewriting code)? I thought that the result cache is automatically disabled for non-deterministic functions...or is this an expected behavior?
    Thanks,
    Ivan

    Interesting.. you are right:
    SELECT /*+ RESULT_CACHE */ 'dog' FROM DUAL;
    And at the second execution:
    | Id  | Operation        | Name                       | Rows  | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT |                            |     1 |     2   (0)| 00:00:01 |
    |   1 |  RESULT CACHE    | cc5k01xyqz3ypf9t0j28r5gtd1 |       |            |          |
    |   2 |   FAST DUAL      |                            |     1 |     2   (0)| 00:00:01 |
    Hmmm..

  • Get result from PL/SQL function through XDBUri (10g)

    Hi!
    I have to call a PL/SQL function that takes two parameters and return one parameter. (I will do this from Oracle Service Bus).
    It is possible to get relational data as xml through an XDBUri type over http by using the XML DB functionality. But is it possible to get the result of a PL/SQL function as XML as well?
    I have tried to wrap the PL/SQL procedure inside a view, but cant get the variable to be bound into the sql.
    I have tried with stuff like this:
    create or replace view test (a, b)
    as
    select function(a, b) from dual
    But since I dont have a table returning the values i cant get it work.
    If I can make this view, I can call it through the XDMUri type.
    Sombody that can help me to manage this?
    /Helge
    Edited by: user3169245 on 03.apr.2009 12:06

    Here's a code snippet that may help
    package com.oracle.st.xmldb.pm.xfiles;
    import com.oracle.st.xmldb.pm.multipart.InputStreamProcessor;
    import com.oracle.st.xmldb.pm.multipart.MultipartInputStream;
    import java.io.IOException;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import oracle.jdbc.OracleConnection;
    import oracle.jdbc.OracleDriver;
    import oracle.jdbc.OracleCallableStatement;
    import com.oracle.st.xmldb.pm.multipart.MultipartProcessor;
    import com.oracle.st.xmldb.pm.multipart.MultipartProcessorImpl;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.io.Reader;
    import java.io.StringReader;
    import java.io.StringWriter;
    import java.io.Writer;
    import java.sql.DatabaseMetaData;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.Timestamp;
    import java.text.SimpleDateFormat;
    import java.util.Enumeration;
    import oracle.jdbc.OraclePreparedStatement;
    import oracle.jdbc.OracleResultSet;
    import oracle.jdbc.OracleTypes;
    import oracle.sql.BLOB;
    import oracle.sql.CLOB;
    import oracle.xdb.XMLType;
    import oracle.xml.parser.v2.XMLDocument;
    import org.w3c.dom.Attr;
    import org.w3c.dom.CDATASection;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Text;
    public class XFilesServlet extends HttpServlet implements InputStreamProcessor {
        public static String TARGET_PATH      = "target";
        public static String STYLESHEET_PATH      = "stylesheet"; 
        private static String CREATE_RESOURCE_SQL =
        "begin " +
        "  XFILES_SOAP_SERVICES.UPLOADRESOURCE" +
        "  ( " +
        "    P_RESOURCE_PATH => :1, " +
        "    P_CONTENT => :2, " +
        "    P_CONTENT_TYPE => :3," +
        "    P_DESCRIPTION => :4," +
        "    P_LANGUAGE => :5," +
        "    P_CHARACTER_SET => :6," +
        "    P_DUPLICATE_POLICY => :7" +
        "  );" +
        "end;";
        private static String GET_FOLDER_HTML_PAGE_SQL =
        "select xdburitype('/XFILES/lite/Folder.html').getClob() from dual";
        private static String WRITE_LOG_RECORD_SQL =
        "begin xfiles_logging.enqueue_log_record(:1); end;";
        private OracleConnection dbConnection;
        private OracleCallableStatement createResource;
        private OracleCallableStatement writeLogRecord;
        private DatabaseMetaData dbMetadata;
        private static final int FILE_UPLOAD = 1;
        private static final int PUBLISH_RSS = 2;
        private static final int DB_REST_SERVICE = 3;
        private static final int FORCE_AUTHENTICATION = 4;
        private static final int SET_PASSWORD = 5;
        private static final int DISPLAY_XML = 6;
        private static final int ENABLE_RSS = 7;
        public static final int XDB_ACCESS_DENIED = 31050;
        private static String SERVLET_ROOT = "/sys/servlets/XFILES";
        private static final String FILE_UPLOAD_PATH = "fileUpload";
        private static final String PUBLISH_RSS_PATH = "publishRSS";
        private static final String SET_PASSWORD_PATH = "setPassword";
        private static final String DB_REST_SERVICE_PATH = "dbRestService";
        private static final String FORCE_AUTHENTICATION_PATH = "doAuthentication";
        private static final String DISPLAY_XML_PATH = "displayXML";
        private static final String ENABLE_RSS_PATH = "enableRSS";
        public static String POST_UPLOAD_URL = "postUploadRedirect";
        public static String DULPLICATE_POLICY = "duplicatePolicy";
        public static String SOURCE_FILE_PATH = "sourceFilePath";
        public static String RESOURCE_FILENAME = "targetFileName";
        public static String RESOURCE_DESCRIPTION = "description";
        public static String UPLOAD_LANGUAGE = "UploadLanguage";
        public static String UPLOAD_CHARACTERSET = "UploadCharset";
        public static String PASSWORD = "password";
        public static String XML_DOCUMENT = "content";
        public static String XML_CHUNK = "chunk";
        public static String RESOURCE_ID = "resid";
        public static String DATABASE_SCHEMA = "DatabaseSchema";
        public static String PACKAGE  = "Package";
        public static String METHOD = "Method";
        public static String SQL_CALL = "SqlOperation";
        protected XMLDocument logRecord;
        protected Element parameterList;
        protected Element timings;
        protected int currentOperation;
        public String xmlContent;
        public static String XML_TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS000";
        public static String LOG_TIMESTAMP_FORMAT = "HH:mm:ss.SSS000";
        protected SimpleDateFormat xmlDateFormatter  = new SimpleDateFormat(XML_TIMESTAMP_FORMAT); 
        private String postUploadURL;
        private String targetFolder;
        private String onDuplicateAction;
        private String sourceFile;
        private BLOB   resourceContent;
        private String contentType;
        private String resourceName;
        private String resourceComment;
        private String uploadLanguage;
        private String uploadCharacterSet;
        public XFilesServlet() {
        private void logParameter(Document doc)
           this.parameterList.appendChild(logRecord.importNode(doc.getDocumentElement().cloneNode(true),true));
        private void logParameter(String parameterName, String[] values)
          Element e = this.logRecord.createElement(parameterName);
          this.parameterList.appendChild(e);
          if (values != null)
            Attr a = this.logRecord.createAttribute("Length");
            e.setAttributeNode(a);
            a.setValue(Integer.toString(values.length));
            for (int i = 0; i < values.length; i++)
              Element v = this.logRecord.createElement("parameterValue");
              e.appendChild(v);
              Text t = this.logRecord.createTextNode(values);
    v.appendChild(t);
    a = this.logRecord.createAttribute("Index");
    v.setAttributeNode(a);
    a.setValue(Integer.toString(i));
    public void logParameter(String parameterName,String value)
    Element e = this.logRecord.createElement(parameterName);
    this.parameterList.appendChild(e);
    if (value != null)
    Text t = this.logRecord.createTextNode(value);
    e.appendChild(t);
    private void logParameterCDATA(String parameterName,String value)
    Element e = this.logRecord.createElement(parameterName);
    this.parameterList.appendChild(e);
    if (value != null)
    CDATASection c = this.logRecord.createCDATASection(value);
    e.appendChild(c);
    private void logException(Exception e) {
    Element stackTrace = this.logRecord.createElement("StackTrace");
    this.logRecord.getDocumentElement().appendChild(stackTrace);
    this.appendException(stackTrace,e);
    private void appendException(Element stackTrace, Throwable error)
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    error.printStackTrace(pw);
    pw.flush();
    pw.close();
    Text t = this.logRecord.createCDATASection(sw.toString());
    stackTrace.appendChild(t);
    if (error.getCause() != null)
    Element causedBy = this.logRecord.createElement("CausedBy");
    stackTrace.appendChild(causedBy);
    appendException(causedBy,error.getCause());
    else {
    if (error instanceof ServletException) {
    ServletException se = (ServletException) error;
    if (se.getRootCause() != null) {
    Element causedBy = this.logRecord.createElement("CausedBy");
    stackTrace.appendChild(causedBy);
    appendException(causedBy,se.getRootCause());
    private void logTimestamp(String eventName)
    Timestamp ts = new Timestamp(System.currentTimeMillis());
    Element element = logRecord.createElement(eventName);
    this.timings.appendChild(element);
    Text text = logRecord.createTextNode(this.xmlDateFormatter.format(ts));
    element.appendChild(text);
    protected void initiateLogging(HttpServletRequest request)
    throws IOException
    this.logRecord = new XMLDocument();
    Element root = this.logRecord.createElement("XFilesLogRecord");
    this.logRecord.appendChild(root);
    Element e = this.logRecord.createElement("HttpRequest");
    root.appendChild(e);
    Element e1 = this.logRecord.createElement("ServletName");
    Text t = this.logRecord.createTextNode(this.getClass().getName());
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("HttpMethod");
    t = this.logRecord.createTextNode(request.getMethod());
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("RequestURI");
    t = this.logRecord.createTextNode(request.getRequestURI());
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("PathTranslated");
    t = this.logRecord.createTextNode(request.getPathTranslated());
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("RequestURL");
    t = this.logRecord.createTextNode(new String(request.getRequestURL()));
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("Protocol");
    t = this.logRecord.createTextNode(request.getProtocol());
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("ServerName");
    t = this.logRecord.createTextNode(request.getServerName());
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("ContentType");
    t = this.logRecord.createTextNode(request.getContentType());
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("LocalAddr");
    t = this.logRecord.createTextNode(request.getLocalAddr());
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("LocalName");
    t = this.logRecord.createTextNode(request.getLocalName());
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("LocalPort");
    t = this.logRecord.createTextNode(Integer.toString(request.getLocalPort()));
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("Port");
    t = this.logRecord.createTextNode(Integer.toString(request.getServerPort()));
    e1.appendChild(t);
    e.appendChild(e1);
    this.timings = this.logRecord.createElement("Timestamps");
    root.appendChild(this.timings);
    logTimestamp("Init");
    e = this.logRecord.createElement("Remote");
    root.appendChild(e);
    e1 = this.logRecord.createElement("RemoteHost");
    t = this.logRecord.createTextNode(request.getRemoteHost());
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("RemoteAddress");
    t = this.logRecord.createTextNode(request.getRemoteAddr());
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("RemotePort");
    t = this.logRecord.createTextNode(Integer.toString(request.getRemotePort()));
    e1.appendChild(t);
    e.appendChild(e1);
    e1 = this.logRecord.createElement("RemoteUser");
    t = this.logRecord.createTextNode(request.getRemoteUser());
    e1.appendChild(t);
    e.appendChild(e1);
    e = this.logRecord.createElement("RequestHeaders");
    root.appendChild(e);
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements())
    String headerName = (String) headerNames.nextElement();
    e1 = this.logRecord.createElement(headerName);
    t = this.logRecord.createTextNode(request.getHeader(headerName));
    e1.appendChild(t);
    e.appendChild(e1);
    this.parameterList = this.logRecord.createElement("ServletParameters");
    root.appendChild(parameterList);
    public void writeLogRecord(XMLDocument logRecord) throws SQLException , IOException {
    XMLType xml = new XMLType(this.dbConnection, logRecord);
    this.writeLogRecord.setObject(1, xml);
    this.writeLogRecord.execute();
    this.dbConnection.commit();
    protected String readParameter(HttpServletRequest request,String parameterName,String defaultValue)
    String value = request.getParameter(parameterName);
    if (value != null)
    if (value.length() == 0) {
    value = null;
    if (value == null) {
    value = defaultValue;
    logParameter(parameterName,value);
    return value;
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException
    try {
    try {  
    initiateLogging(request);
    initializeDatabaseConnection();
    String requestURI = request.getRequestURI();
    this.currentOperation = getOperation(requestURI);
    switch (this.currentOperation) {
    case DB_REST_SERVICE:
    restResponse(request,response);
    break;
    default:
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    logTimestamp("Complete");
    writeLogRecord(this.logRecord);
    this.dbConnection.commit();
    catch (Exception e) {
    try {
    this.dbConnection.rollback();
    logTimestamp("Exception");
    logException(e);
    writeLogRecord(this.logRecord);
    catch (Exception wle) {
    System.out.println("XFilesServlet : Fatal error while logging Error : ");
    e.printStackTrace(System.out);
    System.out.flush();
    wle.printStackTrace(System.out);
    System.out.flush();
    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    finally {
    try {
    this.createResource.close();
    this.writeLogRecord.close();
    catch (SQLException e) {
    System.out.println("XFilesServlet : Fatal error while closing statements : ");
    e.printStackTrace(System.out);
    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (IOException ioe) {
    System.out.println("XFilesServlet : Fatal error while Sending Error Status : ");
    ioe.printStackTrace(System.out);
    System.out.flush();
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    doGet(req, res);
    private void initializeDatabaseConnection() throws SQLException {
    DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
    OracleDriver ora = new OracleDriver();
    this.dbConnection = (OracleConnection) ora.defaultConnection();
    this.createResource = (OracleCallableStatement) this.dbConnection.prepareCall(this.CREATE_RESOURCE_SQL);
    this.writeLogRecord = (OracleCallableStatement) this.dbConnection.prepareCall(this.WRITE_LOG_RECORD_SQL);
    this.dbMetadata = this.dbConnection.getMetaData();
    private int getOperation(String requestURI) {
    String servletTarget = requestURI.substring(this.SERVLET_ROOT.length()+1);
    if (servletTarget.indexOf('/') > -1) {
    servletTarget = servletTarget.substring(0,servletTarget.indexOf("/"));
    if (servletTarget.equals(this.FILE_UPLOAD_PATH)) return FILE_UPLOAD;
    if (servletTarget.equals(this.FORCE_AUTHENTICATION_PATH)) return this.FORCE_AUTHENTICATION;
    if (servletTarget.equals(this.PUBLISH_RSS_PATH)) return this.PUBLISH_RSS;
    if (servletTarget.equals(this.DB_REST_SERVICE_PATH)) return this.DB_REST_SERVICE;
    if (servletTarget.equals(this.SET_PASSWORD_PATH)) return this.SET_PASSWORD;
    if (servletTarget.equals(this.DISPLAY_XML_PATH)) return this.DISPLAY_XML;
    if (servletTarget.equals(this.ENABLE_RSS_PATH)) return this.ENABLE_RSS;
    return 0;
    public void processParameter(String name, String value)
    throws SQLException {
    logParameter(name,value);
    if (name.equals(this.TARGET_PATH)) {
    this.targetFolder = value;
    if (name.equals(this.POST_UPLOAD_URL)) {
    this.postUploadURL = value;
    if (name.equals(this.UPLOAD_LANGUAGE)) {
    this.uploadLanguage = value;
    if (name.equals(this.UPLOAD_CHARACTERSET)) {
    this.uploadCharacterSet = value;
    if (name.equals(this.DULPLICATE_POLICY)) {
    this.onDuplicateAction = value;
    if (name.equals(this.SOURCE_FILE_PATH)) {
    this.sourceFile = value;
    if (name.equals(MultipartProcessor.MULTIPART_CONTENT_TYPE)) {
    this.contentType = value;
    if (name.equals(this.RESOURCE_FILENAME)) {
    this.resourceName = value;
    if (name.equals(this.RESOURCE_DESCRIPTION)) {
    this.resourceComment = value;
    createNewResource();
    private void restResponse(HttpServletRequest request, HttpServletResponse response)
    throws IOException, SQLException, ServletException {
    String requestURI = request.getRequestURI();
    String restTarget = requestURI.substring(this.SERVLET_ROOT.length() + this.DB_REST_SERVICE_PATH.length()+1);
    if (restTarget.contains("//")) {
    // Cannot have // in URL
    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    return;
    if (restTarget.length() < 4) {
    // URL is too short to be valid - Minumum is /A/B
    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    return;
    if (!restTarget.startsWith("/")) {
    // Invalid URL
    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    return;
    if (!restTarget.substring(1).contains("/")) {
    // URL must contain /Schema/Method, may Contain /Schema/Package/Method
    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    return;
    String schemaName = restTarget.substring(1,restTarget.substring(1).indexOf("/")+1);
    restTarget = restTarget.substring(schemaName.length()+1);
    logParameter(this.DATABASE_SCHEMA,schemaName);
    String packageName = null;
    if (restTarget.substring(1).contains("/")) {
    // URL contains /Schema/Package/Method
    packageName = restTarget.substring(1,restTarget.substring(1).indexOf("/")+1);
    restTarget = restTarget.substring(packageName.length()+1);
    logParameter(this.PACKAGE,packageName);
    if (restTarget.substring(1).contains("/")) {
    // URL must be /Schema/Method or /Schema/Package/Method, anything else is junk
    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    return;
    String methodName = restTarget.substring(1);
    logParameter(this.METHOD,methodName);
    int responseCode = verifyTarget(request,schemaName,packageName,methodName);
    if (responseCode != HttpServletResponse.SC_OK) {
    System.out.println("Status Code = " + responseCode);
    response.sendError(responseCode);
    return;
    String target = "\"" + schemaName + "\".";
    if (packageName != null) {
    target = target + "\"" + packageName + "\".";
    target = target + "\"" + methodName + "\"";
    int index;
    Enumeration parmNames;
    String sqlStatementText =
    "begin" + "\n" +
    " :1 := " + target + "(" + "\n";
    index = 1;
    parmNames = request.getParameterNames();
    while (parmNames.hasMoreElements()) {
    index++;
    sqlStatementText = sqlStatementText + "\"" + parmNames.nextElement() + "\" => :" + index + " ";
    if (parmNames.hasMoreElements()) {
    sqlStatementText = sqlStatementText + ",\n";
    sqlStatementText = sqlStatementText + ");\nend;";
    logParameterCDATA(this.SQL_CALL,sqlStatementText);
    OracleCallableStatement statement = (OracleCallableStatement) this.dbConnection.prepareCall(sqlStatementText);
    index = 1;
    parmNames = request.getParameterNames();
    while (parmNames.hasMoreElements()) {
    index++;
    String parameterName = (String) parmNames.nextElement();
    String parameterValue = (String) request.getParameter(parameterName);
    logParameter(parameterName,parameterValue);
    statement.setString(index,parameterValue);
    XMLType xml = null;
    try {
    statement.registerOutParameter(1,OracleTypes.OPAQUE,"SYS.XMLTYPE");
    statement.execute();
    xml = (XMLType) statement.getObject(1);
    statement.close();
    catch (SQLException sqle) {
    statement.close();
    if (xml != null) xml.close();
    if (sqle.getErrorCode() == this.XDB_ACCESS_DENIED) {
    logTimestamp("RequestAuthorization");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return;
    ServletException se = new ServletException("Unexpected SQL Error",sqle);
    throw se;
    response.setContentLength(0);
    response.setContentType("text/xml");
    xml.writeToOutputStream(response.getOutputStream());
    xml.close();
    response.getOutputStream().flush();
    response.getOutputStream().write( new byte[] {'\r','\n'} );
    // response.getOutputStream().flush();
    response.getOutputStream().close();
    response.setStatus(HttpServletResponse.SC_OK);
    private int verifyTarget(HttpServletRequest request, String schemaName, String packageName, String methodName)
    throws SQLException {
    int response = HttpServletResponse.SC_NOT_FOUND;
    boolean parameterValid = false;
    ResultSet procedure = null;
    procedure = this.dbMetadata.getProcedures(packageName,schemaName,methodName);
    while (procedure.next()) {
    response = HttpServletResponse.SC_OK;
    response = verifyMandatoryParameters(request,schemaName,packageName,methodName);
    if (response == HttpServletResponse.SC_OK) {
    response = verifyOptionalParameters(request,schemaName,packageName,methodName);
    return response;
    private int verifyMandatoryParameters(HttpServletRequest request, String schemaName, String packageName, String methodName) throws SQLException {
    // Check Mandatory Parameters are present.
    ResultSet columns = null;
    columns = this.dbMetadata.getProcedureColumns(packageName,schemaName,methodName,"%");
    while (columns.next()) {
    short nullable = columns.getShort(12);
    String columnName = columns.getString(4);
    if (nullable == DatabaseMetaData.procedureNoNulls) {
    if (request.getParameter(columnName) == null) {
    columns.close();
    return HttpServletResponse.SC_BAD_REQUEST;
    return HttpServletResponse.SC_OK;
    private int verifyOptionalParameters(HttpServletRequest request, String schemaName, String packageName, String methodName) throws SQLException {
    // Check Optional Parameters are valid
    Enumeration parms = request.getParameterNames();
    ResultSet column = null;
    while (parms.hasMoreElements()) {
    String columnName = (String) parms.nextElement();
    column = this.dbMetadata.getProcedureColumns(packageName,schemaName,methodName,columnName);
    if (!column.next()) {
    column.close();
    return HttpServletResponse.SC_BAD_REQUEST;
    column.close();
    return HttpServletResponse.SC_OK;

  • How display result set of a PL/ SQL function call in a dialog box

    Hello,
    I am calling a PL/ SQL function from Apex, which returns - List of varchar.
    In Apex, it should show this list of varchar and "Yes" and "No" buttons on a message window.
    Can you please suggest a way to achieve the same.
    Thanks,
    Girish

    Hello,
    This application process "vrl_popup" is to get the values from PL/ SQL function. For popup window - confirm(). Also declared the LV_list as Application Item.
    Which is coded in the region part of the button. After pressing this button popup window should come with the list.
    <script type="text/javascript">
    <!--
    function doAjaxRequestParam( process, parameter)
    var ajaxRequest = new htmldb_Get(null,&APP_ID.,'vrl_popup='+process,0);
    ajaxRequest.add('lv_list', parameter );
    var jsonResult = eval('('+ ajaxRequest.get() +')');
    return jsonResult;
    var answer = confirm ("can try this?")
    alert (v_list)
    if (answer)
    alert ("done")
    else
    alert ("Unsuccessful")
    // -->
    </script>
    In apex I created following Application process by name = vrl_popup,
    declare
    lv_List varchar2(2000) := '';
    begin
    begin
    lv_List := select vrl_type_process_pkg.get_regd_reg_lste() from dual;
    exception when no_data_found then null;
    end;
    htp.prn(lv_List);
    end;
    Kindly help in fixing this.
    Edited by: Girish on Jun 17, 2010 12:57 AM

Maybe you are looking for

  • Burning AVI files to DVD

    Can someone please recommend a freeware or open source program to burn AVI files to DVD? Thanks in advance for any help!

  • Change source (sql) of interactive report based on column value?

    I've got an Interactive report displaying 10 columns. What I'd like to do is show different columns depending on the value of the first column. All the rows in the result will have the same value in the first column. If value in column 1 (on any row)

  • 1 click effects not working

    When I press the effects icon in edit view nothing happens? The effects panel does not appear. Does anyone else have this problem?

  • Indesign CS4 - now very slow

    On one identity (mac), our indesign is super slow.  Pinwheel displays every time we try to move an object or type character, etc.  Its seems to be less of a problem on a different identity on the same mac.  We tried everything we know to troubleshoot

  • In App Purchase An unknown error has occurred with test user account

    I have created a test app that has in app purchasing. I am able to connect to the store and verify my product ID's. I then use my test user account to purchase a product. And guess what... it works... the first time. If I try to use the test user acc