]> git.argeo.org Git - lgpl/argeo-commons.git/blob - AbstractCmsEntryPoint.java
931f53768eb274dffbfc1154cec3484da20d5508
[lgpl/argeo-commons.git] / AbstractCmsEntryPoint.java
1 package org.argeo.cms;
2
3 import java.security.PrivilegedAction;
4 import java.util.HashMap;
5 import java.util.Map;
6
7 import javax.jcr.Node;
8 import javax.jcr.PathNotFoundException;
9 import javax.jcr.Property;
10 import javax.jcr.Repository;
11 import javax.jcr.RepositoryException;
12 import javax.jcr.Session;
13 import javax.jcr.nodetype.NodeType;
14 import javax.security.auth.Subject;
15 import javax.security.auth.login.CredentialNotFoundException;
16 import javax.security.auth.login.LoginContext;
17 import javax.security.auth.login.LoginException;
18 import javax.servlet.http.HttpServletRequest;
19
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22 import org.argeo.ArgeoException;
23 import org.argeo.cms.auth.AuthConstants;
24 import org.argeo.cms.auth.HttpRequestCallbackHandler;
25 import org.argeo.eclipse.ui.specific.UiContext;
26 import org.argeo.jcr.JcrUtils;
27 import org.eclipse.rap.rwt.RWT;
28 import org.eclipse.rap.rwt.application.AbstractEntryPoint;
29 import org.eclipse.rap.rwt.client.WebClient;
30 import org.eclipse.rap.rwt.client.service.BrowserNavigation;
31 import org.eclipse.rap.rwt.client.service.BrowserNavigationEvent;
32 import org.eclipse.rap.rwt.client.service.BrowserNavigationListener;
33 import org.eclipse.rap.rwt.client.service.JavaScriptExecutor;
34 import org.eclipse.swt.widgets.Composite;
35 import org.eclipse.swt.widgets.Display;
36 import org.eclipse.swt.widgets.Shell;
37
38 /** Manages history and navigation */
39 public abstract class AbstractCmsEntryPoint extends AbstractEntryPoint implements CmsView {
40 private final Log log = LogFactory.getLog(AbstractCmsEntryPoint.class);
41
42 private final Subject subject;
43 private LoginContext loginContext;
44
45 private final Repository repository;
46 private final String workspace;
47 private final String defaultPath;
48 private final Map<String, String> factoryProperties;
49
50 // Current state
51 private Session session;
52 private Node node;
53 private String nodePath;// useful when changing auth
54 private String state;
55 private String page;
56 private Throwable exception;
57
58 // Client services
59 private final JavaScriptExecutor jsExecutor;
60 private final BrowserNavigation browserNavigation;
61
62 public AbstractCmsEntryPoint(Repository repository, String workspace, String defaultPath,
63 Map<String, String> factoryProperties) {
64 this.repository = repository;
65 this.workspace = workspace;
66 this.defaultPath = defaultPath;
67 this.factoryProperties = new HashMap<String, String>(factoryProperties);
68 subject = new Subject();
69
70 // Initial login
71 try {
72 loginContext = new LoginContext(AuthConstants.LOGIN_CONTEXT_USER, subject,
73 new HttpRequestCallbackHandler(UiContext.getHttpRequest()));
74 loginContext.login();
75 } catch (CredentialNotFoundException e) {
76 try {
77 loginContext = new LoginContext(AuthConstants.LOGIN_CONTEXT_ANONYMOUS, subject);
78 loginContext.login();
79 } catch (LoginException e1) {
80 throw new ArgeoException("Cannot log as anonymous", e);
81 }
82 } catch (LoginException e) {
83 throw new ArgeoException("Cannot initialize subject", e);
84 }
85 authChange(loginContext);
86
87 jsExecutor = RWT.getClient().getService(JavaScriptExecutor.class);
88 browserNavigation = RWT.getClient().getService(BrowserNavigation.class);
89 if (browserNavigation != null)
90 browserNavigation.addBrowserNavigationListener(new CmsNavigationListener());
91 }
92
93 @Override
94 protected Shell createShell(Display display) {
95 Shell shell = super.createShell(display);
96 shell.setData(RWT.CUSTOM_VARIANT, CmsStyles.CMS_SHELL);
97 display.disposeExec(new Runnable() {
98
99 @Override
100 public void run() {
101 if (log.isTraceEnabled())
102 log.trace("Logging out " + session);
103 JcrUtils.logoutQuietly(session);
104 }
105 });
106 return shell;
107 }
108
109 @Override
110 protected final void createContents(final Composite parent) {
111 UiContext.setData(CmsView.KEY, this);
112 Subject.doAs(subject, new PrivilegedAction<Void>() {
113 @Override
114 public Void run() {
115 try {
116 initUi(parent);
117 } catch (Exception e) {
118 throw new CmsException("Cannot create entrypoint contents", e);
119 }
120 return null;
121 }
122 });
123 }
124
125 /** Create UI */
126 protected abstract void initUi(Composite parent);
127
128 /** Recreate UI after navigation or auth change */
129 protected abstract void refresh();
130
131 /**
132 * The node to return when no node was found (for authenticated users and
133 * anonymous)
134 */
135 protected Node getDefaultNode(Session session) throws RepositoryException {
136 if (!session.hasPermission(defaultPath, "read")) {
137 if (session.getUserID().equals(AuthConstants.ROLE_ANONYMOUS))
138 // TODO throw a special exception
139 throw new CmsException("Login required");
140 else
141 throw new CmsException("Unauthorized");
142 }
143 return session.getNode(defaultPath);
144 }
145
146 protected String getBaseTitle() {
147 return factoryProperties.get(WebClient.PAGE_TITLE);
148 }
149
150 public void navigateTo(String state) {
151 exception = null;
152 String title = setState(state);
153 doRefresh();
154 if (browserNavigation != null)
155 browserNavigation.pushState(state, title);
156 }
157
158 @Override
159 public synchronized Subject getSubject() {
160 return subject;
161 }
162
163 @Override
164 public synchronized void logout() {
165 if (loginContext == null)
166 throw new CmsException("Login context should not be null");
167 try {
168 loginContext.logout();
169 LoginContext anonymousLc = new LoginContext(AuthConstants.LOGIN_CONTEXT_ANONYMOUS, subject);
170 anonymousLc.login();
171 authChange(anonymousLc);
172 } catch (LoginException e) {
173 throw new CmsException("Cannot logout", e);
174 }
175 }
176
177 @Override
178 public synchronized void authChange(LoginContext loginContext) {
179 if (loginContext == null)
180 throw new CmsException("Login context cannot be null");
181 this.loginContext = loginContext;
182 Subject.doAs(loginContext.getSubject(), new PrivilegedAction<Void>() {
183
184 @Override
185 public Void run() {
186 try {
187 JcrUtils.logoutQuietly(session);
188 session = repository.login(workspace);
189 if (nodePath != null)
190 try {
191 node = session.getNode(nodePath);
192 } catch (PathNotFoundException e) {
193 // logout();
194 // session = repository.login(workspace);
195 navigateTo("~");
196 throw e;
197 }
198
199 // refresh UI
200 doRefresh();
201 } catch (RepositoryException e) {
202 throw new CmsException("Cannot perform auth change", e);
203 }
204 return null;
205 }
206
207 });
208
209 }
210
211 @Override
212 public void exception(final Throwable e) {
213 AbstractCmsEntryPoint.this.exception = e;
214 log.error("Unexpected exception in CMS", e);
215 doRefresh();
216 }
217
218 protected synchronized void doRefresh() {
219 Subject.doAs(subject, new PrivilegedAction<Void>() {
220 @Override
221 public Void run() {
222 refresh();
223 return null;
224 }
225 });
226 }
227
228 /** Sets the state of the entry point and retrieve the related JCR node. */
229 protected synchronized String setState(String newState) {
230 String previousState = this.state;
231
232 Node node = null;
233 page = null;
234 this.state = newState;
235 if (newState.equals("~"))
236 this.state = "";
237
238 try {
239 int firstSlash = state.indexOf('/');
240 if (firstSlash == 0) {
241 if (session.nodeExists(state))
242 node = session.getNode(state);
243 else
244 throw new CmsException("Data " + state + " does not exist");
245 page = "";
246 } else if (firstSlash > 0) {
247 String prefix = state.substring(0, firstSlash);
248 String path = state.substring(firstSlash);
249 if (session.nodeExists(path))
250 node = session.getNode(path);
251 else
252 throw new CmsException("Data " + path + " does not exist");
253 page = prefix;
254 } else {
255 node = getDefaultNode(session);
256 page = state;
257 }
258 setNode(node);
259 String title = publishMetaData(node);
260
261 if (log.isTraceEnabled())
262 log.trace("node=" + node + ", state=" + state + " (page=" + page + ")");
263
264 return title;
265 } catch (Exception e) {
266 log.error("Cannot set state '" + state + "'", e);
267 if (previousState.equals(""))
268 previousState = "~";
269 navigateTo(previousState);
270 throw new CmsException("Unexpected issue when accessing #" + newState, e);
271 }
272 }
273
274 private String publishMetaData(Node node) throws RepositoryException {
275 // Title
276 String title;
277 if (node.isNodeType(NodeType.MIX_TITLE) && node.hasProperty(Property.JCR_TITLE))
278 title = node.getProperty(Property.JCR_TITLE).getString() + " - " + getBaseTitle();
279 else
280 title = getBaseTitle();
281
282 HttpServletRequest request = UiContext.getHttpRequest();
283 if (request == null)
284 return null;
285
286 StringBuilder js = new StringBuilder();
287 title = title.replace("'", "\\'");// sanitize
288 js.append("document.title = '" + title + "';");
289 jsExecutor.execute(js.toString());
290 return title;
291 }
292
293 // Simply remove some illegal character
294 // private String clean(String stringToClean) {
295 // return stringToClean.replaceAll("'", "").replaceAll("\\n", "")
296 // .replaceAll("\\t", "");
297 // }
298
299 protected synchronized Node getNode() {
300 return node;
301 }
302
303 private synchronized void setNode(Node node) throws RepositoryException {
304 this.node = node;
305 this.nodePath = node == null ? null : node.getPath();
306 }
307
308 protected String getState() {
309 return state;
310 }
311
312 protected Throwable getException() {
313 return exception;
314 }
315
316 protected void resetException() {
317 exception = null;
318 }
319
320 protected Session getSession() {
321 return session;
322 }
323
324 private class CmsNavigationListener implements BrowserNavigationListener {
325 private static final long serialVersionUID = -3591018803430389270L;
326
327 @Override
328 public void navigated(BrowserNavigationEvent event) {
329 setState(event.getState());
330 refresh();
331 }
332 }
333 }