Search in sources :

Example 6 with ReadableArchive

use of org.glassfish.api.deployment.archive.ReadableArchive in project Payara by payara.

the class CreateApplicationRefCommand method execute.

/**
 * Entry point from the framework into the command execution
 * @param context context for the command.
 */
public void execute(AdminCommandContext context) {
    final ActionReport report = context.getActionReport();
    final Logger logger = context.getLogger();
    // retrieve matched version(s) if exist
    List<String> matchedVersions = null;
    if (enabled) {
        try {
            // warn users that they can use version expressions
            VersioningUtils.checkIdentifier(name);
            matchedVersions = new ArrayList<String>(1);
            matchedVersions.add(name);
        } catch (VersioningWildcardException ex) {
            // a version expression is supplied with enabled == true
            report.setMessage(localStrings.getLocalString("wildcard.not.allowed", "WARNING : version expression are available only with --enabled=false"));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        } catch (VersioningSyntaxException ex) {
            report.setMessage(ex.getLocalizedMessage());
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
        if (!deployment.isRegistered(name)) {
            report.setMessage(localStrings.getLocalString("application.notreg", "Application {0} not registered", name));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    } else {
        // retrieve matched version(s) if exist
        try {
            matchedVersions = versioningService.getMatchedVersions(name, null);
        } catch (VersioningException e) {
            report.failure(logger, e.getMessage());
            return;
        }
        // this is an unversioned behavior and the given application is not registered
        if (matchedVersions.isEmpty()) {
            report.setMessage(localStrings.getLocalString("ref.not.referenced.target", "Application {0} is not referenced by target {1}", name, target));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    }
    ActionReport.MessagePart part = report.getTopMessagePart();
    boolean isVersionExpression = VersioningUtils.isVersionExpression(name);
    // for each matched version
    Iterator it = matchedVersions.iterator();
    while (it.hasNext()) {
        String appName = (String) it.next();
        Application applicationInfo = applications.getApplication(appName);
        List<DeploymentGroup> deploymentGroups = domain.getDeploymentGroupsForInstance(target);
        boolean isAppOnDeploymentGroupInstance = false;
        if (deploymentGroups != null && deploymentGroups.isEmpty()) {
            List<Application> applicationsInTarget = domain.getApplicationsInTarget(target);
            List<String> listOfApplications = new ArrayList<>();
            for (Application application : applicationsInTarget) {
                listOfApplications.add(application.getName());
            }
            if (listOfApplications.contains(appName)) {
                isAppOnDeploymentGroupInstance = true;
                break;
            }
        }
        if (!isAppOnDeploymentGroupInstance) {
            ApplicationRef applicationRef = domain.getApplicationRefInTarget(appName, target);
            if (applicationRef != null) {
                // if a versioned name has been provided to the command
                if (isVersionExpression) {
                    ActionReport.MessagePart childPart = part.addChild();
                    childPart.setMessage(localStrings.getLocalString("appref.already.exists", "Application reference {0} already exists in target {1}.", appName, target));
                } else {
                    // returns failure if an untagged name has been provided to the command
                    report.setMessage(localStrings.getLocalString("appref.already.exists", "Application reference {0} already exists in target {1}.", name, target));
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    return;
                }
            } else {
                Transaction t = new Transaction();
                if (applicationInfo.isLifecycleModule()) {
                    handleLifecycleModule(context, t);
                    return;
                }
                ReadableArchive archive;
                File file = null;
                DeployCommandParameters commandParams = null;
                Properties contextProps;
                Map<String, Properties> modulePropsMap = null;
                ApplicationConfigInfo savedAppConfig = null;
                try {
                    commandParams = applicationInfo.getDeployParameters(null);
                    commandParams.origin = Origin.create_application_ref;
                    commandParams.command = Command.create_application_ref;
                    commandParams.target = target;
                    commandParams.virtualservers = virtualservers;
                    commandParams.enabled = enabled;
                    if (lbenabled != null) {
                        commandParams.lbenabled = lbenabled;
                    }
                    commandParams.type = applicationInfo.archiveType();
                    contextProps = applicationInfo.getDeployProperties();
                    modulePropsMap = applicationInfo.getModulePropertiesMap();
                    savedAppConfig = new ApplicationConfigInfo(applicationInfo);
                    URI uri = new URI(applicationInfo.getLocation());
                    file = new File(uri);
                    if (!file.exists()) {
                        report.setMessage(localStrings.getLocalString("fnf", "File not found", file.getAbsolutePath()));
                        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                        return;
                    }
                    archive = archiveFactory.openArchive(file);
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "Error opening deployable artifact : " + file.getAbsolutePath(), e);
                    report.setMessage(localStrings.getLocalString("unknownarchiveformat", "Archive format not recognized"));
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    return;
                }
                try {
                    final ExtendedDeploymentContext deploymentContext = deployment.getBuilder(logger, commandParams, report).source(archive).build();
                    Properties appProps = deploymentContext.getAppProps();
                    appProps.putAll(contextProps);
                    // relativize the location so it could be set properly in
                    // domain.xml
                    String location = DeploymentUtils.relativizeWithinDomainIfPossible(new URI(applicationInfo.getLocation()));
                    appProps.setProperty(ServerTags.LOCATION, location);
                    // relativize the URI properties so they could store in the
                    // domain.xml properly on the instances
                    String appLocation = appProps.getProperty(Application.APP_LOCATION_PROP_NAME);
                    appProps.setProperty(Application.APP_LOCATION_PROP_NAME, DeploymentUtils.relativizeWithinDomainIfPossible(new URI(appLocation)));
                    String planLocation = appProps.getProperty(Application.DEPLOYMENT_PLAN_LOCATION_PROP_NAME);
                    if (planLocation != null) {
                        appProps.setProperty(Application.DEPLOYMENT_PLAN_LOCATION_PROP_NAME, DeploymentUtils.relativizeWithinDomainIfPossible(new URI(planLocation)));
                    }
                    String altDDLocation = appProps.getProperty(Application.ALT_DD_LOCATION_PROP_NAME);
                    if (altDDLocation != null) {
                        appProps.setProperty(Application.ALT_DD_LOCATION_PROP_NAME, DeploymentUtils.relativizeWithinDomainIfPossible(new URI(altDDLocation)));
                    }
                    String runtimeAltDDLocation = appProps.getProperty(Application.RUNTIME_ALT_DD_LOCATION_PROP_NAME);
                    if (runtimeAltDDLocation != null) {
                        appProps.setProperty(Application.RUNTIME_ALT_DD_LOCATION_PROP_NAME, DeploymentUtils.relativizeWithinDomainIfPossible(new URI(runtimeAltDDLocation)));
                    }
                    savedAppConfig.store(appProps);
                    if (modulePropsMap != null) {
                        deploymentContext.setModulePropsMap(modulePropsMap);
                    }
                    if (enabled) {
                        versioningService.handleDisable(appName, target, deploymentContext.getActionReport(), context.getSubject());
                    }
                    if (domain.isCurrentInstanceMatchingTarget(target, appName, server.getName(), null)) {
                        deployment.deploy(deployment.getSniffersFromApp(applicationInfo), deploymentContext);
                    } else {
                        // send the APPLICATION_PREPARED event for DAS
                        events.send(new Event<DeploymentContext>(Deployment.APPLICATION_PREPARED, deploymentContext), false);
                    }
                    final List<String> targets = new ArrayList<String>(Arrays.asList(commandParams.target.split(",")));
                    List<String> deploymentTarget = new ArrayList<>();
                    // If targets contains Deployment Group, check if the application is already deployed to instances in it.
                    for (String target : targets) {
                        if (isDeploymentGroup(target)) {
                            List<Server> instances = domain.getDeploymentGroupNamed(target).getInstances();
                            for (Server instance : instances) {
                                List<Application> applications = domain.getApplicationsInTarget(instance.getName());
                                List<String> listOfApplications = new ArrayList<>();
                                for (Application application : applications) {
                                    listOfApplications.add(application.getName());
                                }
                                if (!listOfApplications.contains(appName)) {
                                    deploymentTarget.add(instance.getName());
                                }
                            }
                        }
                    }
                    if (report.getActionExitCode().equals(ActionReport.ExitCode.SUCCESS)) {
                        try {
                            deployment.registerAppInDomainXML(null, deploymentContext, t, true);
                        } catch (TransactionFailure e) {
                            logger.warning("failed to create application ref for " + appName);
                        }
                    }
                    // if the target is DAS, we do not need to do anything more
                    if (!isVersionExpression && DeploymentUtils.isDASTarget(target)) {
                        return;
                    }
                    final ParameterMap paramMap = deployment.prepareInstanceDeployParamMap(deploymentContext);
                    if (!deploymentTarget.isEmpty()) {
                        replicateCommand(deploymentTarget, context, paramMap);
                    } else {
                        replicateCommand(targets, context, paramMap);
                    }
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "Error during creating application ref ", e);
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                } finally {
                    try {
                        archive.close();
                    } catch (IOException e) {
                        logger.log(Level.INFO, "Error while closing deployable artifact : " + file.getAbsolutePath(), e);
                    }
                }
            }
        }
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) VersioningWildcardException(org.glassfish.deployment.versioning.VersioningWildcardException) ArrayList(java.util.ArrayList) ActionReport(org.glassfish.api.ActionReport) Logger(java.util.logging.Logger) DeploymentProperties(org.glassfish.deployment.common.DeploymentProperties) Properties(java.util.Properties) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) URI(java.net.URI) Iterator(java.util.Iterator) VersioningException(org.glassfish.deployment.versioning.VersioningException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) ParameterMap(org.glassfish.api.admin.ParameterMap) IOException(java.io.IOException) VersioningException(org.glassfish.deployment.versioning.VersioningException) VersioningWildcardException(org.glassfish.deployment.versioning.VersioningWildcardException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) IOException(java.io.IOException) DeployCommandParameters(org.glassfish.api.deployment.DeployCommandParameters) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) Transaction(org.jvnet.hk2.config.Transaction) ApplicationConfigInfo(org.glassfish.deployment.common.ApplicationConfigInfo) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) File(java.io.File) DeploymentGroup(fish.payara.enterprise.config.serverbeans.DeploymentGroup)

Example 7 with ReadableArchive

use of org.glassfish.api.deployment.archive.ReadableArchive in project Payara by payara.

the class WeldSniffer method handles.

/**
 * Returns true if the archive contains beans.xml as defined by packaging rules of Weld
 */
@Override
public boolean handles(DeploymentContext context) {
    ArchiveType archiveType = habitat.getService(ArchiveType.class, context.getArchiveHandler().getArchiveType());
    if (archiveType != null && !supportsArchiveType(archiveType)) {
        return false;
    }
    ReadableArchive archive = context.getSource();
    boolean isWeldArchive = false;
    // a Weld archive
    if (isEntryPresent(archive, WeldUtils.WEB_INF)) {
        isWeldArchive = isArchiveCDIEnabled(context, archive, WeldUtils.WEB_INF_BEANS_XML) || isArchiveCDIEnabled(context, archive, WeldUtils.WEB_INF_CLASSES_META_INF_BEANS_XML);
        if (!isWeldArchive) {
            // Check jars under WEB_INF/lib
            if (isEntryPresent(archive, WeldUtils.WEB_INF_LIB)) {
                isWeldArchive = scanLibDir(context, archive, WeldUtils.WEB_INF_LIB);
            }
        }
    }
    // TODO This doesn't seem to match the ReadableArchive for a stand-alone ejb-jar.
    // It might only be true for an ejb-jar within an .ear.  Revisit when officially
    // adding support for .ears
    String archiveName = archive.getName();
    if (!isWeldArchive && archiveName != null && archiveName.endsWith(WeldUtils.EXPANDED_JAR_SUFFIX)) {
        isWeldArchive = isArchiveCDIEnabled(context, archive, WeldUtils.META_INF_BEANS_XML);
    }
    // If stand-alone ejb-jar
    if (!isWeldArchive && isArchiveCDIEnabled(context, archive, WeldUtils.META_INF_BEANS_XML)) {
        isWeldArchive = true;
    }
    if (!isWeldArchive && archiveName != null && archiveName.endsWith(WeldUtils.EXPANDED_RAR_SUFFIX)) {
        isWeldArchive = isArchiveCDIEnabled(context, archive, WeldUtils.META_INF_BEANS_XML);
        if (!isWeldArchive) {
            // Check jars in root dir of rar
            isWeldArchive = scanLibDir(context, archive, "");
        }
    }
    return isWeldArchive;
}
Also used : ArchiveType(org.glassfish.api.deployment.archive.ArchiveType) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive)

Example 8 with ReadableArchive

use of org.glassfish.api.deployment.archive.ReadableArchive in project Payara by payara.

the class WebArchivist method readStandardFragments.

/**
 * This method will return the list of web fragment in the desired order.
 */
private List<WebFragmentDescriptor> readStandardFragments(WebBundleDescriptorImpl descriptor, ReadableArchive archive) throws IOException {
    List<WebFragmentDescriptor> wfList = new ArrayList<WebFragmentDescriptor>();
    Vector libs = getLibraries(archive);
    if (libs != null && libs.size() > 0) {
        for (int i = 0; i < libs.size(); i++) {
            String lib = (String) libs.get(i);
            Archivist wfArchivist = new WebFragmentArchivist(this, habitat);
            wfArchivist.setRuntimeXMLValidation(this.getRuntimeXMLValidation());
            wfArchivist.setRuntimeXMLValidationLevel(this.getRuntimeXMLValidationLevel());
            wfArchivist.setAnnotationProcessingRequested(false);
            WebFragmentDescriptor wfDesc = null;
            ReadableArchive embeddedArchive = archive.getSubArchive(lib);
            try {
                if (embeddedArchive != null && wfArchivist.hasStandardDeploymentDescriptor(embeddedArchive)) {
                    try {
                        wfDesc = (WebFragmentDescriptor) wfArchivist.open(embeddedArchive);
                    } catch (SAXParseException ex) {
                        IOException ioex = new IOException();
                        ioex.initCause(ex);
                        throw ioex;
                    }
                } else {
                    wfDesc = new WebFragmentDescriptor();
                    wfDesc.setExists(false);
                }
            } finally {
                if (embeddedArchive != null) {
                    embeddedArchive.close();
                }
            }
            wfDesc.setJarName(lib.substring(lib.lastIndexOf('/') + 1));
            wfList.add(wfDesc);
            descriptor.putJarNameWebFragmentNamePair(wfDesc.getJarName(), wfDesc.getName());
        }
        if (((WebBundleDescriptorImpl) descriptor).getAbsoluteOrderingDescriptor() != null) {
            wfList = ((WebBundleDescriptorImpl) descriptor).getAbsoluteOrderingDescriptor().order(wfList);
        } else {
            OrderingDescriptor.sort(wfList);
        }
        for (WebFragmentDescriptor wf : wfList) {
            descriptor.addOrderedLib(wf.getJarName());
        }
    }
    return wfList;
}
Also used : Archivist(com.sun.enterprise.deployment.archivist.Archivist) ExtensionsArchivist(com.sun.enterprise.deployment.archivist.ExtensionsArchivist) SAXParseException(org.xml.sax.SAXParseException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) Vector(java.util.Vector)

Example 9 with ReadableArchive

use of org.glassfish.api.deployment.archive.ReadableArchive in project Payara by payara.

the class WebServicesDeployer method copyExtraFilesToGeneratedFolder.

/**
 * This is to be used for file publishing only. In case of wsdlImports and wsdlIncludes we need to
 * copy the nested wsdls from applications folder to the generated/xml folder
 */
private void copyExtraFilesToGeneratedFolder(DeploymentContext context) throws IOException {
    Archivist archivist = habitat.getService(Archivist.class);
    ReadableArchive archive = archiveFactory.openArchive(context.getSourceDir());
    WritableArchive archive2 = archiveFactory.createArchive(context.getScratchDir("xml"));
    // copy the additional webservice elements etc
    archivist.copyExtraElements(archive, archive2);
}
Also used : Archivist(com.sun.enterprise.deployment.archivist.Archivist) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) WritableArchive(org.glassfish.api.deployment.archive.WritableArchive)

Example 10 with ReadableArchive

use of org.glassfish.api.deployment.archive.ReadableArchive in project Payara by payara.

the class UpgradeStartup method repackageApplication.

private File repackageApplication(File appDir, String targetParentDir, String suffix) throws IOException {
    String appName = appDir.getName();
    ReadableArchive source = archiveFactory.openArchive(appDir);
    File tempEar = new File(targetParentDir, appName + suffix);
    if (tempEar.exists()) {
        boolean isDeleted = tempEar.delete();
        if (!isDeleted) {
            logger.log(Level.WARNING, "Error in deleting file " + tempEar.getAbsolutePath());
        }
    }
    WritableArchive target = archiveFactory.createArchive("jar", tempEar);
    Collection<String> directoryEntries = source.getDirectories();
    List<String> subModuleEntries = new ArrayList<String>();
    List<String> entriesToExclude = new ArrayList<String>();
    // first put all the sub module jars to the target archive
    for (String directoryEntry : directoryEntries) {
        if (directoryEntry.endsWith("_jar") || directoryEntry.endsWith("_war") || directoryEntry.endsWith("_rar")) {
            subModuleEntries.add(directoryEntry);
            File moduleJar = processModule(new File(appDir, directoryEntry), targetParentDir, null);
            OutputStream os = null;
            InputStream is = new BufferedInputStream(new FileInputStream(moduleJar));
            try {
                os = target.putNextEntry(moduleJar.getName());
                FileUtils.copy(is, os, moduleJar.length());
            } finally {
                if (os != null) {
                    target.closeEntry();
                }
                is.close();
            }
        }
    }
    // basically all sub module entries should be excluded
    for (String subModuleEntry : subModuleEntries) {
        Enumeration<String> ee = source.entries(subModuleEntry);
        while (ee.hasMoreElements()) {
            String eeEntryName = ee.nextElement();
            entriesToExclude.add(eeEntryName);
        }
    }
    // now copy the rest of the entries
    Enumeration<String> e = source.entries();
    while (e.hasMoreElements()) {
        String entryName = e.nextElement();
        if (!entriesToExclude.contains(entryName)) {
            InputStream sis = source.getEntry(entryName);
            if (isSigFile(entryName)) {
                logger.log(Level.INFO, "Excluding signature file: " + entryName + " from repackaged application: " + appName + "\n");
                continue;
            }
            if (sis != null) {
                InputStream is = new BufferedInputStream(sis);
                OutputStream os = null;
                try {
                    os = target.putNextEntry(entryName);
                    FileUtils.copy(is, os, source.getEntrySize(entryName));
                } finally {
                    if (os != null) {
                        target.closeEntry();
                    }
                    is.close();
                }
            }
        }
    }
    // last is manifest if existing.
    Manifest m = source.getManifest();
    if (m != null) {
        processManifest(m, appName);
        OutputStream os = target.putNextEntry(JarFile.MANIFEST_NAME);
        m.write(os);
        target.closeEntry();
    }
    source.close();
    target.close();
    return tempEar;
}
Also used : WritableArchive(org.glassfish.api.deployment.archive.WritableArchive) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive)

Aggregations

ReadableArchive (org.glassfish.api.deployment.archive.ReadableArchive)97 IOException (java.io.IOException)46 File (java.io.File)28 URI (java.net.URI)18 ActionReport (org.glassfish.api.ActionReport)17 ExtendedDeploymentContext (org.glassfish.internal.deployment.ExtendedDeploymentContext)14 DeployCommandParameters (org.glassfish.api.deployment.DeployCommandParameters)12 WritableArchive (org.glassfish.api.deployment.archive.WritableArchive)12 Application (com.sun.enterprise.deployment.Application)10 JarFile (java.util.jar.JarFile)10 ArchiveHandler (org.glassfish.api.deployment.archive.ArchiveHandler)10 ApplicationInfo (org.glassfish.internal.data.ApplicationInfo)10 ArrayList (java.util.ArrayList)9 ModuleDescriptor (org.glassfish.deployment.common.ModuleDescriptor)9 ConfigurationDeploymentDescriptorFile (com.sun.enterprise.deployment.io.ConfigurationDeploymentDescriptorFile)8 Logger (java.util.logging.Logger)8 DeploymentDescriptorFile (com.sun.enterprise.deployment.io.DeploymentDescriptorFile)7 Manifest (java.util.jar.Manifest)7 HashSet (java.util.HashSet)6 HashMap (java.util.HashMap)5