001 package com.khubla.pragmatach.plugin.jcr; 002 003 import javax.jcr.Repository; 004 import javax.jcr.Session; 005 import javax.jcr.SimpleCredentials; 006 007 import org.apache.jackrabbit.commons.JcrUtils; 008 import org.apache.log4j.Logger; 009 010 import com.khubla.pragmatach.framework.api.PragmatachException; 011 import com.khubla.pragmatach.framework.application.Application; 012 013 /** 014 * @author tome 015 */ 016 public class JCRSessionFactory { 017 /** 018 * logger 019 */ 020 private final Logger logger = Logger.getLogger(this.getClass()); 021 022 /** 023 * get password 024 */ 025 private char[] getPassword() throws PragmatachException { 026 try { 027 final String pwd = Application.getConfiguration().getParameter("jcr.password"); 028 if (null != pwd) { 029 return pwd.toCharArray(); 030 } 031 return null; 032 } catch (final Exception e) { 033 throw new PragmatachException("Exception in getPassword", e); 034 } 035 } 036 037 /** 038 * get a repository Session 039 */ 040 public Session getSession() throws PragmatachException { 041 try { 042 /* 043 * connect to repo 044 */ 045 final String repositoryURL = getURL(); 046 if ((null != repositoryURL) && (repositoryURL.length() > 0)) { 047 final Repository repository = JcrUtils.getRepository(repositoryURL); 048 if (null != repository) { 049 /* 050 * log 051 */ 052 logger.info("Found repository '" + repositoryURL + "'"); 053 /* 054 * login to workspace 055 */ 056 final SimpleCredentials credentials = new SimpleCredentials(getUsername(), getPassword()); 057 final String workspace = getWorkspace(); 058 final Session session = repository.login(credentials, workspace); 059 /* 060 * log 061 */ 062 logger.info("Logged into workspace '" + workspace + "'"); 063 /* 064 * done 065 */ 066 return session; 067 } else { 068 throw new PragmatachException("Unable to connect to repository '" + repositoryURL + "'"); 069 } 070 } else { 071 throw new PragmatachException("Please suppy a repository URL"); 072 } 073 } catch (final Exception e) { 074 throw new PragmatachException("Exception in getRepository", e); 075 } 076 } 077 078 /** 079 * get url 080 */ 081 private String getURL() throws PragmatachException { 082 try { 083 return Application.getConfiguration().getParameter("jcr.url"); 084 } catch (final Exception e) { 085 throw new PragmatachException("Exception in getUsername", e); 086 } 087 } 088 089 /** 090 * get username 091 */ 092 private String getUsername() throws PragmatachException { 093 try { 094 return Application.getConfiguration().getParameter("jcr.username"); 095 } catch (final Exception e) { 096 throw new PragmatachException("Exception in getUsername", e); 097 } 098 } 099 100 /** 101 * get workspace 102 */ 103 private String getWorkspace() throws PragmatachException { 104 try { 105 return Application.getConfiguration().getParameter("jcr.workspace"); 106 } catch (final Exception e) { 107 throw new PragmatachException("Exception in getUsername", e); 108 } 109 } 110 }