Search in sources :

Example 1 with Optional

use of org.jvnet.hk2.annotations.Optional in project Payara by payara.

the class ApplicationLifecycle method prepare.

@Override
public ApplicationDeployment prepare(Collection<? extends Sniffer> sniffers, final ExtendedDeploymentContext context) {
    StructuredDeploymentTracing tracing = StructuredDeploymentTracing.load(context);
    DeploymentSpan eventSpan = tracing.startSpan(DeploymentTracing.AppStage.PROCESS_EVENTS, Deployment.DEPLOYMENT_START.type());
    events.send(new Event<>(Deployment.DEPLOYMENT_START, context), false);
    eventSpan.close();
    currentDeploymentContext.get().push(context);
    final ActionReport report = context.getActionReport();
    final DeployCommandParameters commandParams = context.getCommandParameters(DeployCommandParameters.class);
    final String appName = commandParams.name();
    ApplicationInfo appInfo;
    Optional<ApplicationState> appState = hotDeployService.getApplicationState(context);
    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<>(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 (DeploymentSpan topSpan = tracing.startSpan(DeploymentTracing.AppStage.PREPARE);
        SpanSequence span = tracing.startSequence(DeploymentTracing.AppStage.PREPARE, "ArchiveMetadata")) {
        if (commandParams.origin == OpsParams.Origin.deploy && appRegistry.get(appName) != null && !commandParams.hotDeploy) {
            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);
        span.start("ArchiveHandler");
        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;
        }
        span.start(DeploymentTracing.AppStage.CLASS_SCANNING);
        if (handler.requiresAnnotationScanning(context.getSource())) {
            getDeployableTypes(context);
        }
        span.finish();
        // is that some container do not support to be restarted.
        if (sniffers != null && logger.isLoggable(Level.FINE)) {
            for (Sniffer sniffer : sniffers) {
                logger.log(FINE, "Before Sorting{0}", sniffer.getModuleType());
            }
        }
        span.start(DeploymentTracing.AppStage.PREPARE, "Sniffer");
        sniffers = getSniffers(handler, sniffers, context);
        final Collection<? extends Sniffer> selectedSniffers = sniffers;
        appState.ifPresent(s -> s.setSniffers(selectedSniffers));
        span.start(DeploymentTracing.AppStage.PREPARE, "ClassLoaderHierarchy");
        ClassLoaderHierarchy clh = habitat.getService(ClassLoaderHierarchy.class);
        span.start(DeploymentTracing.AppStage.PREPARE, "ClassLoader");
        context.createDeploymentClassLoader(clh, handler);
        events.send(new Event<>(Deployment.AFTER_DEPLOYMENT_CLASSLOADER_CREATION, context), false);
        Thread.currentThread().setContextClassLoader(context.getClassLoader());
        span.start(DeploymentTracing.AppStage.PREPARE, "Container");
        final List<EngineInfo> sortedEngineInfos;
        if (appState.map(ApplicationState::getEngineInfos).isPresent()) {
            sortedEngineInfos = appState.get().getEngineInfos();
            loadDeployers(sortedEngineInfos.stream().collect(toMap(EngineInfo::getDeployer, Function.identity())), context);
        } else {
            sortedEngineInfos = setupContainerInfos(handler, sniffers, context);
            appState.ifPresent(s -> s.setEngineInfos(sortedEngineInfos));
        }
        // a bit more is happening here, but I cannot quite describe it yet
        span.start(DeploymentTracing.AppStage.CREATE_CLASSLOADER);
        if (sortedEngineInfos.isEmpty()) {
            throw new DeploymentException(localStrings.getLocalString("unknowncontainertype", "There is no installed container capable of handling this application {0}", context.getSource().getName()));
        }
        if (logger.isLoggable(Level.FINE)) {
            for (EngineInfo info : sortedEngineInfos) {
                logger.log(FINE, "After Sorting {0}", info.getSniffer().getModuleType());
            }
        }
        // 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(SEVERE, KernelLoggerInfo.lifecycleException, interceptorException);
            tracker.actOn(logger);
            return null;
        }
        events.send(new Event<>(Deployment.DEPLOYMENT_BEFORE_CLASSLOADER_CREATION, context), false);
        context.createApplicationClassLoader(clh, handler);
        tempAppInfo.setAppClassLoader(context.getFinalClassLoader());
        events.send(new Event<>(Deployment.AFTER_APPLICATION_CLASSLOADER_CREATION, context), false);
        // 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
        final ModuleInfo moduleInfo;
        try (SpanSequence innerSpan = span.start(DeploymentTracing.AppStage.PREPARE, "Module")) {
            if (appState.map(ApplicationState::getModuleInfo).isPresent()) {
                moduleInfo = appState.get().getModuleInfo();
                moduleInfo.reset();
            } else {
                moduleInfo = prepareModule(sortedEngineInfos, appName, context, tracker);
                appState.ifPresent(s -> s.setModuleInfo(moduleInfo));
            }
            // 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(SEVERE, KernelLoggerInfo.lifecycleException, prepareException);
            tracker.actOn(logger);
            return null;
        }
        span.start(DeploymentTracing.AppStage.PROCESS_EVENTS, Deployment.APPLICATION_PREPARED.type());
        // is not a composite module.
        if (appState.map(ApplicationState::getApplicationInfo).isPresent()) {
            appInfo = appState.get().getApplicationInfo();
            appInfo.reset(context.getSource());
            for (Object metadata : context.getModuleMetadata()) {
                moduleInfo.addMetaData(metadata);
                appInfo.addMetaData(metadata);
            }
        } else if ((appInfo = context.getModuleMetaData(ApplicationInfo.class)) == null) {
            ApplicationInfo applicationInfo = new ApplicationInfo(events, context.getSource(), appName);
            appInfo = applicationInfo;
            appInfo.addModule(moduleInfo);
            appState.ifPresent(s -> s.setApplicationInfo(applicationInfo));
            for (Object metadata : context.getModuleMetadata()) {
                moduleInfo.addMetaData(metadata);
                appInfo.addMetaData(metadata);
            }
        } 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);
        // 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());
        appState.ifPresent(s -> s.setApplicationClassLoader(context.getClassLoader()));
        events.send(new Event<>(Deployment.APPLICATION_PREPARED, context), false);
        if (loadOnCurrentInstance(context)) {
            appInfo.setLibraries(commandParams.libraries());
            try (SpanSequence innerSpan = span.start(DeploymentTracing.AppStage.LOAD)) {
                notifyLifecycleInterceptorsBefore(ExtendedDeploymentContext.Phase.LOAD, context);
                appInfo.load(context, tracker);
                notifyLifecycleInterceptorsAfter(ExtendedDeploymentContext.Phase.LOAD, context);
            } catch (Throwable loadException) {
                logger.log(SEVERE, KernelLoggerInfo.lifecycleException, loadException);
                report.failure(logger, "Exception while loading the app", null);
                report.setFailureCause(loadException);
                tracker.actOn(logger);
                return null;
            }
        }
    } catch (DeploymentException de) {
        report.failure(logger, de.getMessage());
        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(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;
}
Also used : StructuredDeploymentTracing(org.glassfish.internal.deployment.analysis.StructuredDeploymentTracing) ApplicationMetaDataProvider(org.glassfish.api.deployment.ApplicationMetaDataProvider) BufferedInputStream(java.io.BufferedInputStream) Event(org.glassfish.api.event.EventListener.Event) KernelLoggerInfo(org.glassfish.kernel.KernelLoggerInfo) ParsingConfig(org.glassfish.hk2.classmodel.reflect.util.ParsingConfig) TraceContext(org.glassfish.internal.deployment.analysis.TraceContext) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) ServerEnvironment(org.glassfish.api.admin.ServerEnvironment) FileArchive(com.sun.enterprise.deploy.shared.FileArchive) Property(org.jvnet.hk2.config.types.Property) HotDeployService(fish.payara.nucleus.hotdeploy.HotDeployService) DeploymentTracing(org.glassfish.internal.deployment.DeploymentTracing) ParameterMapExtractor(org.glassfish.common.util.admin.ParameterMapExtractor) WARNING(java.util.logging.Level.WARNING) CommonModelRegistry(org.glassfish.hk2.classmodel.reflect.util.CommonModelRegistry) com.sun.enterprise.config.serverbeans(com.sun.enterprise.config.serverbeans) MultiException(org.glassfish.hk2.api.MultiException) Service(org.jvnet.hk2.annotations.Service) Container(org.glassfish.api.container.Container) DeploymentException(org.glassfish.deployment.common.DeploymentException) ServiceLocator(org.glassfish.hk2.api.ServiceLocator) ZipOutputStream(java.util.zip.ZipOutputStream) DeploymentContextImpl(org.glassfish.deployment.common.DeploymentContextImpl) ProgressTracker(org.glassfish.internal.data.ProgressTracker) java.util(java.util) Dom(org.jvnet.hk2.config.Dom) OpsParams(org.glassfish.api.deployment.OpsParams) ClassLoaderHierarchy(org.glassfish.internal.api.ClassLoaderHierarchy) EngineRef(org.glassfish.internal.data.EngineRef) BufferedOutputStream(java.io.BufferedOutputStream) ArchiveFactory(com.sun.enterprise.deploy.shared.ArchiveFactory) ArchiveDetector(org.glassfish.api.deployment.archive.ArchiveDetector) LocalStringManagerImpl(com.sun.enterprise.util.LocalStringManagerImpl) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) VersioningUtils(org.glassfish.deployment.versioning.VersioningUtils) ApplicationLifecycleInterceptor(org.glassfish.internal.deployment.ApplicationLifecycleInterceptor) Sniffer(org.glassfish.api.container.Sniffer) WritableArchive(org.glassfish.api.deployment.archive.WritableArchive) ApplicationName(org.glassfish.api.admin.config.ApplicationName) Named(javax.inject.Named) PreDestroy(org.glassfish.hk2.api.PreDestroy) DeploymentProperties(org.glassfish.deployment.common.DeploymentProperties) ApplicationConfigInfo(org.glassfish.deployment.common.ApplicationConfigInfo) ServerEnvironmentImpl(org.glassfish.server.ServerEnvironmentImpl) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) SingleConfigCode(org.jvnet.hk2.config.SingleConfigCode) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) ConfigSupport(org.jvnet.hk2.config.ConfigSupport) DeploymentSpan(org.glassfish.internal.deployment.analysis.DeploymentSpan) File(java.io.File) PostConstruct(org.glassfish.hk2.api.PostConstruct) Parser(org.glassfish.hk2.classmodel.reflect.Parser) MetaData(org.glassfish.api.deployment.MetaData) EngineInfo(org.glassfish.internal.data.EngineInfo) ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) ApplicationRegistry(org.glassfish.internal.data.ApplicationRegistry) FileUtils(com.sun.enterprise.util.io.FileUtils) ResourceLocator(org.glassfish.hk2.classmodel.reflect.util.ResourceLocator) SpanSequence(org.glassfish.internal.deployment.analysis.SpanSequence) Events(org.glassfish.api.event.Events) DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) PropertyVetoException(java.beans.PropertyVetoException) ArchiveHandler(org.glassfish.api.deployment.archive.ArchiveHandler) Collectors.toMap(java.util.stream.Collectors.toMap) TransactionFailure(org.jvnet.hk2.config.TransactionFailure) URI(java.net.URI) ThreadFactory(java.util.concurrent.ThreadFactory) ZipEntry(java.util.zip.ZipEntry) ContainerRegistry(org.glassfish.internal.data.ContainerRegistry) RetryableException(org.jvnet.hk2.config.RetryableException) ClientJarWriter(org.glassfish.deployment.common.ClientJarWriter) ParameterMap(org.glassfish.api.admin.ParameterMap) Logger(java.util.logging.Logger) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ApplicationState(fish.payara.nucleus.hotdeploy.ApplicationState) DeploymentLifecycleProbeProvider(org.glassfish.deployment.monitor.DeploymentLifecycleProbeProvider) UndeployCommandParameters(org.glassfish.api.deployment.UndeployCommandParameters) DeploymentGroup(fish.payara.enterprise.config.serverbeans.DeploymentGroup) Deployment(org.glassfish.internal.deployment.Deployment) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) INFO(java.util.logging.Level.INFO) Singleton(javax.inject.Singleton) Function(java.util.function.Function) Level(java.util.logging.Level) SEVERE(java.util.logging.Level.SEVERE) ActionReport(org.glassfish.api.ActionReport) Inject(javax.inject.Inject) PayaraExecutorService(fish.payara.nucleus.executorservice.PayaraExecutorService) ExecutorService(java.util.concurrent.ExecutorService) Types(org.glassfish.hk2.classmodel.reflect.Types) FINE(java.util.logging.Level.FINE) Deployer(org.glassfish.api.deployment.Deployer) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) DeploymentUtils(org.glassfish.deployment.common.DeploymentUtils) FileInputStream(java.io.FileInputStream) ModuleInfo(org.glassfish.internal.data.ModuleInfo) TimeUnit(java.util.concurrent.TimeUnit) VirtualizationEnv(org.glassfish.api.virtualization.VirtualizationEnv) ConfigBean(org.jvnet.hk2.config.ConfigBean) Transaction(org.jvnet.hk2.config.Transaction) CompositeHandler(org.glassfish.api.deployment.archive.CompositeHandler) ParsingContext(org.glassfish.hk2.classmodel.reflect.ParsingContext) InputStream(java.io.InputStream) ArchiveHandler(org.glassfish.api.deployment.archive.ArchiveHandler) ProgressTracker(org.glassfish.internal.data.ProgressTracker) ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) ActionReport(org.glassfish.api.ActionReport) Logger(java.util.logging.Logger) ClassLoaderHierarchy(org.glassfish.internal.api.ClassLoaderHierarchy) EngineInfo(org.glassfish.internal.data.EngineInfo) StructuredDeploymentTracing(org.glassfish.internal.deployment.analysis.StructuredDeploymentTracing) SpanSequence(org.glassfish.internal.deployment.analysis.SpanSequence) ApplicationState(fish.payara.nucleus.hotdeploy.ApplicationState) ClientJarWriter(org.glassfish.deployment.common.ClientJarWriter) Sniffer(org.glassfish.api.container.Sniffer) EngineRef(org.glassfish.internal.data.EngineRef) MultiException(org.glassfish.hk2.api.MultiException) DeploymentException(org.glassfish.deployment.common.DeploymentException) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException) RetryableException(org.jvnet.hk2.config.RetryableException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) ModuleInfo(org.glassfish.internal.data.ModuleInfo) PreDestroy(org.glassfish.hk2.api.PreDestroy) DeploymentException(org.glassfish.deployment.common.DeploymentException) DeploymentSpan(org.glassfish.internal.deployment.analysis.DeploymentSpan)

Example 2 with Optional

use of org.jvnet.hk2.annotations.Optional in project Payara by payara.

the class GetHttpListener method execute.

@Override
public void execute(AdminCommandContext context) {
    ActionReport report = context.getActionReport();
    // Check that a configuration can be found
    if (targetUtil.getConfig(target) == null) {
        report.failure(logger, MessageFormat.format(logger.getResourceBundle().getString(LogFacade.UNKNOWN_CONFIG), target));
        return;
    }
    Config config = targetUtil.getConfig(target);
    // Check that a matching listener can be found
    List<NetworkListener> listeners = config.getNetworkConfig().getNetworkListeners().getNetworkListener();
    Optional<NetworkListener> optionalListener = listeners.stream().filter(listener -> listener.getName().equals(listenerName)).findFirst();
    if (!optionalListener.isPresent()) {
        report.failure(logger, MessageFormat.format(logger.getResourceBundle().getString(LogFacade.UNKNOWN_NETWORK_LISTENER), listenerName, target));
        return;
    }
    NetworkListener listener = optionalListener.get();
    // Write message body
    report.appendMessage(String.format("Name: %s\n", listener.getName()));
    report.appendMessage(String.format("Enabled: %s\n", listener.getEnabled()));
    report.appendMessage(String.format("Port: %s\n", listener.getPort()));
    if (listener.getPortRange() != null) {
        report.appendMessage(String.format("Port Range: %s\n", listener.getPortRange()));
    }
    report.appendMessage(String.format("Address: %s\n", listener.getAddress()));
    report.appendMessage(String.format("Protocol: %s\n", listener.getProtocol()));
    if (verbose) {
        report.appendMessage(String.format("Transport: %s\n", listener.getTransport()));
        report.appendMessage(String.format("Type: %s\n", listener.getType()));
        report.appendMessage(String.format("Thread Pool: %s\n", listener.getThreadPool()));
        report.appendMessage(String.format("JK Enabled: %s\n", listener.getJkEnabled()));
        report.appendMessage(String.format("JK Configuration File: %s\n", listener.getJkConfigurationFile()));
    }
    // Write the variables as properties
    Properties properties = new Properties();
    properties.put("name", listener.getName());
    properties.put("enabled", listener.getEnabled());
    properties.put("port", listener.getPort());
    if (listener.getPortRange() != null) {
        properties.put("portRange", listener.getPortRange());
    }
    properties.put("address", listener.getAddress());
    properties.put("protocol", listener.getProtocol());
    properties.put("transport", listener.getTransport());
    properties.put("type", listener.getType());
    properties.put("threadPool", listener.getThreadPool());
    properties.put("jkEnabled", listener.getJkEnabled());
    properties.put("jkConfigurationFile", listener.getJkConfigurationFile());
    report.setExtraProperties(properties);
}
Also used : Param(org.glassfish.api.Param) LogFacade(org.glassfish.web.admin.LogFacade) RestEndpoint(org.glassfish.api.admin.RestEndpoint) CommandLock(org.glassfish.api.admin.CommandLock) MessageFormat(java.text.MessageFormat) I18n(org.glassfish.api.I18n) PerLookup(org.glassfish.hk2.api.PerLookup) Inject(javax.inject.Inject) ActionReport(org.glassfish.api.ActionReport) ExecuteOn(org.glassfish.api.admin.ExecuteOn) RuntimeType(org.glassfish.api.admin.RuntimeType) NetworkListener(org.glassfish.grizzly.config.dom.NetworkListener) RestEndpoints(org.glassfish.api.admin.RestEndpoints) AdminCommand(org.glassfish.api.admin.AdminCommand) Properties(java.util.Properties) TargetType(org.glassfish.config.support.TargetType) Logger(java.util.logging.Logger) List(java.util.List) Target(org.glassfish.internal.api.Target) Service(org.jvnet.hk2.annotations.Service) AdminCommandContext(org.glassfish.api.admin.AdminCommandContext) CommandTarget(org.glassfish.config.support.CommandTarget) HttpService(com.sun.enterprise.config.serverbeans.HttpService) Optional(java.util.Optional) SystemPropertyConstants(com.sun.enterprise.util.SystemPropertyConstants) Config(com.sun.enterprise.config.serverbeans.Config) Config(com.sun.enterprise.config.serverbeans.Config) ActionReport(org.glassfish.api.ActionReport) Properties(java.util.Properties) NetworkListener(org.glassfish.grizzly.config.dom.NetworkListener)

Example 3 with Optional

use of org.jvnet.hk2.annotations.Optional in project launcher by fujitsu.

the class CommandRunnerImpl method generateUsageText.

/**
 * Generate the usage-text from the annotated Param in the command class.
 *
 * @param model command model
 * @return generated usagetext
 */
private static String generateUsageText(CommandModel model) {
    StringBuffer usageText = new StringBuffer();
    usageText.append(adminStrings.getLocalString("adapter.usage", "Usage: "));
    usageText.append(model.getCommandName());
    usageText.append(" ");
    StringBuffer operand = new StringBuffer();
    for (CommandModel.ParamModel pModel : model.getParameters()) {
        final Param param = pModel.getParam();
        final String paramName = pModel.getName().toLowerCase(Locale.ENGLISH);
        // skip "hidden" options
        if (paramName.startsWith("_")) {
            continue;
        }
        // do not want to display password as an option
        if (param.password()) {
            continue;
        }
        // do not want to display obsolete options
        if (param.obsolete()) {
            continue;
        }
        final boolean optional = param.optional();
        final Class<?> ftype = pModel.getType();
        Object fvalue = null;
        String fvalueString = null;
        try {
            fvalue = param.defaultValue();
            if (fvalue != null) {
                fvalueString = fvalue.toString();
            }
        } catch (Exception e) {
        // just leave it as null...
        }
        // this is a param.
        if (param.primary()) {
            if (optional) {
                operand.append("[").append(paramName).append("] ");
            } else {
                operand.append(paramName).append(" ");
            }
            continue;
        }
        if (optional) {
            usageText.append("[");
        }
        usageText.append("--").append(paramName);
        if (ok(param.defaultValue())) {
            usageText.append("=").append(param.defaultValue());
        } else if (ftype.isAssignableFrom(String.class)) {
            // check if there is a default value assigned
            if (ok(fvalueString)) {
                usageText.append("=").append(fvalueString);
            } else {
                usageText.append("=").append(paramName);
            }
        } else if (ftype.isAssignableFrom(Boolean.class)) {
            // note: There is no defaultValue for this param.  It might
            // hava  value -- but we don't care -- it isn't an official
            // default value.
            usageText.append("=").append("true|false");
        } else {
            usageText.append("=").append(paramName);
        }
        if (optional) {
            usageText.append("] ");
        } else {
            usageText.append(" ");
        }
    }
    usageText.append(operand);
    return usageText.toString();
}
Also used : Param(org.glassfish.api.Param) MultiException(org.glassfish.hk2.api.MultiException) UnacceptableValueException(org.glassfish.common.util.admin.UnacceptableValueException) UnsatisfiedDependencyException(org.jvnet.hk2.config.UnsatisfiedDependencyException)

Example 4 with Optional

use of org.jvnet.hk2.annotations.Optional in project glassfish-hk2 by eclipse-ee4j.

the class Utilities method getParamInformation.

private static AnnotationInformation getParamInformation(Annotation[] memberAnnotations) {
    boolean useDefault = true;
    Set<Annotation> qualifiers = null;
    boolean optional = false;
    boolean self = false;
    Unqualified unqualified = null;
    for (Annotation anno : memberAnnotations) {
        if (ReflectionHelper.isAnnotationAQualifier(anno)) {
            if (qualifiers == null)
                qualifiers = new HashSet<Annotation>();
            qualifiers.add(anno);
            useDefault = false;
        } else if (Optional.class.equals(anno.annotationType())) {
            optional = true;
            useDefault = false;
        } else if (Self.class.equals(anno.annotationType())) {
            self = true;
            useDefault = false;
        } else if (Unqualified.class.equals(anno.annotationType())) {
            unqualified = (Unqualified) anno;
            useDefault = false;
        }
    }
    if (useDefault)
        return DEFAULT_ANNOTATION_INFORMATION;
    if (qualifiers == null)
        qualifiers = DEFAULT_ANNOTATION_INFORMATION.qualifiers;
    return new AnnotationInformation(qualifiers, optional, self, unqualified);
}
Also used : Optional(org.jvnet.hk2.annotations.Optional) Unqualified(org.glassfish.hk2.api.Unqualified) Annotation(java.lang.annotation.Annotation) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 5 with Optional

use of org.jvnet.hk2.annotations.Optional in project Payara by payara.

the class DolProvider method processDOL.

private Application processDOL(DeploymentContext dc) throws IOException {
    ReadableArchive sourceArchive = dc.getSource();
    sourceArchive.setExtraData(Types.class, dc.getTransientAppMetaData(Types.class.getName(), Types.class));
    sourceArchive.setExtraData(Parser.class, dc.getTransientAppMetaData(Parser.class.getName(), Parser.class));
    Optional<ApplicationState> appState = hotDeployService.getApplicationState(dc);
    appState.ifPresent(state -> sourceArchive.setExtraData(ApplicationState.class, state));
    ClassLoader cl = dc.getClassLoader();
    DeployCommandParameters params = dc.getCommandParameters(DeployCommandParameters.class);
    sourceArchive.addArchiveMetaData(DeploymentProperties.APP_PROPS, dc.getAppProps());
    sourceArchive.addArchiveMetaData(DeploymentProperties.COMMAND_PARAMS, params);
    String name = params.name();
    String archiveType = dc.getArchiveHandler().getArchiveType();
    Archivist archivist = archivistFactory.getArchivist(archiveType, cl);
    if (archivist == null) {
        // an empty Application object
        return Application.createApplication();
    }
    archivist.setAnnotationProcessingRequested(true);
    String xmlValidationLevel = dasConfig.getDeployXmlValidation();
    archivist.setXMLValidationLevel(xmlValidationLevel);
    if (xmlValidationLevel.equals("none")) {
        archivist.setXMLValidation(false);
    }
    archivist.setRuntimeXMLValidationLevel(xmlValidationLevel);
    if (xmlValidationLevel.equals("none")) {
        archivist.setRuntimeXMLValidation(false);
    }
    Collection<Sniffer> sniffers = dc.getTransientAppMetaData(DeploymentProperties.SNIFFERS, Collection.class);
    archivist.setExtensionArchivists(archivistFactory.getExtensionsArchivists(sniffers, archivist.getModuleType()));
    ApplicationHolder holder = dc.getModuleMetaData(ApplicationHolder.class);
    File deploymentPlan = params.deploymentplan;
    handleDeploymentPlan(deploymentPlan, archivist, sourceArchive, holder);
    long start = System.currentTimeMillis();
    Application application = appState.map(state -> state.getModuleMetaData(Application.class)).orElse(holder != null ? holder.app : null);
    if (application != null) {
        application.setAppName(name);
        application.setClassLoader(cl);
        application.setRoleMapper(null);
        if (application.isVirtual()) {
            ModuleDescriptor md = application.getStandaloneBundleDescriptor().getModuleDescriptor();
            md.setModuleName(name);
            if (appState.map(ApplicationState::isActive).orElse(false)) {
                application.getStandaloneBundleDescriptor().setClassLoader(cl);
                dc.addModuleMetaData(application.getStandaloneBundleDescriptor());
                for (RootDeploymentDescriptor extension : application.getStandaloneBundleDescriptor().getExtensionsDescriptors()) {
                    extension.setClassLoader(cl);
                    dc.addModuleMetaData(extension);
                }
            }
        }
        try {
            applicationFactory.openWith(application, sourceArchive, archivist);
        } catch (SAXParseException e) {
            throw new IOException(e);
        }
    } else {
        // and it's a standalone module
        try {
            application = applicationFactory.openArchive(name, archivist, sourceArchive, true);
            application.setAppName(name);
            ModuleDescriptor md = application.getStandaloneBundleDescriptor().getModuleDescriptor();
            md.setModuleName(name);
        } catch (SAXParseException e) {
            throw new IOException(e);
        }
    }
    application.setRegistrationName(name);
    sourceArchive.removeExtraData(Types.class);
    sourceArchive.removeExtraData(Parser.class);
    Logger.getAnonymousLogger().log(FINE, "DOL Loading time{0}", System.currentTimeMillis() - start);
    return application;
}
Also used : StructuredDeploymentTracing(org.glassfish.internal.deployment.analysis.StructuredDeploymentTracing) FileUtils(com.sun.enterprise.util.io.FileUtils) ApplicationMetaDataProvider(org.glassfish.api.deployment.ApplicationMetaDataProvider) Provider(javax.inject.Provider) Util(com.sun.enterprise.deployment.deploy.shared.Util) ClassLoaderHierarchy(org.glassfish.internal.api.ClassLoaderHierarchy) DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) Level(java.util.logging.Level) ActionReport(org.glassfish.api.ActionReport) Inject(javax.inject.Inject) ArchiveFactory(com.sun.enterprise.deploy.shared.ArchiveFactory) ArchiveHandler(org.glassfish.api.deployment.archive.ArchiveHandler) DasConfig(com.sun.enterprise.config.serverbeans.DasConfig) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) ApplicationInfoProvider(org.glassfish.internal.deployment.ApplicationInfoProvider) LocalStringManagerImpl(com.sun.enterprise.util.LocalStringManagerImpl) ServerEnvironment(org.glassfish.api.admin.ServerEnvironment) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) FileArchive(com.sun.enterprise.deploy.shared.FileArchive) HTMLActionReporter(com.sun.enterprise.admin.report.HTMLActionReporter) WritableArchive(org.glassfish.api.deployment.archive.WritableArchive) Sniffer(org.glassfish.api.container.Sniffer) HotDeployService(fish.payara.nucleus.hotdeploy.HotDeployService) PreDestroy(org.glassfish.hk2.api.PreDestroy) DeploymentTracing(org.glassfish.internal.deployment.DeploymentTracing) Types(org.glassfish.hk2.classmodel.reflect.Types) FINE(java.util.logging.Level.FINE) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) Module(com.sun.enterprise.config.serverbeans.Module) Collection(java.util.Collection) IOException(java.io.IOException) com.sun.enterprise.deployment.archivist(com.sun.enterprise.deployment.archivist) DeploymentSpan(org.glassfish.internal.deployment.analysis.DeploymentSpan) Logger(java.util.logging.Logger) File(java.io.File) DeploymentPlanArchive(com.sun.enterprise.deployment.deploy.shared.DeploymentPlanArchive) Parser(org.glassfish.hk2.classmodel.reflect.Parser) ApplicationState(fish.payara.nucleus.hotdeploy.ApplicationState) SAXParseException(org.xml.sax.SAXParseException) List(java.util.List) Service(org.jvnet.hk2.annotations.Service) MetaData(org.glassfish.api.deployment.MetaData) Domain(com.sun.enterprise.config.serverbeans.Domain) InputJarArchive(com.sun.enterprise.deployment.deploy.shared.InputJarArchive) org.glassfish.deployment.common(org.glassfish.deployment.common) Optional(java.util.Optional) Application(com.sun.enterprise.deployment.Application) Deployment(org.glassfish.internal.deployment.Deployment) Types(org.glassfish.hk2.classmodel.reflect.Types) ApplicationState(fish.payara.nucleus.hotdeploy.ApplicationState) Sniffer(org.glassfish.api.container.Sniffer) IOException(java.io.IOException) Parser(org.glassfish.hk2.classmodel.reflect.Parser) DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) SAXParseException(org.xml.sax.SAXParseException) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) File(java.io.File) Application(com.sun.enterprise.deployment.Application)

Aggregations

ActionReport (org.glassfish.api.ActionReport)6 IOException (java.io.IOException)4 List (java.util.List)4 Optional (java.util.Optional)4 Logger (java.util.logging.Logger)4 Inject (javax.inject.Inject)4 Param (org.glassfish.api.Param)4 Service (org.jvnet.hk2.annotations.Service)4 AbstractModule (com.google.inject.AbstractModule)3 Injector (com.google.inject.Injector)3 FileArchive (com.sun.enterprise.deploy.shared.FileArchive)3 ApplicationState (fish.payara.nucleus.hotdeploy.ApplicationState)3 File (java.io.File)3 Properties (java.util.Properties)3 Test (org.junit.Test)3 GuiceIntoHK2Bridge (org.jvnet.hk2.guice.bridge.api.GuiceIntoHK2Bridge)3 Config (com.sun.enterprise.config.serverbeans.Config)2 HttpService (com.sun.enterprise.config.serverbeans.HttpService)2 ArchiveFactory (com.sun.enterprise.deploy.shared.ArchiveFactory)2 LocalStringManagerImpl (com.sun.enterprise.util.LocalStringManagerImpl)2