use of org.glassfish.hk2.external.org.objectweb.asm.Type 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.external.org.objectweb.asm.Type in project Payara by payara.
the class ArchiveFactory method openArchive.
/**
* Opens an existing archivist using the URL as the path.
* The URL protocol will defines the type of desired archive
* (jar, file, memory, etc...)
* @param path url to the existing archive
* @return the appropriate archive
*/
public ReadableArchive openArchive(URI path) throws IOException {
String provider = path.getScheme();
if (provider.equals("file")) {
// this could be a jar file or a directory
File f = new File(path);
if (!f.exists())
throw new FileNotFoundException(f.getPath());
if (f.isFile()) {
provider = "jar";
}
}
try {
ReadableArchive archive = habitat.getService(ReadableArchive.class, provider);
if (archive == null) {
deplLogger.log(Level.SEVERE, IMPLEMENTATION_NOT_FOUND, provider);
throw new MalformedURLException("Protocol not supported : " + provider);
}
archive.open(path);
return archive;
} catch (MultiException e) {
LogRecord lr = new LogRecord(Level.SEVERE, IMPLEMENTATION_NOT_FOUND);
lr.setParameters(new Object[] { provider });
lr.setThrown(e);
deplLogger.log(lr);
throw new MalformedURLException("Protocol not supported : " + provider);
}
}
use of org.glassfish.hk2.external.org.objectweb.asm.Type in project Payara by payara.
the class GrizzlyService method postConstruct.
/**
* The component has been injected with any dependency and
* will be placed into commission by the subsystem.
*/
@Override
public void postConstruct() {
events.register(this);
final NetworkConfig networkConfig = config.getNetworkConfig();
configListener = new DynamicConfigListener(config, LOGGER);
ObservableBean bean = (ObservableBean) ConfigSupport.getImpl(networkConfig.getNetworkListeners());
bean.addListener(configListener);
bean = (ObservableBean) ConfigSupport.getImpl(config.getHttpService());
bean.addListener(configListener);
transactions.addListenerForType(SystemProperty.class, configListener);
configListener.setGrizzlyService(this);
try {
boolean isAtLeastOneProxyStarted = false;
futures = new ArrayList<Future<Result<Thread>>>();
// Record how long it took for the listeners to start up
final long startTime = System.currentTimeMillis();
// Keep a list of successfully started listeners
List<NetworkListener> startedListeners = new ArrayList<>();
for (NetworkListener listener : networkConfig.getNetworkListeners().getNetworkListener()) {
if (createNetworkProxy(listener) != null) {
isAtLeastOneProxyStarted = true;
startedListeners.add(listener);
}
}
if (isAtLeastOneProxyStarted) {
// Get the startup time
final long startupTime = System.currentTimeMillis() - startTime;
// Log the listeners which started.
String boundAddresses = Arrays.toString(startedListeners.stream().map(listener -> listener.getAddress() + ":" + listener.getPort()).collect(Collectors.toList()).toArray());
LOGGER.log(Level.INFO, KernelLoggerInfo.grizzlyStarted, new Object[] { Grizzly.getDotedVersion(), startupTime, boundAddresses });
registerContainerAdapters();
}
} catch (RuntimeException e) {
// So far postConstruct can not throw any other exception type
LOGGER.log(Level.SEVERE, KernelLoggerInfo.grizzlyCantStart, e);
for (NetworkProxy proxy : proxies) {
try {
proxy.stop();
} catch (Exception proxyStopException) {
LOGGER.log(Level.SEVERE, KernelLoggerInfo.grizzlyCloseException, new Object[] { proxy.getPort(), proxyStopException });
}
}
throw e;
}
registerMonitoringStatsProviders();
}
use of org.glassfish.hk2.external.org.objectweb.asm.Type in project Payara by payara.
the class GetHabitatInfo method dumpTypes.
private void dumpTypes(StringBuilder sb) {
sb.append("\n\n*********** Sorted List of all Types in the Habitat **************\n\n");
List<ActiveDescriptor<?>> allDescriptors = serviceLocator.getDescriptors(BuilderHelper.allFilter());
HashSet<String> allTypes = new HashSet<String>();
for (ActiveDescriptor<?> aDescriptor : allDescriptors) {
allTypes.add(aDescriptor.getImplementation());
}
Iterator<String> it = allTypes.iterator();
if (// PP (paranoid programmer)
it == null)
return;
SortedSet<String> types = new TreeSet<String>();
while (it.hasNext()) {
types.add(it.next());
}
// now the types are sorted...
it = types.iterator();
for (int i = 1; it.hasNext(); i++) {
sb.append("Type-" + i + ": " + it.next() + "\n");
}
}
use of org.glassfish.hk2.external.org.objectweb.asm.Type in project Payara by payara.
the class BtraceClientGenerator method generateBtraceClientClassData.
public static byte[] generateBtraceClientClassData(int clientID, Collection<FlashlightProbe> probes) {
// create a unique name. It does not matter what the name is.
String generatedClassName = "com/sun/btrace/flashlight/BTrace_Flashlight_" + clientID;
// Start of writing a class using ASM, which will be our BTrace Client
int cwFlags = ClassWriter.COMPUTE_FRAMES + ClassWriter.COMPUTE_MAXS;
ClassWriter cw = new ClassWriter(cwFlags);
// Define the access identifiers for the BTrace Client class
int access = Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL;
cw.visit(Opcodes.V1_5, access, generatedClassName, null, "java/lang/Object", null);
// Need a @OnMethod annotation, so prepare your Annotation Visitor for that
cw.visitAnnotation("Lcom/sun/btrace/annotations/BTrace;", true);
// Iterate through the probes, so you will create one method for each probe
int methodCounter = 0;
for (FlashlightProbe probe : probes) {
// Preparing the class method header and params (type) for @OnMethod annotation
StringBuilder typeDesc = new StringBuilder("void ");
StringBuilder methodDesc = new StringBuilder("void __");
methodDesc.append(probe.getProviderJavaMethodName()).append("__");
methodDesc.append(clientID).append("_").append(methodCounter).append("_");
methodDesc.append("(");
typeDesc.append("(");
String delim = "";
String typeDelim = "";
Class[] paramTypes = probe.getParamTypes();
for (int index = 0; index < paramTypes.length; index++) {
Class paramType = paramTypes[index];
methodDesc.append(delim).append(paramType.getName());
// Dont add the param type for type desc, if self is the first index
if (!(probe.hasSelf() && (index == 0))) {
typeDesc.append(typeDelim).append(paramType.getName());
typeDelim = ",";
}
delim = ", ";
}
methodDesc.append(")");
typeDesc.append(")");
// Creating the class method
Method m = Method.getMethod(methodDesc.toString());
GeneratorAdapter gen = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, m, null, null, cw);
// Add the @Self annotation
if (probe.hasSelf()) {
String[] paramNames = probe.getProbeParamNames();
for (int index = 0; index < paramNames.length; index++) {
if (paramNames[index].equalsIgnoreCase(FlashlightProbe.SELF)) {
AnnotationVisitor paramVisitor = gen.visitParameterAnnotation(index, "Lcom/sun/btrace/annotations/Self;", true);
paramVisitor.visitEnd();
}
}
}
// Add the @OnMethod annotation to this method
AnnotationVisitor av = gen.visitAnnotation("Lcom/sun/btrace/annotations/OnMethod;", true);
av.visit("clazz", "" + probe.getProviderClazz().getName());
av.visit("method", probe.getProviderJavaMethodName());
av.visit("type", typeDesc.toString());
av.visitEnd();
// Add the body
gen.push(probe.getId());
gen.loadArgArray();
gen.invokeStatic(Type.getType(ProbeRegistry.class), Method.getMethod("void invokeProbe(int, Object[])"));
gen.returnValue();
gen.endMethod();
methodCounter++;
}
BtraceClientGenerator.generateConstructor(cw);
cw.visitEnd();
byte[] classData = cw.toByteArray();
writeClass(classData, generatedClassName);
return classData;
}
Aggregations