My first foray into shell scripting: tomcatctl

I've written a tomcatctl script (a script for controlling Tomcat, loosely based on all those other somethingctl scripts for controlling things, like apachectl).
It does start, stop, restart, status and version. It seems to work okay on my MacBook Pro, however, on my old, creaky G4 server, there seems to be a problem with restart. Apparently it tries to restart Tomcat before it has completely quit, leaving Tomcat in a weird, undead, zombielike state where it appears to be running, writing zero k log files, and not responding to requests, and it stays this way until I reboot the machine.
If anyone out there is brave enough to try it out, I'd like to get some feedback, especially from people with different configurations and people with a little shell scripting experience.
I'm sure I've made every conceivable noob scripting mistake, and I can't assume any responsibility for any damage it might cause, although I didn't manage to destroy anything while I was writing it, and it even worked fairly well on a 7 1/2 year old machine, except for the issue noted above.
Download: http://idisk.mac.com/dlivesay-Public/tomcatctl.zip
Unzip and put it in your command path. Please read it first and understand before you run. There are some lines at the top that have to be commented out or removed before it will run. You will probably also need to configure at least the "$CATALINA_HOME" environment variable before it will work.
Please, please, pleeeease don't use this on a production server until it has been throughly tested on a similarly-configured machine!

Joshua S wrote:
What if you put in sleep between the stop and start (for restarting) so tomcat has time to shut down gracefully?
That is not a very elegant solution. There is no way to know how long to wait. There should be some mechanism to determine when tomcat has successully shut down.
Or, it could be a problem with the way you are starting tomcat. Follow the instructions in this thread to track it down.

Similar Messages

  • Turn commands into shell script

    Hey. I want to do this repetitive task and I'd like to write a shell script to do it. The commands that I want the machine to repeat look like this:
    cd /srv/web-data/conferences
    pwd
    ls -al >> /srv/web-data/work.txt
    cd /srv/web-data/conferences/gurt99
    pwd
    ls -al >> /srv/web-data/conferences/gurt99
    And the machine I'm working on tells me this about itself:
    System = SunOS
    Node = gusun
    Release = 5.8
    KernelID = Generic_108528-10
    Machine = sun4u
    BusType =
    Serial =
    Users =
    OEM# = 0
    Origin# = 1
    NumCPU = 5
    What do I have to do to turn a text file with a list of commands like the above into a shell script?
    Thanks, Rebecca

    Kai,
    Here are 3 function you can use in shell script for executing a statement, sqlfile and procedure
    function execStmt {
      typeset stmt=$4
      echo "
        set feedback off
        set verify off
        set heading off
        set pagesize 0
        whenever sqlerror exit 1
        whenever oserror exit 2
        $stmt;
        commit;
        exit 0
      " |  sqlplus -s  $1/$2@$3
      ret=$?
      if [ $ret -ne 0 ]
       then
          return 1;
       else
          return 0;
       fi
    function execSql {
      typeset sqlfile=$1
      if [ ! -f $sqlfile ]
      then
           echo
           echo "File containing extract count doesn't exist...." 
           echo "Exiting ..."
           echo
           exit 1;
      fi
      echo "
        set feedback off
        set verify off
        set heading off
        set pagesize 0
        whenever sqlerror exit 1
        whenever oserror exit 2
        @$sqlfile;
        exit 0
      " |  sqlplus -s  $2/$3@$4
      retcode=$?
      if [ $retcode -ne 0 ]
      then
           return 1;
      else
           return 0;
      fi
    function execPkg {
       echo "
       set feedback off
       set verify off
       set heading off
       set pagesize 0
       whenever sqlerror exit 1
       whenever oserror exit 2
       exec mypkg.procedure_name($4,$5); -- $4,$5 are argument list
        exit
      " |  sqlplus -s  $1/$2@$3
      ret=$?
      if [ $ret -ne 0 ]
      then
           return 1;
      else
           return 0;
      fi
    }Regards

  • Issue passing variable into shell script

    Please see terminal session.
    -  calling pwd, unset, or echo alleviate the issue.
    - running the script 'plain' also exihibit an issue
    - calling 'cat test.sh' causes an issue
    I can repeat the issue on OSX 10.5.8
    On Ubuntu, two a's always print out with: A=a B=$A ./test.sh
    Terminal session:
    bash-3.2$ ls -l test.sh
    -rwxr-xr-x  1 axure  staff  16 Mar 29 09:27 test.sh
    bash-3.2$ cat test.sh
    echo $A
    echo $B
    bash-3.2$ pwd
    /Users/axure
    bash-3.2$ A=a B=$A ./test.sh
    a
    a
    bash-3.2$ A=a B=$A ./test.sh
    a
    bash-3.2$ $A
    bash-3.2$ $B
    bash-3.2$ echo $A
    bash-3.2$ echo $B
    bash-3.2$ unset
    bash-3.2$ A=a B=$A ./test.sh
    a
    a
    bash-3.2$ A=a B=$A ./test.sh
    a
    bash-3.2$ pwd
    /Users/axure
    bash-3.2$ A=a B=$A ./test.sh
    a
    a
    bash-3.2$ A=a B=$A ./test.sh
    a
    bash-3.2$ unset
    bash-3.2$ cat test.sh
    echo $A
    echo $B
    bash-3.2$ A=a B=$A ./test.sh
    a
    bash-3.2$ unset
    bash-3.2$ A=a B=$A ./test.sh
    a
    a
    bash-3.2$ A=a B=$A ./test.sh
    a
    bash-3.2$ unset
    bash-3.2$ ./test.sh
    bash-3.2$ A=a B=$A ./test.sh
    a
    bash-3.2$

    bash-3.2$ ls -l test.sh
    -rwxr-xr-x  1 axure  staff  16 Mar 29 09:27 test.sh
    bash-3.2$ cat test.sh
    echo $A
    echo $B
    bash-3.2$ pwd
    /Users/axure
    bash-3.2$ A=a B=$A ./test.sh
    a
    a
    As I would expect
    bash-3.2$ A=a B=$A ./test.sh
    a
    NOT what I would expect.  I tested this using bash 3.2 and got the same results, HOWEVER, when I tested this with bash 4.0, I got what I expected, namely your first results everytime.
    So I think there is a bug in bash 3.2.  You can get the bash sources, and build your own bash if you wish, or use a different method of setting 1 time envionment variables for use in a subprocess.
    bash-3.2$ $A
    bash-3.2$ $B
    bash-3.2$ echo $A
    bash-3.2$ echo $B
    As expected, as the way you set A & B were as 1 time environment variables that were only seen by the subprocess created when test.sh was run.  A & B were NOT created in the current shell environment, so the current shell environment would not have any values for A & B
    bash-3.2$ unset
    bash-3.2$ A=a B=$A ./test.sh
    a
    a
    bash-3.2$ A=a B=$A ./test.sh
    a
    Again, now what I would expect, but as I have already stated, I think there is a bug in bash 3.2 that does not exist in bash 4.0.
    Now a bigger question, why are you passing A & B as 1 time envionment variables?  Why not just pass them on the command line?
    test.sh a a
    where test.sh would be
    echo $1
    echo $2
    Or you could use export to create environment variables A & B
    export A=a
    export B=$A
    test.sh
    Now A & B would still exist after test.sh, which I assume you do not want to do.
    You could try ceating test.sh as a bash function and see if that changes the behavior
    test()
        echo $A
        echo $B
    A=a B=$A test
    You would have to define test() in your shell initialization scirpt if you needed each time you started a terminal session.
    While I have used 1 time environment variables, I more frequently just pass arguments on the command line.

  • First foray into Java, Suggestions welcome

    So I'm in the middle of the Collections trail, and I thought I'd make a new version of the Queue that orders it's items randomly (as opposed to priority or fifo). A sample case, and the one I used to make sure it worked, is as a deck of cards.
    Since this is the first non-hello world-ish thing I've done, I'd love any comments or suggestions you have.
    Also, I found it a little odd that I had to do that much wrapper code just to add a few things. I had thought that perhaps the AbstractQueue would be a better base, but I couldn't find where it was actually storing it's items, so that was out.
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Queue;
    import java.util.Random;
    class RandomQueue<E> implements Queue<E> {
        private Queue<E> items = new LinkedList<E>();
        private Random rnd = new Random();
        public RandomQueue() {
            // nothing to see here
        public RandomQueue(Collection<E> c) {
            addAll(c);
        /** Inserts the item in a random location. */
        public synchronized boolean add(E e) {
            boolean flag = true;
            if (size() > 0) {
                ((List<E>)items).add(rnd.nextInt(size()), e);
            } else {
                flag = items.add(e);
            return flag;
        /** Adds all the items, then shuffles the Queue. */
        public synchronized boolean addAll(Collection<? extends E> c) {
            List<E> tmp = new LinkedList<E>(items);
            tmp.addAll(c);
            Collections.shuffle(tmp, rnd);
            items = (Queue<E>)tmp;
            return true;
        public void clear() {
            items.clear();
        public boolean contains(Object o) {
            return items.contains(o);
        public boolean containsAll(Collection<?> c) {
            return items.containsAll(c);
        public E element() {
            return items.element();
        public boolean isEmpty() {
            return items.isEmpty();
        public Iterator<E> iterator() {
            return items.iterator();
        public boolean offer(E e) {
            return items.offer(e);
        public E peek() {
            return items.peek();
        public E poll() {
            return items.poll();
        public E remove() {
            return items.remove();
        public boolean remove(Object o) {
            return items.remove(o);
        public boolean removeAll(Collection<?> c) {
            return items.removeAll(c);
        public boolean retainAll(Collection<?> c) {
            return items.retainAll(c);
        public int size() {
            return items.size();
        public Object[] toArray() {
            return items.toArray();
        public <T> T[] toArray(T[] a) {
            return items.toArray(a);
        @Override
        public String toString() {
            // get a decent toString()
            return ((List)items).toString();
        public static void main(String[] args) {
            System.out.println("This class is meant to be instantiated, not run directly.");
    public class Deck {
        // testsuite follows
        public static void main(String[] args) {
            System.out.println("First, add()ing each item...");
            RandomQueue<String> q = new RandomQueue<String>();
            String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
            String[] faces = {"Jack", "Queen", "King", "Ace"};
            System.out.println(q);
            for (String suit : suits) {
                for (int i=2; i<=10; i++) {
                    q.add(String.format("%s of %s", i, suit));
                for (String face : faces) {
                    q.add(String.format("%s of %s", face, suit));
            System.out.println(q);
            System.out.format("%nAnd now, add()ed all at once..%n");
            RandomQueue<String> q2 = new RandomQueue<String>();
            q2.addAll(q);
            System.out.println(q2);
            System.out.format("%nFinally, all added through constructor...%n");
            System.out.println(new RandomQueue<String>(q2));
            System.out.format("%nAnd now to remove() every item...%n");
            while (!q.isEmpty())
                System.out.println(q.remove());
            System.out.println(q);
            System.out.format("Random card: %s%n", new RandomQueue<String>(q2).remove());
    }

    And now for a little update. I really think it would be better to use an abstract base class, so I re-wrote it to do so. Then I added a Stack class that also extends this base. Again, suggestions/comments welcome./* To run:
    * -Save this as Deck.java
    * -$ javac Deck.java                       # compiles the source
    * -$ jar cfe Deck.jar Deck *.class         # builds a jar file
    * -$ java -jar Deck.jar                    # executes the jar
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Queue;
    import java.util.Random;
    * Extended Abstract Queue.  add() and addAll() methods MUST be implemented,
    *      others as needed.
    abstract class AbstractQueueEx<E> implements Queue<E> {
        protected Queue<E> items = new LinkedList<E>();
        public abstract boolean add(E e);
        public abstract boolean addAll(Collection<? extends E> c);
        public AbstractQueueEx() {
            // nothing to see here
        public AbstractQueueEx(Collection<E> c) {
            addAll(c);
        public void clear() {
            items.clear();
        public boolean contains(Object o) {
            return items.contains(o);
        public boolean containsAll(Collection<?> c) {
            return items.containsAll(c);
        public E element() {
            return items.element();
        public boolean isEmpty() {
            return items.isEmpty();
        public Iterator<E> iterator() {
            return items.iterator();
        public boolean offer(E e) {
            return items.offer(e);
        public E peek() {
            return items.peek();
        public E poll() {
            return items.poll();
        public E remove() {
            return items.remove();
        public boolean remove(Object o) {
            return items.remove(o);
        public boolean removeAll(Collection<?> c) {
            return items.removeAll(c);
        public boolean retainAll(Collection<?> c) {
            return items.retainAll(c);
        public int size() {
            return items.size();
        public Object[] toArray() {
            return items.toArray();
        public <T> T[] toArray(T[] a) {
            return items.toArray(a);
        @Override
        public String toString() {
            // get a decent toString()
            return ((List)items).toString();
    * Items in this queue are stored in random order.
    class RandomQueue<E> extends AbstractQueueEx<E> {
        private static final Random rnd = new Random();
        public RandomQueue() {}
        public RandomQueue (Collection<E> c) {
            super(c);
        /** Inserts the item in a random location. */
        public synchronized boolean add(E e) {
            boolean flag = true;
            if (size() > 0) {
                ((List<E>)items).add(rnd.nextInt(size()), e);
            } else {
                flag = items.add(e);
            return flag;
        /** Adds all the items, then shuffles the Queue. */
        public synchronized boolean addAll(Collection<? extends E> c) {
            List<E> tmp = new LinkedList<E>(items);
            tmp.addAll(c);
            Collections.shuffle(tmp, rnd);
            items = (Queue<E>)tmp;
            return true;
    * LIFO queue.
    class Stack<E> extends AbstractQueueEx<E> {
        public Stack() {}
        public Stack(Collection<E> c) {
            super(c);
        /** Inserts the item in a random location. */
        public synchronized boolean add(E e) {
            ((List<E>)items).add(0, e);
            return true;
        /** Adds all the items, then shuffles the Queue. */
        public synchronized boolean addAll(Collection<? extends E> c) {
            /* Items come in, add them reversed, so that the last item in the
             * collection is the first remove()d
            List<E> tmp = new LinkedList<E>(c);
            Collections.reverse(tmp);
            tmp.addAll(items);
            items = (Queue<E>)tmp;
            return true;
    * Just a Stack with another name.
    class LIFOQueue<E> extends Stack<E> {
        public LIFOQueue() {}
        public LIFOQueue(Collection<E> c) {
            super(c);
    public class Deck {
        // testsuite follows
        public static void main(String[] args) {
            System.out.println("First, add()ing each item...");
            RandomQueue<String> q = new RandomQueue<String>();
            String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
            String[] faces = {"Jack", "Queen", "King", "Ace"};
            System.out.println(q);
            for (String suit : suits) {
                for (int i=2; i<=10; i++) {
                    q.add(String.format("%s of %s", i, suit));
                for (String face : faces) {
                    q.add(String.format("%s of %s", face, suit));
            System.out.println(q);
            System.out.format("%nAnd now, add()ed all at once...%n");
            RandomQueue<String> q2 = new RandomQueue<String>();
            q2.addAll(q);
            System.out.println(q2);
            System.out.format("%nFinally, all added through constructor...%n");
            System.out.println(new RandomQueue<String>(q2));
            System.out.format("%nAnd now to remove() every item...%n");
            while (!q.isEmpty())
                System.out.println(q.remove());
            System.out.println(q);
            System.out.format("Random card: %s%n", new RandomQueue<String>(q2).remove());
            System.out.format("%nAnd now for some stacks...%n");
            LIFOQueue<String> lq = new LIFOQueue<String>();
            lq.add("foo");
            lq.add("bar");
            lq.add("baz");
            LIFOQueue<String> lq2 = new LIFOQueue<String>(lq);
            while (!lq.isEmpty())
                System.out.println(lq.remove());
            System.out.println("Testing addition through constructor...");
            while (!lq2.isEmpty())
                System.out.println(lq2.remove());
    }

  • First Foray into BPM, please advise

    Hi,
    I am trying to work through a basic BPM setup, because the process is going to get more complicated. So, I decided to take the basic process that does not require BPM and put it in a BPM. The reason is that I will be receiving syncronous PO confirmation in the future and will have to use BPM for this extension on the basic PO to vendor scenario. How does the steps below look. I am struggling with the ID setup more than the IR development.
    IR
    1) Created abstract MI's for the Orders IDOC and the outbound message format XCBL30
    2) Created an interface mapping between the two abstract interfaces(is this needed?)
    In BPM Design:
    1) Created two containers based on each abstract interface
    2) Created a recieve step and assigned the abstract interface associated with the outbound IDOC
    3) Created a transformation step, the source being the abstract IDOC interface and the target being the outbound XCBL abstract interface, choosing the IM created above.
    4) Created a reciever list container and step using the inbound abstract interface(IS THIS NEEDED??)
    5) Created a send step for the outbound XCBL abstract interface
    In ID
    This is where I get confused, what steps are needed here?
    1) Assigned the process as a service for my party
    2) I tried to create a receiver determination this way:
      A) The sender interface is the IDOC TYPE ORDERS05, the 
         abstract interface is not allowed here.
      B) I choose the Integration Process as the receiver
      C) For the interface determination, the inbound
         interface is the abstract interface for the IDOC.
         NO MAPPING is chosen(Is this correct???)
      D) A receiver agreement is not allowed for the
         integration process, so I created a receiver  
         agreement for the normal XCBL message, not the
         abstract one.
    Questions:
    1) How do the steps above look, any ideas?
    2) I tried to run it and got a BPE_ADAPTER Error
       "Unknown Message"
    Thanks,
    Chris

    Hey,
    So this is my "new" plan of action for the directory steps
    1) One receiver determination where, the R/3 system and the IDOC are the sender service and interface. The business process is the reciever.
    2) One interface determination where the abstract interface  is the inbound interface for the above determination. No mapping is specified and no receiver agreement is required.
    3) One receiver determination where, the business process is the sender service and the outbound abstract interface is the sender interface.
    4) One interface determination where the inbound interface is the xCBL message, no mapping is specified.
    5) One reciever agreement, where the communication channel is specified for sending the message to the vendor.
    I will let ya'll know how it goes! Any other feedback is appreciated! The SXI_CACHE is return code 0. So I think my problem is in the ID confige that I am about to change.
    Thanks Alot,
    Chris

  • Shell Script - Sleep

    Hello All,
    We are printing pdf file outputs from shell script. Here we faced a problem that the shell script tried to access the output file(pdf file) while the concurrent program is running. For that we added the concurrent program names into shell script programs incompatibility list. This is working fine.
    But there are more than 20 reports using the same shell script. If all the programs are running shell script waits until all the 20 programs completed.
    I am thinking of another solution that, I have to issue a sleep command in shell script until the program completes, or until the output file is generated and the shell script can generate post script file from the output file.
    I dont know what kind of lock the concurrent program is using, because shell script says no such file or directory while generating post script file.
    Kindly help.

    You would probably find more concurrent manager experts in the Apps forums. You could try using the output of ps -ef to see if the program your script should wait for is still running. Or you can use the lsof command to see if the file you are supposed to process is still open in another process. For example, lsof -f -- /output/my.pdf shows all processes that have the file /output/my.pdf open.
    Edited by: herb on Jan 11, 2010 11:47 PM

  • Shell scripts to read data from a text file and to load it into a table

    Hi All,
    I have a text file consisting of rows and columns as follows,
    GEF001 000093625 MKL002510 000001 000000 000000 000000 000000 000000 000001
    GEF001 000093625 MKL003604 000001 000000 000000 000000 000000 000000 000001
    GEF001 000093625 MKL005675 000001 000000 000000 000000 000000 000000 000001 My requirement is that, i should read the first 3 columns of this file using a shell script and then i have to insert the data into a table consisting of 3 rows in oracle .
    the whole application is deployed in unix and that text file comes from mainframe. am working in the unix side of the application and i cant access the data directly from the mainframe. so am required to write a script which reads the data from text file which is placed in certain location and i have to load it to oracle database.
    so I can't use SQL * loader.
    Please help me something with this...
    Thanks in advance.

    1. Create a dictionary object in Oracle and assign it to the folder where your file resides
    2. Write a little procedure which opens the file in the newly created directory object using ULT_FILE and inside the FOR LOOP and do INSERTs to table you want
    3. Create a shell script and call that procedure
    You can use the post in my Blog for such issues
    [Using Oracle UTL_FILE, UTL_SMTP packages and Linux Shell Scripting and Cron utility together|http://kamranagayev.wordpress.com/2009/02/23/using-oracle-utl_file-utl_smtp-packages-and-linux-shell-scripting-and-cron-utility-together-2/]
    Kamran Agayev A. (10g OCP)
    http://kamranagayev.wordpress.com

  • Shell Script Programming -- Loading data into table

    Hello Gurus
    I am using Oracle's sql*loader utility to load data into a table. Lately, I got an unlikely scenario where in I need to process the data file first before loading it into the table and where I need help from you guys.
    Consider the following data line
    "Emp", DOB, Gender, Subject
    "1",01/01/1980,"M","Physics:01/05/2010"
    "2",01/01/1981,"M","Chemistry:02/05/2010|Maths:02/06/2011"
    "3",01/01/1982,"M","Maths:03/05/2010|Physics:06/07/2010|Chemistry:08/09/2011"
    "4",01/01/1983,"M","Biology:09/09/2010|English:10/10/2010"Employee - 1 will get loaded as a single record in the table. But I need to put Subject value into two separate fields into table. i.e. Physics into one column and date - 01/05/2010 into separate column.
    Here big problem starts
    Employee - 2 Should get loaded as 2 records into the table. The first record should have Chemistry as subject and date as 02/05/2010 and the next record should have all other fields same except the subject should be Maths and date as 02/06/2011. The subjects are separated by a pipe "|" in the data file.
    Similarly, Employee 3 should get loaded as 3 records. One as Maths, second as Physics and third as Chemistry along with their respective dates.
    I hope I have made my problem clear to everyone.
    I am looking to do something in shell scripting such that before finally running the sql*loader script, the above 4 employees have their records repeated as many times as their subject changes.
    In summary 2 problems are described above.
    1. To load subject and date into 2 separate fields in Oracle table at the time of load.
    2. If their exists multiple subjects then a record is to be loaded that many times as there exists any changes in employee's subject.
    Any help would be much appreciated.
    Thanks.

    Here are some comments. Perl can be a little cryptic but once you get used to it, it can be pretty powerful.
    #!/usr/bin/perl -w
    my $line_count = 0;
    open FILE, "test_file" or die $!;
    # Read each line from the file.
    while (my $line = <FILE>) {
        # Print the header if it is the first line.
        if ($line_count == 0) {
            chomp($line);
            print $line . ", Date\n";
            ++$line_count;
            next;   
        # Get all the columns (as separated by ',' into an array)
        my @columns = split(',', $line);
        # Remove the newline from the fourth column.
        chomp($columns[3]); 
        # Read the fields (separated by pipe) from the fourth column into an array.
        my @subject_and_date = split('\|', $columns[3]);     
        # Loop for each subject and date.
        foreach my $sub_and_date (@subject_and_date) {
            # Print value of Emp, DOB, and Gender first.
            print $columns[0] . "," . $columns[1] . "," . $columns[2] . ",";
            # Remove all double quotes from the subject and date string.
            $sub_and_date =~ s/"//g;
            # Replace ':' with '","'
            $sub_and_date =~ s/:/","/;
            print '"' . $sub_and_date . '"' . "\n";       
        ++$line_count;
    close FILE;

  • Do the shell script have to login into Oracle Apps

    I am calling the Document Processor Java API from a shell script. The problem I have that its unable to find the
    xdo://PO.POXPRPOLXMLRTF.en.US/?getSource=true
    file within the control file.
    Is this because somewhere a shell variable needs to be set, or a login need to be made into the Oracle Apps, so this template stored in XML Publisher is accessible.
    Please advise!

    Another things you can do is
    begin
    tmp_res := apps.fnd_web_sec.CHANGE_PASSWORD('TESTUSER','changeme',false);
    update fnd_user set password_date = null where user_name = 'TESTUSER'';
    end;
    Once you do this, when the TESTUSER logs in with the password=changeme, he/she will be redirected to the change password page.
    Hope this helps,
    Sandeep Gandhi

  • Moving files into directory using shell script

    Can someone tell me how I move files into directory using *nix/linux shell script?
    I have files which created from stored procedures using utl_file. The files name for example:
    DKH_104_12345
    DKE_101_42324242
    DKH_102_32432
    DKE_101_34553
    Then I create directories automatically for example:
    /oradata/apps/dmp/output/101
    /oradata/apps/dmp/output/102
    /oradata/apps/dmp/output/103
    /oradata/apps/dmp/output/104
    Using this procedure :
    CREATE OR REPLACE PROCEDURE Xorganize AS
    v_item VARCHAR2(5);
    v_DirName VARCHAR2(50);
    v_FileName VARCHAR2(50):='xorganize';
    v_FileExt VARCHAR2(5):='.sh';
    v_ID UTL_FILE.file_type;
    CURSOR res IS
    --find the directory name from table
    SELECT brn_cde FROM vcr_brn_cde ORDER BY 1;
    BEGIN
    --used by utl.file funtion
    SELECT PRD_DIR INTO v_DirName
    FROM CR_SYS_PRM
    WHERE CLT_CDE ='FIF';
    SELECT v_FileName||v_FileExt INTO v_FileName FROM dual;
    v_ID:=UTL_FILE.FOPEN(v_DirName,v_FileName, 'w');
    utl_file.PUTF(v_ID,'%s\n','@@echo OFF');
    utl_file.PUTF(v_ID,'%s\n','cls');
    utl_file.PUTF(v_ID,'%s\n','echo Reorganizing ...');
    OPEN res;
         LOOP
              FETCH res INTO v_item;
              EXIT WHEN res%NOTFOUND;
              utl_file.PUTF(v_ID,'%s\n','mkdir '||v_item);
         END LOOP;
    CLOSE res;
    OPEN res;
         LOOP
              FETCH res INTO v_item;
              EXIT WHEN res%NOTFOUND;
              utl_file.PUTF(v_ID,'%s\n','move _'||v_item||'_.* '||v_item||'\');
         END LOOP;
    CLOSE res;
    utl_file.PUTF(v_ID,'%s\n','FOR /F "usebackq delims=" %%1 IN (`dir /b *.`) DO @rd/q %%1');
    utl_file.PUTF(v_ID,'%s\n','cls');
    utl_file.PUTF(v_ID,'%s\n','echo Reorganizing ...Done');
    utl_file.fclose(v_ID);
    END;
    Everything works fine, BUT, the script is generated in dos/windows scripting.
    Now I need to run the script in *nix/linux shell, which I still can’t do it (because of my knowledge :p).
    And also I don’t know if the script already generated in *nix/linux shell version, how do I chmod +x the script from stored procedure, I can’t use ‘host’ command in my tools
    Thanks a lot
    -firman

    If you're using 9i then UTL_FILE.FRENAME() will execute something like a Unix mv command.
    If you want to do a chmod then you'll need to check out how to use a Java Stored Procedure to execute OS calls.
    Cheers, APC

  • SQL-Scripts into a Shell script

    Hi!
    After creating the database on a Linux machine, we need to create our Schema in that database.This Schema has many objects(tables, views,
    procs, triggers etc.). So executing each individual script would not be sensible. Is it possible to pack all sql scripts into one shell script and run that one?
    Thanks for your feedback/examples/links!

    If it's one-off task, why not put all of them in a SQL file and run it from SQL* Plus rather than using shell to cause sql plus which will in turn have to call the script?
    If it's a recurring task and you insist that you want to do it from Unix shell, you can do something like this:
    Place all scripts in a single file and put it under $HOME for ex. (save it as run_all_scripts.sql)
    Then write a shell script something like this:
    #!/bin/ksh
    connect_schema=scott/tiger
    sqlplus -s $connect_schema <<EOF
    @$HOME/run_all_scripts.sql
    EOF
    Regards
    Venkat

  • Passing Shell Script Path into theweb service http:address location

    Hi,
    Can we pass Shell Script Path into the web service <http:address location=shell scriptpathhere />
    can you please suggest on this ?
    Thanks,
    Bharath
    Edited by: user1175364 on Oct 26, 2010 1:57 PM

    Hi,
    Its better you use java to call the shell script and make it a web service and consume it in bpel...u can also try this with java embedding avtivity as well.

  • Passing parameters into a shell script through alias Names ????

    I have two alias names ord and dev. And the content of them are as follows.
    alias ord
    ord='cd ${ORDER}/bin; export APPL_NAME=order; . SetupAppl order'
    alias dev
    dev='cd ${APPL_ROOT}/bin; export APPL_ENV=dev; . SetupEnv dev'
    Alias ord calls a shell script called SetupAppl. Alias dev calls a shell script called SetupEnv.
    I am trying to pass a parameter when calling the alias name dev, something like dev WEST. And I
    want to read that parameter inside the shell script SetupEnv.
    The way I want to execute them, first run the alias ord and then the alias dev. But, when I try
    to read the parameter in SetupEnv by $1 it is showing the value of the parameter passed to SetupAppl
    ie order and not WEST.
    Is there any way to read the value (WEST) passed as a parameter when executing the alias name.
    example : dev WEST and reading the value WEST inside SetupEnv
    The reason I am executing those scripts (SetupAppl and SetupEnv) with dot(.) in the front is because
    those scripts have some export statements which needs to exported to the environment.
    Any help on this is highly apprecaited

    Hi everybody,
    I posted same question earlier for UNIX/shell script and rec'd one response. Thanks to Bob.
    But the requirement has been changed and now my mgr wants the same task using PL/SQL. Could somebody help me ?
    Question again....
    I am working on a task which gets report on every remote database.
    I created a small database: ‘REPORTS_DB’ and I created 6 'sql' scripts on that database. While executing the first script, it calls the other 5 different 'sql' scripts. All these 5 sql scripts use a '@db_link' (hard coded) and gets that database's report to the database: REPORT_DB.
    It is working well. But,
    We have 42 databases and I have to get reports of all the 42 databases. Since it is not efficient to create 42 sets of sql scripts, I want to make it automated.
    I know (but I don't know HOW) I can pass a parameter (database link name) while running the first script (which calls the other 5 scripts), so that the parameter replaces the @db_link in all the 5 scripts and gets the report of the related (@db_link) database.
    Could somebody tell me how to do this task using SQL and PL/SQL ?
    OR
    send me a sample PL/SQL script to do this task?
    Sorry for the inconvenience and thanks in advance.
    - JT

  • How to write dbms_out traces into a file (in a shell script)?

    I'm afraid this is a shell scripting question:
    I have the following lines in a script:
    ls $salida/EXAR* | while read FILE
    do
    sqlplus -s user@isntance/password << EOF
    set serveroutput on size 1000000
    set feedback off
    --set trimspool on
    var p_out_result_nv number
    var p_out_DescError_SV varchar2(4000)
    var p_out_Traza_SV varchar2(4000)
    var p_Fich_Entrada varchar2(4000)
    --spool $mi_fich_log
    begin
    :p_Fich_Entrada := replace(('$FILE'),('$salida/'),'');
    dbms_output.put_line('Tratando archivo: '||:p_Fich_Entrada);
    :p_out_result_nv := 0;
    SJPAMIOB.SJPRPRIN('01',:p_Fich_Entrada,:p_Fich_Entrada,'EXSJ_ENTRADA','EXSJ_SALIDA',
    :p_out_result_nv,:p_out_DescError_SV,:p_out_Traza_SV);
    end;
    --spool off
    exit :p_out_result_nv
    EOF
    How can I write all dbms_output.put_line in a file?
    Thanks in advance.

    you can use the package utl_file.
    for this you either
    - need a directory object in the database which points to the folder where your file is located you want to write to:
    CREATE DIRECTORY lutz_dir AS ´/home/oracle/UTL_FILE_DIR´;
    You will need create any directory privilege for this.
    or
    - you must have the init.ora parameter UTL_FILE_DIR set to the location.
    Regards,
    Lutz

  • How to call a shell script from a java code

    Hello can any one suggest me how to call a shell script from a java program that takes three parameters.
    i have a shell script (msp_restore_gui) when i run this script in the command line in a RHEL5 ,SUSE10 and Debian machine it works fine .I even tested to call it from a java program and it also worked fine but when i used the same in a J2ee application where the user when clicks the restore button in a webserver this inturn sends the request to a java file named BackupManager.java where i call the shell script.But here it fails.Waiting for your suggestions.If you want i can put the code also here

    yes the script is in /usr/local/mss/tools/backup and the script (msp_restore_gui) is as follows
    #!/bin/sh
    TIMESTAMP=`date +%d_%b_%y-%H-%M`
    touch /var/backups/mss/mss_restore_"$TIMESTAMP".log
    LOGFILE="/var/backups/mss/mss_restore_"$TIMESTAMP".log"
    ### Explode tgz file
    cd /
    # Checks to be done:
    # root login
    # assume he passes the parameter as msp_backup_<timestamp>
    # check for the existence of the .tz and fileList.txt
    # Checking for the root login and if not logged on as root
    # permission will be denied to execute this script
    logmsg(){
    echo "`date`: $*" >> $LOGFILE 2>&1
    echo "$*"
    #usage of this script
    while [ $#  -ne 0 ]
    do
    case $1 in
    -n)
    shift
    ARCHIVE_NAME=`find / \( -name "$1.tz" -o -name "$1.tgz" \) 2>/dev/null`
    FILE_NAME=`find / -name $1_filesList.txt 2>/dev/null`
    if [ x$ARCHIVE_NAME = x -a y$FILE_NAME = y ]
    then
    logmsg "ERROR: Files not found, Restore cannot proceed"
    usage
    else
    tar tvzf $ARCHIVE_NAME > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
    echo "ERROR: The tar file $ARCHIVE_NAME is not proper. Restore cannot proceed"
    exit 1
    else
              echo "Backedup files are present, proceeding with restore......" >> $LOGFILE 2>&1
    fi
    fi
    usage
    SKIP_CLEANUP=1
    STATUS=1
    exit
    esac
    shift
    done
    rm -rf ./newfile
    curr_ver_file="/usr/local/mss/etc/version"
    /usr/local/mss/tools/backup/check_version $curr_ver_file $FILE_NAME
    ret_code=$?
    echo "Exit value of check_version is $ret_code"
    if [ "$ret_code" != 0 ]
    then
    logmsg "MSP Version not matching. Exiting from restore now...."
    errormsg=`cat /usr/local/mss/temp/ver_err_mesg`
    logmsg $errormsg
    rm -f /usr/local/mss/temp/ver_err_mesg
    exit 1
    else
    echo "Version check is successful"
    fi
    #### ShutDown MSS########
    /etc/init.d/mss stop
    sleep 2
    ### Shutdown semm
    /etc/init.d/semm stop
    sleep 2
    rm -rf `grep -v "MSP Version:" $FILE_NAME`
    logmsg "MSP restore in progress......"
    tar mxvfz $ARCHIVE_NAME >> $LOGFILE
    sleep 5
    ### Call mysql restore script
    /usr/local/mss/bin/mysql_alldb_restore.sh >> $LOGFILE 2>&1
    if [ $? -ne 0 ]; then
    logmsg "Database restore Failed. Cannot proceed further"
    exit 1 ;
    else
    logmsg "Database restore Succeeded."
    fi
    ### Remove DB Dump Files
    rm -f /var/lib/mysql-dumps/*
    ### Trigger cleanup of airprism database tables
    #touch /usr/local/mss/airprism/server/config/reinitdb
    ### Trigger re-import of software packages
    touch /usr/local/mss/swdepot/reimport
    ### Remove log files under the "apps" directory
    find /usr/local/mss/apps -name '*.log*' | xargs rm -f
    find /usr/local/mss/logs -follow -name '*[._]log*' | xargs rm -f
    if [ $? -ne 0 ]; then
    logmsg "MSP restore Failed. Cannot proceed further"
    exit 1 ;
    else
    logmsg "MSP restore Succeeded."
    fi
    # reinstall_patch is touched so that patches are re-installed after restoring of MSP.
    touch /usr/local/mss/patch/bin/reinstall_patch
    ##### Start MSS
    logmsg "restarting MSP server "
    /etc/init.d/mss start
    sleep 5
    ### Start semm
    /etc/init.d/semm start
    sleep 5
    logmsg "MSP server is now restarted"
    my jsp page backup.jsp is as follows
    <%@taglib uri="portlet.tld" prefix="uif" %>
    <%@taglib uri="msp-console.tld" prefix="msp" %>
    <uif:defineObjects/>
    <%@page import="javax.portlet.*" %>
    <%@ page import="java.util.Date" %>
    <%@ page import="java.util.Vector" %>
    <%@ page import="java.text.DateFormat" %>
    <%@ page import="com.symbol.mss.console.admin.backup.BackupManager" %>
    <%@ page import="com.symbol.mss.console.admin.system.SystemInfoPortlet" %>
    <%
         String STYLE_NAME = request.getParameter("style");
         if (STYLE_NAME == null) STYLE_NAME = STYLE_DEFAULT;
         final String ua = request.getHeader("User-Agent");
         BackupManager helper = null;
         PortletSession portletSession = renderRequest.getPortletSession();
         helper = (BackupManager)portletSession.getAttribute("helper");
         if (helper == null) {
              //System.err.println("Created new BackupManager");
              helper = new BackupManager();
              portletSession.setAttribute("helper", helper);
         final BackupManager backupManager = helper;
         String action = "";
         final String backupName = renderRequest.getParameter("backupName");
         String completePath = backupManager.getBackupDir() + backupName + backupManager.getBackupFileExt();
         if (backupName != null) {
              action = "backup";
         if(backupManager.backup(backupName)) {
              SystemInfoPortlet.beginRestartMSP();
              } else {
                   action = "backuperror";          
         final String cmd = renderRequest.getParameter("submitButton");
    final String selectedBackup = renderRequest.getParameter("selectedBackup");
    int tarFileStatus =0;
    String backupTarFile ="";
    String backupFileList ="";
         if ("Restore".equals(cmd)) {
    if (selectedBackup != null) {
         tarFileStatus = backupManager.verifyTarFile(selectedBackup);
         //backupTarFile = backupManager.getRestoreFile(Integer.parseInt(selectedBackup));
         //backupFileList = backupTarFile.substring(0, backupTarFile.lastIndexOf(backupManager.getBackupFileExt()))+"_filesList.txt";
                   if (tarFileStatus == 0){
         action = "restore";
         backupManager.restore(selectedBackup);
                        SystemInfoPortlet.beginRestartMSP();
              } else {
                   action = "error";
    } else if ("Remove".equals(cmd)) {
    backupManager.remove(Integer.parseInt(selectedBackup));
         DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
         PortletURL restoreURL = renderResponse.createActionURL();
    %>
    <%@ include file="/jsp/core/constants.jspf" %>
    <% if (action.length() > 0) {
         if ("backup".equals(action))
    %>
         <p>The MSP Appliance has been shut down in order to create the <%=backupName %> backup file,
              and will automatically restart as soon as the file has been created.
              To continue your work, please log out of the MSP Console, wait for the appliance
              to restart, and then log back in. The amount of time you'll have to wait for the
              MSP Appliance to come back online depends on the amount of information you have
              stored in the MSP Database.</p>
         <p>The full pathname for the backup file is: <%=completePath %></p>     
    <%     }
         else if ("restore".equals(action))
    %>
         <p>The MSP Appliance has been shut down in order to restore from the <%=backupTarFile%> backup file,
              and will automatically restart as soon as the restore is complete.
              To continue your work, please log out of the MSP Console, wait for the appliance
              to restart, and then log back in. The amount of time you'll have to wait for the
              MSP Appliance to come back online depends on the amount of information you have
              stored in the MSP Database.</p>     
    <%     } else if ("backuperror".equals(action)) { %>
              <p><img src="images/dialogue/error_16.gif" class="icon" alt="Notify" /> Errors occurred while taking back up of MSP. Please see the backup service log file for more details.
              </P>
    <%     } else if ("error".equals(action)) {
              if (tarFileStatus == 4) { %>
                   <p><img src="images/dialogue/error_16.gif" class="icon" alt="Notify" /> The backup file <%=backupTarFile%> contains errors. This backup can't be restored. Please restore a valid back up.
                   </P>
              <%} else if (tarFileStatus == 3) { %>
                   <p><img src="images/dialogue/error_16.gif" class="icon" alt="Notify" /> The backup file list <%=backupFileList %> is missing. This file is required to restoring backup. Please get the backup file list and proceed with restoring backup.</p>
              <%} else if (tarFileStatus == 2) { %>
                   <p> <img src="images/dialogue/error_16.gif" class="icon" alt="Notify" /> The backup file <%=backupTarFile%> contains errors and the backup file list <%=backupFileList%> is missing. This backup can't be restored. </p>
              <%} %>
    <%     }
    } else { %>
    <p><strong>Note</strong>: Both backup and restore will shut down MSP temporarily. MSP will be unable to collect data from devices, send notifications, or provide MSP Console access during this time. When the backup or restore operation is complete, MSP will come back online automatically.</p>
    <h3>Backup</h3>
    <form action="<%= restoreURL.toString() %>" method="post">
    <p>Please provide a name for your backup. MSP will provide the date automatically in the list of backups.</p>
    <p><label for="<uif:namespace />backupName">Name</label> <input type="text" name="<uif:namespace />backupName" id="<uif:namespace />backupName" size="20" maxlength="256" /> <input type="submit" name="<uif:namespace />submitButton" value="Back up now" onclick="return <uif:namespace/>validateName()"/></p>
    </form>
    <h3>Restore</h3>
    <p>This will restore all databases (device assets, collected device data, software packages, policies, etc.) to their state as of the time the backup was made. Changes since then <em>except for backups</em> will be destroyed.</p>
    <%
    Vector restoreList = helper.getRestoreEntries();
    Vector restoreDates = helper.getRestoreDates();
    Vector restoreVersions = helper.getRestoreVersions();
    Vector filesStatus = helper.getBackupFilesStatus();
    %>
    <% if (restoreList.size() == 0) { %>
    <p>There are no backups currently available.</p>
    <% } else { %>
    <form action="<%= restoreURL.toString() %>" method="post">
    <table class="input-radios" id="<uif:namespace />existingBackups">
    <thead>
    <tr>
    <th></th>
    <th>Name</th>
    <th>Date</th>
    <th>MSP Version</th>
    <th>Remarks </th>
    </tr>
    </thead>
    <tfoot>
    <tr>
    <td colspan="4" class="actionsOnSelected">
    <input type="submit" name="<uif:namespace />submitButton" value="Restore" onclick="return confirm('This action requires MSP and all related services to be shut down. Console will be unavailable if the request is submitted. The server will restart automatically once restore has been completed.');" />
    <input type="submit" name="<uif:namespace />submitButton" value="Remove" onclick="return confirm('This action will remove the backup archive. You will no longer be able to restore this backup. Continue?');" />
    </td>
    </tr>
    </tfoot>
    <tbody><%-- First one (most recent) is checked by default. Every other row has class="portlet-section-alternate". Note that each ID must be unique and must match the value of the "for" attribute on the corresponding "label" element. --%>
    <%
    for (int i = 0; i < restoreList.size(); i++) {
    %>
    <tr <%= (i % 2 == 1) ? " class=\"portlet-section-alternate\"" : "" %>>
    <td><input type="radio" name="<uif:namespace />selectedBackup" value="<%= i %>" id="<uif:namespace />selectedBackup-<%= i %>" <%= (i == 0) ? "checked=\"checked\"" : "" %> /></td>
    <td><label for="<uif:namespace />selectedBackup-<%= i %>"><%= restoreList.elementAt(i) %></label></td>
    <td><%= dateFormat.format((Date)restoreDates.elementAt(i)) %></td>
    <td><%= restoreVersions.elementAt(i) %></td>
    <td><%= filesStatus.elementAt(i) %></td>
    </tr>
    <%
    %>
    </tbody>
    </table>
    </form>
    <% } %>
    <% } %>
    <script type="text/javascript">
    <!--//--><![CDATA[//><!--
    function <uif:namespace/>validateName() {
    var name =document.getElementById("<uif:namespace />backupName");
    var msg= "<msp:i18n key="BackupMsg"/>";
    var str=name.value;
    var re = /^[A-Za-z0-9_]+$/;
    if (!str.match(re)) {
         alert(msg);
         name.focus();
         return false;
         } else {
    return confirm('This action requires MSP and all related services to be shutdown. Console will be unavailable if the request is submitted. The server will restart automatically once backup has been completed.');
    //--><!]]>
    </script>
    and my BackupManager.java is as follows where the code in bold and italic is called the restore()
    //============================================================================
    // Symbol Technologies P R O P R I E T A R Y S O U R C E C O D E
    // C O N F I D E N T I A L
    // Copyright (c) 2003 Symbol Technologies. All Rights Reserved.
    // All information contained herein is the property of Symbol Technologies,
    // or its Licensors, and are protected copyrights and trade secrets, and may
    // be covered by U.S. patents. Any reproduction or dissemination of any
    // portion of this document, of the software, or other works derived from it
    // is strictly forbidden unless prior written permission is obtained from
    // Symbol Technologies.
    //============================================================================
    package com.symbol.mss.sdf.services.backup;
    import java.io.*;
    import java.sql.Time;
    import java.text.DateFormat;
    import java.util.logging.FileHandler;
    import java.util.logging.Formatter;
    import java.util.logging.LogRecord;
    import java.lang.Process;
    import java.util.*;
    import org.apache.avalon.framework.configuration.Configurable;
    import org.apache.avalon.framework.configuration.Configuration;
    import org.apache.avalon.framework.configuration.ConfigurationException;
    import org.apache.avalon.framework.logger.LogEnabled;
    import org.apache.avalon.framework.logger.Logger;
    import com.symbol.mss.sdf.admin.AdministratorService;
    import com.symbol.mss.sdf.backup.*;
    import com.symbol.mss.sdf.data.*;
    * @author nramaiah
    * Service to perform scheduled backups of the system state.
    public class BackupManager implements BackupService, DataHandler,
    LogEnabled, Configurable {
    // MSS Home Path
    private static String mssHome = System.getProperty("phoenix.home", File.separator + "usr" +
    File.separator + "local" +
    File.separator + "mss" +
    File.separator);
    // Backup related definitions
    private static final String BACKUP_LIST_FILE_NAME = "conf" + File.separator + "files_to_backup.txt";
    private static final String BACKED_UP_LIST_FILE_NAME_SUFFIX = "_filesList.txt";
    private static final String BACKUP_LOCATION = File.separator + "var" + File.separator + "lib" +
    File.separator + "mss-backups" + File.separator;
    private static final String BACKUP_PARTITION = File.separator + "var" + File.separator + "lib";
    private static final String VERIFY_BACKUP = File.separator + "usr" + File.separator + "local" +
                                                           File.separator + "mss" + File.separator+"tools"+
                                                           File.separator+"backup"+File.separator+"verifyBackup.sh";
    // DB backup/restore related definitions
    private static final String DB_DUMP_LOCATION = File.separator + "var" + File.separator +
    "lib" + File.separator +
    "mysql-dumps" + File.separator;
    private static final String DB_BACKUP_SCRIPT = "bin" + File.separator + "mysql_alldb_backup.sh";
    private static final String DB_RESTORE_SCRIPT = "bin" + File.separator + "mysql_alldb_restore.sh";
    // Private variables
    private AdministratorService m_admin = null;
    private Logger m_logger = null;
    private String backupLocation = null;
    private String backupListFileName = null;
    private String backupPartition = null;
    private int backupPartitionLimit = 90;
    private String dbDumpLocation = null;
    private String dbBackupScript = null;
    private String dbRestoreScript = null;
    private List servicesBackupList = null;
    private String tarFileExtension =".tgz";
    private String errFileExtension =".err";
    private int exitValue=0;
    * Default Constructor
    public BackupManager() {
    servicesBackupList = new ArrayList();
    * Set the administrator service implementation. Link established by Broker service.
    * @param admin reference to an implementation of AdministratorService
    public void setAdministrator(AdministratorService admin) {
    m_admin = admin;
    * Set the job publisher service implementation. Link established by Broker service.
    * @param jobPublisher reference to an implementation of JobPublisherService
    public void setJobPublisher(DataChannel jobPublisher) {
    jobPublisher.subscribe(this);
    * Gets the backup manager object.
    * @return backup manager object
    public BackupService getBackupService() {
    return this;
    * Service lifecycle method.
    * @param logger logger object to be used by the service
    public void enableLogging(Logger logger) {
    m_logger = logger;
    * Service lifecycle method.
    * @param configuration service configuration object
    public void configure(Configuration configuration) throws ConfigurationException {
    // Verify MSS Home path
    if (!mssHome.endsWith(File.separator))
    mssHome += File.separator;
    // Get the location where the backup file needs to be placed
    backupLocation = configuration.getChild("BackupLocation").getValue(BACKUP_LOCATION);
    // Verify backup directory path
    if (!backupLocation.startsWith(File.separator))
    backupLocation = mssHome + backupLocation;
    if (!backupLocation.endsWith(File.separator))
    backupLocation += File.separator;
    // Get the file listing the files/directories to be backed up
    backupListFileName = configuration.getChild("FilesList").getValue(BACKUP_LIST_FILE_NAME);
    // Verify backup list file name path
    if (!backupListFileName.startsWith(File.separator))
    backupListFileName = mssHome + backupListFileName;
    // Get the partition where the backups are kept
    backupPartition = configuration.getChild("BackupPartition").getValue(BACKUP_PARTITION);
    // Verify backup partition path
    if (!backupPartition.startsWith(File.separator))
    backupPartition = File.separator + backupPartition;
    if (backupPartition.endsWith(File.separator))
    backupPartition = backupPartition.substring(0, (backupPartition.length()-1));
    // Get the limit on the amount of free space on the backup partition
    backupPartitionLimit = configuration.getChild("BackupPartitionLimit").getValueAsInteger(backupPartitionLimit);
    // Get the location where the DB dump files will be placed
    dbDumpLocation = configuration.getChild("DBDumpLocation").getValue(DB_DUMP_LOCATION);
    // Verify DB dump directory path
    if (!dbDumpLocation.startsWith(File.separator))
    dbDumpLocation = mssHome + dbDumpLocation;
    if (!dbDumpLocation.endsWith(File.separator))
    dbDumpLocation += File.separator;
    // Get the name of DB dump backup script
    dbBackupScript = configuration.getChild("DBBackupScript").getValue(DB_BACKUP_SCRIPT);
    // Verify backup script path
    if (!dbBackupScript.startsWith(File.separator))
    dbBackupScript = mssHome + dbBackupScript;
    // Get the name of DB dump restore script
    dbRestoreScript = configuration.getChild("DBRestoreScript").getValue(DB_RESTORE_SCRIPT);
    // Verify restore script path
    if (!dbRestoreScript.startsWith(File.separator))
    dbRestoreScript = mssHome + dbRestoreScript;
    * Individual services can supply a list of files/directories to be backed up.
    * These are files apart from the files specified in conf/files_to_backup.txt and
    * will be backed up as well.
    * @param files list of files/directories
    public void filesToBackup(List files) {
    synchronized(this) {
    if (files != null) {
    if (files.size() > 0) {
    // Add the list contents to the current backup list
    for (int i=0; i<files.size(); i++) {
    String tStr = (String)files.get(i);
    // Check for absolute or relative path
    if (tStr.startsWith(File.separator))
    servicesBackupList.add(tStr);
    else
    servicesBackupList.add(mssHome + tStr);
    else
    m_logger.info("Empty list of filenames. Nothing added.");
    else
    m_logger.info("Null list of filenames. Nothing added.");
    * Individual services can supply a list of files/directories to be backed up.
    * Specified files will be added to the file defining the list of files to be backed up.
    * @param files list of files/directories
    private void persistFilesToBackup(List files) {
    synchronized(this) {
    if (files != null) {
    if (files.size() > 0) {
    // Add the list of files provided to the end of file
    try {
    File file = new File(backupListFileName);
    if ((file == null) || (!file.exists()))
    file.createNewFile();
    // Seek to the end of the file
    RandomAccessFile rFile = new RandomAccessFile(file, "rw");
    if (rFile != null) {
    rFile.seek(rFile.length());
    // Write the list contents to the file
    for (int i=0; i<files.size(); i++) {
    String tStr = (String)files.get(i);
    // Check for absolute or relative path
    if (tStr.startsWith(File.separator))
    rFile.writeBytes(tStr + "\n");
    else
    rFile.writeBytes(mssHome + tStr + "\n");
    else
    m_logger.error("Error opening file " + backupListFileName);
    rFile.close();
    catch (Exception ex) {
    ex.printStackTrace();
    m_logger.error("Error adding entries to file " + backupListFileName, ex);
    else
    m_logger.info("Empty list of filenames. Nothing added.");
    else
    m_logger.info("Null list of filenames. Nothing added.");
    * Command to be run during the backup process. Individual services can
    * provide shell commands that will be executed before backing up the files.
    * @param command shell command to be executed
    private void runCommand(String command) {
    * Creates a shell script at the specified location that will backup the
    * files listed in the List passed in.
    * @param scriptFileName location where the script needs to be created
    * @param backupFileName name for the tar file being created
    * @param backupList list of files to be backed up
    private void createBackupScript(String scriptFileName, String backupFileName, ArrayList backupList) throws Exception {
    // Create a new StringBuffer to build the contents to be written to the script file
    StringBuffer buffer = new StringBuffer();
    // Add the initial comment in the start script
    buffer.append("#!/bin/sh\n" + "set -x\n\n");
    // Check if the partition has enough space
    buffer.append("### Check if the partition has enough space\n" +
    // "diskUsed=`df -k | grep \"" + backupPartition + "\" | awk '{print $5}' | cut -d\"%\" -f1`\n" +
                   " diskUsed=`df -k \"" + backupPartition + "\" | awk '{print $5}' | cut -d\"%\" -f1 | grep -v Use`\n" +     
    "echo \"Partition " + backupPartition + " is $diskUsed% used.\"\n" +
    "if [ \"$diskUsed\" -lt \"" + backupPartitionLimit + "\" ]\nthen\n" +
    " echo \"Starting backup...\"\n\n");
    // Shutdown semmd
    buffer.append(" ### Shutdown semm\n" + " /etc/init.d/semm stop\n" +
    " sleep 2\n\n");
    // MSP Limited release and earlier builds stop mysql DB and backup the
    // /var/lib/mysql directory as it is. Starting MSP 1.0 GA release, mysql
    // dump script will be integrated which will create sql scripts to
    // restore the database.
    // Check if mysql dump creation script exists
    File mysqlDumpScript = new File(dbBackupScript);
    if (mysqlDumpScript.exists()) {
    // MSP 1.0 GA and later releases
    // Run the script that will generate sql scripts that would re-create the DB as it is
    buffer.append(" ### Call mysql dump script\n" +
    " " + dbBackupScript + "\n\n");
    else {
    // MSP Limited release
    // Add command to shutdown mysql
    buffer.append(" ### Shutdown mysql\n" + " /etc/init.d/mysql stop\n\n");
    // Change to root directory and create the tgz file
    buffer.append(" ### Create tgz file\n" + " cd /\n");
    // Build up the tar file name from the current date and time
    String fileName = null;
    if ((backupFileName != null) && (backupFileName.length() > 0))
    fileName = backupFileName;
    else {
    // File name not provided by user, build one using the timestamp
    Calendar cal = Calendar.getInstance();
    Date date = cal.getTime();
    fileName = "MSS-"
    + DateFormat.getDateInstance().format(date).replaceAll(" ", "").replaceAll(",", "")+ "-"
    + (new Time(cal.getTimeInMillis())).toString().replaceAll(":", "").substring(0,4);
    String tarFileName = fileName + ".tgz";
    // Get the current MSP Version
    String mspVersion = getMSPVersion();
    // Gather all the files to be backed up. Add them to the tar command and
    // also dump them into the file maintaining the list of files being backed up
    String listStr = "";
    for (int i=0; i<backupList.size(); i++)
    listStr += (String)backupList.get(i) + "\n";
    // Dump the current MSP version and the list of files being backed up into a manifest file
    String listFileName = fileName + BACKED_UP_LIST_FILE_NAME_SUFFIX;
    RandomAccessFile file = new RandomAccessFile(backupLocation + listFileName, "rw");
    m_logger.info("List of files/directories being backed up:\n" + listStr);
    file.writeBytes("### MSP Version: " + mspVersion + " ###\n");
    file.writeBytes(listStr);
    file.close();
    // Add the tar command to the script
    buffer.append(" echo \"Creating " + backupLocation + tarFileName + "...\"\n" +
    " tar cvhfz " + backupLocation + tarFileName + " `grep -v \"MSP Version:\" " +
    backupLocation + listFileName + "`\n\n");
    // Check if free space on the backup partition has reduced below the limit
    // If enough space left, backup is retained, "mss" is made the owner of the files,
    // "backup" is made the group the files belong to,
    // permissions changed to be "0660" and
    // backup action declared a success
    // Else, backup files are deleted and declared a failure
    buffer.append(" ### Check if the partition has enough space left\n" +
    //" diskLeft=`df -k | grep \"" + backupPartition + "\" | awk '{print $5}' | cut -d\"%\" -f1`\n" +
    " diskLeft=`df -k \"" + backupPartition + "\" | awk '{print $5}' | cut -d\"%\" -f1 | grep -v Use`\n" +
    " echo \"Partition " + backupPartition + " is $diskLeft% used.\"\n" +
    " if [ \"$diskLeft\" -gt \"" + backupPartitionLimit + "\" ]\n" +
    " then\n" +
    " ### Failure\n" +
    " echo \"Partition " + backupPartition + " does not have enough space.\"\n" +
    " echo \"Backup " + backupLocation + tarFileName + " will be removed.\"\n" +
    " rm -f " + backupLocation + fileName + "*\n" +
    " echo \"Backup Failed.\"\n" +
    " else\n" +
                        " tar tvzf " + backupLocation + tarFileName + " > /dev/null 2>&1\n" +
    " if [ ! -s " + backupLocation + tarFileName + " -o $? -ne 0 ] \n" +
                        " then\n" +
                        " echo \"MSP Backup operation is not successful. The tar file " + backupLocation + tarFileName + " contains errors.\"\n" +
                        " echo \"Please take the backup again\"\n" +
                        "     touch "+backupLocation+fileName+".err\n" +
    " else \n" +
    " ### Success\n" +
    " ### Change the owner, group and permissions for the backup files\n" +
    " chown mss " + backupLocation + fileName + "*\n" +
    " chgrp backup " + backupLocation + fileName + "*\n" +
    " chmod 0660 " + backupLocation + fileName + "*\n" +
    " echo \"Backup Completed.\"\n" +
    " fi\n" +
    " fi\n\n");
    // MSP Limited release and earlier builds re-start mysql. Starting
    // MSP 1.0 GA release, mysql is not stopped and so re-start is not
    // needed. sql scripts created by the dump script get packed into
    // the tar file and so are deleted.
    // Check if mysql dump creation script exists
    if (mysqlDumpScript.exists()) {
    // MSP 1.0 GA and later releases
    // Remove DB dump files
    buffer.append(" ### Remove DB Dump Files\n" + " rm -f " + dbDumpLocation + "*\n\n");
    else {
    // MSP Limited release
    // Start mysql
    buffer.append(" ### Start mysql\n" + " /etc/init

Maybe you are looking for

  • OAM 11g is supporting direct integration with E Business ??

    Hi All, Is OAM 11g supporting Direct integration with E Business suite instead of going through the OSSO ?? Please give me some pointers how to do the OAM 11g and E Business suite integration. Thanks & Regards, Vaasu.

  • After system copy DTP pointing to Prod Sourcesystem in Quality

    Hi, We have copied BWP system to BWQ. All the transformations are correctly pointing to R3Q system. But DTPs are still pointing to R3P system. How to convert this source system assignment for all the DTPs and InfoPackages? Regards SSS

  • Customize Column Name in Drillthrough Action

    When we do the Drillthrough Action, the data is displayed with the column name like this :   [$Test_Dim_Customer].[theCustomerId] It is really bad look. I want to display like this : [theCustomerId] But don't know how.  I read the sample from Microso

  • Deleting the first word in a string

    hi! i'm learning regex and with this code i would like to 1) print a string (from "Hi my name is SandraPandra. do not print this") 2) remove the first word and print the new, shorter string 3) remove the first word in the new, shorter string and prin

  • Equium P200-1IR - How to remove internal keyboard?

    This notebook had soup spilled on the keyboard and now won't boot, even with a USB keyboard connected. I want to disconnect the internal keyboard, because it looks like that's what's causing the problem. (I have relevant experience.) But I can't see