2013-11-21 76 views
1

我需要瀏覽JackRabbit存儲庫。我正在使用下面的代碼來連接:如何在Java中設置連接超時到jackrabbit存儲庫

Repository repository = JcrUtils.getRepository(url); 
SimpleCredentials credentials = new SimpleCredentials(user, password.toCharArray()); 
session = repository.login(credentials, workspace); 

但是,如果由於某種原因某些參數不正確,我的web應用程序將卡住。我需要做的是設置超時連接(如30秒),但我無法在jcr API中找到任何方法。
任何意見或代碼示例關於我怎麼能做到這一點?

PS:我使用的jackrabbit版本是2.2.10。

回答

1

所以我設法添加使用FutureTask連接超時。
我已創建一個實現Callable接口的類和在call()方法我把連接邏輯:

public class CallableSession implements Callable<Session> { 

private final String url; 
private final String user; 
private final String password; 
private final String workspace; 

public CallableSession(String url, String user, String password, String workspace) { 
    this.url = url; 
    this.user = user; 
    this.password = password; 
    this.workspace = workspace; 
} 

@Override 
public Session call() throws Exception { 

    Repository repository = JcrUtils.getRepository(url); 
    SimpleCredentials credentials = new SimpleCredentials(user, password.toCharArray()); 
    Session session = repository.login(credentials, workspace); 

    return session; 
} 

接着,在內部getSession()函數I創建FutureTask我的連接器類,執行,並把有一個連接超時:

public Session getSession() { 

    if (session == null) { 
     try { 
      CallableSession cs = new CallableSession(url, user, password, workspace); 
      FutureTask<Session> future = new FutureTask<Session>(cs); 
      ExecutorService executor = Executors.newSingleThreadExecutor(); 
      executor.execute(future); 
      session = future.get(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS); 

     } catch (InterruptedException ex) { 
      Logger.getLogger(JackRabbitConnector.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (ExecutionException ex) { 
      Logger.getLogger(JackRabbitConnector.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (TimeoutException ex) { 
      Logger.getLogger(JackRabbitConnector.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
    return session; 
} 
相關問題