1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.jcr_blog.persistence;
23
24 import java.io.*;
25 import java.util.Arrays;
26 import java.util.Properties;
27 import javax.annotation.PostConstruct;
28 import javax.enterprise.context.ApplicationScoped;
29 import javax.enterprise.context.RequestScoped;
30 import javax.enterprise.inject.Disposes;
31 import javax.enterprise.inject.Produces;
32 import javax.inject.Inject;
33 import javax.inject.Named;
34 import javax.jcr.Credentials;
35 import javax.jcr.NamespaceRegistry;
36 import javax.jcr.Repository;
37 import javax.jcr.RepositoryException;
38 import javax.jcr.Session;
39 import javax.jcr.SimpleCredentials;
40 import org.slf4j.Logger;
41 import static org.jcr_blog.persistence.JcrBlogNamespace.*;
42
43
44
45
46
47 @Named
48 @ApplicationScoped
49 public class SessionProvider {
50
51 @Inject
52 private Logger logger;
53 @Inject
54 private Repository repository;
55
56 private Credentials credentials;
57
58 @PostConstruct
59 void init() throws Exception {
60 final Properties p = new Properties();
61 try {
62 InputStream in = this.getClass().getClassLoader().getResourceAsStream("jcr.properties");
63 if (in == null) {
64 this.logger.warn("jcr.properties file not found => using defaults");
65 } else {
66 p.load(in);
67 }
68 this.credentials = new SimpleCredentials(
69 p.getProperty("username", "anonymous"),
70 p.getProperty("password", "").toCharArray());
71
72 } catch (IOException ex) {
73 this.logger.error("unable to open required configuration file jcr.properties", ex);
74 this.credentials = null;
75 }
76
77 }
78
79 private void initNamespaceRegistry(final Session session) throws RepositoryException {
80 try {
81 final NamespaceRegistry namespaceRegistry = session.getWorkspace().getNamespaceRegistry();
82 if (!Arrays.asList(namespaceRegistry.getURIs()).contains(JCRBLOG_NAMESPACE_URI)) {
83 this.logger.info("adding missing namespace binding for: {}", JCRBLOG_NAMESPACE_URI);
84 namespaceRegistry.registerNamespace(JCRBLOG_NAMESPACE_PREFIX, JCRBLOG_NAMESPACE_URI);
85 } else if (!namespaceRegistry.getPrefix(JCRBLOG_NAMESPACE_URI).equals(JCRBLOG_NAMESPACE_PREFIX)) {
86 throw new AssertionError(String.format("namespace %s bound to wrong prefix! expected %s but was %s", JCRBLOG_NAMESPACE_URI, JCRBLOG_NAMESPACE_PREFIX, namespaceRegistry.getPrefix(JCRBLOG_NAMESPACE_URI)));
87 }
88
89 } catch (RepositoryException ex) {
90 this.logger.error("problem initializing namespace registry", ex);
91 throw ex;
92 }
93 }
94
95
96
97
98
99 @Produces
100 @Named
101 @RequestScoped
102 @JcrSession
103 public Session getSession() throws RepositoryException {
104 this.logger.debug("creating jcr session");
105 final Session session = this.repository.login(credentials);
106 initNamespaceRegistry(session);
107 return session;
108 }
109
110
111
112
113
114
115 public void closeSession(@Disposes @JcrSession final Session session) {
116 this.logger.debug("disposing jcr session");
117 session.logout();
118 }
119
120 }