Execute Javascript from our JAVA code

Hi all,
I have a question:
It's possible to execute a javascript code from the back bean page. For example , we execute a button action (Conect to a db, insert data) and if all it's ok we execute a simple alert ("The insert is ok!!");
Any way to do this??
Thx!

I don't know enough about Javascript, but I don't think it can be executed from within Java code.
If you can't, an alternative is to provide a status code and/or status message that is accessible to the page. There are a number of ways to do this. One option is to put the information in a hidden field. Another option is to put the information in a session bean and add appropriate JSP code to your page to get that information.
You can link a Javascript function to the page's onLoad event. The function can get the status code/status message and create the alert.

Similar Messages

  • Execute jar from my java code

    Hi,
    My CDC application run in Windows Mobile, with Creme JVM.
    I need from my java code, run other .jar. and later, finish may application atual.
    I try like this:
    Runtime.getRuntime().exec("\\Windows\\CrEme\\bin\\CrEme.exe -jar \\Windows\\sample\\cube.jar");
    System.exit(0);
    But my second jar its not started. Anybody can help me?
    Other question, If I getRuntime(), am I using the atual instance of my JVM. If I exec other JAR, and later exit() my atual, the second jar its exit too?
    I'm building a automatic upgrade module in my application. With Hessian (Web Service), I download my new jar. But, I need have other jar, start it and close my jar atual. My second jar showld be delete my atual, rename the new jar downloaded for the standard name, and later start the jar download, how new version.
    thanks,
    Fabio
    Edited by: FabioPinheiro on Mar 28, 2008 4:41 AM

    Hi all,
    The Mr. Rene (from NSIcom) answer my question
    Just
    Add flag -mi.
    (multiple instance)
    I try and work fine.
    thanks Rene..
    Fabio

  • Execute PL/SQL block with named binds from within java code?

    Hi guys,
    Is there any good way to execute my PL/SQL code, for example
    BEGIN         :x := :x+1; END;
    from my Java code? I need nothing complicated, just static code block with named binds.
    I have tried the Oracle exetnded JDBC (setXXXbyName methods):
      public static void main(String[] args){     try {     Class.forName("oracle.jdbc.driver.OracleConnection");     Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","user","password"); String SQL="begin :x:=:x+1; end;"; OracleCallableStatement stmt; stmt=(OracleCallableStatement)conn.prepareCall(SQL); stmt.setIntAtName("x", 5); stmt.registerOutParameter("x", Types.INTEGER); stmt.execute(); System.out.println(stmt.getInt("x"));     } catch (Exception x) { x.printStackTrace();    }   }
    And get the java.sql.SQLException: operation not allowed: Ordinal binding and Named binding cannot be combined!
    Then i've tried SQLJ appoach:
      public static void main(String[] args){     try {     Class.forName("oracle.jdbc.driver.OracleConnection");     Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","user","password");       Oracle.connect(conn);       System.out.println("Connected!");           int x=3;       #sql { BEGIN         :x := :x+1;       END; };           System.out.println("x=" + x);     } catch (Exception x) { x.printStackTrace();    }   }
    And x=3 had retuned... Although 4 expected.
    Then, I've set parameter sqlj.bind-by-identifier=true
    And result is another exception! java.sql.SQLException: Missing IN or OUT parameter at index:: 2
    Can you please mark my mistakes/point to correct solution?
    Thanks in advance,
    Alexey

    Found another solution, this time working at least...
      public void testPLSQL() {
           String dynamicSQL=
                "declare\n" +
                "  v_CursorID  INTEGER;\n" +
                "  v_BlockStr  VARCHAR2(500);\n" +
                "  v_Dummy     INTEGER;\n" +
                "  v_x         String(18);\n" +
                "BEGIN\n" +
                "  v_CursorID := DBMS_SQL.OPEN_CURSOR;\n" +
                "  v_BlockStr :=?;" +
                "  DBMS_SQL.PARSE(v_CursorID, v_BlockStr, DBMS_SQL.V7);\n" +
                "  v_x:=?;"+
                "  DBMS_SQL.BIND_VARIABLE(v_CursorID, ':x', v_x,18);\n" +
                "  v_Dummy := DBMS_SQL.EXECUTE(v_CursorID);\n" +
                "  DBMS_SQL.VARIABLE_VALUE(v_CursorID, ':x', v_x);\n" +
                "  DBMS_SQL.CLOSE_CURSOR(v_CursorID);\n" +
                "  ?:=v_x;"+
                "  COMMIT;\n" +
                "EXCEPTION\n" +
                "  WHEN OTHERS THEN\n" +
                "    DBMS_SQL.CLOSE_CURSOR(v_CursorID);\n" +
                "    RAISE;\n" +
                "END DynamicPLSQL;";
             try {
                   Class.forName("oracle.jdbc.driver.OracleConnection");
                   Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","user", "password");
                   System.out.println("Profit");
         String SQL="begin :x:=:x+1; end;";
         OracleCallableStatement stmt;
         stmt=(OracleCallableStatement)conn.prepareCall(dynamicSQL);
         stmt.setString(1, SQL);
         int x=3;
         stmt.setInt(2, x);
         stmt.registerOutParameter(3,     Types.INTEGER);
         stmt.execute();
         x=stmt.getInt(3);
         System.out.println(x);
         assertEquals(4, x);
             } catch (Exception ex) {
                  ex.printStackTrace();
                  assertTrue(false);
      }Now the only thing I need is to code some kind of preprocessor of SQL block, to prepare the dynamicSQL lair for SQL critter...
    Please please please show me something less complicated! :8}

  • Pls Help:Running a C executable from my Java Code

    I am trying to run a C/C++ executable a.out from my Java code but its not working pls help me out...Its very very important
    I am writing a segment of the code pls point out if i am making any mistakes
             public void itemStateChanged(ItemEvent a)
              int i=c1.getSelectedIndex();
              Runtime r=Runtime.getRuntime();
              try
                   if(i==0);               
                   if(i==1);
                   if(i==2);     
                   if(i==3)
                        r.exec("./prog/a.out");               
                        System.exit(0);
              }catch(Exception e){}
         }I am working in UNIX enviornment

    Before any other attempt read: [url http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]When Runtime.exec() won't.

  • How to create windows executable file from a java file. Please help.

    Hi,
    For my project I developed the codes in Java. It is working well with java run time environment. But without that I can not run it. I need to create a exe file (windows executable file) from the java source code. If you have any idea please share it with me.
    Even if you know it very lightly, please help with what you know. That would be a big help for me.
    Thank you very much.

    Does anybody know how to read a manual?
    Matt Richardson
    Certified LabVIEW Developer
    MSR Consulting, LLC

  • [Best practice] How to call a service from custom Java code

    Hi all,
    I'm wondering what the best method is to call a standard service from custom Java code?
    In a specific situation iDoc script is extended with custom functions with a custom component. There's Java code mapping to these functions that is executing these functions. The iDoc script functions are called from a workflow entry script.
    In the Java code that runs when the custom iDoc functions are called, I want to call a standard Content Server service. I don't think that the m_service variable is available, so filling the binder and using m_service.executeService() probably isn't possible.
    Also, if it were possible (that is, if I want to call a standard service from my own custom service Java code), what would then be the best method to do so?
    Regards, Stijn

    Hi Sapan,
    Let me explain a bit further.
    I'm an UCM consultant trying to solve a problem that occured at a client when they installed the CS10gR35CoreUpdateBundle.
    Content items are entered into a Workflow when they are checked in. Part of one of the entry scripts of the a workflow step is that related content to the content item in the workflow is (re)submitted for conversion.
    To achive this, a custom component provides an iDoc script extension. This iDoc function (resubmitForConversion) is implemented in Java (the class extends ScriptExtensionsAdaptor).
    In this Java method, first the related content items are fetched. Then the service RESUBMIT_FOR_CONVERSION should be called for all dID's in of the related content.
    Thus, at a certain point in the custom Java code, a native Content Server service must be called. Of course the class of this Java code does not extend the Service class, so the m_service object isn't available.
    The thing is: before installed the 10gR35CoreUpdateBundle everything worked OK. This code was used to execute the service:
            Workspace workspace = CommonUtils.getSystemWorkspace();
            String cmd = binder.getLocal("IdcService");
            if (cmd == null) throw new DataException("!csIdcServiceMissing");
            ServiceData serviceData = ServiceManager.getFullService(cmd);
            if (serviceData == null) throw new DataException(LocaleUtils.encodeMessage("!csNoServiceDefined", null, cmd));
            Service service = ServiceManager.createService(serviceData.m_classID, workspace, null, binder, serviceData);
            UserData fullUserData = CommonUtils.getFullUserData(userName, service);
            service.setUserData(fullUserData);
            binder.m_environment.put("REMOTE_USER", userName);
            ServiceException error = null;
            try {
                service.setSendFlags(true, true);
                service.initDelegatedObjects();
                service.globalSecurityCheck();
                service.preActions();
                service.doActions();
                service.postActions();
                service.updateSubjectInformation(true);
                service.updateTopicInformation(binder);
            } catch (ServiceException e) {
                error = e;
            } finally {
                service.cleanUp(true);
                if (!CommonUtils.isWorkspaceConnectionInTransaction(workspace)) {
                     workspace.releaseConnection();
            }the first problem was that the CS began to complain that a transaction was started within another transaction. So I suspect that the 10gR35 update wrapped a transaction around a workflow script entry.
    With some decompiling I figured out how a service is called from iDoc with the <$executeService()$> command. So I replaced the code above with:
                  String cmd = binder.getLocal("IdcService");
                ServiceData serviceData = ServiceManager.getFullService(cmd);
                if (serviceData == null) throw new DataException(LocaleUtils.encodeMessage("!csNoServiceDefined", null, cmd));
                Workspace workspace = CommonUtils.getSystemWorkspace();
                Service service = ServiceManager.createService(serviceData.m_classID, workspace, null, binder, serviceData);
                UserData fullUserData = CommonUtils.getFullUserData(userName, service);
                service.setUserData(fullUserData);
                binder.m_environment.put("REMOTE_USER", userName);
                service.initDelegatedObjects();
                service.executeSafeServiceInNewContext(cmd, true);This solved the transaction problem but introduces another problem: !csUnableToResubmitItem,(null)!csIllegalScriptAccess,RESUBMIT_FOR_CONVERSION
    The Service Reference Guide says that the access level for RESUBMIT_FOR_CONVERION is 33 (Read, Scriptable). However, in shared/config/resources/std_services.htm the access level is specified as 2 (write).
    Thus, my question still is:
    What is the best method to call a standard Content Server service from any Java code (so without extending the Service class, or having the m_service object available)?

  • Runnig DOS commands from the java code?

    Hi reader,
    how can I execute DOS commands (I am on an Windows XP Machine) from my java code and also capture the output?
    I think the
    runtime.exec(command)
    only executes win32 processes.
    Please suggest
    TIA
    Ayusman

    Again, this link should tell you most of what you need to know:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    You're not limited to the Win32 platform unless you're using specific DOS commands. Perhaps if you're just after file system information then some of the classes in the java.io package can help.
    If it's not enough, perhaps a resource bundle or something similar can provide you with the names of the external programs you need to run, i.e. "dir" for win and "ls" for *nix.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to get the Weblogic Server Id from within java code

    I would like to log which server (among a cluster) a certain job is running on. Is there a way to get the server id from within Java code (this code is in a session bean if that is relevant.)
    By server id I mean the "Name" column in the summary of servers on the weblogic console.
    Thanks,
    ken

    Use the two entries close to the bottom of the page: "list WebLogic
    MBeans:listMBeans.jsp
    display MBean attributes and operations:showMBean.jsp"
    Nils
    Anatoly wrote:
    >
    Cameron,
    That page has these items on it:
    which one do you think helps with my issue?
    Misc WebLogic examples
    LongRunningTask
    Execute tasks in parallel using WebLogic Execute Threads
    Weblogic stats (5.1)
    Reload Servlet(s) programmatically (5.1)
    Network classload from WebLogic:using reflection,or the launcher
    Weblogic 5.1 debugging properties
    Seppuku pattern readme
    Using dynamic proxies to intercept EJB invocations (6.1)
    list WebLogic MBeans:listMBeans.jsp
    display MBean attributes and operations:showMBean
    Thanks to Marcelo Caldas for filter by type option and nice UI!
    Using com.sun.jdmk.comm.HtmlAdaptorServer with WebLogic 6.1
    Cool
    EJBGen
    Dimitri
    back
    "Cameron Purdy" <[email protected]> wrote in message news:<3c7a745d$[email protected]>...
    JMX ... see http://dima.dhs.org/misc/ for some info on JMX in Weblogic.
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    Clustering Weblogic? You're either using Coherence, or you should be!
    Download a Tangosol Coherence eval today at http://www.tangosol.com/
    "Anatoly" <[email protected]> wrote in message
    news:[email protected]..
    Does anyone know who to get the managing server URL's port
    from within the EJB code running on Weblogic 6.1?
    The URL port is not default (not 7001), but when creating
    initial context, I am not specifying the URL in properties.
    Due to that, trying to the the PROVIDER_URL property from
    environment does not return anything.
    Appreciate any responses.
    -Anatoly
    ============================
    [email protected]

  • How to call IAC Iview from WebDynpro java code

    Hi Team,
    I am tring to call IAC Iview from WebDynpro Java code. we are passing value but blank page  displayed and there is no error show on error log.
    Below is Java Code which i am calling.
      public void wdDoInit()
          try {
                String strURL = "portal_content/TestSRM/iView/TestSRM";                           //WDProtocolAdapter.getProtocolAdapter().getRequestParameter("application");
                 String random = WDProtocolAdapter.getProtocolAdapter().getRequestObject().getParameter("random_code");     
                 //wdContext.currentContextElement().setRandomNumber(random);
    //below we are call URL           
    WDPortalNavigation.navigateAbsolute("ROLES://portal_content/TestSRM/iView/TestSRM?VAL="+random,WDPortalNavigationMode.SHOW_INPLACE,(String)null, (String)null,
                       WDPortalNavigationHistoryMode.NO_DUPLICATIONS,(String)null,(String)null, " ");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
    I am passing value from URL.
    http://<host Name>:<port>/webdynpro/resources/local/staruser/StarUser?random_code=111111111
    when we call above URL we getting blank screen.
    Regards
    Pankaj Kamble

    Hi Vinod,
    read this document (from pages 7 ).
    <a href="https://www.sdn.sap.comhttp://www.sdn.sap.comhttp://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/b5380089-0c01-0010-22ae-bd9fa40ddc62">https://www.sdn.sap.comhttp://www.sdn.sap.comhttp://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/b5380089-0c01-0010-22ae-bd9fa40ddc62</a>
    In addition lok at these links: (Navigation Between Web Dynpro Applications in the Portal)
    <a href="http://help.sap.com/saphelp_erp2005/helpdata/en/ae/36d93f130f9115e10000000a155106/frameset.htm">http://help.sap.com/saphelp_erp2005/helpdata/en/ae/36d93f130f9115e10000000a155106/frameset.htm</a>
    <a href="http://help.sap.com/saphelp_erp2004/helpdata/en/b5/424f9c88970f48ba918ad68af9a656/frameset.htm">http://help.sap.com/saphelp_erp2004/helpdata/en/b5/424f9c88970f48ba918ad68af9a656/frameset.htm</a>
    It may be helpful for you.
    Best regards,
    Gianluca Barile

  • How to register a dll from the java code

    Hi,
    We can use windows utility Regsv32.exe to register a the components. Is it possible to register the Dll from the java code. If possible please try to provide me the code for the registring the dll.
    Thanks in adavance
    Aswad

    if a try this variant it doesnt work
    static {
            System.loadLibrary("shellExec.dll");
    but in this way it work (without .dll extension)
    static {
            System.loadLibrary("shellExec");
    }

  • How to start an executable program from a java program ?

    Hi,
    does someone know how to start an executable program from a JAVA program ?
    Thanks, Fred.

    Take a look at the Runtime class.
    -S-

  • How do I pass an error status from my java code back to the Program Job Ser

    How do I pass an error status from my java code back to the Program Job Server?
    I have a jar program object that reports a scheduled status of "Success" even if the java code errors out.

    Exceptions thrown from the program object are ignored by the program job server.
    You need to configure the Program Object, then stream out a special string sequence to the stdout of the Program Object, to set the scheduled instance status to Failed.
    Look up SAP KBase  1201804 - How to programmatically set the status of a Program object to "Failed"
    Sincerely,
    Ted Ueda

  • Do quires from my java code

    i am supposed to work on a project that dos query from my java code on one of the web medical sites,but I dont how to start on this ,if any one could help me with an exmple or link??

    hi,
    thank you for responding on my email , I went to the website you recommended ,but it gave me list of projects ,I dont know what to choose , please be advised I am just A biggennner and I have to do ap roject, that uses any language either java or c++ to do an automatic search from a certain website and retrieve the recordes to process ,
    I dont know which easier to work with c++ or java ,and how to do theat qurey search,
    i will be more than grateful if you advice and perhaps lead me to an example on this
    all the best.

  • Using a Java Program to execute JavaScript from a website

    Okay, let me try and explain as good as I can. I have a program now, that searched through all files and folders in Unix (Solaris machine) and gets the list of files in the bin and sbin folders.
    Well, I want to find the version of each of these files from the bin and sbin folders and not all of them have the -v, -V or -version feature (or any others there may be). But, I found this page:
    http://sunsolve.sun.com/pub-cgi/fileFingerprints.pl
    where if you go to the page I can find an md5 number, place it in the box and click submit to find versions, if available.
    My thing is, as I find the number from my java program, I want to be able to open this page, insert in the box (or maybe even call the javascript function) and then submit to get the version numbers. That would mean I could need to get back info from the javascript function.
    I hope that explains what I need and hope that someone can help me.
    I have found information on the JSObject, but not sure what that means exactly so if someone can explain this:
    JSObject win = JSObject.getWindow(this);
    JSObject doc = (JSObject) win.getMember("document");
    JSObject loc = (JSObject) doc.getMember("location");
    String s = (String) loc.getMember("href"); // document.location.href
    win.call("f", null);     
    it would be greatly appreciated. But, this may not even be what I need. I see that the win.call is where I would call the function needed and I am guessing the null could be where I put the number if that is how the function i need works like that. But, what I dont understand is what "document" is and "location". Also, i the "href" the page I put above? I am just lost on that. Hope someone will understand.
    Thank again for the help!

    Exactly so. Check out the last item - reading and writing to a URL - writing to a URL.
    Pulling out the form code from that page:
    <FORM METHOD="POST"  ENCTYPE="application/x-www-form-urlencoded">
    <TEXTAREA NAME="md5list" ROWS=16 COLS=66 MAXLENGTH="33792"></TEXTAREA>
    <BR><INPUT TYPE="submit" NAME="submit" VALUE="submit">
    <INPUT TYPE="reset" VALUE="reset">
    </FORM>You should end up with something like this (copying and pasting from the example):
    URL url = new URL("http://http://sunsolve.sun.com/pub-cgi/fileFingerprints.pl");
    String sNumbers = "put your serial nos in this string"
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    PrintWriter out = new PrintWriter(connection.getOutputStream());
    out.println("md5list=" + sNumbers);
    out.close();
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null){
      // read in the HTML page result for later parsing?
    in.close();

  • 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

  • IPhone 4 (No longer rotates) after 4.2.1

    Hi, has anyone had an issue after updating to OS4.2.1 and loosing the abilty for the phone to rotate. I have checked the button to lock the orientation is not turned on but it has no effect. The phone will simply no longer rotate in any application,

  • Aperture vs PSE8 vs iPhoto

    I have all three SW's on a Mac and have three questions: 1. Is there really a difference between Aperture and PSE8 when it comes to basic photo manipulation? They both offer SW for use with RAW images but at least with PSE I can do some broader and d

  • Can I upgrade from MAC OS X v10.5.8 to Lion without upgrading to snow Leopard first?

    I have the Core 2 duo and 4 GB memory, but it looks as if Apple makes me first purchase snow L then purchase Lion to upgrade via their download?

  • CK40N - Update for material with price control 'V'

    i Experts, When im running standard cost estimate in CK40N, say for material types semi finished. The components that is raw materials of the SFG is also updated with the price, meaning for a raw material with price control 'V' has a price of 10, aft

  • Folders at Top in Finder and Home/End Keys

    As a recently converted former Windows user, I'm trying to get comfortable with the the Mac way of doing things. A lot I like, but two things I'd like to change: the sorting of folders alphabetically in Finder (instead of appearing before the files)