use of com.sun.enterprise.deploy.shared.FileArchive in project Payara by payara.
the class JaxRpcRICodegen method run.
@Override
public void run(ServiceLocator habitat, DeploymentContext context, String cp) throws Exception {
rootLocation_ = new FileArchive();
BundleDescriptor bundle = DOLUtils.getCurrentBundleForContext(context);
if (bundle.hasWebServiceClients() && (bundle instanceof ApplicationClientDescriptor)) {
hasWebServiceClients = true;
}
if (bundle.isStandalone()) {
rootLocation_.open(context.getSourceDir().toURI());
} else {
rootLocation_.open(context.getSource().getParentArchive().getURI());
}
this.context = context;
this.habitat = habitat;
this.moduleClassPath = cp;
Application application = context.getModuleMetaData(Application.class);
application.visit(this);
}
use of com.sun.enterprise.deploy.shared.FileArchive 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;
Optional<ApplicationState> appState = Optional.empty();
final ActionReport report = context.getActionReport();
try (SpanSequence span = structuredTracing.startSequence(DeploymentTracing.AppStage.VALIDATE_TARGET, "registry")) {
if (!hotDeploy) {
hotDeployService.removeApplicationState(initialContext.getSourceDir());
} else if (!(appState = hotDeployService.getApplicationState(initialContext.getSourceDir())).isPresent()) {
ApplicationState applicationState = new ApplicationState(name, path, initialContext);
applicationState.setTarget(target);
appState = Optional.of(applicationState);
}
// 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);
ActionReport.MessagePart part = report.getTopMessagePart();
part.addProperty(DeploymentProperties.NAME, name);
ApplicationConfigInfo savedAppConfig = new ApplicationConfigInfo(apps.getModule(Application.class, name));
Properties undeployProps = null;
if (appState.map(ApplicationState::isInactive).orElse(true)) {
undeployProps = handleRedeploy(name, report, context);
}
appState.filter(ApplicationState::isInactive).ifPresent(hotDeployService::addApplicationState);
if (enabled == null) {
enabled = Boolean.TRUE;
}
// clean up any left over repository files
if (!keepreposdir) {
span.start(DeploymentTracing.AppStage.CLEANUP, "applications");
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();
}
span.finish();
}
if (!DeploymentUtils.isDomainTarget(target) && enabled) {
// try to disable the enabled version, if exist
try (SpanSequence innerSpan = span.start(DeploymentTracing.AppStage.SWITCH_VERSIONS)) {
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;
}
}
span.start(DeploymentTracing.AppStage.CREATE_DEPLOYMENT_CONTEXT, "Full");
// create the parent class loader
deploymentContext = deployment.getBuilder(logger, this, report).source(initialContext.getSource()).archiveHandler(archiveHandler).build(initialContext);
String transformNS = System.getProperty(TRANSFORM_NAMESPACE);
Types types = deployment.getDeployableTypes(deploymentContext);
if (Boolean.valueOf(transformNS) || (transformNS == null && PayaraTransformer.isJakartaEEApplication(types))) {
span.start(DeploymentTracing.AppStage.TRANSFORM_ARCHIVE);
deploymentContext.getSource().close();
File output = PayaraTransformer.transformApplication(path, context, isDirectoryDeployed);
if (output == null) {
return;
}
deploymentContext.setSource((FileArchive) archiveFactory.createArchive(output));
// reset transient and module data of orignal deployed archive
deploymentContext.removeTransientAppMetaData(Types.class.getName());
deploymentContext.removeTransientAppMetaData(Parser.class.getName());
deploymentContext.resetModuleMetaData();
structuredTracing.register(deploymentContext);
}
// 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);
}
span.start(DeploymentTracing.AppStage.CLEANUP, "generated");
// clean up any generated files
deploymentContext.clean();
span.start(DeploymentTracing.AppStage.PREPARE, "ServerConfig");
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 tx = deployment.prepareAppConfigChanges(deploymentContext);
// next phase is launched by prepare
span.finish();
Deployment.ApplicationDeployment deplResult = deployment.prepare(null, deploymentContext);
if (deplResult != null && !loadOnly) {
appState.ifPresent(s -> s.storeMetaData(deploymentContext));
// initialize makes its own phase as well
deployment.initialize(deplResult.appInfo, deplResult.appInfo.getSniffers(), deplResult.context);
}
ApplicationInfo appInfo = deplResult != null ? deplResult.appInfo : null;
/*
* 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 (SpanSequence innerSpan = span.start(DeploymentTracing.AppStage.REGISTRATION)) {
moveAppFilesToPermanentLocation(deploymentContext, logger);
recordFileLocations(appProps);
downloadableArtifacts.record(appProps);
generatedArtifacts.record(appProps);
timeTakenToDeploy = timing.elapsed();
deploymentTimeMillis = System.currentTimeMillis();
if (tx != null) {
Application application = deploymentContext.getTransientAppMetaData("application", Application.class);
// Set the application deploy time
application.setDeploymentTime(Long.toString(timeTakenToDeploy));
application.setTimeDeployed(Long.toString(deploymentTimeMillis));
// register application information in domain.xml
deployment.registerAppInDomainXML(appInfo, deploymentContext, tx);
}
if (retrieve != null) {
retrieveArtifacts(context, downloadableArtifacts.getArtifacts(), retrieve, false, name);
}
suppInfo.setDeploymentContext(deploymentContext);
// send new event to notify the deployment process is finish
events.send(new Event<ApplicationInfo>(Deployment.DEPLOYMENT_COMMAND_FINISH, appInfo), false);
// 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);
report.setFailureCause(e);
if (e.getMessage() != null) {
report.setMessage(e.getMessage());
}
} 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 (structuredTracing.isEnabled()) {
structuredTracing.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);
}
}
appState.map(ApplicationState::getPath).ifPresent(hotDeployService::removeApplicationState);
}
if (deploymentContext != null && !loadOnly) {
deploymentContext.postDeployClean(true);
}
appState.ifPresent(ApplicationState::close);
}
}
use of com.sun.enterprise.deploy.shared.FileArchive in project Payara by payara.
the class ResourcesUtil method getConnectorDescriptorFromUri.
public ConnectorDescriptor getConnectorDescriptorFromUri(String rarName, String raLoc) {
try {
String appName = rarName.substring(0, rarName.indexOf(ConnectorConstants.EMBEDDEDRAR_NAME_DELIMITER));
// String actualRarName = rarName.substring(rarName.indexOf(ConnectorConstants.EMBEDDEDRAR_NAME_DELIMITER) + 1);
String appDeployLocation = ResourcesUtil.createInstance().getApplicationDeployLocation(appName);
FileArchive in = ConnectorRuntime.getRuntime().getFileArchive();
in.open(new URI(appDeployLocation));
ApplicationArchivist archivist = ConnectorRuntime.getRuntime().getApplicationArchivist();
com.sun.enterprise.deployment.Application application = archivist.open(in);
return application.getModuleByTypeAndUri(ConnectorDescriptor.class, raLoc);
} catch (Exception e) {
Object[] params = new Object[] { rarName, e };
_logger.log(Level.WARNING, "error.getting.connector.descriptor", params);
}
return null;
}
use of com.sun.enterprise.deploy.shared.FileArchive in project Payara by payara.
the class ConnectorDDTransformUtils method getConnectorDescriptor.
/**
* Get the ConnectorDescriptor object which represents the ra.xml and
* sun-ra.xml from an exploded rar module.
*
* @param moduleDir Directory where rar is exploded.
* @return ConnectorDescriptor object which
* represents the ra.xml and sun-ra.xml
* @throws ConnectorRuntimeException if ra.xml could not be located or
* invalid. For 1.0 type rar if sun-ra.xml is not present or
* invalid this exception is thrown. For 1.5 type rar sun-ra.xml
* should not be present.
*/
public static ConnectorDescriptor getConnectorDescriptor(String moduleDir, String rarModuleName) throws ConnectorRuntimeException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
File module = new File(moduleDir);
FileArchive fileArchive = new FileArchive();
// directory where rar is exploded
fileArchive.open(module.toURI());
ConnectorRuntime runtime = ConnectorRuntime.getRuntime();
ClassLoader loader;
if (ConnectorsUtil.belongsToSystemRA(rarModuleName)) {
loader = ConnectorRuntime.getRuntime().getSystemRARClassLoader(rarModuleName);
Thread.currentThread().setContextClassLoader(loader);
} else {
loader = runtime.createConnectorClassLoader(moduleDir, null, rarModuleName);
}
ConnectorArchivist connectorArchivist = runtime.getConnectorArchvist();
// TODO V3 what happens to embedded .rar ? as its parent classloader should be application CL
// setting the classloader so that annotation processor can make use of it.
connectorArchivist.setClassLoader(loader);
// fileArchive.entries("META-INF/ra.xml");
// TODO V3 need to check whether ra.xml is present, if so, check the version. process annotations
// only if its 1.6 or above ?
connectorArchivist.setAnnotationProcessingRequested(true);
return connectorArchivist.open(fileArchive);
} catch (IOException ex) {
ConnectorRuntimeException cre = new ConnectorRuntimeException("Failed to read the connector deployment descriptors");
cre.initCause(ex);
_logger.log(Level.SEVERE, "rardeployment.connector_descriptor_read_error", moduleDir);
_logger.log(Level.SEVERE, "", cre);
throw cre;
} catch (SAXParseException ex) {
ConnectorRuntimeException cre = new ConnectorRuntimeException("Failed to parse the connector deployment descriptors");
cre.initCause(ex);
_logger.log(Level.SEVERE, "rardeployment.connector_descriptor_parse_error", moduleDir);
_logger.log(Level.SEVERE, "", cre);
throw cre;
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
use of com.sun.enterprise.deploy.shared.FileArchive in project Payara by payara.
the class AppClientScanner method doProcess.
/**
* This scanner will scan the given main class for annotation processing.
* The archiveFile and libJarFiles correspond to classpath.
* @param archiveFile
* @param desc
* @param classLoader
*/
private void doProcess(ReadableArchive archive, ApplicationClientDescriptor desc, ClassLoader classLoader) throws IOException {
if (AnnotationUtils.getLogger().isLoggable(Level.FINE)) {
AnnotationUtils.getLogger().fine("archiveFile is " + archive.getURI().toASCIIString());
AnnotationUtils.getLogger().fine("classLoader is " + classLoader);
}
// always add main class
String mainClassName = desc.getMainClassName();
addScanClassName(mainClassName);
// add callback handle if it exist in appclient-client.xml
String callbackHandler = desc.getCallbackHandler();
if (callbackHandler != null && !callbackHandler.trim().equals("")) {
addScanClassName(desc.getCallbackHandler());
}
GenericAnnotationDetector detector = new GenericAnnotationDetector(managedBeanAnnotations);
if (detector.hasAnnotationInArchive(archive)) {
if (archive instanceof FileArchive) {
addScanDirectory(new File(archive.getURI()));
} else if (archive instanceof InputJarArchive) {
/*
* This is during deployment, so use the faster code path using
* the File object.
*/
URI uriToAdd = archive.getURI();
addScanJar(scanJar(uriToAdd));
} else if (archive instanceof MultiReadableArchive) {
/*
* During app client launches, scan the developer's archive
* which is in slot #1, not the facade archive which is in
* slot #0. Also, use URIs instead of File objects because
* during Java Web Start launches we don't have access to
* File objects.
*/
addScanURI(scanURI(((MultiReadableArchive) archive).getURI(1)));
}
}
this.classLoader = classLoader;
// = archive;
this.archiveFile = null;
}
Aggregations