Java code invokes shell script and passes in parameter implementation DB2 database table export to file

Source: Internet
Author: User
Tags getmessage

This article calls the shell script through Java code and passes in the parameter implementation DB2 the database table exports to the file, the code is as follows:

Import Java.io.file;import java.io.ioexception;import java.io.inputstreamreader;import java.io.LineNumberReader; Import Java.util.HashMap; Import Org.slf4j.logger;import org.slf4j.LoggerFactory; Import Com.*.dmp.bean.agentconfiginfo;import com.*.dmp.bean.mapkeys;import com.*.dmp.bean.runstatus;import com.*. Dmp.common.SpringUtils; public class ExportDataServiceDB2 {agentconfiginfo Agentconfiginfo = Springutils.getcontext (). Getbean (Agentconfiginf    O.class);    Private Logger LOG = Loggerfactory.getlogger (Exportdataservicedb2.class);    Private StringBuffer resultmsg = new StringBuffer ();    String IsOK = "0"; private string Exportshell = Agentconfiginfo.getexport_shell ();//private String exportcmd = Agentconfiginfo.getexport_    CMD ();         Private StringBuffer Exportfilepath = Agentconfiginfo.getexport_file_path (); /** * @Title: ExportData * @Description: Invoke shell script to implement DB2 data export * @param dataMap * @throws IOException for methods Description of the parameter * @return Hashmap<string,string> return type */public hashmap<string, string> exportdata (hashmap<string, string> dataMap) throws Ioexce        ption {String DbSchema = datamap.get ("Db_schema");        String DbUser = Datamap.get ("Db_user");        String Dbpassword = Datamap.get ("Db_password");        String tableName = datamap.get ("table_name");        String interfile = Datamap.get ("Inter_file");        String delimiter = datamap.get ("delimiter");                 String exportlimit = Datamap.get ("Export_limit");        String FilePath = Mkdirectory (Exportfilepath, interfile);                 Datamap.put ("File_abs_path", FilePath); String Cmdpara = Createexportshellparams (DbSchema, DbUser, Dbpassword, TableName, FilePath, delimiter, Expo         Rtlimit);        Log.info ("Export Parameters:" + Cmdpara);                 Resultmsg.append ("Export Parameters:" + Cmdpara + "\ n");                 String cmd = Exportshell + "" + Cmdpara;        Process PS = null; InputstreamreadeR ISR = null;        LineNumberReader input = null;         String line = null;            try {log.info ("Run Command:" + cmd);                         Resultmsg.append ("Run Command:" + cmd + "\ n");            PS = Runtime.getruntime (). exec (CMD); ISR = new InputStreamReader (Ps.getinputstream ());             Input read and print using reader = new LineNumberReader (ISR);                while (null! = (line = Input.readline ())) {Log.info (line);                Resultmsg.append (line);                    if (Line.contains ("Failed") | | | line.contains ("failed") | | line.contains ("failed") | | line.contains ("error")} {                    IsOK = Runstatus.export_fail;                    Datamap.put ("Export_status", IsOK); Datamap.put ("Proc_log", resultmsg.tostring ());//DataMap = Packageresult (IsOK, resultmsg.tostring ());                Assemble the returned message return DATAMAP; } else {IsOK = Runstatus.proc_run_sucCess;              }}/if (0! = ps.waitfor ()) {//IsOK = runstatus.export_fail;// } else {//IsOK = runstatus.proc_run_success;//}} catch (IOException e)            {Log.error ("Run the Command Exception:" + cmd + ":" + e.getmessage ());            Resultmsg.append ("Run the Command Exception:" + cmd + ":" + e.getmessage () + "\ n");        IsOK = Runstatus.export_fail;            } finally {if (null! = input) {input.close ();            } if (null! = ISR) {isr.close ();                } if (null! = PS) {Ps.destroy ();            PS = null;        }} datamap.put ("Export_status", IsOK); Datamap.put ("Proc_log", resultmsg.tostring ());//DataMap = Packageresult (IsOK, resultmsg.tostring ());     Assemble the returned message return DATAMAP; }/** * @Title: CreateexpOrtshellparams * @Description: Assembly parameters * @param msgId * @param dbSchema * @param dbUser * @param dbpass Word * @param tableName * @param filePath * @param delimiter * @param exportlimit * @return String return class Type * @throws */private string Createexportshellparams (String DbSchema, String dbUser, String Dbpass  Word, String tableName, String FilePath, String delimiter, String exportlimit) {StringBuilder params =        New StringBuilder (); Params.append (DbSchema + ""). Append (DbUser + ""). Append (Dbpassword + ""). Append (TableName + ""). Append (fil         Epath + ""). Append (delimiter + ""). Append (Exportlimit);    return params.tostring ();     }/** * @Title: Mkdirectory * @Description: According to the configured path and file name, determine whether the file path exists, if not, then create, stitching the export file absolute path. * @param filePath * @param interfile * @return Describes the parameters of the method * @return String return type * @throws */privat E String mkdirectory (StringBuffer filEpath, String interfile) {File File = new file (filepath.tostring ());             if (File.isdirectory ()) {if (filepath.tostring (). EndsWith ("/")) {filepath.append (interfile);            } else {filepath.append ("/"). Append (Interfile);            }} else {Log.info ("The file path is not exists, need to being created now.");            File.mkdir ();            if (filepath.tostring (). EndsWith ("/")) {filepath.append (interfile);            } else {filepath.append ("/"). Append (Interfile);    }} return filepath.tostring (); /** return Message Assembly result */private hashmap<string, string> packageresult (String IsOK, String resultmsg) {Hashm        ap<string, string> hsmap = new hashmap<string, string> ();        Hsmap.put (Mapkeys.proc_status, IsOK);        Hsmap.put (Mapkeys.proc_log, resultmsg);    return hsmap; } }

  

The incoming execution parameters are placed in a map (hashmap<string, string> dataMap):

/**  EXPORT TEST  */map.put ("Db_schema", "MD") Map.put ("Db_user", "root"), Map.put ("Db_password", "root"); Map.put ("table_name", "Inter_log"), Map.put ("Inter_file", "Inter_log_20140915.avl"), Map.put ("delimiter", "|"); Map.put ("Export_limit", "" ");

  

After the code executes, the execution log and execution results are also returned in the map:

Datamap.put ("Export_status", IsOK);d atamap.put ("Proc_log", resultmsg.tostring ()); return DATAMAP;

  

Execution result Interface:

Java code invokes shell script and passes in parameter implementation DB2 database table export to file

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.