Java Procedure

--connect as system to grant permisiions to scott
--java classes
connect system/manager@srinivas
begin
dbms_java.grant_permission
('SCOTT',
'java.io.FilePermission',
'h:\oracle\loader_scripts',
'read');
dbms_java.grant_permission
('SCOTT',
'java.io.FilePermission',
'sqlldr.exe',
'execute');
dbms_java.grant_permission
('SCOTT',
'java.lang.RuntimePermission',
'writerFileDescriptor');
end;
-- now connect as scott
connect scott/tiger@srinivas
-- create a temporary table
drop table dir_list;
create table dir_list
(filename varchar2(255))
--create java source
drop java source "DirList";
create or replace
and resolve java source named "DirList"
as
import java.io.*;
import java.sql.*;
public class DirList
public static void getList(String directory)
               throws SQLException
     File path = new File(directory);
     String[] list = path.list();
     String element;
     for (int i=0; i < list.length; i++)
          element = list;
          #sql { insert into dir_list(filename)
          values(:element)
-- create procedure
drop procedure get_dir_list;
create or replace procedure get_dir_list(p_directory in varchar2)
as
language java
name 'DirList.getList( java.lang.String)';
-- execute the proc
exec get_dir_list('h:\oracle\loader_scripts');
-- select the data from dirlist temporary table to make sure that data is there
select * from dir_list;
rem      connect as scott/tiger and then create this java source
create or replace and compile
java source named "Util"
as
import java.io.*;
import java.lang.*;
public class Util extends Object
public static int RunThis(String[] args)
Runtime rt = Runtime.getRuntime();
int rc = -1;
try
               Process p = rt.exec(args[0]);
int bufSize = 4096;
BufferedInputStream bis =
new BufferedInputStream(p.getInputStream(), bufSize);
int len;
byte buffer[]=new byte[bufSize];
               while((len=bis.read(buffer,0,bufSize)) != -1)
               System.out.write(buffer,0,len);
               rc=p.waitFor();
catch (Exception e)
e.printStackTrace();
rc = -1;
finally
return rc;
rem now create a function
connect scott/tiger@srinivas
create or replace function run_cmd(p_cmd in varchar2) return number
as
language java
name 'Util.RunThis(java.lang.String[]) return integer';
rem create this procedure as scott
create or replace procedure Exec_Cmd(p_cmd in varchar2)
as
x number;
v_date_format varchar2(255);
begin
v_date_format:='mon-dd-yyyy hh24:mi:ss';
Execute immediate ' alter session set nls_date_format ='''|| v_date_format||'''';
x:=run_cmd(p_cmd);
if x = 0 then
INSERT INTO TAB_LOAD_FAIL_DETAIL (
                    DATETIME,
                    RESULT,
DISCARD_DIR,
BAD_DIR,
LOG_DIR
VALUES (
sysdate,
'Succeeded',
                    'H:\Oracle\ldr_discard\',
                    'H:\Oracle\ldr_bad\',
'H:\Oracle\ldr_log\'
commit;
elsif x <> 0 then
INSERT INTO TAB_LOAD_FAIL_DETAIL (
                    DATETIME,
                    RESULT,
DISCARD_DIR,
BAD_DIR,
LOG_DIR
VALUES (
sysdate,
'Failed',
                    'H:\Oracle\ldr_discard\',
                    'H:\Oracle\ldr_bad\',
'H:\Oracle\ldr_log\'
commit;
end if;
end;
CREATE OR REPLACE PROCEDURE compare_file_name
as
cursor tab is select table_name from dba_tables where owner =user;
v_file varchar2(255);
v_date_format varchar2(255);
v_cmd_string varchar2(255);
begin
Execute immediate' delete from dir_list';
get_dir_list('H:\Oracle\loader_scripts');
v_date_format:='mon-dd-yyyy hh24:mi:ss';
Execute immediate ' alter session set nls_date_format ='''|| v_date_format||'''';
for tab_rec in tab loop
--dbms_output.put_line(tab_rec.table_name);
for x in (select upper(substr(filename,1,instr(filename,'.')-1)) filename from dir_list)
loop
v_file := x.filename;
if tab_rec.table_name = v_file then
               INSERT INTO TAB_LOAD_DATA_DETAIL
               VALUES ( sysdate,tab_rec.table_name,'H:\Oracle\loader_scripts\'||v_file||'.dat');
               commit;
               dbms_output.put_line(tab_rec.table_name ||' '||v_file||' '||' You Got that');
                    Exec_Cmd(chr(39)||'sqlldr parfile=H:\Oracle\ldr_par_files\'||tab_rec.table_name||'.ctl'||chr(39));
end if;
end loop;
end loop;
end;
EXEC COMPARE_FILE_NAME;
when executed the following errors are observed
================================================
it is failing to execute sql loader with the following messages
EMP EMP You Got that
java.io.IOException
at oracle.aurora.java.lang.OracleProcess.create(OracleProcess.java)
at oracle.aurora.java.lang.OracleProcess.construct(OracleProcess.java)
at java.lang.Runtime.execInternal(Runtime.java)
at java.lang.Runtime.exec(Runtime.java:272)
at java.lang.Runtime.exec(Runtime.java:195)
at java.lang.Runtime.exec(Runtime.java:152)
at Util.RunThis(Util:12)
PL/SQL procedure successfully completed.
===================================
my email id is [email protected]
====================================
help me execute sql loader successfully through this procedure.
thanks for the help in advance.

SQL> create or replace and resolve java source named PrimeClass as
  2 
  3  public class PrimeClass {
  4 
  5   public static boolean isPrime ( int num )
  6    {
  7      boolean prime = true;
  8      int limit = (int) Math.sqrt ( num ); 
  9 
10      for ( int i = 2; i <= limit; i++ )
11      {
12        if ( num % i == 0 )
13        {
14          prime = false;
15         break;
16        }
17      }
18     
19      return prime;
20    }
21   
22    }
23  /
Java created.
SQL> create or replace function myprime (p_str in number) return number as
  2 
  3  language Java name 'PrimeClass.isPrime(int) return int';
  4  /
Function created.
SQL>
SQL> set serveroutput on
SQL>
SQL> declare
  2  l_str  number;
  3  begin
  4  l_str :=  myprime(11);
  5  if l_str=0 then
  6  dbms_output.put_line('number is not prime');
  7  else
  8  dbms_output.put_line('number is prime'); 
  9  end if;
10  end;
11  /
number is prime
PL/SQL procedure successfully completed.

Similar Messages

  • Error 03113 while executing java procedure with pl.sql

    Hi All,
    I am using oracle 10g on linux server. Client machine is on xp. I hava a java procedure which executes the sqlldr on server. Earlier it was working fine, but after reinstalling the oracle 10g on server. It started giving "end of Communication channel error". I am not aware that what paramete has to set. Can some body put light on this error.
    Bye
    Sachin

    According to the documentation:
    ORA-01555: snapshot too old: rollback segment number string with name "string" too small
    Cause: Rollback records needed by a reader for consistent read are overwritten by other writers.
    Action: If in Automatic Undo Management mode, increase the setting of UNDO_RETENTION. Otherwise, use larger rollback segments.
    Error: ORA-01555: snapshot too old (rollback segment too small)
    Cause: This error can be caused by one of the problems, as described below.
    Action: The options to resolve this Oracle error are:
    This error can be the result of there being insufficient rollback segments.
    A query may not be able to create the snapshot because the rollback data is not available. This can happen when there are many transactions that are modifying data, and performing commits and rollbacks. Rollback data is overwritten when the rollback segments are too small for the size and number of changes that are being performed.
    To correct this problem, make more larger rollback segments available. Your rollback data for completed transactions will be kept longer.
    This error can be the result of programs not closing cursors after repeated FETCH and UPDATE statements.
    To correct this problem, make sure that you are closing cursors when you no longer require them.
    This error can occur if a FETCH is executed after a COMMIT is issued.
    The number of rollback records created since the last CLOSE of your cursor will fill the rollback segments and you will begin overwriting earlier records.

  • End Of communication Error while executing java procedure (Urgent)

    Hi All,
    I am using oracle 10g on linux server. Client machine is on xp. I hava a java procedure which executes the sqlldr on server. Earlier it was working fine, but after reinstalling the oracle 10g on server. It started giving "end of Communication channel error". I am not aware that what paramete has to set. Can some body put light on this error.
    Bye
    Sachin

    This is the most frequently asked question from Oracle developers.. Never mind putting some light on this error, I want to put it alight! ;-)
    First thing. It is not The Error. It is a sympton of an error.
    This message does not come from the database. It comes from the client OCI (of JDBC) drivers - which suddenly discovered that the Oracle connection (usually a TCP socket connection) has been torn down at the server side. It attempts to write to that socket, only to find that the other party has hung up.
    Why has the other party hung up? That party is either a Dedicated Server Process or a Dispatcher Process. If a dedicated server dies (crashes), it will take its socket handles with it to The Great Recycle Bin In The Sky. If you was serviced by a shared server and it died, the Dispatcher (who handles the TCP comms for it), will automatically close that shared server's connection.
    Usually when a process dies on the Oracle server, it leaves behind an error in the alert log, and trace files. That is where you will find the inklings of what The Error was that caused your client to get the EOF on comms channel message.

  • Using mysql-connector-java-5.0.5 from oracle's java procedure.

    I need to write the java procedure in Oracle, which will get connection to mySQL server and put some data into it. I am using official mysql-connector-java-5.0.5 driver for this job. Java class for this job work well outside the Oracle. The problem is:
    When I try to import jar file of mysql connectior it fail son resolving inside the Oracle db. How can I get access to mysql from Oracle?

    Thanks for this quick reply!!
    --When adding a connection and clicking 'Test' in the end of the wizard or when right-click on the connection and click 'connect'.
    Also, I've just noticed this: when I start IDE using jdev.exe I'm getting:
    java.lang.NullPointerException at oracle.jdevimpl.cm.dt.DatabaseAddin._registerIDEObjects(DatabaseAddin.java:353)
    at oracle.jdevimpl.cm.dt.DatabaseAddin.initialize(DatabaseAddin.java:155
    at oracle.ideimpl.extension.AddinManagerImpl.initializeAddin(AddinManage
    rImpl.java:425)
    at oracle.ideimpl.extension.AddinManagerImpl.initializeAddins(AddinManag
    erImpl.java:240)
    at oracle.ideimpl.extension.AddinManagerImpl.initProductAndUserAddins(Ad
    dinManagerImpl.java:154)
    at oracle.ide.IdeCore.initProductAndUserAddins(IdeCore.java:1431)
    at oracle.ide.IdeCore.startupImpl(IdeCore.java:1196)
    at oracle.ide.Ide.startup(Ide.java:674)
    at oracle.ideimpl.Main.start(Main.java:49)
    at oracle.ideimpl.Main.main(Main.java:25)
    Does not look right to me.
    I've never tried to add a DB connection under this IDE installation earlier.
    Just yeasterday I've created a project with some DB related (mySQL and Hibernate) libraries, although it compiled fine.

  • Problem: Use an ODI variable in a Java Procedure

    Hi and thanks in advance,
    i need to use a project variable in a java procedure i've written. In particular i should read a file (and manage it...), but its name is stored in avariable called #fileName that i refresh each time.
    writing something like:
    <% FileInputStream fis = new FileInputStream(C:\\"+"#filename");
    etc.
    etc.
    %>
    doesn't work...
    How can i use the value of my ODI variable inside the Java code?
    Please, help me if you can...
    Thank you very much.

    Any Idea? Please, this question is blocking me...

  • Call RFC  using java procedure

    Hi
    How can I to use java procedure and call RFC for to access tables of SAP ?
    Thank You

    RFC? That term in the IT environment usually means "+Request For Comments+" and refers to Internet protocol and usage standards.
    Do you perhaps means RPC (Remote Process/Procedure Calls)? Or something else?
    Also, SAP is a company. Not a product. SAP has a product called R3. This runs inside a database.
    Connecting from Java to a database typically requires nothing more than a JDBC driver. So why can't you use a JDBC driver and need to call the database (and access tables) using another method?

  • OS Commands not executing through published java procedure... :(

    Hello all :)
    Im trying to get a PL/SQL block to delete a file out in the OS. Theres plenty of examples out there and the one I got came from burleson consulting, and incorporates a java method and a call to java wrapped in PL/SQL.. after all suggested grants, using the procedure yields no result. Here is the source code
    -- java procedure used to execute OS command
    CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "Host" AS
    import java.io.*;
    public class Host {
    public static void executeCommand(String command) {
    try {
    String[] finalCommand;
    if (isWindows()) {
    finalCommand = new String[4];
    finalCommand[0] = "C:\\WINDOWS\\system32\\cmd.exe";
    finalCommand[1] = "/y";
    finalCommand[2] = "/c";
    finalCommand[3] = command;
    else {
    finalCommand = new String[3];
    finalCommand[0] = "/bin/sh";
    finalCommand[1] = "-c";
    finalCommand[2] = command;
    final Process pr = Runtime.getRuntime().exec(finalCommand);
    new Thread(new Runnable() {
    public void run() {
    try {
    BufferedReader br_in = new BufferedReader(new
    InputStreamReader(pr.getInputStream()));
    String buff = null;
    while ((buff = br_in.readLine()) != null) {
    System.out.println(buff);
    try {Thread.sleep(100); } catch(Exception e) {}
    br_in.close();
    catch (IOException ioe) {
    System.out.println("Exception caught printing process output.");
    ioe.printStackTrace();
    }).start();
    new Thread(new Runnable() {
    public void run() {
    try {
    BufferedReader br_err = new BufferedReader(new
    InputStreamReader(pr.getErrorStream()));
    String buff = null;
    while ((buff = br_err.readLine()) != null) {
    System.out.println(buff);
    try {Thread.sleep(100); } catch(Exception e) {}
    br_err.close();
    catch (IOException ioe) {
    System.out.println("Exception caught printing process error.");
    ioe.printStackTrace();
    }).start();
    catch (Exception ex) {
    System.out.println(ex.getLocalizedMessage());
    public static boolean isWindows() {
    if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1)
    return true;
    else
    return false;
    -- PL/SQL wrapper to publish java method.
    CREATE OR REPLACE PROCEDURE host_command (p_command IN VARCHAR2)
    AS LANGUAGE JAVA
    NAME 'Host.executeCommand (java.lang.String)';
    these are the grants I am issuing on install:
    BEGIN
    DBMS_JAVA.grant_permission ('LOANADMIN', 'java.io.FilePermission',
    '<>', 'read ,write, execute, delete');
    DBMS_JAVA.grant_permission ('LOANADMIN', 'SYS:java.lang.RuntimePermission',
    'writeFileDescriptor', '');
    DBMS_JAVA.grant_permission ('LOANADMIN', 'SYS:java.lang.RuntimePermission',
    'readFileDescriptor', '');
    END;
    -- and this is the block I am using to execute the OS command..
    1 BEGIN
    2 host_command (p_command => 'DEL C:\PRETEND.TXT');
    3* END;
    SQL> /
    PL/SQL procedure successfully completed.
    Everything returns as successfully completed. But the file is not deleted from the server. I know im missing some kind of privilege. Can anyone help me? Thanks
    Mo

    Burleson consulting...
    Says it all. Exposure on the Net doesn't mean quality.
    Burleson code usually has not been tested, is not robust, and quite often doesn't work.
    Why didn't you implement run_cmd, as suggested earlier?
    THAT works!
    Sybrand Bakker
    Senior Oracle DBA

  • How to return sdo_geometry from java procedure

    How can I return a SDO_GEOMETRY object from a java-stored-procedure to PL/SQL.
    I have a java class with methods that creates a specific polygon based on some user values. I want to return this polygon as a SDO_GEOMETRY object to a PL/SQL procedure.
    JDeveloper does not accept SDO_GEOMETRY as a return type.
    Can this be done?

    Justin,
    I have a PL/SQL package that contains several functions. One of them does selection and filtering of spatial features based on a user's location and preferences. For this purpose a web-application runs this function.
    I would like this function to do the following:
    1. the function is called, user parameters are passed in
    2. a call to a java-stored-procedure is made. This java procedure creates a polygon based on the user's location and preferences.
    3. the polygon is returned to the PL/SQL function
    4. the funtion uses the returned polygon to query spatial features that intersect, etc.
    I can do the call to the java-stored-procedure but where I get stuck is how to get the polygon from java to pl/sql. I can return a String or a number from java but how can I return the polygon (e.g., STRUCT, java object)?
    The current solution uses a work-around by storing the polygon in a temporary table. I would like to change this because once the function has run, the polygon is not needed anymore so I would like to do without having to store the polygon.
    Markus

  • Calling stored java-procedure in Oracle9i Lite from ODBC

    I've got a problem:
    I try to call a stored java-procedure through ODBC. The stored
    java-procedure in Oracle 9i Lite is called successfully from
    server console (MSQL). When I call my stored java-procedure from
    my web-application (ASP) through ODBC connection (ODBC drivers
    are from Oracle 9i Lite set V3.51) the server returns an error
    (Microsoft OLE DB Provider for ODBC Drivers (0x80004005) [POL-
    8000] could not start the Java Virtual Machine),
    however 'select' without java-procedure calls works
    successfully. PATH and CLASSPATH variables are properly set up.
    File jvm.dll is present.
    Can anybody help me?

    Pass String[] as an argument to mainbook():
    create or replace PROCEDURE openpdffile
    AS LANGUAGE JAVA
    NAME 'pdfopenbook.mainbook(java.lang.String[])';Have you posted it on the Database forum?
    Regards,
    Nick

  • Write a file on client from java procedure

    Hello to all, my problem is that i want to write a file from a java procedure using the normal java class. But when i try to write
    File file=new File("C:\\DiscoD\\myFile.txt");
    FileWriter fw=new FileWriter(file);
    fw.write("ciao");
    nothing happens and no file is created. How can i write a file on my pc client from java procedure?
    Thanks to anyone that want helps me.

    I want to write a java procedure loading java class on oracle with utility loadjava and this work for example for classical Hello World. Now i want to write data on a text file on my hard disk using class java calling the procedure for example in this mode:
    begin
    procedure('ciao'); //this procedure have to write on a file located on my pc the word ciao
    end;
    But nothing happens. Why? There is a special reason related to how oracle works(privileges, permission etc)?
    Thanks

  • Ora-03113 with Java Procedure On 10g Enterprise Edition Release 10.1.0.3.1

    Hi All,
    I am getting Ora-03113 (End-of-Communication) while executing Java Stored procedure. Java Stored Procedure executes Sqlldr on server. Server OS is Linux 86x.
    Database is -- Oracle with Infrastructure.
    Oracle Database 10g Enterprise Edition Release 10.1.0.3.1 - Prod
    PL/SQL Release 10.1.0.3.1 - Production
    CORE 10.1.0.3.0 Production
    TNS for Linux: Version 10.1.0.3.0 - Production
    NLSRTL Version 10.1.0.3.0 - Production
    Same java procedure was working properly when database was 10.1.0.2.1. Any suggestion
    SKM

    Check in Ur programs -Application Tool bar, Whether your have two oracle or not.
    You can unintall the OLD version from your PC using the Oracle Unistaller

  • Java procedure equivalent in Oralce 7.3.4 ??

    Hi,
    Oracle 8i supports Java procedures, is
    there any workaround way of calling
    Java functions or Java programmes from
    PL/SQL in Oralce 7.3.4 (Solaris).
    Thanks in advance,
    -Sudarshan
    [email protected]

    Are there any trace files created on the server?
    Did you see if they have any more information?
    Generally, these types of errors suggest contacting Oracle support to resolve the issue, but with the Oracle version you are using being already desupported, it would be an issue.
    Alternatively, you could search metalink to see if there is any support note on this type of error.

  • Create java procedure using jdbc

    Hi,
    I am trying to create java procedure using jdbc connection, I am using Oracle 11.2. When I create the procedure using sqlplus it works fine. Using jdbcit fails; code sniplet below:
                   ddl =
                   "create or replace java source named \"UTLCMD\" as \r\n"+
                   "import java.lang.Runtime; \r\n"+
                   "public class execHostCommand \r\n"+
                   "{ \r\n"+
                   "public static void execute (String command) \r\n"+
                   " throws java.io.IOException \r\n"+
                   " { \r\n"+
                   " Runtime rt = java.lang.Runtime.getRuntime(); \r\n"+
                   " rt.exec(command); \r\n"+
                   " } \r\n"+
                   statement = conn.createStatement();
                   statement.executeUpdate(ddl);
    I am getting this error:
    2013-01-26 12:45:31.835 UTC: ERROR: Exception "java.sql.SQLException: ORA-29536: badly formed source: Encountered "ublic" at line 3, column 1.
    Was expecting one of:
    "extends" ...
    "implements" ...
    "<" ...
    ". Stack dump:

    Hi,
    We can load java class using blob column, for example :
    create or replace and compile java class using blob select code from java_code;If class is OK, but resolution of referenced names to other classes failed, statement.execute() will not show any error and we need to 'select from user_errors' view for errors. How can we got the required object name for loaded class?

  • Trigger and Java procedure

    There's a way to pass all :new and :old values to a java
    procedure as a collection or something similar without
    referencing any single value with :new.fildname and
    writing a procedure with tens of parameters?

    Rather than specifying the key parameter to the trigger as int[], make it an Integer[]. When you assign to it, use:
    next_person_id[0] =
    new Integer(rset.getInt(1));
    For example:
    public static void beforeInsertBulletin( Connection aConnection,
    Integer[] aBulletinID,
    String aCreateUser,
    String[] aUpdateUser,
    Date[] aCreateTime,
    Date[] aUpdateTime )
    throws SQLException
    Statement lStatement = null;
    aUpdateUser[0] = aCreateUser;
    aCreateTime[0] = getCurrentDate();
    aUpdateTime[0] = aCreateTime[0];
    try
    lStatement = aConnection.createStatement();
    ResultSet lResult = lStatement.executeQuery( "SELECT BULTN_ID_SQN.NEXTVAL AS SEQUENCE FROM DUAL" );
    lResult.next();
    aBulletinID[0] = new Integer( lResult.getInt( "SEQUENCE" ));
    finally
    if ( lStatement != null )
    lStatement.close();
    }

  • To call Java Procedure inside Forms6i

    How do i call a java procedure (Stored either in Oracle8i database or application server )from Oracle Forms6i trigger / procedure.If this possible please let me know.
    Your help in this regard would be appreciated

    For java procedures in the database (stored java procedures) you just call the pl/sql wrapper function that was created for the java function.
    To call java functions on the application server you can use the java importer utility available with forms6i patch2 and above.

  • External Java Procedure Errors

    I'm trying to write an external Java procedure as per the white paper. It seems to start properly but always hangs on the first process activity. The state says active rather than deferred and the only thing the procedure does it update an attribute, which is not being done, so I don't think the procedure is being executed. There are no clues in the viewer; it thinks the process is active.
    How can I tell what's going on? Is there any error message output or way to debug these external procedures so I can tell why the process is hanging here?

    Robert,
    WF_OUTBOUND queue is created during the WF install
    (uses a ‘payload’ of system.wf_payload_t)
    WF_INBOUND is created during the WF install
    When the Workflow Engine comes across a ‘Java Function Activity’ it will put a message on the WF_OUTBOUND queue.
    The ‘Java Function Activity Agent’ pulls the message off the WF_OUTBOUND queue, executes the java procedure and determines any results from that procedure and puts a message onto the WF_INBOUND queue.
    The Workflow Background Engine should be run to process the message from the WF_INBOUND queue.
    You should be able to query the queues to ensure that messages are being queued correctly.

Maybe you are looking for