com.sun.enterprise.deployment.archivist.ApplicationArchivist Maven / Gradle / Ivy
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.enterprise.deployment.archivist;
import com.sun.enterprise.deploy.shared.ArchiveFactory;
import com.sun.enterprise.deployment.Application;
import com.sun.enterprise.deployment.BundleDescriptor;
import com.sun.enterprise.deployment.RootDeploymentDescriptor;
import com.sun.enterprise.deployment.io.ApplicationDeploymentDescriptorFile;
import com.sun.enterprise.deployment.io.DeploymentDescriptorFile;
import com.sun.enterprise.deployment.io.runtime.ApplicationRuntimeDDFile;
import com.sun.enterprise.deployment.util.ApplicationValidator;
import com.sun.enterprise.deployment.util.ApplicationVisitor;
import com.sun.enterprise.deployment.util.DOLUtils;
import com.sun.enterprise.deployment.util.ModuleDescriptor;
import com.sun.enterprise.util.LocalStringManagerImpl;
import com.sun.enterprise.util.io.FileUtils;
import com.sun.enterprise.util.shared.ArchivistUtils;
import org.glassfish.api.deployment.archive.Archive;
import org.glassfish.api.deployment.archive.ReadableArchive;
import org.glassfish.api.deployment.archive.WritableArchive;
import org.jvnet.hk2.annotations.Inject;
import org.jvnet.hk2.annotations.Scoped;
import org.jvnet.hk2.annotations.Service;
import org.jvnet.hk2.component.Habitat;
import org.jvnet.hk2.component.PerLookup;
import org.xml.sax.SAXParseException;
import javax.enterprise.deploy.shared.ModuleType;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
/**
* This class is responsible for handling application archive files
*
* @author Jerome Dochez
* @version
*/
@Service
@Scoped(PerLookup.class)
public class ApplicationArchivist extends Archivist {
@Inject
ArchiveFactory archiveFactory;
@Inject
ArchivistFactory archivistFactory;
@Inject
Habitat habitat;
/**
* The DeploymentDescriptorFile handlers we are delegating for XML i/o
*/
DeploymentDescriptorFile standardDD = new ApplicationDeploymentDescriptorFile();
/** resources... */
private static LocalStringManagerImpl localStrings =
new LocalStringManagerImpl(ApplicationArchivist.class);
/** Creates new ApplicationArchivist */
public ApplicationArchivist() {
handleRuntimeInfo = true;
}
/**
* @return the module type handled by this archivist
* as defined in the application DTD
*
*/
@Override
public ModuleType getModuleType() {
return ModuleType.EAR;
}
/**
* writes the content of an archive to a JarFile
*
* @param in the descriptors to use for writing
* @param out the output stream to write to
*/
@Override
protected void writeContents(ReadableArchive in, WritableArchive out) throws IOException {
Vector filesToSkip = new Vector();
if(DOLUtils.getDefaultLogger().isLoggable(Level.FINE)) {
DOLUtils.getDefaultLogger().fine("Write " + out.getURI() + " with " + this);
}
// any files already written to the output should never be rewritten
for (Enumeration alreadyWritten = out.entries(); alreadyWritten.hasMoreElements();) {
String elementName = (String) alreadyWritten.nextElement();
filesToSkip.add(elementName);
}
// write this application .ear file contents...
for (ModuleDescriptor aModule : descriptor.getModules()) {
Archivist subArchivist = archivistFactory.getPrivateArchivistFor(aModule.getModuleType());
subArchivist.initializeContext(this);
subArchivist.setModuleDescriptor(aModule);
if(DOLUtils.getDefaultLogger().isLoggable(Level.FINE)) {
DOLUtils.getDefaultLogger().info("Write " + aModule.getArchiveUri() + " with " + subArchivist);
}
if (aModule.getAlternateDescriptor()!=null) {
// no need to rewrite the original bundle since
// the deployment descriptors are saved at the application level
// so I don't put it in the list of files to be skipped and it will
// be copied as a library.
// but I need to save the deployment descriptor for this bundle
OutputStream os = out.putNextEntry(aModule.getAlternateDescriptor());
subArchivist.writeStandardDeploymentDescriptors(os);
out.closeEntry();
// now write runtime descriptors
if (isHandlingRuntimeInfo()) {
os = out.putNextEntry("sun-" + aModule.getAlternateDescriptor());
subArchivist.writeRuntimeDeploymentDescriptors(os);
out.closeEntry();
}
} else {
// Create a new jar file inside the application .ear
WritableArchive internalJar = out.createSubArchive(aModule.getArchiveUri());
// we need to copy the old archive to a temp file so
// the save method can copy its original contents from
InputStream is = in.getEntry(aModule.getArchiveUri());
File tmpFile=null;
try {
if (in instanceof WritableArchive) {
subArchivist.setArchiveUri(internalJar.getURI().getSchemeSpecificPart());
} else {
tmpFile = getTempFile(path);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile));
ArchivistUtils.copy(is, bos);
// configure archivist
subArchivist.setArchiveUri(tmpFile.getAbsolutePath());
}
subArchivist.writeContents(internalJar);
out.closeEntry(internalJar);
} catch(IOException ioe) {
throw ioe;
} finally {
if (tmpFile!=null)
tmpFile.delete();
}
// no need to copy the bundle from the original jar file
filesToSkip.add(aModule.getArchiveUri());
}
}
// now write the old contents and new descriptors
super.writeContents(in, out, filesToSkip);
}
/**
/**
* @return a default BundleDescriptor for this archivist
*/
@Override
public Application getDefaultBundleDescriptor() {
return new Application(habitat);
}
/**
* open a new application archive file, read all the deployment descriptors
*
* @param appArchive the file path for the J2EE Application archive
*/
@Override
public Application open(ReadableArchive appArchive)
throws IOException, SAXParseException {
setManifest(appArchive.getManifest());
// read the standard deployment descriptors
Application appDesc = readStandardDeploymentDescriptor(appArchive);
setDescriptor(appDesc);
// Now that we have parsed the standard DD, let's read all the
// PersistenceUnits defined in the ear level.
readPersistenceDeploymentDescriptors(appArchive, getDescriptor());
// read the modules deployment descriptors
if (!readModulesDescriptors(appDesc, appArchive))
return null;
// now read the runtime deployment descriptors
super.readRuntimeDeploymentDescriptor(appArchive, appDesc);
// validate...
if (classLoader!=null && isHandlingRuntimeInfo()) {
validate(null);
}
return appDesc;
}
/**
* read the modules deployment descriptor from this application object using
* the passed archive
* @param app application containing the list of modules.
* @param appArchive containing the sub modules files.
* @return true if everything went fine
*/
public boolean readModulesDescriptors(Application app, ReadableArchive appArchive)
throws IOException, SAXParseException {
for (ModuleDescriptor aModule : app.getModules()) {
if(DOLUtils.getDefaultLogger().isLoggable(Level.FINE)) {
DOLUtils.getDefaultLogger().fine("Opening sub-module " + aModule);
}
RootDeploymentDescriptor descriptor = null;
Archivist newArchivist = archivistFactory.getPrivateArchivistFor(aModule.getModuleType());
newArchivist.initializeContext(this);
newArchivist.setRuntimeXMLValidation(this.getRuntimeXMLValidation());
newArchivist.setRuntimeXMLValidationLevel(
this.getRuntimeXMLValidationLevel());
ReadableArchive embeddedArchive = appArchive.getSubArchive(aModule.getArchiveUri());
if (aModule.getAlternateDescriptor()!=null) {
// the module use alternate deployement descriptor, ignore the
// DDs in the archive.
InputStream is = appArchive.getEntry(aModule.getAlternateDescriptor());
DeploymentDescriptorFile ddFile = newArchivist.getStandardDDFile();
ddFile.setXMLValidation(newArchivist.getXMLValidation());
ddFile.setXMLValidationLevel(newArchivist.getXMLValidationLevel());
if (appArchive.getURI()!=null) {
ddFile.setErrorReportingString(appArchive.getURI().getSchemeSpecificPart());
}
descriptor = (BundleDescriptor) ddFile.read(is);
is.close();
newArchivist.readWebServicesDescriptor(embeddedArchive, descriptor);
newArchivist.readPersistenceDeploymentDescriptors(embeddedArchive, descriptor);
newArchivist.postStandardDDsRead(descriptor, embeddedArchive);
newArchivist.readAnnotations(embeddedArchive, descriptor);
newArchivist.postAnnotationProcess(descriptor, embeddedArchive);
newArchivist.postOpen(descriptor, embeddedArchive);
// now reads the runtime deployment descriptor...
if (isHandlingRuntimeInfo()) {
is = appArchive.getEntry("sun-" + aModule.getAlternateDescriptor());
if (is!=null) {
DeploymentDescriptorFile confDD =
newArchivist.getConfigurationDDFile();
confDD.setXMLValidation(
newArchivist.getRuntimeXMLValidation());
confDD.setXMLValidationLevel(
newArchivist.getRuntimeXMLValidationLevel());
if (appArchive.getURI()!=null) {
confDD.setErrorReportingString(
appArchive.getURI().getSchemeSpecificPart());
}
confDD.read(descriptor, is);
is.close();
newArchivist.postRuntimeDDsRead((RootDeploymentDescriptor)descriptor, embeddedArchive);
} else {
if (embeddedArchive!=null) {
newArchivist.readRuntimeDeploymentDescriptor(embeddedArchive,descriptor);
}
}
}
} else {
// open the subarchive to get the deployment descriptor...
if (embeddedArchive!=null) {
descriptor = newArchivist.open(embeddedArchive);
} else {
DOLUtils.getDefaultLogger().info(localStrings.getLocalString(
"enterprise.deployment.cannotfindmodule",
"Cannot find module {0} in application bundle",
new Object[] {aModule.getArchiveUri()}));
return false;
}
}
if (embeddedArchive!=null) {
embeddedArchive.close();
}
if (descriptor != null && descriptor instanceof BundleDescriptor) {
aModule.setDescriptor((BundleDescriptor) descriptor);
((BundleDescriptor) descriptor).setApplication(app);
aModule.setManifest(newArchivist.getManifest());
} else {
// display a message only if we had a handle on the sub archive
if (embeddedArchive!=null) {
DOLUtils.getDefaultLogger().info(localStrings.getLocalString(
"enterprise.deployment.cannotreadDDs",
"Cannot read the Deployment Descriptors for module {0}",
new Object[] {aModule.getArchiveUri()}));
}
return false;
}
}
return true;
}
/**
* Read the runtime deployment descriptors (can contained in one or
* many file) set the corresponding information in the passed descriptor.
* By default, the runtime deployment descriptors are all contained in
* the xml file characterized with the path returned by
*
* @param archive the input archive
* @param descriptor the initialized deployment descriptor
*/
@Override
public void readRuntimeDeploymentDescriptor(ReadableArchive archive, Application descriptor)
throws IOException, SAXParseException {
if (descriptor != null) {
// each modules first...
for (ModuleDescriptor md : descriptor.getModules()) {
Archivist archivist = archivistFactory.getPrivateArchivistFor(md.getModuleType());
archivist.initializeContext(this);
archivist.setRuntimeXMLValidation(
this.getRuntimeXMLValidation());
archivist.setRuntimeXMLValidationLevel(
this.getRuntimeXMLValidationLevel());
InputStream is = null;
if (md.getAlternateDescriptor()!=null) {
// we are using alternate deployment descriptors
is = archive.getEntry("sun-" + md.getAlternateDescriptor());
if (is!=null) {
DeploymentDescriptorFile confDD =
archivist.getConfigurationDDFile();
confDD.setXMLValidation(
archivist.getRuntimeXMLValidation());
confDD.setXMLValidationLevel(
archivist.getRuntimeXMLValidationLevel());
if (archive.getURI()!=null) {
confDD.setErrorReportingString(
archive.getURI().getSchemeSpecificPart());
}
confDD.read(md.getDescriptor(), is);
is.close();
}
}
// if is variable is null, it means that we are either
// not using alternate deployment descriptors or we could
// not find the appropriate sun-???.xml alternate DD.
if (is==null) {
ReadableArchive subArchive = archive.getSubArchive(md.getArchiveUri());
archivist.readRuntimeDeploymentDescriptor(subArchive, md.getDescriptor());
}
}
}
// for the application
super.readRuntimeDeploymentDescriptor(archive, descriptor);
}
/**
* Read the runtime deployment descriptors (can contained in one or
* many file) from a deployment plan archive, set the corresponding
* information in the passed descriptor.
*/
@Override
public void readRuntimeDDFromDeploymentPlan(
ReadableArchive planArchive, Application descriptor)
throws IOException, SAXParseException {
if (planArchive == null) {
return;
}
// list of entries in the deployment plan
Vector dpEntries = new Vector();
for (Enumeration e = planArchive.entries(); e.hasMoreElements();) {
dpEntries.add(e.nextElement());
}
if (descriptor instanceof Application) {
Application application = (Application) descriptor;
//runtime deployment descriptor for the sub modules
for (ModuleDescriptor moduleDesc : application.getModules()) {
Archivist subArchivist = archivistFactory.getPrivateArchivistFor(moduleDesc.getModuleType());
String archiveUri = moduleDesc.getArchiveUri();
String runtimeDDPath = subArchivist.getRuntimeDeploymentDescriptorPath();
if (runtimeDDPath!=null) {
String mangledName;
// the runtime deployment descriptor from the deployment file
mangledName = archiveUri + "."
+ runtimeDDPath.substring(runtimeDDPath.lastIndexOf('/')+1);
DOLUtils.getDefaultLogger().fine("mangledName is " + mangledName);
if (dpEntries.contains(mangledName)) {
subArchivist.readRuntimeDDFromDeploymentPlan(
mangledName, planArchive, moduleDesc.getDescriptor());
}
}
}
}
//for sun-application.xml
super.readRuntimeDDFromDeploymentPlan(planArchive, descriptor);
}
/**
* validates the DOL Objects associated with this archivist, usually
* it requires that a class loader being set on this archivist or passed
* as a parameter
*/
@Override
public void validate(ClassLoader aClassLoader) {
ClassLoader cl = aClassLoader;
if (cl==null) {
cl = classLoader;
}
if (cl==null) {
return;
}
descriptor.setClassLoader(cl);
descriptor.visit((ApplicationVisitor) new ApplicationValidator());
}
/**
* @return the DeploymentDescriptorFile responsible for handling
* standard deployment descriptor
*/
@Override
public DeploymentDescriptorFile getStandardDDFile() {
return standardDD;
}
/**
* @return if exists the DeploymentDescriptorFile responsible for
* handling the configuration deployment descriptors
*/
@Override
public DeploymentDescriptorFile getConfigurationDDFile() {
return new ApplicationRuntimeDDFile();
}
/**
* Perform Optional packages dependencies checking on an archive
*/
@Override
public boolean performOptionalPkgDependenciesCheck(ReadableArchive archive) throws IOException {
if (!super.performOptionalPkgDependenciesCheck(archive))
return false;
// now check sub modules
if (descriptor==null) {
throw new IOException("Application object not set on archivist");
}
boolean returnValue = true;
for (ModuleDescriptor md : descriptor.getModules()) {
ReadableArchive sub = archive.getSubArchive(md.getArchiveUri());
if (sub!=null) {
Archivist subArchivist = archivistFactory.getPrivateArchivistFor(md.getModuleType());
if (!subArchivist.performOptionalPkgDependenciesCheck(sub))
returnValue = false;
}
}
return returnValue;
}
/**
* Copy this archivist to a new abstract archive
* @param source the archive to copy from
* @param target the new archive to use to copy our contents into
*/
public void copyInto(ReadableArchive source, WritableArchive target) throws IOException {
try {
Application a = readStandardDeploymentDescriptor(source);
copyInto(a, source, target);
} catch(SAXParseException spe) {
spe.printStackTrace();
DOLUtils.getDefaultLogger().log(Level.SEVERE, "enterprise.deployment.backend.fileCopyFailure");
}
}
/**
* Copy this archivist to a new abstract archive
* @param a the deployment descriptor for an application
* @param source the source archive
* @param target the target archive
*/
public void copyInto(Application a, ReadableArchive source, WritableArchive target) throws IOException {
copyInto(a, source, target, true);
}
/**
* Copy this archivist to a new abstract archive
* @param a the deployment descriptor for an application
* @param source the source archive
* @param target the target archive
* @param overwriteManifest if true, the manifest in source archive overwrites the one in target
*/
public void copyInto(Application a, ReadableArchive source,
WritableArchive target, boolean overwriteManifest)
throws IOException {
Vector entriesAdded = new Vector();
for (ModuleDescriptor aModule : a.getModules()) {
entriesAdded.add(aModule.getArchiveUri());
ReadableArchive subSource = source.getSubArchive(aModule.getArchiveUri());
WritableArchive subTarget = target.createSubArchive(aModule.getArchiveUri());
Archivist newArchivist = archivistFactory.getPrivateArchivistFor(aModule.getModuleType());
newArchivist.copyInto(subSource, subTarget, overwriteManifest);
target.closeEntry(subTarget);
String subModulePath = subSource.getURI().getSchemeSpecificPart();
if (subModulePath.startsWith(subModulePath)) {
subModulePath = subModulePath.substring(subModulePath.length()+File.separator.length());
for (Enumeration subEntries = subSource.entries();subEntries.hasMoreElements();) {
String anEntry = (String) subEntries.nextElement();
entriesAdded.add(subModulePath + "/" + anEntry);
}
}
subSource.close();
}
super.copyInto(source, target, entriesAdded, overwriteManifest);
}
/**
* This method will be invoked if and only if the following is true:
* 1. directory deployment with neither standard nor runtime DD
* 2. JSR88 DeploymentManager.distribute using InputStream with neither
* standard nor runtime DD
*
* Note that we will only venture a guess for case 1. JSR88 deployment
* of an application (ear) using InputStream without any deployment
* descriptor will NOT be supported at this time.
*/
@Override
protected boolean postHandles(ReadableArchive abstractArchive)
throws IOException {
// Only try to make a guess if the archive is a directory
// We will try to conclude if a directory represents an application
// by looking at if it contains any Java EE modules.
// We are supporting directory names with both "_suffix" and ".suffix".
File file = new File(abstractArchive.getURI());
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File content : files) {
if (content.isDirectory()) {
String dirPath = content.getPath();
if (dirPath.endsWith("_war")
|| dirPath.endsWith(".war")
|| dirPath.endsWith("_jar")
|| dirPath.endsWith(".jar")
|| dirPath.endsWith("_rar")
|| dirPath.endsWith(".rar")) {
return true;
}
}
}
}
return false;
}
@Override
protected String getArchiveExtension() {
return APPLICATION_EXTENSION;
}
@Override
public void readPersistenceDeploymentDescriptors(
ReadableArchive appArchive, Application descriptor) throws IOException, SAXParseException {
if(logger.isLoggable(Level.FINE)) {
logger.logp(Level.FINE, "ApplicationArchivist",
"readPersistenceDeploymentDescriptors", "archive = {0}",
appArchive.getURI());
}
Application application = Application.class.cast(descriptor);
Map subArchives = new HashMap();
try{
Enumeration entries = appArchive.entries();
while(entries.hasMoreElements()){
String entry = String.class.cast(entries.nextElement());
// at ear level only jar files can be root of PU.
if (entry.endsWith(".jar")) {
boolean belongsToSomeModule = false;
for (ModuleDescriptor md : application.getModules()) {
// We need to do the following check because we don't want
// to process files like foo_war/WEB-INF/lib/a.jar.
// So the following check ensures that
// we have found a .jar embedded in ear file which is
// neither an appclient jar nor an ejb jar and nor is it
// part of a rar or war.
String explodedModuleURI = FileUtils.makeFriendlyFilename(
md.getArchiveUri()) + "/"; // add '/' to indicate its a directory
if(entry.startsWith(explodedModuleURI)){
belongsToSomeModule = true;
break; // no need to see if it belongs to some other module
}
}
if(!belongsToSomeModule) {
subArchives.put(entry, appArchive.getSubArchive(entry));
}
}
}
for(Map.Entry pathToArchiveEntry : subArchives.entrySet()) {
readPersistenceDeploymentDescriptor(pathToArchiveEntry.getValue(), pathToArchiveEntry.getKey(), descriptor);
}
}finally{
for(Archive subArchive : subArchives.values()) {
subArchive.close();
}
}
}
/**
* This is a helper method.
* This method is needed because we sometimes have to read PU descriptors
* from the original app exploded dir as opposed to generated dir
* because generated XML do not contain any information about PUs.
* This method also handles the case where application object is virtual,
* (a virtual application represents a standalone module deployment object).
* @param archive from where persistence descriptors will be read from.
* @param application the application object whose persistence units
* will be read. This method will read all the persistence units
* recurssively and register at appropriate level.
* @throws IOException
* @throws SAXParseException
*/
public void readPersistenceDeploymentDescriptorsRecursively(
ReadableArchive archive, Application application) throws IOException,
SAXParseException {
if(!application.isVirtual()) {
ApplicationArchivist appArchivist = new ApplicationArchivist();
appArchivist.readPersistenceDeploymentDescriptors(archive, application);
for(ModuleDescriptor moduleDescriptor : application.getModules()) {
Archivist moduleArchivist = archivistFactory.getPrivateArchivistFor(moduleDescriptor.getModuleType());
ReadableArchive moduleArchive = archive.getSubArchive(
moduleDescriptor.getArchiveUri());
try{
moduleArchivist.readPersistenceDeploymentDescriptors(
moduleArchive, moduleDescriptor.getDescriptor());
} finally {
moduleArchive.close();
}
}
} else {
// it's a standalone war/jar/rar etc.
final ModuleDescriptor module = application.getModules().iterator().next();
Archivist archivist =
archivistFactory.getPrivateArchivistFor(module.getModuleType());
archivist.readPersistenceDeploymentDescriptors(
archive, module.getDescriptor());
}
}
}