]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/internal/kernel/KernelUtils.java
Make deploy config initialisation more robust.
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / internal / kernel / KernelUtils.java
1 package org.argeo.cms.internal.kernel;
2
3 import static org.argeo.cms.internal.kernel.KernelConstants.WEBDAV_PRIVATE;
4 import static org.argeo.cms.internal.kernel.KernelConstants.WEBDAV_PUBLIC;
5
6 import java.io.File;
7 import java.io.IOException;
8 import java.net.MalformedURLException;
9 import java.net.URI;
10 import java.net.URISyntaxException;
11 import java.net.URL;
12 import java.nio.file.Path;
13 import java.nio.file.Paths;
14 import java.security.PrivilegedAction;
15 import java.util.Dictionary;
16 import java.util.Enumeration;
17 import java.util.Hashtable;
18 import java.util.Properties;
19 import java.util.TreeSet;
20
21 import javax.jcr.Node;
22 import javax.jcr.Repository;
23 import javax.jcr.RepositoryException;
24 import javax.jcr.Session;
25 import javax.security.auth.Subject;
26 import javax.security.auth.login.LoginContext;
27 import javax.security.auth.login.LoginException;
28 import javax.servlet.http.HttpServletRequest;
29
30 import org.apache.commons.logging.Log;
31 import org.argeo.cms.CmsException;
32 import org.argeo.cms.auth.AuthConstants;
33 import org.argeo.jcr.ArgeoJcrConstants;
34 import org.osgi.framework.Bundle;
35 import org.osgi.framework.BundleContext;
36 import org.osgi.framework.FrameworkUtil;
37
38 /** Package utilities */
39 class KernelUtils implements KernelConstants {
40 final static String OSGI_INSTANCE_AREA = "osgi.instance.area";
41 final static String OSGI_CONFIGURATION_AREA = "osgi.configuration.area";
42
43 static Dictionary<String, ?> asDictionary(Properties props) {
44 Hashtable<String, Object> hashtable = new Hashtable<String, Object>();
45 for (Object key : props.keySet()) {
46 hashtable.put(key.toString(), props.get(key));
47 }
48 return hashtable;
49 }
50
51 static Dictionary<String, ?> asDictionary(ClassLoader cl, String resource) {
52 Properties props = new Properties();
53 try {
54 props.load(cl.getResourceAsStream(resource));
55 } catch (IOException e) {
56 throw new CmsException("Cannot load " + resource + " from classpath", e);
57 }
58 return asDictionary(props);
59 }
60
61 static File getExecutionDir(String relativePath) {
62 File executionDir = new File(getFrameworkProp("user.dir"));
63 if (relativePath == null)
64 return executionDir;
65 try {
66 return new File(executionDir, relativePath).getCanonicalFile();
67 } catch (IOException e) {
68 throw new CmsException("Cannot get canonical file", e);
69 }
70 }
71
72 static File getOsgiInstanceDir() {
73 return new File(getBundleContext().getProperty(OSGI_INSTANCE_AREA).substring("file:".length()))
74 .getAbsoluteFile();
75 }
76
77 static Path getOsgiInstancePath(String relativePath) {
78 return Paths.get(getOsgiInstanceUri(relativePath));
79 }
80
81 static URI getOsgiInstanceUri(String relativePath) {
82 String osgiInstanceBaseUri = getFrameworkProp(OSGI_INSTANCE_AREA);
83 return safeUri(osgiInstanceBaseUri + (relativePath != null ? relativePath : ""));
84 }
85
86 // static String getOsgiInstancePath(String relativePath) {
87 // try {
88 // if (relativePath == null)
89 // return getOsgiInstanceDir().getCanonicalPath();
90 // else
91 // return new File(getOsgiInstanceDir(), relativePath).getCanonicalPath();
92 // } catch (IOException e) {
93 // throw new CmsException("Cannot get instance path for " + relativePath,
94 // e);
95 // }
96 // }
97
98 static File getOsgiConfigurationFile(String relativePath) {
99 try {
100 return new File(new URI(getBundleContext().getProperty(OSGI_CONFIGURATION_AREA) + relativePath))
101 .getCanonicalFile();
102 } catch (Exception e) {
103 throw new CmsException("Cannot get configuration file for " + relativePath, e);
104 }
105 }
106
107 static String getFrameworkProp(String key, String def) {
108 String value = getBundleContext().getProperty(key);
109 if (value == null)
110 return def;
111 return value;
112 }
113
114 static String getFrameworkProp(String key) {
115 return getFrameworkProp(key, null);
116 }
117
118 // Security
119 static Subject anonymousLogin() {
120 Subject subject = new Subject();
121 LoginContext lc;
122 try {
123 lc = new LoginContext(AuthConstants.LOGIN_CONTEXT_ANONYMOUS, subject);
124 lc.login();
125 return subject;
126 } catch (LoginException e) {
127 throw new CmsException("Cannot login as anonymous", e);
128 }
129 }
130
131 // HTTP
132 static void logRequestHeaders(Log log, HttpServletRequest request) {
133 if (!log.isDebugEnabled())
134 return;
135 for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) {
136 String headerName = headerNames.nextElement();
137 Object headerValue = request.getHeader(headerName);
138 log.debug(headerName + ": " + headerValue);
139 }
140 log.debug(request.getRequestURI() + "\n");
141 }
142
143 static void logFrameworkProperties(Log log) {
144 BundleContext bc = getBundleContext();
145 for (Object sysProp : new TreeSet<Object>(System.getProperties().keySet())) {
146 log.debug(sysProp + "=" + bc.getProperty(sysProp.toString()));
147 }
148 // String[] keys = { Constants.FRAMEWORK_STORAGE,
149 // Constants.FRAMEWORK_OS_NAME, Constants.FRAMEWORK_OS_VERSION,
150 // Constants.FRAMEWORK_PROCESSOR, Constants.FRAMEWORK_SECURITY,
151 // Constants.FRAMEWORK_TRUST_REPOSITORIES,
152 // Constants.FRAMEWORK_WINDOWSYSTEM, Constants.FRAMEWORK_VENDOR,
153 // Constants.FRAMEWORK_VERSION, Constants.FRAMEWORK_STORAGE_CLEAN,
154 // Constants.FRAMEWORK_LANGUAGE, Constants.FRAMEWORK_UUID };
155 // for (String key : keys)
156 // log.debug(key + "=" + bc.getProperty(key));
157 }
158
159 static Session openAdminSession(Repository repository) {
160 return openAdminSession(repository, null);
161 }
162
163 static Session openAdminSession(final Repository repository, final String workspaceName) {
164 ClassLoader currentCl = Thread.currentThread().getContextClassLoader();
165 Thread.currentThread().setContextClassLoader(KernelUtils.class.getClassLoader());
166 LoginContext loginContext;
167 try {
168 loginContext = new LoginContext(AuthConstants.LOGIN_CONTEXT_DATA_ADMIN);
169 loginContext.login();
170 } catch (LoginException e1) {
171 throw new CmsException("Could not login as data admin", e1);
172 } finally {
173 Thread.currentThread().setContextClassLoader(currentCl);
174 }
175 return Subject.doAs(loginContext.getSubject(), new PrivilegedAction<Session>() {
176
177 @Override
178 public Session run() {
179 try {
180 return repository.login(workspaceName);
181 } catch (RepositoryException e) {
182 throw new CmsException("Cannot open admin session", e);
183 }
184 }
185
186 });
187 }
188
189 /**
190 * @return the {@link BundleContext} of the {@link Bundle} which provided
191 * this class, never null.
192 * @throws CmsException
193 * if the related bundle is not active
194 */
195 public static BundleContext getBundleContext(Class<?> clzz) {
196 Bundle bundle = FrameworkUtil.getBundle(clzz);
197 BundleContext bc = bundle.getBundleContext();
198 if (bc == null)
199 throw new CmsException("Bundle " + bundle.getSymbolicName() + " is not active");
200 return bc;
201 }
202
203 private static BundleContext getBundleContext() {
204 return getBundleContext(KernelUtils.class);
205 }
206
207 private static URI safeUri(String uri) {
208 if (uri == null)
209 throw new CmsException("URI cannot be null");
210 try {
211 return new URI(uri);
212 } catch (URISyntaxException e) {
213 throw new CmsException("Dadly formatted URI " + uri, e);
214 }
215 }
216
217 // DATA
218 public static StringBuilder getServerBaseUrl(HttpServletRequest request) {
219 try {
220 URL url = new URL(request.getRequestURL().toString());
221 StringBuilder buf = new StringBuilder();
222 buf.append(url.getProtocol()).append("://").append(url.getHost());
223 if (url.getPort() != -1)
224 buf.append(':').append(url.getPort());
225 return buf;
226 } catch (MalformedURLException e) {
227 throw new CmsException("Cannot extract server base URL from " + request.getRequestURL(), e);
228 }
229 }
230
231 public static String getDataUrl(Node node, HttpServletRequest request) throws RepositoryException {
232 try {
233 StringBuilder buf = getServerBaseUrl(request);
234 buf.append(getDataPath(node));
235 return new URL(buf.toString()).toString();
236 } catch (MalformedURLException e) {
237 throw new CmsException("Cannot build data URL for " + node, e);
238 }
239 }
240
241 public static String getDataPath(Node node) throws RepositoryException {
242 assert node != null;
243 String userId = node.getSession().getUserID();
244 // if (log.isTraceEnabled())
245 // log.trace(userId + " : " + node.getPath());
246 StringBuilder buf = new StringBuilder();
247 boolean isAnonymous = userId.equalsIgnoreCase(AuthConstants.ROLE_ANONYMOUS);
248 if (isAnonymous)
249 buf.append(WEBDAV_PUBLIC);
250 else
251 buf.append(WEBDAV_PRIVATE);
252 // TODO convey repo alias vie repository properties
253 return buf.append('/').append(ArgeoJcrConstants.ALIAS_NODE).append('/').append(node.getSession().getWorkspace().getName())
254 .append(node.getPath()).toString();
255 }
256
257 public static String getCanonicalUrl(Node node, HttpServletRequest request) throws RepositoryException {
258 try {
259 StringBuilder buf = getServerBaseUrl(request);
260 buf.append('/').append('!').append(node.getPath());
261 return new URL(buf.toString()).toString();
262 } catch (MalformedURLException e) {
263 throw new CmsException("Cannot build data URL for " + node, e);
264 }
265 // return request.getRequestURL().append('!').append(node.getPath())
266 // .toString();
267 }
268
269
270 private KernelUtils() {
271
272 }
273 }