Can't execute OS-level command from java stored proc

I've written a couple simple java stored procs, the first of which writes an file and the second attempts a chown on it. I can write the file (which is written as the oracle user) just fine. I need to chown it, but can't. Here's the first proc:
public static String writefile()
String fileName = "/joetest/test.xml";
try {
File f = new File(fileName);
FileOutputStream out = new FileOutputStream(f);
PrintStream p = new PrintStream(out);
p.println("this is only a test");
p.close();
return "create file successful!!!";
} catch (Exception e) {
return "Exception occurred writing file:"+e;
Here's the proc I've been stuggling with:
public static String chown(String inString)
String[] command = {"/bin/sh", "-c", "/usr/bin/chown notjoe /joetest/test.xml"};
if (inString != null) {
command[2] = inString;
try {
Process p = Runtime.getRuntime().exec(command);
return "Ownership change success!! "+p;
} catch (Exception e) {
return "Ownership change failure?? err="+e;
The package is created with:
CREATE OR REPLACE PACKAGE JOE.THISISATEST AS
FUNCTION writefile
return VARCHAR2
AS
LANGUAGE java
NAME 'thisisatest.writefile() return java.lang.String';
FUNCTION chown(Param1 VARCHAR2)
return VARCHAR2
AS
LANGUAGE java
NAME 'thisisatest.chown(java.lang.String) return java.lang.String';
end;
And I've granted the following privileges:
begin
dbms_java.grant_permission('JOE', 'java.io.FilePermission', '/joetest/test.xml', 'read, write, execute, delete');
end;
begin
dbms_java.grant_permission('JOE', 'java.io.FilePermission', '/usr/bin/chown', 'execute');
end;
begin
dbms_java.grant_permission('JOE', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
end;
begin
dbms_java.grant_permission('JOE', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');
end;
Here's the error that I'm getting:
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
Coincidentally, this is the same error that I used to get when I wrote the file without having been granted write privileges. Once I granted myself the proper 'write' permissions I could perform file IO just fine. Is there some runtime permission that I need to grant myself to run chown? I'm just guessing, as I can't find any permission like that in the java documentation. I have 'execute' permission on /usr/bin/chown and the oracle user can execute the command I'm attempting from the command line. ARRRRRGH.
I am at my wits end with this. I've tried what seems like a thousand different syntaxes for the OS command and ran it from many different directories. Anyone have any thoughts at all as to why this is happening? I'm just clutching at straws now...

Hmmmm. Granting 'execute' on '<<ALL FILES>>' to user JOE fixes this problem:
begin
dbms_java.grant_permission('JOE', 'java.io.FilePermission', '<<ALL FILES>>', 'execute');
end;
My security folks will not allow this when I port to production, but at least it is something.
Message was edited by:
user603023

Similar Messages

  • Can I execute MySql's command from java application?

    Can I execute MySql's command from java application? And how?
    For example :
    load data local infile 'D:\\myData.txt'
    into table myTable
    fields terminated by ';'
    lines terminated by '\n';

    1. get the jdbc driver for mysql from the mysql site at: http://dev.mysql.com/downloads/connector/j/5.0.html
    2. follow the installation instructiions... which you'll also find in your mysql manual...
    Happy travels. Keith.

  • Executing a dos command from java in windows nt

    i need to execute the
    " net send"
    command from the command line in windows nt, from within my java program... is there any way that i can execute cmommands in the dos command shell? or rather, does anybody know a way i can send a message ( in windows ) from java, from one computer to another over the lan?? I cannot have a java programming running on all the other computers, so i cannot make my program serve, it must just send the messges using a lan command....
    (the net send command just sends a message in the form of a pop up box on the receiver's screeen)
    thanks a bunch guys!!!
    Thanks a bunch guys!!!!

    you can do that with exec() in Runtime.
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(command here);but before you do that you need to read this:
    http://www.javaworld.com/jw-12-2000/jw-1229-traps.html
    hth
    partha

  • Executing a bash command from Java

    I want to execute a bash command from within a Java application on the server. I know how to do simple commands, but this command is killing me. I get nothing back when I send it.
    p = Runtime.getRuntime().exec(new String[]{"ps","-ef","","grep","evolution"});
    There is also another part where I want the results piped to awk and fetch out the pids. BUt with this not working the rest is a waste for now.
    Robbie

    evgeni00 wrote:
    Thank you for assuming the posters' stupidity.I can only see the information that you provide. You didn't say you tried the recommendations.
    I read the article and I tried the things he/she is proposing, also the error stream, guess what it outputs: nothing.Maybe you did it wrong. If you didn't do it wrong, then that program you're invoking is poorly written, because it dies in error without producing any error messages.
    And I also searched for the exitValue 138, but didn't get much further than that its some system specific value. If you know where I can find more information, I would appreciate if you let me know about it. As jschell pointed out it's probably app specific. You can search the source code and/or documentation of that program to see if they say what 138 means.
    Apart from that -- it seems that environment and run directory issues can trip this up. Try checking that stuff out. Maybe your program expects something on the executable PATH that isn't there. Or maybe you're not running it in the working directory that you think you are.

  • Calling an EJB deployed in OC4J from Java Stored Proc in Oracle

    Hello!
    Trying to make a call to an EJB deployed in OCJ4 from a oracle java stored proc. After loaded orion.jar and crimson.jar lib into SCOTT schema, I can't get the JNDI Context working because of this error:
    ============================================
    javax.naming.NoInitialContextException: Cannot instantiate class:
    com.evermind.server.ApplicationClientInitialContextFactory. Root exception is
    java.lang.ClassNotFoundException:
    com/evermind/server/ApplicationClientInitialContextFactory
    at java.lang.Class.forName0(Class.java)
    at java.lang.Class.forName(Class.java)
    at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:45)
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java)
    at javax.naming.InitialContext.init(InitialContext.java)
    at javax.naming.InitialContext.<init>(InitialContext.java)
    ===============================
    I did load the java with "loadjava" with on time with the "resolve" option and time time no option and still no working.
    Here is the EJB client code:
    =======================================
    import java.sql.*;
    import java.util.*;
    import javax.naming.*;
    import com.evermind.server.ApplicationClientInitialContextFactory;
    class EmpRemoteCall {
    public static void main(String[] args) {
    System.out.println(getEmpName());
    public static String getEmpName() {
    String ejbUrl = "java:comp/env/ejb/Emp";
    String username = "admin";
    String password = "admin";
    Hashtable environment = new Hashtable();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.evermind.server.ApplicationClientInitialContextFactory");
    environment.put(Context.PROVIDER_URL, "ormi://127.0.0.1/testemp");
    environment.put(Context.SECURITY_PRINCIPAL, username);
    environment.put(Context.SECURITY_CREDENTIALS, password);
    //environment.put(Context.SECURITY_AUTHENTICATION, ServiceCtx.NON_SSL_LOGIN);
    //environment.put(javax.naming.Context.URL_PKG_PREFIXES, "oracle.aurora.jndi");
    com.kboum.sertir.essais.EmpHome homeInterface = null;
    try {
    Class.forName("com.evermind.server.ApplicationClientInitialContextFactory", true, ClassLoader.getSystemClassLoader());
    System.out.println("Creating an initial context");
    Context ic = new InitialContext(environment);
    System.out.println("Looking for the EJB published as 'java:comp/env/ejb/Emp'");
    homeInterface = (com.kboum.sertir.essais.EmpHome) ic.lookup(ejbUrl);
    catch (CommunicationException e) {
    System.out.println("Unable to connect: " + ejbUrl);
    e.printStackTrace();
    //System.exit(1);
    catch (NamingException e) {
    System.out.println("Exception occurred!");
    System.out.println("Cause: This may be an unknown URL, or some" +
    " classes required by the EJB are missing from your classpath.");
    System.out.println("Suggestion: Check the components of the URL," +
    " and make sure your project includes a library containing the" +
    " EJB .jar files generated by the deployment utility.");
    e.printStackTrace();
    //System.exit(1);
    catch (ClassNotFoundException e) {
    System.out.println("Unable to connect: " + ejbUrl);
    e.printStackTrace();
    //System.exit(1);
    try {
    System.out.println("Creating a new EJB instance");
    com.kboum.sertir.essais.Emp remoteInterface = homeInterface.findByPrimaryKey(Integer.valueOf("7369"));
    System.out.println(remoteInterface.getENAME());
    System.out.println(remoteInterface.getSAL());
    remoteInterface.setSAL(2);
    System.out.println(remoteInterface.getSAL());
    return remoteInterface.getENAME();
    catch (Exception e) {
    System.out.println(e.getMessage());
    e.printStackTrace();
    return "error";
    null

    What I did to solve this problem was to
    create a simple RMI remote object that
    resides outside the database JVM and that
    serves as a proxy EJB client for your java
    stored procedure. The stored procedure can
    invoke a method on the remote RMI object
    which then looks up the EJBean's home
    interface and invokes the relevant method on
    the bean's remote interface, and relays any
    return values back to the java stored
    procedure.
    Hope this helps,
    Avi.
    null

  • REF CURSOR from Java Stored Proc

    Does Oracle 8i/9i allow to return REF CURSROR from Java Stored Procedure?

    Sorry,
    No I don't think this type of Java->SQL mapping was ever fixed. I know it was discussed here on the OTN forums as far back as the 8i driver, but I don't think they have ever implemented this. Perhaps someone who has actually made it work will speak up.

  • How to execute any cmd command from java application?

    Hi all,
    How to execute or call any command of cmd from java application??
    Is there any method to do so??
    Or, is it possible to do it using Runtime.exec() ??? And if so, how to use it, please explain with ab example...
    I'll highly appreciate....
    Thank you.

    If google would be the best option, then I would not be on Sun's forums and I would not have asked experts like you, sir !! :-)
    Neway, I got the solution from PhHein !!
    Good link indeed..
    Cheers..

  • Invoking a UNIX shell command from Java stored procedure

    The program below is suppose do send an email using UNIX mailx program. It works correctly when I compile it in UNIX and invoke it from the command line by sending an email to the given address.
    I need this program to run as a stored procedure, however. I deploy it as such and try to invoke it. It prints the results correctly to the standard output. It does not send any emails, however. One other difference in execution is that when invoked from the command line, the program takes about a minute to return. When invoked as a stored procedure in PL/SQL program or SQL*Plus anonymous block, it returns immediately.
    Why would mailx invocation not work from a stored procedure? Are there other ways to invoke mailx from PL/SQL?
    Thank you.
    Michael
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    public class MailUtility
    public static void main(String[] args)
    System.out.println(mailx("Hey, there", "Hello", "oracle@solaris10ora", 1));
    * Sends a message using UNIX mailx command.
    * @param message message contents
    * @param subject message subject
    * @param addressee message addressee
    * @param display if greater than 0, display the command
    * @return OS process return code
    public static int mailx(String message, String subject,
    String addressee, int display)
    System.out.println("In mailx()");
    try
    String command =
    "echo \"" + message + "\" | mailx -r [email protected]" + " -s \"" + subject + "\" " + addressee;
    if (display > 0)
    System.out.println(command);
    try
    Process process = Runtime.getRuntime().exec("/bin/bash");
    BufferedWriter outCommand =
    new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
    outCommand.write(command, 0, command.length());
    outCommand.newLine();
    outCommand.write("exit", 0, 4);
    outCommand.newLine();
    outCommand.flush();
    process.waitFor();
    outCommand.close();
    return process.exitValue();
    catch (IOException e)
    e.printStackTrace();
    return -1;
    catch (Exception e)
    e.printStackTrace();
    return -1;

    try adding the full explicit path to "mailx" in the command string that gets sent to Runtime. i would guess that the shell that gets spawned might not have a proper environment and thus mailx might not be found.
    == sfisque

  • Throwing exceptions from Java Stored Procs

    Hi,
    We'd like to be able to define our own exceptions from our Java Stored Procedures (i'm going to call them JSP's even thought that's not PC). I am aware that the manual says "When a Java stored procedure executes a SQL statement, any exception thrown is materialized to the procedure as a subclass of java.sql.SQLexception. That class has the methods getErrorCode() and getMessage(), which return the Oracle error code and message, respectively."
    Does this mean that we can't really extend the SQLException class and define our own set of methods for handling exceptions in JSP's? Is there a work around for handling exceptions in JSP's? Since exception handling is such a powerful component of Java, I figure someone has addressed the limitations of the above paragraph.
    Thanks,
    Kristi
    null

    Unfortunately, right now GCC's standard C++ runtime library is NOT threadsafe. You can find documentation supporting this on the GCC website. Since you're running a multithreaded Java/JNI application, you'll certainly hit this shortcoming.
    <p>
    Supposedly, this will all be fixed in GCC 3.0.
    <p>
    In the meantime, if you're using SPARC, the only option you have is either using SC4.2 or Forte 6 Update 2 (this particular version is VERY important for several reasons).

  • Executing sqlplus / sqlldr command from java code

    hi,
    I have my application on one server(tomcat) and oracle server is installed on other server. i.e. Both are on different machine.
    Now i want to run sqlplus / sqlldr command on oracle server from my java code.
    Again my script for lodder command is in temp of tomcat.
    How to do that?
    Thanks,

    Hi,
    I am using JDBC to executed queries...but i need to run sqlplus command to run script if some condition is satisfied and same for sqllodder to load large record like 500000. This code is in the thread and is working fine for same machine. Need to execute it on another machine where oracle is installed.
    From command prompt i am able to run sqlplus on Oracle server. Same command I am not able to run from the code. I have shared bin direcotry of Oracle from server.
    Let me know if any query
    Regards,
    Edited by: Sun_Nut on Dec 16, 2007 9:53 PM

  • Problems to execute "cd" DOS command from Java program

    Anyone try to exec command "cd.." or "cd directory", it doesn't have any action. No exceptions, just don't do anything.
    Runtime.getRuntime().exec("cd\\");
    Runtime.getRuntime().exec("cd hello");
    However, when I try the following, it is working fine. Any ideas???
    Runtime.getRuntime().exec("explorer");
    Runtime.getRuntime().exec("javac Test1.java");

    That's because cd is built into the command
    interpreter in Windows. Runtime.getRuntime().exec()
    can only be used to launch external programs. This
    article should get you going:And that's not the only reason why you can't do this.
    When you do
    Runtime.getRuntime().exec("cd c:\\");
    (or, heck, "cmd /c cd c:\\"): the new command that you spawn will cd to the destination specified, and then exit. The parent process (your java program, that is launching this command) won't go anywhere - the "cd" doesn't affect it.
    The only way to change your OS directory in Java is to invoke native code. And even then, the effects are undefined (in terms of how your CLASSPATH will be affected, etc.).

  • How can I run a dos command from java on windows 98, 95?

    The usage of cmd.exe in the java program to run a dos command on windows 98. 95 doesn't work as the equivalent command is command.exe
    But using the command.exe in the java program makes my program to hang.

    hi,
    As u mentioned, u cannot use the cmd.exe in win9x environment as cmd.exe is specific to windows NT, you can use the command.exe without any hitches.
    for eg
    java.lang.Runtime.getRuntime().exec("start command /K a.bat"); should run the batch file a.bat..
    if the problem persists, try posting the snippet of code that you are using.
    cheerz
    ynkrish

  • Executing a dos command from java

    Hi guys.
    This line works fine:
    process = Runtime.getRuntime().exec("command.com /C c:\\test.bat");
    But this line do nothing:
    process = Runtime.getRuntime().exec("command.com /C c:\\test\\test.bat");
    I need to run a dos file in some directory in my HD. It works fine in root, but do nothing when I change to directory. I do this from an applet.
    Any ideas/suggestions?

    Any ideas/suggestions?The file isn't actually there (it isn't in the directory.)
    There is a permisions problem (which is unusual but not impossible on windows.)
    The script itself is failing - you didn't indicate "how" it doesn't work so this is possible.

  • Calling a WebServices From Java Stored Proc fails with Connection refused

    I have followed the example in Note:220662.1 on Metalink step by step.
    I am using two windows machines (2000 SP4). I have Oracle 9.2.0.5 EE on one of them and OC4J 9.0.4 standalone on the other(running on JVM 1.4.2_05-b04). The 2 servers "see" each other over the network.
    I can execute the stub from the database machine:
    C:\WebServices\HelloWorld>java HelloWorldImplWSStub
    Hello World - The current time is Sat Aug 21 11:56:20 EDT 2004When running it from the database, I get:
    SQL> select ws_hello_world from dual;
    select ws_hello_world from dual
    ERROR at line 1:
    ORA-29532: Java call terminated by uncaught Java exception: [SOAPException:
    faultCode=SOAP-ENV:IOException; msg=Connection refused;
    targetException=java.net.ConnectException: Connection refused]
    Elapsed: 00:00:21.02The trace file generated on the database server machine looks like:
    [SOAPException: faultCode=SOAP-ENV:IOException; msg=Connection refused; targetException=java.net.ConnectException: Connection refused]
      at oracle.soap.transport.http.OracleSOAPHTTPConnection.send(OracleSOAPHTTPConnection.java:765)
      at org.apache.soap.rpc.Call.invoke(Call.java:261)
      at HelloWorldImplWSStub.sayHelloWorld(HelloWorldImplWSStub.java:52)Here is the stub code generated using JDeveloper 9.0.5.1:
    import oracle.soap.transport.http.OracleSOAPHTTPConnection;
    import org.apache.soap.encoding.SOAPMappingRegistry;
    import java.net.URL;
    import org.apache.soap.rpc.Call;
    import org.apache.soap.Constants;
    import java.util.Vector;
    import org.apache.soap.rpc.Response;
    import org.apache.soap.rpc.Parameter;
    import org.apache.soap.Fault;
    import org.apache.soap.SOAPException;
    import java.util.Properties;
    public class HelloWorldImplWSStub  {
      public HelloWorldImplWSStub() {
        m_httpConnection = new OracleSOAPHTTPConnection();
        m_smr = new SOAPMappingRegistry();
      public static String endpoint = "http://oc4jsrv:8888/MyWorkarea-OC4J-context-root/HelloWorldImplWS";
      public String getEndpoint() {
        return _endpoint;
      public void setEndpoint(String endpoint) {
        _endpoint = endpoint;
      private static OracleSOAPHTTPConnection m_httpConnection = null;
      private static SOAPMappingRegistry m_smr = null;
      public static String sayHelloWorld() throws Exception {
        String returnVal = null;
        URL endpointURL = new URL(_endpoint);
        Call call = new Call();
        call.setSOAPTransport(m_httpConnection);
        call.setTargetObjectURI("HelloWorldImplWS");
        call.setMethodName("sayHelloWorld");
        call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
        Vector params = new Vector();
        call.setParams(params);
        call.setSOAPMappingRegistry(m_smr);
        Response response = call.invoke(endpointURL, "");
        if (!response.generatedFault()) {
          Parameter result = response.getReturnValue();
          returnVal = (String)result.getValue();
        else {
          Fault fault = response.getFault();
          throw new SOAPException(fault.getFaultCode(), fault.getFaultString());
        return returnVal;
      public void setMaintainSession(boolean maintainSession) {
        m_httpConnection.setMaintainSession(maintainSession);
      public boolean getMaintainSession() {
        return m_httpConnection.getMaintainSession();
      public void setTransportProperties(Properties props) {
        m_httpConnection.setProperties(props);
      public Properties getTransportProperties() {
        return m_httpConnection.getProperties();
       public static void main(String[] argv) throws Exception   {    
        HelloWorldImplWSStub hstub = new HelloWorldImplWSStub();    
        System.out.println(hstub.sayHelloWorld());  
    }The PL/SQL function code:
    CREATE OR REPLACE FUNCTION ws_hello_world RETURN VARCHAR2
    AS LANGUAGE JAVA
    NAME 'HelloWorldImplWSStub.sayHelloWorld() return java.lang.String';Any help would be greatly appreciated.

    Hello,I have the same problem. Did you find any solution to it?
    Thanks. Diego (Argentina)

  • Execute unix commands from Java

    Hi,
    I have a client application running on windows. This client should connect to a unix server and check for the existence of a file and display the result as "File found/File not found". In order to connect from windows to the unix server, I used the sockets and the connection is successfully established. The second part is to check for the presence of the file in unix server. I searched in google.com and the option I found to execute a unix command from java is the "Runtime.exec()". Runtime.exec is considered as the less effective (not a favorable) one.
    Is there any other option available (other than the Runtime) to execute the unix command from java? Can you please let me know.
    Thanks a lot
    Aishu

    So, please let me know how I can execute the above unix commands without Runtime.exec()You have a client and a server.
    You want something to run on the server, not the client.
    That means that something must in fact being running on the server before the client does anything at all.
    For example telnet. Or a J2EE server application.
    So is something like that running?
    If not then there absolutely no way to do what you want, even with Runtime.exec().
    If yes then what you do depends on what is running. So Runtime.exec() would be pointless if a J2EE server was running.

Maybe you are looking for

  • Problem with descriptions in Siebel Configuration Wizzard

    Hi, I'm trying to solve problem with siebel 8.1.1, after reainstalation of Enterprise, SWSE, and webclient language (enu language package) on windows XP proffesional , after configuration of oracle 11g database, and IIS server, I found out that there

  • Is it possible to give Direct print of Excel format XML Report

    Guru, As far my understnading Excel Format reports are not supported for direct print in EBS, I could see the following error in CM request logfile and came across couple of metalink Note :  387104.1 & 1317314.1 However iam not sure on this functiona

  • Problem in activating trial download

    I downloaded Framemake 11 trial version. The software was successfully installed but during activation I get an error message"Please connect to the internet and try". My computer is conected to the internet. The system timings are right. But still th

  • Not sure how to use iChat

    To use iChat do u use it to have all accounts in one (MSN, skype, AIM, etc)?

  • How do I REACTIVATE my Apple ID?

    I got my money being stolen by other people so my Apple ID was disabled, now i re-entered my money info and said it was done, yet it still says my account is disabled...HOW DO I REACTIVATE IT?