Question

I need to browse a JackRabbit repository. I am using the following code to connect:

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

However, if for some reason some parameter is incorrect, my webapp will get stuck. What i need to do is set a timeout connection (like 30 seconds) but I can't find any method in the jcr API.
Any advice or code sample regarding how I could do that?

PS: The version of jackrabbit that I use is 2.2.10.

Was it helpful?

Solution

So I managed to add a connection timeout using FutureTask.
I have created a class that implements the Callable interface and in the call() method I put the connection logic:

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;
}

Next, in my connector class inside getSession() function I created a FutureTask, executed it and put there a connection timeout:

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top