Function in shell script
Hello,
I have the following function in PL/SQL:
Create or replace function fqman."test" (name in varchar2, url in varchar 2, page in varchar2, uname in varchar2, password
in varchar 2, key_ in varchar2, pass in varchar2, file1 in varchar2, file2 in varchar2) return number
as language java
name 'Data.file(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,
java.lang.String,java.lang.String,java.lang.String) return int;Data is a java class I have in my /home directory (AIX machine). I would like to run this function NOT through Oracle, but through a shell script. So, I have to write the test function in a .sh file.
I started doing that. I did the following:
fntest()
name =$1
url=$2
page=$3
uname=$4
password=$5
key_=$6
pass=$7
file1=$8
file2=$9
}I do not know how to finish the function. Any help will be appreciated
Perhaps the following will do:
#!/bin/bash
fntest() {
name="'$1'"
url="'$2'"
page="'$3'"
uname="'$4'"
password="'$5'"
key="'$6'"
pass="'$7'"
file1="'$8'"
file2="'$9'"
ORACLE_SID="ORCL"
export ORAENV_ASK=NO
. oraenv -s
sqlplus -s / nolog <<EOF
set pages 0 feed off
connect username/password
BEGIN DBMS_OUTPUT.PUT_LINE(fqman.test($name,$url,$page,$uname, etc..)); END; /
exit;
EOF
Similar Messages
-
PL/SQL function - unix shell script
Hello,
I have an application that calls a unix shell script This unix shell script calls a oracle function in the PL/SQL package. For example,
In package pkg_test, there is function f_test. This function returns pls_interger.
How can I write a unix shell script to return the value from the oracle function, so that the application can get the value from the unix shell script?
Many thanks.Thank you for your response.
The Oracle functuion pkg_name.proc_name will return different values, 0, 1, 2, 3 in diffefrent conditions.
The unix script, myscript.ksh calls pkg_name.proc_name.
The other application will call myscript.ksh and this application will need to get the values 0, 1, 2, 3 from myscript.ksh.
Can we make it without using the unix shelll function?
Thanks.
Edited by: slsam01 on Jun 2, 2009 9:21 PM -
Oracle declare function in shell script
Please tell me oracle declare function now able to run in shell script?
I am calling in shell script like @/myscript.sql it is not working properly, reset update and other oracle command is working fine in shell script.I am running below code.
#!/bin/sh
sqlplus system/manager@prod_db <<ENDOFSQL
update apps.fnd_concurrent_queues set node_name = 'host1', target_node ='host1' where node_name='host3';
update apps.fnd_concurrent_queues set node_name = 'host2', target_node ='host2' where node_name='host4';
commit;
DECLARE
VALUE BOOLEAN;
l_node_id number;
BEGIN
select node_id into l_node_id from fnd_nodes where NODE_NAME = 'host5';
VALUE := fnd_profile.save ('NODE_TRUST_LEVEL', 3, 'SERVER',l_node_id,null,null);
END;
ENDOFSQL
Below ERROR i am getting after running above code via shell script with oracle user
SQL>
0 rows updated.
SQL>
0 rows updated.
SQL>
Commit complete.
SQL> SQL> DECLARE
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 5 -
Call Unix Shell Script From OBIEE
Hi All,
Is it possible to do a call to a Unix Shell Script with the Action Framework from OBIEE.
Thanks in AdvanceI dont think so but we can go for it instead of BI side. Try to port the same functionality on shell script side, so that the script can identify your report using tail of nqquery log and execute the rest of your lines in shell script.
This can doable and works as expected. If at all you are going with my suggestion you can go for a small key word to identify your report instead of that lengthy logical query.
Pls mark if helps -
Catch a value from a pl*sql function in a shell script
Hi all,
I have a shell script that simply calls the following pl*sql function.
echo "execute scott.my_pkg.test('FDLmaster');\n exit;" >./pippo.sql
sqlplus scott/tiger @/fidcap_ftp/FDL/SCRIPTS/pippo.sql
What I have to do to catch the value returned from the function test?
Thanks in advance
best regards
MarioSQL> create or replace function do_something return varchar2 is
2 begin
3 return ('Something');
4* end;
SQL> /
Function created.
SQL> select do_something from dual;
DO_SOMETHING
Something
SQL> save pippo
Created file pippo.sql
SQL> exit
Disconnected from Oracle Database 10g Enterprise Edition Release 10.1.0.3.0 - Production
With the Partitioning, OLAP and Data Mining options
[linuxas tmp test10]$ echo exit >>pippo.sql
[linuxas tmp test10]$ VAR=`sqlplus -s scott/tiger @pippo`
[linuxas tmp test10]$ echo $VAR | cut -f3 -d" "
Something
[linuxas tmp test10]$ -
Arguments in function passed through shell script
HI all,
I have a shell script test.sh
it contains the following
A=$1
B=$2
C=$3
D=$4
sqlplus usr/pwd<<eof
a varchar2(10);
b varchar2(10);
c date;
d date;
a:='$A';
b:='$B';
c:='$C';
d:='$D';
func(a,b,c,d(;
eof
func() defbn
func(name varchar2,trc varchar2,dt1 date,dt2 date)
end;
When icall test.sh as
./test.sh xyz 0100 01-NOV-09 06-NOV-09
It appneds dt1 with 06-NOV-09 and dt2 remains null.
It should be like:
dt1=01-NOV-09
dt2=06-NOV-09
inside function
ThanksAre you sure there is no problem in SQL function *"func"* that you are calling?
You haven't pasted the function code so can't really comment on that.
Below test shows that it works really fine:
kallo:DZHLHFC1> cat 1.ksh
A=$1
B=$2
C=$3
D=$4
echo "Shell vars = $A,$B,$C,$D"
sqlplus -s username/pass<<eof
alter session set nls_date_format='DD-MON-YY';
set serverout on size 10000
declare
a varchar2(10);
b varchar2(10);
c date;
d date;
begin
a:='$A';
b:='$B';
c:='$C';
d:='$D';
dbms_output.put_line('');
dbms_output.put_line('SQL vars =' ||a||',' ||b||',' ||c||',' ||d);
end;
eof
kallo:DZHLHFC1> ./1.ksh xyz 0100 01-NOV-09 06-NOV-09
Shell vars = xyz,0100,01-NOV-09,06-NOV-09
Session altered.
SQL vars =xyz,0100,01-NOV-09,06-NOV-09
PL/SQL procedure successfully completed. -
Oracle Workflow Erroring on Function/Shell Script
We are in the process of upgrading databases and reimported all the OWB code into the new database.
Currently our OWB mappings all seem to run ok, but when I try to run a process flow I am hitting the following error
RPE--2075: Oracle Workflow failed to process the execution request for activity LD_EDW_MAIN:F_GET_DB_NAME. This may be because dependant objects have not yet been deployed. ORA-20010
F_GET_DB_NAME is a function and I checked and I see that the function executes properly
I also hit a similar error when trying to execute a shell script.
How would I go about deploying a function or a shell script?
Im relatively new to OWB and am being "force fed" learning since we lost our main OWB colleague.
Thank youThanks! for your reply.
I am using this API outside the workflow.I am using this API for iExpense to approve an Expense Report. In Expenses Workflow below are the processes:
1. AP_MANAGER_APPROVALPROCESS whihc is using NON_AME_APPROVAL_PROCESS and this is using REQUEST_APPROVAL_PROCESS and under this process there is a notification APPROVAL_REQUES. Now, I am completing this ACTIVITY as Approve and I am able to do that but problem is that REQUEST_APPROVAL__PROCESS is itself not getting completed and stuck here.
Please let me know how can I achieve that.
Thansks!
Sandy -
Trying to create a shell script to cut/paste files in finder. Help needed.
I'm trying to create an automator shell script to cut/paste. It'll function exactly like copy/paste. i.e. I'll just copy file/files with command+c like always, but then I'll create an automator which uses the "mv" terminal app to move the files which works exactly like cut paste.
I need some help since I don't know the syntax for creating shell scripts.
What I did so far is to do it in automator with Apple Script which goes like the following:
on run {input, parameters}
tell application "Finder"
set theWindow to window 1
set thePath to quoted form of (POSIX path of (target of theWindow as string))
end tell
tell application "Terminal"
do script with command "mv \"" & input & "\"" & thePath in window 1
end tell
return input
end run
This gets the copied file path from clipboard before, as input, and then recognizes the active finder window as thePath so then executes the mv command for the input file to the thePath window.
It doesn't work as expected since it connects both file/window paths into a single path instead of leaving a space between them so the mv command can't recognize two separate paths.
What's the correct syntax for that line
do script with command "mv \"" & input & "\"" & thePath in window 1
to leave a space between input and thePath under the mv command?
Also this requires the terminal app to be open in the background.
After I get this to work I want to do the exact same thing using shell script within automator, so I won't need Terminal to be open all the time.
And the next step will be to cut/paste multiple files/folders but that should be easy to do once I get the hang of it.Try using:
on run {input, parameters}
tell application "Finder"
set theWindow to window 1
set thePath to quoted form of (POSIX path of (target of theWindow as string))
end tell
do shell script "mv \"" & input & "\" " & thePath
return input
end run
(45977) -
Hai all,
I need to write a script to add in the cron
a) exec a procedure
if successful ,then
b) Truncate one schema table in the DB
c) exec a procedure
Can anyone let me know how to do this ? if anyone have any pointers, for the same , please let me know
DB : 11.
Os: Solaris 5.10
KaiKai,
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 -
Run a shell script at login?
I would like to run a simple shell script each time a user logs in. Currently, I have it wrapped in an Automator executable that is included in "Login Items", but figured there must be a more elegant way? Thanks.
More info:
The problem I'm trying to solve is that of file permissions when sharing one iTunes and one iPhoto library between multiple users on one computer. The libraries are located in /Users/Shared and the apps were pointed to the relocated libraries by holding down 'Option' on startup. The problem is that work done by each user in the iTunes or iPhoto library inherits the default permission settings of that user, making any new additions to the libraries, read-only to the other users. I'm using `chmod` on login to fix it. Let me know if you know of a better way to address this. Thanks again.I wrote a simple shell script that executes each time a user logs in (well, actually, each time I log in, coz' it's not really applicable to other users). It syncs my work and home addressbooks and iCal calendars to one another.
I named it "sync". Then I read somewhere that if you wanted to make it double-clickable (to launch it from the Finder), I appended a ".command" filename extension (so it's now named "sync.command"). I also did a chmod 755 to that file so that it had execute privileges. Depending on whether you give each user their own copy of this thing, or keep a single copy in, say, the /Users/Shared directory, you may have to play around with chmod. Whatever, just so long as the user that has just logged in has execute permissions to the file, and to the entire path to the file, you should be good.
Then, in SysPrefs > Accounts > Login Items, I added that "sync.command" file to the list. So, really the only difference is I'm not wrapping mine inside an Automator script like you are.
I had tried adding it to ~/Library/LaunchAgents and make a launchd plist for it, that would kick it off at login. But I didn't get that to work. Don't know why. But just adding the double-clickable executable unix script to the Login Items list did the trick. Whether the plist has to hang out there with it, I don't know. I still have it there, though, in case I ever get motivated to figure out what's wrong with my launchd plist file. So, if just adding it to the Login Items list doesn't do it for you, you could try making a (functional?) launchd plist for it and plopping them both in ~/Library/LaunchAgents, too. That's how I am now, and, like I said, it launches at user login as that user's process (not as a root process like the above referenced article said how login hooks worked -- although, you may want it to run as root since you want this to work with multiple users...in which case, you might want to listen to Cole and not me...). -
How Can i get PLSQL Procedure out values in Shell Script?
Hi,
I need to use PLSQL Procedure out values in shell script by using that parameter i need to check and call the other procedure. Please can you guide me how can i?
#!/bin/ksh
# Function to call validation program
SQL_PKG_CALL()
echo "Inside SQL_PKG_CALL for $file"
sqlplus -s /nolog << EOF
whenever sqlerror exit failure
connect ${APPS_LOGIN}
variable exit_value NUMBER
set serveroutput on size 100000
DECLARE
l_errbuf VARCHAR2(10000) := NULL; l_retcode NUMBER := NULL;lv_test VARCHAR2(4000) := NULL;
BEGIN
fnd_global.apps_initialize ( USER_ID => ${USER_ID}, RESP_ID => ${RESP_ID}, RESP_APPL_ID => ${RESP_APPL_ID}
, SECURITY_GROUP_ID => ${SECURITY_GROUP_ID}
#Calling PLSQL procedure for create and attache document
XXAFPEEP_SO_DOC_ATTACH_INT.DOCUMENT_ATTACH (p_errbuf => l_errbuf, p_retcode => :RETMSG, p_fileName => $file
, p_debug => 'Y', p_rettest => lv_test);
# to print the procedure return values
DBMS_OUT.PUT_LINE('Return Message: '|| lv_test);
#${RETCODE}=l_retcode;
print :RETMSG;
END;
EXIT 0
EOF
# Program starts here
echo "+---------------------------------------------------------------------------+"
echo "Program Start"
APPS_LOGIN=${1} # Apps Login
USER_ID=${2} # User ID
RESP_ID=${5} # Responsiblity ID
RESP_APPL_ID=${6} # Responsiblity Application ID
SECURITY_GROUP_ID=${7} # Security Group ID
DIRECTORY_PATH=${8} # Directory --Attached file locations
DIRECTORY_NAME=${9} # Directory Name for plsql
echo "User ID : $USER_ID"
echo "Responsibility ID : $RESP_ID"
echo "Responsibilith Application ID : $RESP_APPL_ID"
echo "Security Goup ID : $SECURITY_GROUP_ID"
echo "Directory Path : $DIRECTORY_PATH"
echo "Direcotry Name : $DIRECTORY_NAME"
echo
#files direcotry
cd $DIRECTORY_PATH
echo Present Working Directory: `pwd`
echo
#for all file names
ALL_FILES=`ls *.pdf`
for file in $ALL_FILES
do
if [ -f $file ]
then
#log "Processing $file" # future
echo Processing: $file
# Calling the PL/SQL Program
SQL_PKG_CALL;
#echo "Retcode : $RETCODE"
echo "RetMessage : $RETMSG"
else
log "Skipped $file: invalid file"
echo "Skipping current file $file: not a valid file."
fi
done
Thanks
SudheerSaubhik's provided the solution, but just for fun:
Test procedure:
create or replace procedure get_ename
( p_empno in emp.empno%type
, p_ename_out out emp.ename%type )
is
begin
select ename into p_ename_out
from emp
where empno = p_empno;
end get_ename;Test data:
SQL> select empno, ename from emp order by 1;
EMPNO ENAME
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7876 ADAMS
7900 JAMES
7902 FORD
7934 MILLER
14 rows selectedTest call from SQL*Plus to show it working:
SQL> declare
2 v_ename emp.ename%type;
3 begin
4 get_ename(7844,v_ename);
5 dbms_output.put_line(v_ename);
6 end;
7 /
TURNER
PL/SQL procedure successfully completed.Demo shellscript (borrowing the function idea from Saubhik):
#!/bin/ksh
empno=${1:-NULL}
exec_sql() {
sqlplus -s william/w@//vm.starbase.local:1521/eleven <<END_SQL
spool get_out_value.sh.log
set serverout on size 2000 feedback off
declare
v_name emp.ename%type;
begin
get_ename(${empno},v_name);
dbms_output.put_line('# ' || v_name);
end;
spool off
exit
END_SQL
ename=$(exec_sql ${empno} | awk '/^# / {print $2}')
print Employee ${empno} = ${ename}Demo:
/Users/williamr: get_out_value.sh 7844
Employee 7844 = TURNER
/Users/williamr: get_out_value.sh
Employee NULL =Note this substitutes the word NULL if no empno is passed, and it ignores error output or anything else by only looking for lines beginning '# ' and then taking the following word. Error messages will appear in the logfile. (In this example it probably doesn't need the NULL substitution because a missing parameter would cause a syntax error which the script will handle anyway, but it could be useful in more complex examples.)
For a production script you should probably use an OS authenticated account so you don't have to deal with password strings. -
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 hereyes 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 -
Executing a shell script from pl/sql stored procedure
Hi,
I have Oracle 8i on HP-UX.
I am passing a shell script name as a parameter to a user defined function from a pl/sql stored procedure. This user defined function has insterface to a user defined Java class file in Aurora java virtual machine which is written using runtime class which can execute any OS command or any shell script. I am getting any OS command run successfully, but could not run my own shell script. It's is not getting environment variables of my own, so not getting executed. So please suggest how can get these env variables in my shell script and also suggest other sucurity concerns to be taken into consideration.
If you have any questions please let me know.
This is really a very urgent issue.....
Please help me.
Thanks
Srinivasa Rao KollaYour best bet is to use the dbms_pipe builtin package to send the command to the host
-
Executing a shell script from a java program
Hi,
I'm facing a problem while executing a shell script from a jsp page.
I'm using exec() function.
It's working fine for single statement scripts.But if the script consists of any database processing and some other processing statements,it's not returning the correct exit status of the process.
Will u please help me in this.
If there is any other ways to execute a shell script from a jsp page other than Runtime.exec().If so let me know.
Thanks in advance.I think this shud workMaybe - but it is wrong! Why do you create aReader
and then read bytes which are turned into a String
without worrying about whether or not the bytes area
String and without worrying about the character
encoding if the bytes do represent characters and
without worrying about how many bytes wereactually
read.
Also, both you and the OP should read, digest and
follow the advice given in
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-
traps.htmlI dont care if it is wrong. This code works for me.
We are here to solve problems not to find which post
is wrong.It is wrong! You are posting bad advice that is very wrong! It may work for you but it is wrong in general! WRONG WRONG WRONG.
If you have a solution then post it I did post a solution! The reference I gave will explain to you and the OP exactly how it should be done.
rather then
posting rude comments.I was not rude! I was explaining just some of what was wrong! -
Executing a shell script from a jsp page
Hi,
I'm facing a problem while executing a shell script from a jsp page.
I'm using Runtime.exec() function.
It's working fine for single statement scripts.But if the script consists of any database processing and some other processing statements,it's not returning the correct exit status of the process.
Will u please help me in this.
If there is any other ways to execute a shell script from a jsp page other than Runtime.exec() like RMI etc,.If so let me know.
Thanks in advance.Hello,
It's hard to help you but what you can do is listening to the outputs of your script, you should read the output stream and error stream and send them to the default console.
Check this excellent article : http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
Best regards,
Olivier.
Maybe you are looking for
-
AirPort Extreme Update 2007-004 did not solve my reliability problems.
The latest update from Apple did not fix the problem on my system, and now I don´t know what I should do, is there anything I can do to somehow fix it? I can´t use the computer like this, it´s very annoying, for example I can´t browse the web with Sa
-
MacBook won't even turn on after attempting to Install Windows XP with Bootcamp
Help?!
-
GridBagLayout: JInternalFrames and internal JDesktopPanes?
What I want: A JToolbar a the top of my main JFrame and a JPanel (status bar) at the bottom of my frame that stretches/shrinks with the screen. AND JInternalFrames in the center area (the number is arbitrary and the position is -- for now -- arbitrar
-
Hi, I am working on BI 7.0 but i have access to 3.5 queries i would like make changes in 3.5 query designer i am run time error can any one will guide me how to make modifications for those quereisw.. Thanks
-
Can't launch Final Cut Pro 7 on Snow Leopard
Guys, I have succesfully installed FCP on my MacBook but anytime I start it I get the following error: Process: Final Cut Pro [3227] Path: /Applications/Final Cut Pro.app/Contents/MacOS/Final Cut Pro Identifier: com.apple.FinalCutPro Version: ??? (??