2013-05-30 51 views
2

我最近遇到了這個問題,並想知道是否有人可以幫我解釋一下。通過運行時查詢參數從Java調用mongoexport(編碼問題?)

我正試圖從Java應用程序執行mongoexport,並將導出限制在特定日期範圍內。我構建了我的查詢命令,並將其傳遞給Runtime.exec。這返回代碼2,表示「位置選項太多」。

但是,如果我將傳遞給exec的字符串(在下面註銷)中,並在命令行上運行它,它會完美地工作!

我已經縮小下來的「查詢」的參數 - 如果我不建這個命令,該命令將被通過的Runtime.exec()

我猜它完美地執行一些編碼問題與查詢參數中的引號有關,但我不能爲我的生活弄清楚如何解決它。

下面的代碼:

@Override 
public void doWork() { 
    logger.info("Doing work"); 

    //get the host for performing the mongo dump 
    String mongohome = GlimmerServer.config.getString("mongo.home"); 
    String host = GlimmerServer.config.getString("mongo.dumphost"); 
    String port = GlimmerServer.config.getString("mongo.dumpport"); 
    String db = GlimmerServer.config.getString("mongo.dumpdb"); 
    String collection = "stats_advert_daily"; 
    String query = "'{date : new Date(1320451200000)}'"; //needs to be a proper query for mongo 
    String outputlocation = "/tmp/output.txt"; //needs to be asigned a random number name  

    String command = String.format(mongohome+"/bin/mongoexport " + 
      "--host %s " + 
      "--port %s " + 
      "--db %s " +   
      "--collection %s " +     
      "--query %s " + 
      "--fields _id,account_rid " +    
      "--out %s " +   
      "--slaveOk true " +   
      "--csv " + 
      "-vvvvv", 
      host,port,db,collection,query,outputlocation); 

    logger.info(command); 

    try{    
      Runtime rt = Runtime.getRuntime();    
      Process pr = rt.exec(command); 
      StreamGobbler errorGobbler = new StreamGobbler(pr.getErrorStream(),"ERROR",logger); 
      StreamGobbler outputGobbler = new StreamGobbler(pr.getInputStream(),"OUTPUT",logger); 
      errorGobbler.start(); 
      outputGobbler.start(); 
      int exitVal = pr.waitFor(); 

      logger.info(String.format("Process executed with exit code %d",exitVal)); 

    }catch(Exception e){ 
     logger.error(String.format("Error running task. Exception %s", e.toString())); 
    }  

} 

所有幫助感激!

乾杯, 道格

回答

1

原來這是與此相關的問題:Command fails in script, works in command line

String query = "'{date : new Date(1320451200000)}'"; 

查詢中的空間是造成一些解析問題。

另外,不需要單引號。因此,offfending代碼現在看起來是這樣的:

String query = "{date:Date(1320451200000)}"; 

現在,如果我複製整個命令到一個shell它不工作(需要單引號),但在貫穿的Runtime.exec()。

+0

謝謝!這個對我有用 – Guillaume