How to create JCR connection

In a nutshell, I want to establish a JCR connection with the repository based on Day Communique CMS.  The most common approach for getting the connection by using  JNDI name exposed by Day communique itself . But in this approach you need to know few extra credentials also in terms of userid/password along with the workspace name.

The sample code is as given below.

public static Session getSession() throws NamingException, RepositoryException {

Hashtable<String, String> env = new Hashtable<String, String>();
env.put(”java.naming.provider.url”, “http://jcr.day.com”);
env.put(”java.naming.factory.initial”,
“com.day.util.jndi.provider.MemoryInitialContextFactory”);
InitialContext initial = new InitialContext(env);
Object obj = initial.lookup(”crxauthor”);
Repository repository = (Repository) PortableRemoteObject.narrow(obj, Repository.class);
String workspace = “live_author”;
Session session = repository.login(new SimpleCredentials(”admin”, “admin”.toCharArray()), workspace);
log.error(”Connection successful”);
return session;
}

The above code is perfectly fine if you know all the credentials. But say there could be some scenario where all those credentials will not be known by you.  But nothing to worry. The following piece of code will creating the connection for you irrespective of the required credentials.

public static Session getSession(Ticket ticket) {
Ticket realTicket = ticket;
while (true)
{
try {
Method getTicket = realTicket.getClass().getMethod(”getTicket”, new Class[]{});
getTicket.setAccessible(true);
realTicket = (Ticket) getTicket.invoke(realTicket, new Object[]{});
} catch (Exception e) {
break;
}
}
final Session session = ((TicketAdapter) realTicket).getSession();
try {
session.refresh(true);
} catch (RepositoryException e) {
log.error(”problem”, e);
}
return session;
}

Leave a Reply