簡體   English   中英

將參數從Shell腳本傳遞到Java類

[英]Passing parameters from shell script to java class

我知道那里有很多相關問題,但是我似乎停留在一些瑣碎的問題上。 我已經在Wavemaker中編寫了一個Java服務,只需單擊一個按鈕,即可將2個字符串參數(綁定到前端的編輯器)傳遞到Linux機器上的shell腳本中。 我在Java服務中使用流程生成器來訪問Shell腳本。 代碼如下。

package com.wavemeker;
import com.wavemaker.runtime.javaservice.JavaServiceSuperClass;
import com.wavemaker.runtime.service.annotations.ExposeToClient;
import java.io.IOException;
import java.io.File;
/*
 * This is a client-facing service class.  All
 * public methods will be exposed to the client.  Their return
 * values and parameters will be passed to the client or taken
 * from the client, respectively.  This will be a singleton
 * instance, shared between all requests.  
 * To log, call the superclass method log(LOG_LEVEL, String) or   log(LOG_LEVEL, String, Exception).
 * LOG_LEVEL is one of FATAL, ERROR, WARN, INFO and DEBUG to modify your log  level.
* For info on these levels, look for tomcat/log4j documentation
*/
@ExposeToClient
public class xmlGen extends JavaServiceSuperClass {
    public void readScript(String a, String b) throws IOException, InterruptedException
     {             
              final File dir = new File("/var/lib/tomcat7/webapps/sh/");
              final String shellScript = "./master_script.sh";
              ProcessBuilder pb = new ProcessBuilder(shellScript, a, b);
              pb.directory(dir);
              System.out.println("Executing script...");
              Process proc = pb.start();
        try {
              int shellExitStatus = proc.waitFor();
              if(shellExitStatus != 0)
              {
                System.out.println("Success!!");    
              }
              System.out.println("Script has completed successfully.");
            }
        catch (InterruptedException e)
            {
              System.out.println("Shell Script process was interrupted and did not complete.");
              System.exit(1);
            }
    }  // end method
} // end class

這里,兩個輸入參數“ a”和“ b”綁定到Wavemaker服務變量,因此,如果我在前面的屏幕上輸入“十”和“兩個”,則這些參數是我傳遞給我的Shell腳本的參數。 實際上,它們確實沒有問題,並且執行了“ master_script.sh”。我遇到的問題是,此腳本調用了其他一些腳本,這些腳本又調用了也依賴於這兩個字符串參數的較低級Java代碼。 。master_script.sh看起來像這樣

#!/bin/bash
set -e
./script1.sh "$1" "$2"
./script2.sh "$1" "$2"  
      .
      .
      .

並舉例說明這些腳本之一; 例如,script1.sh看起來像這樣

#!/bin/bash
set -e
FILEPATH1=/var/lib/tomcat7/webapps/data/test.txt
JPATH1=/var/lib/tomcat7/webapps/java/XML/src
> $FILEPATH1 # empties file contents before writing to it...
echo "testing params $1 and $2" > $FILEPATH1
cd $JPATH1
javac pgQuery.java
java -classpath postgresql-9.3-1102.jdbc41.jar:. pgQuery "$1" "$2" >> $FILEPATH1

因此,最終我希望將Java類的輸出附加到文件“ test.txt”中。 我感到奇怪的是,回聲可以正常工作,並將我從Wavemaker輸入的參數輸出到測試文件,但是Java似乎沒有寫任何東西。 為了使事情更清楚,這部分Java通過一條預准備語句訪問了一個postgresql數據庫,並以xml格式(query_to_xml)給出了查詢結果。 為了完整起見,代碼如下:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;

public class pgQuery
{   // Begin Class
    // JDBC driver name and db URL
    static final String JDBC_DRIVER = "org.postgresql.Driver";
    static final String DB_URL = "jdbc:postgresql://path...";

    //  Database credentials
    static final String USER = "username";
    static final String PASS = "password";

public void xml(int a, int b) {   // Begin Main Method

Connection conn = null;
Statement stmt = null;

try  //***START TRY BLOCK****//
{
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
//System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

String sql0 = "select query_to_xml('select cdt as CreationDateAndTime from  table_name where x ='||?||' and  y = '||?||'', true,true,'');";

PreparedStatement ps0 = conn.prepareStatement(sql0);
ps0.setInt(1, a);
ps0.setInt(2, b);
ResultSet rs0 = ps0.executeQuery();

ResultSetMetaData rsmd = rs0.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
while(rs0.next())
{
for(int i=1;i<=numberOfColumns;i++) 
{
System.out.println(rs0.getString(i)+ " ");
}
}

ps0.close();
rs0.close();
conn.close();

}  //****END TRY BLOCK*

catch(SQLException se){
//Handle errors for JDBC
System.out.println("Error with JDBC Connection!!");
se.printStackTrace();
}
catch(Exception e){
//Handle errors for Class.forName
System.out.println("Error with Class.forName... Driver Related!!");
e.printStackTrace();
}
finally{
//finally block to close resources
try{
if(stmt!=null)
   stmt.close();
}
catch(SQLException se2){
}
try{
if(conn!=null)
   conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}//end finally try
}//end try
}//end method

public static void main(String[] args)
{
int a1 = Integer.parseInt(args[0]);;
int b1 = Integer.parseInt(args[1]);;
pgQuery obj1 = new pgQuery();
obj1.xml(a1, b1);
} // end main method
}//end Class

如果我直接從linux執行“ master_script.sh” $ 1“” $ 2“,它的效果就很好。我已經嘗試過用雙引號和單引號將參數組合起來,但是我認為Java代碼的輸出不是按下Wavemaker前端的一個按鈕將其寫入該測試文件,我知道這是一個冗長的問題,但是如果有人對為什么這樣做不起作用有任何見解,我將不勝感激。我確定我只是忽略了一些愚蠢的事情。

在shell腳本中刪除java編譯行之后; javac pgQuery.java傳遞的參數沒有問題。 我不太明白為什么會這樣,只是偶然地我碰巧在腳本中注釋掉了該行並運行了它。 我想一旦Java代碼保持不變,就不需要在每次執行腳本時都進行編譯,但是我仍然不明白為什么每次編譯都會阻止參數的傳遞。 無論哪種方式,我都認為應該將其發布,以防對任何人有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM