Search in sources :

Example 6 with VersioningSyntaxException

use of org.glassfish.deployment.versioning.VersioningSyntaxException in project Payara by payara.

the class ListSubComponentsCommand method execute.

public void execute(AdminCommandContext context) {
    final ActionReport report = context.getActionReport();
    ActionReport.MessagePart part = report.getTopMessagePart();
    String applicationName = modulename;
    if (appname != null) {
        applicationName = appname;
    }
    try {
        VersioningUtils.checkIdentifier(applicationName);
    } catch (VersioningSyntaxException ex) {
        report.setMessage(ex.getLocalizedMessage());
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    if (!deployment.isRegistered(applicationName)) {
        report.setMessage(localStrings.getLocalString("application.notreg", "Application {0} not registered", applicationName));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    Application application = applications.getApplication(applicationName);
    if (application.isLifecycleModule()) {
        if (!terse) {
            part.setMessage(localStrings.getLocalString("listsubcomponents.no.elements.to.list", "Nothing to List."));
        }
        return;
    }
    ApplicationInfo appInfo = appRegistry.get(applicationName);
    if (appInfo == null) {
        report.setMessage(localStrings.getLocalString("application.not.enabled", "Application {0} is not in an enabled state", applicationName));
        return;
    }
    com.sun.enterprise.deployment.Application app = appInfo.getMetaData(com.sun.enterprise.deployment.Application.class);
    if (app == null) {
        if (!terse) {
            part.setMessage(localStrings.getLocalString("listsubcomponents.no.elements.to.list", "Nothing to List."));
        }
        return;
    }
    Map<String, String> subComponents;
    Map<String, String> subComponentsMap = new HashMap<String, String>();
    if (appname == null) {
        subComponents = getAppLevelComponents(app, type, subComponentsMap);
    } else {
        // strip the version suffix (delimited by colon), if present
        int versionSuffix = modulename.indexOf(':');
        String versionLessModuleName = versionSuffix > 0 ? modulename.substring(0, versionSuffix) : modulename;
        BundleDescriptor bundleDesc = app.getModuleByUri(versionLessModuleName);
        if (bundleDesc == null) {
            report.setMessage(localStrings.getLocalString("listsubcomponents.invalidmodulename", "Invalid module name", appname, modulename));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
        subComponents = getModuleLevelComponents(bundleDesc, type, subComponentsMap);
    }
    // the type param can only have values "ejbs" and "servlets"
    if (type != null) {
        if (!type.equals("servlets") && !type.equals("ejbs")) {
            report.setMessage(localStrings.getLocalString("listsubcomponents.invalidtype", "The type option has invalid value {0}. It should have a value of servlets or ejbs.", type));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    }
    List<String> subModuleInfos = new ArrayList<String>();
    if (!app.isVirtual()) {
        subModuleInfos = getSubModulesForEar(app, type);
    }
    int[] longestValue = new int[2];
    for (Map.Entry<String, String> entry : subComponents.entrySet()) {
        String key = entry.getKey();
        if (key.length() > longestValue[0]) {
            longestValue[0] = key.length();
        }
        String value = entry.getValue();
        if (value.length() > longestValue[1]) {
            longestValue[1] = value.length();
        }
    }
    StringBuilder formattedLineBuf = new StringBuilder();
    for (int j = 0; j < 2; j++) {
        longestValue[j] += 2;
        formattedLineBuf.append("%-").append(longestValue[j]).append("s");
    }
    String formattedLine = formattedLineBuf.toString();
    if (!terse && subComponents.isEmpty()) {
        part.setMessage(localStrings.getLocalString("listsubcomponents.no.elements.to.list", "Nothing to List."));
    }
    int i = 0;
    for (String key : subComponents.keySet()) {
        ActionReport.MessagePart childPart = part.addChild();
        childPart.setMessage(String.format(formattedLine, new Object[] { key, subComponents.get(key) }));
        if (appname == null && !app.isVirtual()) {
            // support for JSR88 client
            if (subModuleInfos.get(i) != null) {
                childPart.addProperty("moduleInfo", subModuleInfos.get(i));
            }
        }
        if (resources) {
            Module module = application.getModule(key);
            if (module != null) {
                ActionReport subReport = report.addSubActionsReport();
                CommandRunner.CommandInvocation inv = commandRunner.getCommandInvocation("_list-resources", subReport, context.getSubject());
                final ParameterMap parameters = new ParameterMap();
                parameters.add("appname", application.getName());
                parameters.add("modulename", module.getName());
                inv.parameters(parameters).execute();
                ActionReport.MessagePart subPart = subReport.getTopMessagePart();
                for (ActionReport.MessagePart cp : subPart.getChildren()) {
                    ActionReport.MessagePart resourcesChildPart = childPart.addChild();
                    resourcesChildPart.setMessage("  " + cp.getMessage());
                }
            }
        }
        i++;
    }
    // add the properties for GUI to display
    Set<String> keys = subComponentsMap.keySet();
    for (String key : keys) {
        part.addProperty(key, subComponentsMap.get(key));
    }
    // now this is the normal output for the list-sub-components command
    report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) ArrayList(java.util.ArrayList) ActionReport(org.glassfish.api.ActionReport) CommandRunner(org.glassfish.api.admin.CommandRunner) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) ParameterMap(org.glassfish.api.admin.ParameterMap) RestEndpoint(org.glassfish.api.admin.RestEndpoint) BundleDescriptor(com.sun.enterprise.deployment.BundleDescriptor) WebBundleDescriptor(com.sun.enterprise.deployment.WebBundleDescriptor) EjbBundleDescriptor(com.sun.enterprise.deployment.EjbBundleDescriptor) Module(com.sun.enterprise.config.serverbeans.Module) Application(com.sun.enterprise.config.serverbeans.Application) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ParameterMap(org.glassfish.api.admin.ParameterMap)

Example 7 with VersioningSyntaxException

use of org.glassfish.deployment.versioning.VersioningSyntaxException in project Payara by payara.

the class DeployCommand method execute.

/**
 * Entry point from the framework into the command execution
 *
 * @param context context for the command.
 */
@Override
public void execute(AdminCommandContext context) {
    long timeTakenToDeploy = 0;
    long deploymentTimeMillis = 0;
    try {
        // needs to be fixed in hk2, we don't generate the right innerclass index. it should use $
        Collection<Interceptor> interceptors = habitat.getAllServices(Interceptor.class);
        if (interceptors != null) {
            for (Interceptor interceptor : interceptors) {
                interceptor.intercept(this, initialContext);
            }
        }
        deployment.validateDeploymentTarget(target, name, isredeploy);
        if (tracing != null) {
            tracing.addMark(DeploymentTracing.Mark.TARGET_VALIDATED);
        }
        ActionReport.MessagePart part = report.getTopMessagePart();
        part.addProperty(DeploymentProperties.NAME, name);
        ApplicationConfigInfo savedAppConfig = new ApplicationConfigInfo(apps.getModule(Application.class, name));
        Properties undeployProps = handleRedeploy(name, report, context);
        if (enabled == null) {
            enabled = Boolean.TRUE;
        }
        // clean up any left over repository files
        if (!keepreposdir.booleanValue()) {
            final File reposDir = new File(env.getApplicationRepositoryPath(), VersioningUtils.getRepositoryName(name));
            if (reposDir.exists()) {
                for (int i = 0; i < domain.getApplications().getApplications().size(); i++) {
                    File existrepos = new File(new URI(domain.getApplications().getApplications().get(i).getLocation()));
                    String appname = domain.getApplications().getApplications().get(i).getName();
                    if (!appname.equals(name) && existrepos.getAbsoluteFile().equals(reposDir.getAbsoluteFile())) {
                        report.failure(logger, localStrings.getLocalString("deploy.dupdeployment", "Application {0} is trying to use the same repository directory as application {1}, please choose a different application name to deploy", name, appname));
                        return;
                    }
                }
                /*
                     * Delete the repository directory as an archive to allow
                     * any special processing (such as stale file handling)
                     * to run.
                     */
                final FileArchive arch = DeploymentUtils.openAsFileArchive(reposDir, archiveFactory);
                arch.delete();
            }
        }
        if (!DeploymentUtils.isDomainTarget(target) && enabled) {
            // try to disable the enabled version, if exist
            try {
                versioningService.handleDisable(name, target, report, context.getSubject());
            } catch (VersioningSyntaxException e) {
                report.failure(logger, e.getMessage());
                return;
            }
        }
        File source = new File(archive.getURI().getSchemeSpecificPart());
        boolean isDirectoryDeployed = true;
        if (!source.isDirectory()) {
            isDirectoryDeployed = false;
            expansionDir = new File(domain.getApplicationRoot(), VersioningUtils.getRepositoryName(name));
            path = expansionDir;
        } else {
            // test if a version is already directory deployed from this dir
            String versionFromSameDir = versioningService.getVersionFromSameDir(source);
            if (!force && versionFromSameDir != null) {
                report.failure(logger, VersioningUtils.LOCALSTRINGS.getLocalString("versioning.deployment.dual.inplace", "GlassFish do not support versioning for directory deployment when using the same directory. The directory {0} is already assigned to the version {1}.", source.getPath(), versionFromSameDir));
                return;
            }
        }
        // create the parent class loader
        deploymentContext = deployment.getBuilder(logger, this, report).source(initialContext.getSource()).archiveHandler(archiveHandler).build(initialContext);
        if (tracing != null) {
            tracing.addMark(DeploymentTracing.Mark.CONTEXT_CREATED);
            deploymentContext.addModuleMetaData(tracing);
        }
        // reset the properties (might be null) set by the deployers when undeploying.
        if (undeployProps != null) {
            deploymentContext.getAppProps().putAll(undeployProps);
        }
        if (properties != null || property != null) {
            // check for both
            if (properties == null) {
                properties = new Properties();
            }
            if (property != null) {
                properties.putAll(property);
            }
        }
        if (properties != null) {
            deploymentContext.getAppProps().putAll(properties);
            validateDeploymentProperties(properties, deploymentContext);
        }
        // clean up any generated files
        deploymentContext.clean();
        Properties appProps = deploymentContext.getAppProps();
        /*
             * If the app's location is within the domain's directory then
             * express it in the config as ${com.sun.aas.instanceRootURI}/rest-of-path
             * so users can relocate the entire installation without having
             * to modify the app locations.  Leave the location alone if
             * it does not fall within the domain directory.
             */
        String appLocation = DeploymentUtils.relativizeWithinDomainIfPossible(deploymentContext.getSource().getURI());
        appProps.setProperty(ServerTags.LOCATION, appLocation);
        // set to default "user", deployers can override it
        // during processing
        appProps.setProperty(ServerTags.OBJECT_TYPE, "user");
        if (contextroot != null) {
            appProps.setProperty(ServerTags.CONTEXT_ROOT, contextroot);
        }
        appProps.setProperty(ServerTags.DIRECTORY_DEPLOYED, String.valueOf(isDirectoryDeployed));
        if (type == null) {
            type = archiveHandler.getArchiveType();
        }
        appProps.setProperty(Application.ARCHIVE_TYPE_PROP_NAME, type);
        if (appProps.getProperty(ServerTags.CDI_DEV_MODE_ENABLED_PROP) == null) {
            appProps.setProperty(ServerTags.CDI_DEV_MODE_ENABLED_PROP, Boolean.FALSE.toString());
        }
        savedAppConfig.store(appProps);
        deploymentContext.addTransientAppMetaData(DeploymentProperties.PREVIOUS_TARGETS, previousTargets);
        deploymentContext.addTransientAppMetaData(DeploymentProperties.PREVIOUS_VIRTUAL_SERVERS, previousVirtualServers);
        deploymentContext.addTransientAppMetaData(DeploymentProperties.PREVIOUS_ENABLED_ATTRIBUTES, previousEnabledAttributes);
        Transaction t = deployment.prepareAppConfigChanges(deploymentContext);
        if (tracing != null) {
            tracing.addMark(DeploymentTracing.Mark.DEPLOY);
        }
        Deployment.ApplicationDeployment deplResult = deployment.prepare(null, deploymentContext);
        if (!loadOnly) {
            deployment.initialize(deplResult.appInfo, deplResult.appInfo.getSniffers(), deplResult.context);
        }
        ApplicationInfo appInfo = deplResult.appInfo;
        /*
             * Various deployers might have added to the downloadable or
             * generated artifacts.  Extract them and, if the command succeeded,
             * persist both into the app properties (which will be recorded
             * in domain.xml).
             */
        final Artifacts downloadableArtifacts = DeploymentUtils.downloadableArtifacts(deploymentContext);
        final Artifacts generatedArtifacts = DeploymentUtils.generatedArtifacts(deploymentContext);
        if (report.getActionExitCode() == ActionReport.ExitCode.SUCCESS) {
            try {
                moveAppFilesToPermanentLocation(deploymentContext, logger);
                recordFileLocations(appProps);
                downloadableArtifacts.record(appProps);
                generatedArtifacts.record(appProps);
                // Set the application deploy time
                timeTakenToDeploy = timing.elapsed();
                deploymentContext.getTransientAppMetaData("application", Application.class).setDeploymentTime(Long.toString(timeTakenToDeploy));
                deploymentTimeMillis = System.currentTimeMillis();
                deploymentContext.getTransientAppMetaData("application", Application.class).setTimeDeployed(Long.toString(deploymentTimeMillis));
                // register application information in domain.xml
                deployment.registerAppInDomainXML(appInfo, deploymentContext, t);
                if (tracing != null) {
                    tracing.addMark(DeploymentTracing.Mark.REGISTRATION);
                }
                if (retrieve != null) {
                    retrieveArtifacts(context, downloadableArtifacts.getArtifacts(), retrieve, false, name);
                }
                suppInfo.setDeploymentContext(deploymentContext);
                // Fix for issue 14442
                // We want to report the worst subreport value.
                ActionReport.ExitCode worstExitCode = ExitCode.SUCCESS;
                for (ActionReport subReport : report.getSubActionsReport()) {
                    ActionReport.ExitCode actionExitCode = subReport.getActionExitCode();
                    if (actionExitCode.isWorse(worstExitCode)) {
                        worstExitCode = actionExitCode;
                    }
                }
                report.setActionExitCode(worstExitCode);
                report.setResultType(String.class, name);
            } catch (Exception e) {
                // roll back the deployment and re-throw the exception
                deployment.undeploy(name, deploymentContext);
                deploymentContext.clean();
                throw e;
            }
        }
    } catch (Throwable e) {
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        if (e.getMessage() != null) {
            report.setMessage(e.getMessage());
            report.setFailureCause(e);
        } else {
            report.setFailureCause(null);
        }
    } finally {
        events.unregister(this);
        try {
            archive.close();
        } catch (IOException e) {
            logger.log(Level.FINE, localStrings.getLocalString("errClosingArtifact", "Error while closing deployable artifact : ", path.getAbsolutePath()), e);
        }
        if (tracing != null) {
            tracing.print(System.out);
        }
        if (report.getActionExitCode().equals(ActionReport.ExitCode.SUCCESS)) {
            // Set the app name in the result so that embedded deployer can retrieve it.
            report.setResultType(String.class, name);
            report.setMessage(localStrings.getLocalString("deploy.command.success", "Application deployed with name {0}", name));
            logger.info(localStrings.getLocalString("deploy.done", "Deployment of {0} done is {1} ms at {2}", name, timeTakenToDeploy, DateFormat.getDateInstance().format(new Date(deploymentTimeMillis))));
        } else if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
            String errorMessage = report.getMessage();
            Throwable cause = report.getFailureCause();
            if (cause != null) {
                String causeMessage = cause.getMessage();
                if (causeMessage != null && !causeMessage.equals(errorMessage)) {
                    errorMessage = errorMessage + " : " + cause.getMessage();
                }
                logger.log(Level.SEVERE, errorMessage, cause.getCause());
            }
            report.setMessage(localStrings.getLocalString("deploy.errDuringDepl", "Error occur during deployment: {0}.", errorMessage));
            // reset the failure cause so command framework will not try
            // to print the same message again
            report.setFailureCause(null);
            if (expansionDir != null) {
                final FileArchive arch;
                try {
                    /*
                         * Open and then delete the expansion directory as
                         * a file archive so stale file handling can run.
                         */
                    arch = DeploymentUtils.openAsFileArchive(expansionDir, archiveFactory);
                    arch.delete();
                } catch (IOException ex) {
                    final String msg = localStrings.getLocalString("deploy.errDelRepos", "Error deleting repository directory {0}", expansionDir.getAbsolutePath());
                    report.failure(logger, msg, ex);
                }
            }
        }
        if (deploymentContext != null && !loadOnly) {
            deploymentContext.postDeployClean(true);
        }
    }
}
Also used : ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) ActionReport(org.glassfish.api.ActionReport) URI(java.net.URI) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) ExitCode(org.glassfish.api.ActionReport.ExitCode) IOException(java.io.IOException) RestEndpoint(org.glassfish.api.admin.RestEndpoint) URISyntaxException(java.net.URISyntaxException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) IOException(java.io.IOException) Transaction(org.jvnet.hk2.config.Transaction) FileArchive(com.sun.enterprise.deploy.shared.FileArchive) File(java.io.File)

Example 8 with VersioningSyntaxException

use of org.glassfish.deployment.versioning.VersioningSyntaxException in project Payara by payara.

the class ApplicationLifecycle method getContext.

private ExtendedDeploymentContext getContext(ExtendedDeploymentContext initial, DeploymentContextBuilder builder) throws IOException {
    DeploymentContextBuilder copy = new DeploymentContextBuidlerImpl(builder);
    ReadableArchive archive = getArchive(copy);
    copy.source(archive);
    if (initial == null) {
        initial = new DeploymentContextImpl(copy, env);
    }
    ArchiveHandler archiveHandler = copy.archiveHandler();
    if (archiveHandler == null) {
        String type = null;
        OpsParams params = builder.params();
        if (params != null) {
            if (params instanceof DeployCommandParameters) {
                type = ((DeployCommandParameters) params).type;
            } else if (params instanceof UndeployCommandParameters) {
                type = ((UndeployCommandParameters) params)._type;
            }
        }
        archiveHandler = getArchiveHandler(archive, type);
    }
    // this is needed for autoundeploy to find the application
    // with the archive name
    File sourceFile = new File(archive.getURI().getSchemeSpecificPart());
    initial.getAppProps().put(ServerTags.DEFAULT_APP_NAME, DeploymentUtils.getDefaultEEName(sourceFile.getName()));
    if (!(sourceFile.isDirectory())) {
        String repositoryBitName = copy.params().name();
        try {
            repositoryBitName = VersioningUtils.getRepositoryName(repositoryBitName);
        } catch (VersioningSyntaxException e) {
            ActionReport report = copy.report();
            report.setMessage(e.getMessage());
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        }
        // create a temporary deployment context
        File expansionDir = new File(domain.getApplicationRoot(), repositoryBitName);
        if (!expansionDir.mkdirs()) {
            /*
                 * On Windows especially a previous directory might have
                 * remainded after an earlier undeployment, for example if
                 * a JAR file in the earlier deployment had been locked.
                 * Warn but do not fail in such a case.
                 */
            logger.fine(localStrings.getLocalString("deploy.cannotcreateexpansiondir", "Error while creating directory for jar expansion: {0}", expansionDir));
        }
        try {
            Long start = System.currentTimeMillis();
            final WritableArchive expandedArchive = archiveFactory.createArchive(expansionDir);
            archiveHandler.expand(archive, expandedArchive, initial);
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Deployment expansion took " + (System.currentTimeMillis() - start));
            }
            // Close the JAR archive before losing the reference to it or else the JAR remains locked.
            try {
                archive.close();
            } catch (IOException e) {
                logger.log(Level.SEVERE, KernelLoggerInfo.errorClosingArtifact, new Object[] { archive.getURI().getSchemeSpecificPart(), e });
                throw e;
            }
            archive = (FileArchive) expandedArchive;
            initial.setSource(archive);
        } catch (IOException e) {
            logger.log(Level.SEVERE, KernelLoggerInfo.errorExpandingFile, e);
            throw e;
        }
    }
    initial.setArchiveHandler(archiveHandler);
    return initial;
}
Also used : IOException(java.io.IOException) File(java.io.File) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException)

Aggregations

VersioningSyntaxException (org.glassfish.deployment.versioning.VersioningSyntaxException)8 ActionReport (org.glassfish.api.ActionReport)4 File (java.io.File)3 IOException (java.io.IOException)3 ParameterMap (org.glassfish.api.admin.ParameterMap)3 DeployCommandParameters (org.glassfish.api.deployment.DeployCommandParameters)3 URI (java.net.URI)2 ArrayList (java.util.ArrayList)2 Logger (java.util.logging.Logger)2 RestEndpoint (org.glassfish.api.admin.RestEndpoint)2 DeploymentContext (org.glassfish.api.deployment.DeploymentContext)2 ApplicationInfo (org.glassfish.internal.data.ApplicationInfo)2 ExtendedDeploymentContext (org.glassfish.internal.deployment.ExtendedDeploymentContext)2 Transaction (org.jvnet.hk2.config.Transaction)2 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)2 Application (com.sun.enterprise.config.serverbeans.Application)1 Module (com.sun.enterprise.config.serverbeans.Module)1 FileArchive (com.sun.enterprise.deploy.shared.FileArchive)1 BundleDescriptor (com.sun.enterprise.deployment.BundleDescriptor)1 EjbBundleDescriptor (com.sun.enterprise.deployment.EjbBundleDescriptor)1