This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
/
ZanataInit.java
449 lines (408 loc) · 17.5 KB
/
ZanataInit.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/*
* Copyright 2010, Red Hat, Inc. and individual contributors as indicated by the
* @author tags. See the copyright.txt file in the distribution for a full
* listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
* site: http://www.fsf.org.
*/
package org.zanata;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Proxy;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Calendar;
import java.util.Collection;
import java.util.Properties;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.LinkRef;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Observer;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.contexts.ServletLifecycle;
import org.jboss.seam.mail.MailSession;
import org.zanata.events.ServerStarted;
import org.zanata.exception.ZanataInitializationException;
import org.zanata.rest.dto.VersionInfo;
import org.zanata.util.Event;
import org.zanata.util.VersionUtility;
/**
* This class handles various tasks at startup. It disables warnings for a
* couple of verbose log categories, logs some information about the system
* and configuration, checks for stray Lucene lock files, and finally fires
* the "Zanata.startup" event.
*
* @author Christian Bauer
* @author Sean Flanigan <a href="mailto:sflaniga@redhat.com">sflaniga@redhat.com</a>
*/
@Name("zanataInit")
@Scope(ScopeType.STATELESS)
@Slf4j
public class ZanataInit {
private static final DefaultArtifactVersion MIN_EAP_VERSION =
new DefaultArtifactVersion("6.4.2.GA");
private static final DefaultArtifactVersion MIN_WILDFLY_VERSION =
new DefaultArtifactVersion("9.0.1.Final");
static {
// Prevent JBoss/WildFly from warning about gwt-servlet's
// org.hibernate.validator.ValidationMessages
Logger.getLogger("org.jboss.modules").setLevel(Level.SEVERE);
// Disable "RP discovery / realm validation disabled;"
Logger.getLogger("org.openid4java.server.RealmVerifier").setLevel(
Level.SEVERE);
// Disable "Queue with name '.*' has already been registered"
Logger.getLogger("org.richfaces.log.Components").setLevel(
Level.SEVERE);
}
@In
private ApplicationConfiguration applicationConfiguration;
@In("event")
private Event<ServerStarted> startupEvent;
@In
private EntityManagerFactory entityManagerFactory;
@Observer("org.jboss.seam.postInitialization")
public void initZanata() throws Exception {
checkAppServerVersion();
ServletContext servletContext =
ServletLifecycle.getCurrentServletContext();
String appServerHome = servletContext.getRealPath("/");
File manifestFile = new File(appServerHome, "META-INF/MANIFEST.MF");
VersionInfo zanataVersion;
Attributes atts = null;
if (manifestFile.canRead()) {
Manifest mf = new Manifest();
final FileInputStream fis = new FileInputStream(manifestFile);
try {
mf.read(fis);
} finally {
fis.close();
}
atts = mf.getMainAttributes();
}
zanataVersion = VersionUtility.getVersionInfo(atts, ZanataInit.class);
this.applicationConfiguration.setVersion(zanataVersion.getVersionNo());
this.applicationConfiguration.setBuildTimestamp(zanataVersion.getBuildTimeStamp());
this.applicationConfiguration.setScmDescribe(zanataVersion.getScmDescribe());
logBanner(zanataVersion);
if (this.applicationConfiguration.isDebug()) {
log.info("debug: enabled");
}
boolean authlogged = false;
if (applicationConfiguration.isInternalAuth()) {
log.info("Internal authentication: enabled");
authlogged = true;
}
if (applicationConfiguration.isOpenIdAuth()) {
log.info("OpenID authentication: enabled");
authlogged = true;
}
if (applicationConfiguration.isKerberosAuth()) {
log.info("SPNEGO/Kerberos authentication: enabled");
authlogged = true;
}
if (!authlogged) {
log.info("Using JAAS authentication");
}
log.info("Enable copyTrans: {}",
this.applicationConfiguration.isCopyTransEnabled());
String javamelodyDir =
System.getProperty("javamelody.storage-directory");
log.info("JavaMelody stats directory: " + javamelodyDir);
String indexBase =
System.getProperty("hibernate.search.default.indexBase");
log.info("Lucene index directory: " + indexBase);
if (indexBase != null) {
checkLuceneLocks(new File(indexBase));
}
// Email server information
MailSession mailSession = (MailSession) Component.forName(
"org.jboss.seam.mail.mailSession").newInstance();
log.info("Mail Session (JNDI): {}",
mailSession.getSessionJndiName());
startupEvent.fire(new ServerStarted());
log.info("Started Zanata...");
}
@Destroy
private void destroy() {
// Tell Hibernate Search to clean up indexes and lock files
entityManagerFactory.close();
}
private void checkAppServerVersion()
throws MalformedObjectNameException, AttributeNotFoundException,
MBeanException, ReflectionException, InstanceNotFoundException {
MBeanServer jmx = ManagementFactory.getPlatformMBeanServer();
ObjectName server = new ObjectName("jboss.as:management-root=server");
String releaseCodename =
(String) jmx.getAttribute(server, "releaseCodename");
String releaseVersion =
(String) jmx.getAttribute(server, "releaseVersion");
String productName =
(String) jmx.getAttribute(server, "productName");
String productVersion =
(String) jmx.getAttribute(server, "productVersion");
log.info("App server release codename: {}", releaseCodename);
log.info("App server release version: {}", releaseVersion);
switch ((productName == null) ? "" : productName) {
case "EAP":
checkEAPVersion(productVersion);
break;
case "WildFly Full":
checkWildFlyVersion(productVersion);
break;
default:
log.warn(
"Unknown app server. This application requires EAP >= {} or WildFly Full >= {}",
MIN_EAP_VERSION, MIN_WILDFLY_VERSION);
break;
}
}
private void checkEAPVersion(String productVersion) {
if (productVersion != null) {
DefaultArtifactVersion pv =
new DefaultArtifactVersion(productVersion);
if (pv.compareTo(MIN_EAP_VERSION) < 0) {
log.warn(
"EAP version is {}. Please upgrade to {} or later.",
productVersion, MIN_EAP_VERSION);
} else {
log.info("EAP version: {}", productVersion);
}
} else {
log.warn("EAP version is unknown");
}
}
private void checkWildFlyVersion(String productVersion) {
if (productVersion != null) {
DefaultArtifactVersion pv =
new DefaultArtifactVersion(productVersion);
if (pv.compareTo(MIN_WILDFLY_VERSION) < 0) {
log.warn(
"WildFly Full version is {}. Please upgrade to {} or later.",
productVersion, MIN_WILDFLY_VERSION);
} else {
log.info("WildFly Full version: {}",
productVersion);
}
} else {
log.warn("WildFly Full version is unknown");
}
}
private void checkLuceneLocks(File indexDir)
throws IOException, ZanataInitializationException {
if (!indexDir.exists()) {
if (indexDir.mkdirs()) {
log.info("Created lucene index directory.");
} else {
log.warn("Could not create lucene index directory");
}
}
if (mightUseNFS(indexDir)) {
// we don't trust Lucene's NativeFSLockFactory for NFS locks
String docURL = "http://docs.jboss.org/hibernate/search/4.4/reference/en-US/html/search-configuration.html#search-configuration-directory-lockfactories";
log.warn("The Hibernate Search index dir '{}' might be NFS. " +
"NativeFSLockFactory might not be safe: {}" +
indexDir, docURL);
}
Collection<File> lockFiles =
FileUtils.listFiles(indexDir, new String[] { "lock" }, true);
if (!lockFiles.isEmpty()) {
log.info("Lucene lock files found: {}", lockFiles);
}
}
/**
* Returns true if any of the files appear to be stored in NFS (or we
* can't tell).
*/
private boolean mightUseNFS(File... files) {
try {
FileSystem fileSystem = FileSystems.getDefault();
for (File file: files) {
Path path = fileSystem.getPath(file.getAbsolutePath());
String fileStoreType = Files.getFileStore(path).type();
if (fileStoreType.toLowerCase().contains("nfs")) {
return true;
}
}
return false;
} catch (IOException e) {
log.warn(e.toString(), e);
// assume the worst case
return true;
}
}
/** Utility to debug JBoss JNDI problems */
public static String listJNDITree(String namespace) {
StringBuffer buffer = new StringBuffer(4096);
try {
Properties props = new Properties();
Context context = new InitialContext(props); // From jndi.properties
if (namespace != null) {
context = (Context) context.lookup(namespace);
}
buffer.append("Namespace: ").append(namespace).append("\n");
buffer.append("#####################################\n");
list(context, " ", buffer, true);
buffer.append("#####################################\n");
} catch (NamingException e) {
buffer.append("Failed to get InitialContext, ").append(
e.toString(true));
}
return buffer.toString();
}
private static void list(Context ctx, String indent, StringBuffer buffer,
boolean verbose) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
NamingEnumeration<NameClassPair> ne = ctx.list("");
while (ne.hasMore()) {
NameClassPair pair = ne.next();
String name = pair.getName();
String className = pair.getClassName();
boolean recursive = false;
boolean isLinkRef = false;
boolean isProxy = false;
Class<?> c = null;
try {
c = loader.loadClass(className);
if (Context.class.isAssignableFrom(c)) {
recursive = true;
}
if (LinkRef.class.isAssignableFrom(c)) {
isLinkRef = true;
}
isProxy = Proxy.isProxyClass(c);
} catch (ClassNotFoundException cnfe) {
// If this is a $Proxy* class its a proxy
if (className.startsWith("$Proxy")) {
isProxy = true;
// We have to get the class from the binding
try {
Object p = ctx.lookup(name);
c = p.getClass();
} catch (NamingException e) {
Throwable t = e.getRootCause();
if (t instanceof ClassNotFoundException) {
// Get the class name from the exception msg
String msg = t.getMessage();
if (msg != null) {
// Reset the class name to the CNFE class
className = msg;
}
}
}
}
}
buffer.append(indent).append(" +- ").append(name);
// Display reference targets
if (isLinkRef) {
// Get the
try {
Object obj = ctx.lookupLink(name);
LinkRef link = (LinkRef) obj;
buffer.append("[link -> ");
buffer.append(link.getLinkName());
buffer.append(']');
} catch (Throwable t) {
buffer.append("invalid]");
}
}
// Display proxy interfaces
if (isProxy) {
buffer.append(" (proxy: ").append(pair.getClassName());
if (c != null) {
Class<?>[] ifaces = c.getInterfaces();
buffer.append(" implements ");
for (Class<?> iface : ifaces) {
buffer.append(iface);
buffer.append(',');
}
buffer.setCharAt(buffer.length() - 1, ')');
} else {
buffer.append(" implements ").append(className)
.append(")");
}
} else if (verbose) {
buffer.append(" (class: ").append(pair.getClassName())
.append(")");
}
buffer.append('\n');
if (recursive) {
try {
Object value = ctx.lookup(name);
if (value instanceof Context) {
Context subctx = (Context) value;
list(subctx, indent + " | ", buffer, verbose);
} else {
buffer.append(indent).append(" | NonContext: ")
.append(value);
buffer.append('\n');
}
} catch (Throwable t) {
buffer.append("Failed to lookup: ").append(name)
.append(", errmsg=").append(t.getMessage());
buffer.append('\n');
}
}
}
ne.close();
} catch (NamingException ne) {
buffer.append("error while listing context ")
.append(ctx.toString()).append(": ")
.append(ne.toString(true));
}
}
private void logBanner(VersionInfo ver) {
log.info("============================================");
log.info(" _____ _ ");
log.info(" /__ / ____ _____ ____ _/ /_____ _ ");
log.info(" / / / __ `/ __ \\/ __ `/ __/ __ `/ ");
log.info(" / /__/ /_/ / / / / /_/ / /_/ /_/ / ");
log.info(" /____/\\__,_/_/ /_/\\__,_/\\__/\\__,_/ ");
log.info(" Application version: " + ver.getVersionNo());
log.info(" SCM: " + ver.getScmDescribe());
log.info(" Red Hat Inc 2008-{}",
Calendar.getInstance().get(Calendar.YEAR));
log.info("============================================");
}
}