use of org.glassfish.hk2.api.PreDestroy in project Payara by payara.
the class EarHandler method getClassLoader.
public ClassLoader getClassLoader(final ClassLoader parent, DeploymentContext context) {
final ReadableArchive archive = context.getSource();
final ApplicationHolder holder = getApplicationHolder(archive, context, true);
// the ear classloader hierachy will be
// ear lib classloader <- embedded rar classloader <-
// ear classloader <- various module classloaders
final DelegatingClassLoader embeddedConnCl;
final EarClassLoader cl;
// add the libraries packaged in the application library directory
try {
String compatProp = context.getAppProps().getProperty(DeploymentProperties.COMPATIBILITY);
// let's see if it's defined in glassfish-application.xml
if (compatProp == null) {
GFApplicationXmlParser gfApplicationXmlParser = new GFApplicationXmlParser(context.getSource());
compatProp = gfApplicationXmlParser.getCompatibilityValue();
if (compatProp != null) {
context.getAppProps().put(DeploymentProperties.COMPATIBILITY, compatProp);
}
}
// let's see if it's defined in sun-application.xml
if (compatProp == null) {
SunApplicationXmlParser sunApplicationXmlParser = new SunApplicationXmlParser(context.getSourceDir());
compatProp = sunApplicationXmlParser.getCompatibilityValue();
if (compatProp != null) {
context.getAppProps().put(DeploymentProperties.COMPATIBILITY, compatProp);
}
}
if (System.getSecurityManager() != null) {
// procee declared permissions
earDeclaredPC = PermsArchiveDelegate.getDeclaredPermissions(SMGlobalPolicyUtil.CommponentType.ear, context);
// process ee permissions
processEEPermissions(context);
}
final URL[] earLibURLs = ASClassLoaderUtil.getAppLibDirLibraries(context.getSourceDir(), holder.app.getLibraryDirectory(), compatProp);
final EarLibClassLoader earLibCl = AccessController.doPrivileged(new PrivilegedAction<EarLibClassLoader>() {
@Override
public EarLibClassLoader run() {
return new EarLibClassLoader(earLibURLs, parent);
}
});
String clDelegate = holder.app.getClassLoadingDelegate();
// default to true if null
if (Boolean.parseBoolean(clDelegate == null ? "true" : clDelegate) == false) {
earLibCl.enableCurrentBeforeParentUnconditional();
} else if (clDelegate != null) {
// otherwise clDelegate == true
earLibCl.disableCurrentBeforeParent();
}
if (System.getSecurityManager() != null) {
addEEOrDeclaredPermissions(earLibCl, earDeclaredPC, false);
if (_logger.isLoggable(Level.FINE))
_logger.fine("added declaredPermissions to earlib: " + earDeclaredPC);
addEEOrDeclaredPermissions(earLibCl, eeGarntsMap.get(SMGlobalPolicyUtil.CommponentType.ear), true);
if (_logger.isLoggable(Level.FINE))
_logger.fine("added all ee permissions to earlib: " + eeGarntsMap.get(SMGlobalPolicyUtil.CommponentType.ear));
}
embeddedConnCl = AccessController.doPrivileged(new PrivilegedAction<DelegatingClassLoader>() {
@Override
public DelegatingClassLoader run() {
return new DelegatingClassLoader(earLibCl);
}
});
cl = AccessController.doPrivileged(new PrivilegedAction<EarClassLoader>() {
@Override
public EarClassLoader run() {
return new EarClassLoader(embeddedConnCl, holder.app);
}
});
// add ear lib to module classloader list so we can
// clean it up later
cl.addModuleClassLoader(EAR_LIB, earLibCl);
if (System.getSecurityManager() != null) {
// push declared permissions to ear classloader
addEEOrDeclaredPermissions(cl, earDeclaredPC, false);
if (_logger.isLoggable(Level.FINE))
_logger.fine("declaredPermissions added: " + earDeclaredPC);
// push ejb permissions to ear classloader
addEEOrDeclaredPermissions(cl, eeGarntsMap.get(SMGlobalPolicyUtil.CommponentType.ejb), true);
if (_logger.isLoggable(Level.FINE))
_logger.fine("ee permissions added: " + eeGarntsMap.get(SMGlobalPolicyUtil.CommponentType.ejb));
}
} catch (Exception e) {
_logger.log(Level.SEVERE, strings.get("errAddLibs"), e);
throw new RuntimeException(e);
}
for (ModuleDescriptor md : holder.app.getModules()) {
ReadableArchive sub = null;
String moduleUri = md.getArchiveUri();
try {
sub = archive.getSubArchive(moduleUri);
if (sub instanceof InputJarArchive) {
throw new IllegalArgumentException(strings.get("wrongArchType", moduleUri));
}
} catch (IOException e) {
_logger.log(Level.FINE, "Sub archive " + moduleUri + " seems unreadable", e);
}
if (sub != null) {
try {
ArchiveHandler handler = context.getModuleArchiveHandlers().get(moduleUri);
if (handler == null) {
handler = getArchiveHandlerFromModuleType(md.getModuleType());
if (handler == null) {
handler = deployment.getArchiveHandler(sub);
}
context.getModuleArchiveHandlers().put(moduleUri, handler);
}
if (handler != null) {
ActionReport subReport = context.getActionReport().addSubActionsReport();
// todo : this is a hack, once again,
// the handler is assuming a file:// url
ExtendedDeploymentContext subContext = new DeploymentContextImpl(subReport, sub, context.getCommandParameters(DeployCommandParameters.class), env) {
@Override
public File getScratchDir(String subDirName) {
String modulePortion = Util.getURIName(getSource().getURI());
return (new File(super.getScratchDir(subDirName), modulePortion));
}
};
// sub context will store the root archive handler also
// so we can figure out the enclosing archive type
subContext.setArchiveHandler(context.getArchiveHandler());
subContext.setParentContext((ExtendedDeploymentContext) context);
sub.setParentArchive(context.getSource());
ClassLoader subCl = handler.getClassLoader(cl, subContext);
if ((System.getSecurityManager() != null) && (subCl instanceof DDPermissionsLoader)) {
addEEOrDeclaredPermissions(subCl, earDeclaredPC, false);
if (_logger.isLoggable(Level.FINE))
_logger.fine("added declared permissions to sub module of " + subCl);
}
if (md.getModuleType().equals(DOLUtils.ejbType())) {
// for ejb module, we just add the ejb urls
// to EarClassLoader and use that to load
// ejb module
URL[] moduleURLs = ((URLClassLoader) subCl).getURLs();
for (URL moduleURL : moduleURLs) {
cl.addURL(moduleURL);
}
cl.addModuleClassLoader(moduleUri, cl);
PreDestroy.class.cast(subCl).preDestroy();
} else if (md.getModuleType().equals(DOLUtils.rarType())) {
embeddedConnCl.addDelegate((DelegatingClassLoader.ClassFinder) subCl);
cl.addModuleClassLoader(moduleUri, subCl);
} else {
Boolean isTempClassLoader = context.getTransientAppMetaData(ExtendedDeploymentContext.IS_TEMP_CLASSLOADER, Boolean.class);
if (subCl instanceof URLClassLoader && (isTempClassLoader != null) && isTempClassLoader) {
// for temp classloader, we add all the module
// urls to the top level EarClassLoader
URL[] moduleURLs = ((URLClassLoader) subCl).getURLs();
for (URL moduleURL : moduleURLs) {
cl.addURL(moduleURL);
}
}
cl.addModuleClassLoader(moduleUri, subCl);
}
}
} catch (IOException e) {
_logger.log(Level.SEVERE, strings.get("noClassLoader", moduleUri), e);
}
}
}
return cl;
}
use of org.glassfish.hk2.api.PreDestroy in project Payara by payara.
the class AbstractJMSContextManager method cleanup.
// Close and remove the JMSContext instances
@PreDestroy
public synchronized void cleanup() {
ServiceLocator serviceLocator = Globals.get(ServiceLocator.class);
InvocationManager invMgr = serviceLocator.getService(InvocationManager.class);
ComponentInvocation currentInv = invMgr.getCurrentInvocation();
for (Entry<String, JMSContextEntry> entry : contexts.entrySet()) {
JMSContextEntry contextEntry = entry.getValue();
String ipId = contextEntry.getInjectionPointId();
JMSContext context = contextEntry.getCtx();
if (context != null) {
ComponentInvocation inv = contextEntry.getComponentInvocation();
if (inv != null && currentInv != inv)
invMgr.preInvoke(inv);
try {
context.close();
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, localStrings.getLocalString("JMSContext.impl.close", "Closed JMSContext instance associated with id {0}: {1}.", ipId, context.toString()));
}
} catch (Exception e) {
logger.log(Level.SEVERE, localStrings.getLocalString("JMSContext.impl.close.failure", "Failed to close JMSContext instance associated with id {0}: {1}.", ipId, context.toString()), e);
} finally {
if (inv != null && currentInv != inv)
invMgr.postInvoke(inv);
}
}
}
contexts.clear();
}
use of org.glassfish.hk2.api.PreDestroy in project Payara by payara.
the class ApplicationLifecycle method prepare.
@Override
public ApplicationDeployment prepare(Collection<? extends Sniffer> sniffers, final ExtendedDeploymentContext context) {
events.send(new Event<>(Deployment.DEPLOYMENT_START, context), false);
currentDeploymentContext.get().push(context);
final ActionReport report = context.getActionReport();
final DeployCommandParameters commandParams = context.getCommandParameters(DeployCommandParameters.class);
final String appName = commandParams.name();
ApplicationInfo appInfo;
final ClassLoader currentCL = Thread.currentThread().getContextClassLoader();
ProgressTracker tracker = new ProgressTracker() {
@Override
public void actOn(Logger logger) {
// loaded but may not be started. Issue 18263
for (EngineRef module : get("loaded", EngineRef.class)) {
try {
module.stop(context);
} catch (Exception e) {
// ignore
}
}
try {
PreDestroy.class.cast(context).preDestroy();
} catch (Exception e) {
// ignore
}
for (EngineRef module : get("loaded", EngineRef.class)) {
try {
module.unload(context);
} catch (Exception e) {
// ignore
}
}
try {
ApplicationInfo appInfo = appRegistry.get(appName);
if (appInfo != null) {
// send the event to close necessary resources
events.send(new Event<ApplicationInfo>(Deployment.APPLICATION_DISABLED, appInfo));
}
} catch (Exception e) {
// ignore
}
for (EngineRef module : get("prepared", EngineRef.class)) {
try {
module.clean(context);
} catch (Exception e) {
// ignore
}
}
if (!commandParams.keepfailedstubs) {
try {
context.clean();
} catch (Exception e) {
// ignore
}
}
appRegistry.remove(appName);
}
};
try {
if (commandParams.origin == OpsParams.Origin.deploy && appRegistry.get(appName) != null) {
report.setMessage(localStrings.getLocalString("appnamenotunique", "Application name {0} is already in use. Please pick a different name.", appName));
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
return null;
}
// defined virtual servers minus __asadmin on that target
if (commandParams.virtualservers == null) {
commandParams.virtualservers = DeploymentUtils.getVirtualServers(commandParams.target, env, domain);
}
if (commandParams.enabled == null) {
commandParams.enabled = Boolean.TRUE;
}
if (commandParams.altdd != null) {
context.getSource().addArchiveMetaData(DeploymentProperties.ALT_DD, commandParams.altdd);
}
if (commandParams.runtimealtdd != null) {
context.getSource().addArchiveMetaData(DeploymentProperties.RUNTIME_ALT_DD, commandParams.runtimealtdd);
}
context.addTransientAppMetaData(ExtendedDeploymentContext.TRACKER, tracker);
context.setPhase(DeploymentContextImpl.Phase.PREPARE);
ArchiveHandler handler = context.getArchiveHandler();
if (handler == null) {
handler = getArchiveHandler(context.getSource(), commandParams.type);
context.setArchiveHandler(handler);
}
if (handler == null) {
report.setMessage(localStrings.getLocalString("unknownarchivetype", "Archive type of {0} was not recognized", context.getSourceDir()));
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
return null;
}
DeploymentTracing tracing = context.getModuleMetaData(DeploymentTracing.class);
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.ARCHIVE_HANDLER_OBTAINED);
}
if (handler.requiresAnnotationScanning(context.getSource())) {
getDeployableTypes(context);
}
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.PARSING_DONE);
}
// is that some container do not support to be restarted.
if (sniffers != null && logger.isLoggable(Level.FINE)) {
for (Sniffer sniffer : sniffers) {
logger.fine("Before Sorting" + sniffer.getModuleType());
}
}
sniffers = getSniffers(handler, sniffers, context);
ClassLoaderHierarchy clh = habitat.getService(ClassLoaderHierarchy.class);
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.CLASS_LOADER_HIERARCHY);
}
context.createDeploymentClassLoader(clh, handler);
events.send(new Event<DeploymentContext>(Deployment.AFTER_DEPLOYMENT_CLASSLOADER_CREATION, context), false);
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.CLASS_LOADER_CREATED);
}
Thread.currentThread().setContextClassLoader(context.getClassLoader());
List<EngineInfo> sortedEngineInfos = setupContainerInfos(handler, sniffers, context);
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.CONTAINERS_SETUP_DONE);
}
if (logger.isLoggable(Level.FINE)) {
for (EngineInfo info : sortedEngineInfos) {
logger.fine("After Sorting " + info.getSniffer().getModuleType());
}
}
if (sortedEngineInfos == null || sortedEngineInfos.isEmpty()) {
report.failure(logger, localStrings.getLocalString("unknowncontainertype", "There is no installed container capable of handling this application {0}", context.getSource().getName()));
tracker.actOn(logger);
return null;
}
// create a temporary application info to hold metadata
// so the metadata could be accessed at classloader
// construction time through ApplicationInfo
ApplicationInfo tempAppInfo = new ApplicationInfo(events, context.getSource(), appName);
for (Object m : context.getModuleMetadata()) {
tempAppInfo.addMetaData(m);
}
tempAppInfo.setIsJavaEEApp(sortedEngineInfos);
// set the flag on the archive to indicate whether it's
// a JavaEE archive or not
context.getSource().setExtraData(Boolean.class, tempAppInfo.isJavaEEApp());
appRegistry.add(appName, tempAppInfo);
try {
notifyLifecycleInterceptorsBefore(ExtendedDeploymentContext.Phase.PREPARE, context);
} catch (Throwable interceptorException) {
report.failure(logger, "Exception while invoking the lifecycle interceptor", null);
report.setFailureCause(interceptorException);
logger.log(Level.SEVERE, KernelLoggerInfo.lifecycleException, interceptorException);
tracker.actOn(logger);
return null;
}
events.send(new Event<DeploymentContext>(Deployment.DEPLOYMENT_BEFORE_CLASSLOADER_CREATION, context), false);
context.createApplicationClassLoader(clh, handler);
events.send(new Event<DeploymentContext>(Deployment.AFTER_APPLICATION_CLASSLOADER_CREATION, context), false);
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.CLASS_LOADER_CREATED);
}
// this is a first time deployment as opposed as load following an unload event,
// we need to create the application info
// todo : we should come up with a general Composite API solution
ModuleInfo moduleInfo = null;
try {
moduleInfo = prepareModule(sortedEngineInfos, appName, context, tracker);
// Now that the prepare phase is done, any artifacts
// should be available. Go ahead and create the
// downloadable client JAR. We want to do this now, or
// at least before the load and start phases, because
// (for example) the app client deployer start phase
// needs to find all generated files when it runs.
final ClientJarWriter cjw = new ClientJarWriter(context);
cjw.run();
} catch (Throwable prepareException) {
report.failure(logger, "Exception while preparing the app", null);
report.setFailureCause(prepareException);
logger.log(Level.SEVERE, KernelLoggerInfo.lifecycleException, prepareException);
tracker.actOn(logger);
return null;
}
// the deployer did not take care of populating the application info, this
// is not a composite module.
appInfo = context.getModuleMetaData(ApplicationInfo.class);
if (appInfo == null) {
appInfo = new ApplicationInfo(events, context.getSource(), appName);
appInfo.addModule(moduleInfo);
for (Object m : context.getModuleMetadata()) {
moduleInfo.addMetaData(m);
appInfo.addMetaData(m);
}
} else {
for (EngineRef ref : moduleInfo.getEngineRefs()) {
appInfo.add(ref);
}
}
// remove the temp application info from the registry
// first, then register the real one
appRegistry.remove(appName);
appInfo.setIsJavaEEApp(sortedEngineInfos);
appRegistry.add(appName, appInfo);
notifyLifecycleInterceptorsAfter(ExtendedDeploymentContext.Phase.PREPARE, context);
if (tracing != null) {
tracing.addMark(DeploymentTracing.Mark.PREPARED);
}
// send the APPLICATION_PREPARED event
// set the phase and thread context classloader properly
// before sending the event
context.setPhase(DeploymentContextImpl.Phase.PREPARED);
Thread.currentThread().setContextClassLoader(context.getClassLoader());
appInfo.setAppClassLoader(context.getClassLoader());
events.send(new Event<DeploymentContext>(Deployment.APPLICATION_PREPARED, context), false);
if (loadOnCurrentInstance(context)) {
appInfo.setLibraries(commandParams.libraries());
try {
notifyLifecycleInterceptorsBefore(ExtendedDeploymentContext.Phase.LOAD, context);
appInfo.load(context, tracker);
notifyLifecycleInterceptorsAfter(ExtendedDeploymentContext.Phase.LOAD, context);
} catch (Throwable loadException) {
logger.log(Level.SEVERE, KernelLoggerInfo.lifecycleException, loadException);
report.failure(logger, "Exception while loading the app", null);
report.setFailureCause(loadException);
tracker.actOn(logger);
return null;
}
}
} catch (Exception e) {
report.failure(logger, localStrings.getLocalString("error.deploying.app", "Exception while deploying the app [{0}]", appName), null);
report.setFailureCause(e);
logger.log(Level.SEVERE, KernelLoggerInfo.lifecycleException, e);
tracker.actOn(logger);
return null;
} finally {
Thread.currentThread().setContextClassLoader(currentCL);
if (report.getActionExitCode() != ActionReport.ExitCode.SUCCESS) {
context.postDeployClean(false);
events.send(new Event<>(Deployment.DEPLOYMENT_FAILURE, context));
}
}
ApplicationDeployment depl = new ApplicationDeployment(appInfo, context);
appRegistry.addTransient(depl);
return depl;
}
use of org.glassfish.hk2.api.PreDestroy in project Payara by payara.
the class DolProvider method processDeploymentMetaData.
/**
* This method populates the Application object from a ReadableArchive
* @param archive the archive for the application
*/
public Application processDeploymentMetaData(ReadableArchive archive) throws Exception {
FileArchive expandedArchive = null;
File tmpFile = null;
ExtendedDeploymentContext context = null;
Logger logger = Logger.getAnonymousLogger();
ClassLoader cl = null;
try {
String archiveName = Util.getURIName(archive.getURI());
ArchiveHandler archiveHandler = deployment.getArchiveHandler(archive);
if (archiveHandler == null) {
throw new IllegalArgumentException(localStrings.getLocalString("deploy.unknownarchivetype", "Archive type of {0} was not recognized", archiveName));
}
DeployCommandParameters parameters = new DeployCommandParameters(new File(archive.getURI()));
ActionReport report = new HTMLActionReporter();
context = new DeploymentContextImpl(report, archive, parameters, env);
context.setArchiveHandler(archiveHandler);
String appName = archiveHandler.getDefaultApplicationName(archive, context);
parameters.name = appName;
if (archive instanceof InputJarArchive) {
// we need to expand the archive first in this case
tmpFile = File.createTempFile(archiveName, "");
String path = tmpFile.getAbsolutePath();
if (!tmpFile.delete()) {
logger.log(Level.WARNING, "cannot.delete.temp.file", new Object[] { path });
}
File tmpDir = new File(path);
tmpDir.deleteOnExit();
if (!tmpDir.exists() && !tmpDir.mkdirs()) {
throw new IOException("Unable to create directory " + tmpDir.getAbsolutePath());
}
expandedArchive = (FileArchive) archiveFactory.createArchive(tmpDir);
archiveHandler.expand(archive, expandedArchive, context);
context.setSource(expandedArchive);
}
context.setPhase(DeploymentContextImpl.Phase.PREPARE);
ClassLoaderHierarchy clh = clhProvider.get();
context.createDeploymentClassLoader(clh, archiveHandler);
cl = context.getClassLoader();
deployment.getDeployableTypes(context);
deployment.getSniffers(archiveHandler, null, context);
return processDOL(context);
} finally {
if (cl != null && cl instanceof PreDestroy) {
try {
PreDestroy.class.cast(cl).preDestroy();
} catch (Exception e) {
// ignore
}
}
if (context != null) {
context.postDeployClean(true);
}
if (expandedArchive != null) {
try {
expandedArchive.close();
} catch (Exception e) {
// ignore
}
}
if (tmpFile != null && tmpFile.exists()) {
try {
FileUtils.whack(tmpFile);
} catch (Exception e) {
// ignore
}
}
}
}
use of org.glassfish.hk2.api.PreDestroy in project Payara by payara.
the class EarClassLoader method preDestroy.
@Override
public void preDestroy() {
if (isPreDestroyCalled) {
return;
}
try {
for (ClassLoaderHolder clh : moduleClassLoaders) {
// destroy all the module classloaders
if (!(clh.loader instanceof EarLibClassLoader) && !(clh.loader instanceof EarClassLoader) && !isRARCL(clh.loader)) {
try {
PreDestroy.class.cast(clh.loader).preDestroy();
} catch (Exception e) {
// ignore, the class loader does not need to be
// explicitly stopped.
}
}
}
// destroy itself
super.preDestroy();
// now destroy embedded Connector CLs
DelegatingClassLoader dcl = (DelegatingClassLoader) this.getParent();
for (DelegatingClassLoader.ClassFinder cf : dcl.getDelegates()) {
try {
PreDestroy.class.cast(cf).preDestroy();
} catch (Exception e) {
// ignore, the class loader does not need to be
// explicitly stopped.
}
}
// now destroy the EarLibClassLoader
PreDestroy.class.cast(this.getParent().getParent()).preDestroy();
moduleClassLoaders = null;
} catch (Exception e) {
// ignore, the class loader does not need to be explicitely stopped.
}
isPreDestroyCalled = true;
}
Aggregations