/*
* Created on Jan 31, 2008 Copyright (c) Sybase, Inc. 2008 All rights reserved.
*/
package com.sybase.uep.tooling.deploy.uepserver.operations;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import org.apache.xmlbeans.XmlOptions;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.emf.common.command.BasicCommandStack;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IFileEditorMapping;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.eclipse.ui.internal.registry.EditorDescriptor;
import org.eclipse.ui.internal.registry.EditorRegistry;
import org.eclipse.ui.internal.registry.FileEditorMapping;
import org.eclipse.ui.internal.util.PrefUtil;
import com.sybase.suade.deploy.core.IPackageConfiguration;
import com.sybase.suade.deploy.core.IPackageCreationContext;
import com.sybase.uep.common.logging.Logger;
import com.sybase.uep.tooling.deploy.IDeployConstants;
import com.sybase.uep.tooling.deploy.Messages;
import com.sybase.uep.tooling.deploy.dd.EndpointMappingType;
import com.sybase.uep.tooling.deploy.dd.DeploymentDocument.Deployment;
import com.sybase.uep.tooling.deploy.models.ueppkgdef.Definition;
import com.sybase.uep.tooling.deploy.models.ueppkgdef.PackageJarEntry;
import com.sybase.uep.tooling.deploy.ueppkgdef.ui.configuration.UEPPackageConfiguration;
import com.sybase.uep.tooling.deploy.ueppkgdef.ui.editors.UEPPackageDefinitionEditingDomain;
import com.sybase.uep.tooling.deploy.ueppkgdef.utils.UEPDeployUtilities;
import com.sybase.uep.tooling.om.core.EclipseUEPObjectsManager;
import com.sybase.uep.tooling.om.core.XMLArtifactModelConverter;
import com.sybase.uep.tooling.project.utils.UEPProjectUtils;
import com.sybase.uep.tooling.ui.diagram.part.UEPDiagramEditorPlugin;
/**
* The operation to build a physical package. The result is a zip file containing a deployment unit file and a
* deployment descriptor file
*
* @author rob li
*/
public class CreatePhysicalPackageFileOperation extends WorkspaceModifyOperation
{
// the default editor is WinZip, refer to CR#571716-1.
private static final String DU_EDITOR_LOC = "C://Program Files//WinZip//WINZIP32.EXE"; //$NON-NLS-1$
// flag which reflects whether deployment unit files are associated with certain editors
private static boolean _isDUAssociated = false;
private IFile _packageFile;
private Definition _packageDefinition;
private IPackageCreationContext _context;
private UEPPackageConfiguration _packageConfiguration;
private File _definitionFile;
private File _outputFolder;
private File _outputFile;
private Logger _logger = UEPDiagramEditorPlugin
.getLogger(CreatePhysicalPackageFileOperation.class);
static
{
EditorRegistry registry = (EditorRegistry) WorkbenchPlugin.getDefault().getEditorRegistry();
IFileEditorMapping[] oldMappings = registry.getFileEditorMappings();
boolean found = false;
for (IFileEditorMapping m : oldMappings)
{
if ( ("*." + IDeployConstants.UEP_PHYSICAL_PKG_FILE_EXT).equalsIgnoreCase(m.getLabel()) ) //$NON-NLS-1$
{
found = true;
}
}
_isDUAssociated = found;
}
public File getOutputFile()
{
return _outputFile;
}
@Override
protected void execute(IProgressMonitor monitor)
throws CoreException, InvocationTargetException, InterruptedException
{
MyRunnable myRunnableSimple = new MyRunnable(monitor);
myRunnableSimple.run();
Exception e = myRunnableSimple.getException();
if ( e != null )
{
if ( e instanceof CoreException )
{
throw (CoreException) e;
}
else if ( e instanceof InvocationTargetException )
{
throw (InvocationTargetException) e;
}
else if ( e instanceof InterruptedException )
{
throw (InterruptedException) e;
}
}
checkDUAssociation();
}
private void checkDUAssociation()
{
// skip in case user has already associated *.jar with a certain editor
if ( !_isDUAssociated && existDefaultEditor())
{
final EditorRegistry registry = (EditorRegistry) WorkbenchPlugin.getDefault().getEditorRegistry();
IFileEditorMapping[] oldMappings = registry.getFileEditorMappings();
FileEditorMapping jarMapping = new FileEditorMapping("*", IDeployConstants.UEP_PHYSICAL_PKG_FILE_EXT);
EditorDescriptor editor = EditorDescriptor.createForProgram(DU_EDITOR_LOC);
jarMapping.setDefaultEditor(editor);
FileEditorMapping[] newMappings = (FileEditorMapping[]) Arrays.copyOf(oldMappings,
oldMappings.length + 1);
newMappings[newMappings.length - 1] = jarMapping;
final FileEditorMapping[] fnewMappings = newMappings;
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
registry.setFileEditorMappings(fnewMappings);
registry.saveAssociations();
PrefUtil.savePrefs();
}
});
_isDUAssociated = true;
}
}
private boolean existDefaultEditor()
{
File file = new File(DU_EDITOR_LOC);
return file.exists();
}
public class MyRunnable
implements Runnable
{
private IProgressMonitor _monitor = null;
private Exception _exception = null;
public MyRunnable(IProgressMonitor monitor)
{
_monitor = monitor;
}
public Exception getException()
{
return _exception;
}
public void run()
{
_monitor.beginTask("CreateUEPPackageFileOperation.0", 400); //$NON-NLS-1$
try
{
// some preparations
initialize();
// initialize temporary deployment unit file and deployment descriptor file.
File tempUnit = new Path(getOutputFolder().getAbsolutePath()).append(
Messages.CreatePhysicalPackageFileOperation_Deployment_Unit).toFile();
File tempDescriptor = new Path(getOutputFolder().getAbsolutePath()).append(
Messages.CreatePhysicalPackageFileOperation_Deployment_Descriptor).toFile();
File manifestFile = new Path(getOutputFolder().getAbsolutePath()).append(
IDeployConstants.UEP_PHYSICAL_PKG_MANIFEST_FILE).toFile();
// initialize physical package file
IPath generatedFilePath = new Path(getOutputFolder().getAbsolutePath()).append(
getDefinition().getName()).addFileExtension(IDeployConstants.UEP_PHYSICAL_PKG_FILE_EXT);
_outputFile = generatedFilePath.toFile();
// if we are deploying project, do not show overwrite prompt.
if ( !_packageFile.getName().equals(IDeployConstants.UEP_PKG_DEFAULT_FILE) && _outputFile.exists() ) //$NON-NLS-1$
{
switch (getContext().promptForOverwrite(_outputFile.toString()))
{
case IPackageCreationContext.USE_EXISTING:
return;
case IPackageCreationContext.CANCEL:
_exception = new InterruptedException();
return;
case IPackageCreationContext.OVERWRITE:
}
}
_monitor.worked(50);
// get the configuration
Deployment deployment = null;
if ( _packageConfiguration != null )
{
deployment = _packageConfiguration.getConfiguration().getDeployment();
}
else
{
deployment = UEPDeployUtilities.createDeployment();
deployment.setDeployMode(UEPDeployUtilities
.convertToDeployModeType(IDeployConstants.UEP_DEFAULT_DEPLOY_MODE.ordinal()));
deployment.setPackageName(UEPProjectUtils.getPackageName(_packageFile.getProject()));
}
// get the deployment unit
EclipseUEPObjectsManager om = (EclipseUEPObjectsManager) UEPDiagramEditorPlugin.getInstance()
.getObjectsManager(_packageFile.getProject().getName());
XMLArtifactModelConverter mc = (XMLArtifactModelConverter) om.getModelConverter();
EObject objs[] = getMbos();
String packageName = deployment.getPackageName();
// pass the endpoint mapping to the converter if there are any
Map context = null;
EndpointMappingType[] mappings = null;
if ( _packageConfiguration != null )
{
context = new HashMap();
mappings = deployment.getEndpointMappingArray();
}
if ( mappings != null && mappings.length != 0 )
{
context.put(_context.getTarget(), mappings);
}
String theUnit = (String) mc.convertTo(packageName, objs, context,null);
if ( _logger.isDebug() )
{
_logger.debug((Object) theUnit);
}
// save the unit to the temporary deployment unit file
OutputStreamWriter ow1 = new OutputStreamWriter(new FileOutputStream(tempUnit), IDeployConstants.UTF_8);
ow1.write(theUnit);
ow1.close();
_monitor.worked(100);
// save the deployment descriptor
OutputStreamWriter ow2 = new OutputStreamWriter(new FileOutputStream(tempDescriptor), IDeployConstants.UTF_8);
deployment.save(ow2, new XmlOptions().setSaveOuter());
ow2.close();
_monitor.worked(100);
// compress the temporary files together
// META-INF/MANIFEST.MF
if ( !manifestFile.exists() )
{
manifestFile.createNewFile();
}
FileInputStream mis = new FileInputStream(manifestFile);
Manifest manifest = new Manifest(mis);
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION,
IDeployConstants.UEP_PHYSICAL_PKG_MANIFEST_VERSION);
manifest.getMainAttributes().put(
new Attributes.Name(IDeployConstants.UEP_PHYSICAL_PKG_MANIFEST_ATTRIBUTE_CREATED_BY),
IDeployConstants.UEP_PHYSICAL_PKG_MANIFEST_CREATED_BY);
manifest.getMainAttributes().put(
new Attributes.Name(IDeployConstants.UEP_PHYSICAL_PKG_MANIFEST_ATTRIBUTE_AFX),
Messages.CreatePhysicalPackageFileOperation_Deployment_Unit);
mis.close();
JarOutputStream jos = new JarOutputStream(new FileOutputStream(_outputFile), manifest);
byte[] buffer = new byte[1024];
// deployment unit
FileInputStream in = new FileInputStream(tempUnit);
jos.putNextEntry(new ZipEntry(tempUnit.getName()));
int len = 0;
while ((len = in.read(buffer)) > 0)
{
jos.write(buffer, 0, len);
}
in.close();
jos.closeEntry();
// deployment descriptor
in = new FileInputStream(tempDescriptor);
jos.putNextEntry(new ZipEntry(tempDescriptor.getName()));
len = 0;
while ((len = in.read(buffer)) > 0)
{
jos.write(buffer, 0, len);
}
in.close();
jos.closeEntry();
// TODO#BSHEN.P? generate META-INF/Rolemapping.xml
// package jars
packPackageJars(jos);
jos.close();
// delete the temporary files
tempDescriptor.delete();
tempUnit.delete();
manifestFile.delete();
_monitor.subTask("CreateUEPPackageFileOperation.1"); //$NON-NLS-1$
// refresh the directory
getPackageFile().getParent().refreshLocal(IResource.DEPTH_INFINITE,
new SubProgressMonitor(_monitor, 100));
}
catch (CoreException ce)
{
_exception = ce;
return;
}
catch (IOException e)
{
_exception = new InvocationTargetException(e);
return;
}
catch (Exception e)
{
_exception = new InvocationTargetException(e);
return;
}
finally
{
_monitor.done();
System.clearProperty("javax.xml.parsers.SAXParserFactory"); //$NON-NLS-1$
System.clearProperty("javax.xml.transform.TransformerFactory"); //$NON-NLS-1$
}
}
}
public CreatePhysicalPackageFileOperation(Definition packageDefinition, IPackageCreationContext context)
{
super();
_packageDefinition = packageDefinition;
_context = context;
initPackageFile();
}
void packPackageJars(JarOutputStream jos)
throws IOException
{
byte[] buffer = new byte[1024];
for (PackageJarEntry jar : _packageDefinition.getPkgJars())
{
if ( !UEPDeployUtilities.exists(jar) )
{
continue;
}
File file = null;
Path path = new Path(jar.getPath());
if ( jar.isExternal() )
{
file = path.toFile();
}
else
{
IPath absolutePath = ResourcesPlugin.getWorkspace().getRoot().getFile(path).getLocation();
if ( absolutePath != null )
{
file = absolutePath.toFile();
}
}
if ( file == null )
{
continue;
}
jos.putNextEntry(new ZipEntry(IDeployConstants.UEP_PHYSICAL_PKG_LIB + jar.getName()));
FileInputStream in = new FileInputStream(file);
int len = 0;
while ((len = in.read(buffer)) > 0)
{
jos.write(buffer, 0, len);
}
in.close();
jos.closeEntry();
}
}
/**
* @return
*/
public EObject[] getMbos()
{
return _packageDefinition.getContents().getMbos().toArray(
new EObject[_packageDefinition.getContents().getMbos().size()]);
}
public CreatePhysicalPackageFileOperation(Definition packageDefinition, IPackageCreationContext context,
ISchedulingRule rule)
{
super(rule);
_packageDefinition = packageDefinition;
_context = context;
initPackageFile();
}
public CreatePhysicalPackageFileOperation(IFile packageFile, IPackageCreationContext context,
IPackageConfiguration configuration)
{
super();
_packageFile = packageFile;
_context = context;
_packageConfiguration = (UEPPackageConfiguration) configuration;
}
public CreatePhysicalPackageFileOperation(IFile packageFile, IPackageCreationContext context,
IPackageConfiguration configuration, ISchedulingRule rule)
{
super(rule);
_packageFile = packageFile;
_context = context;
_packageConfiguration = (UEPPackageConfiguration) configuration;
}
public File getOutputFolder()
{
return _outputFolder;
}
protected void initialize()
throws IOException
{
if ( _packageFile != null )
{
loadDefinition();
}
else
{
initPackageFile();
_definitionFile = _packageFile.getLocation().toFile();
}
initOutputFolder();
}
protected void loadDefinition()
throws IOException
{
UEPPackageDefinitionEditingDomain domain = createEditingDomain();
Resource res = domain.loadResource(URI.createPlatformResourceURI(_packageFile.getFullPath().toString())
.toString());
_packageDefinition = (Definition) res.getContents().get(0);
domain.initModel();
_definitionFile = _packageFile.getLocation().toFile();
}
protected UEPPackageDefinitionEditingDomain createEditingDomain()
{
return new UEPPackageDefinitionEditingDomain(createAdapterFactory(), new BasicCommandStack());
}
protected AdapterFactory createAdapterFactory()
{
return UEPDeployUtilities.getItemAdapterFactory();
}
protected void initOutputFolder()
{
if ( _context == null )
{
try
{
URI uri = URI.createFileURI(FileLocator.toFileURL(
new URL(_packageDefinition.eResource().getURI().toString())).getFile());
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(
new Path(uri.device(), uri.path()));
if ( file != null )
{
_outputFolder = file.getProject().getLocation().toFile();
}
else
{
_outputFolder = null;
}
}
catch (MalformedURLException e)
{
_logger.error((Object) e.getMessage(), e);
}
catch (IOException e)
{
_logger.error((Object) e.getMessage(), e);
}
}
else
{
_outputFolder = _context.getOutputFolder();
}
}
protected void initPackageFile()
{
try
{
URI uri = URI.createFileURI(Platform.asLocalURL(new URL(getDefinition().eResource().getURI().toString()))
.getFile());
_packageFile = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(
new Path(uri.device(), uri.path()));
}
catch (MalformedURLException e)
{
_logger.error((Object) e.getMessage(), e);
}
catch (IOException e)
{
_logger.error((Object) e.getMessage(), e);
}
}
protected Map getSaveOptions()
{
Map options = new HashMap();
options.put(XMLResource.OPTION_ENCODING, IDeployConstants.UTF_8);
return options;
}
protected IPackageCreationContext getContext()
{
return _context;
}
protected Definition getDefinition()
{
return _packageDefinition;
}
protected File getDefinitionFile()
{
return _definitionFile;
}
protected IFile getPackageFile()
{
return _packageFile;
}
}
JarInputStream Sample
最新推荐文章于 2018-06-23 17:42:59 发布