### Eclipse Workspace Patch 1.0
#P org.eclipse.jst.ws.axis2.creation.ui
Index: plugin.xml
===================================================================
RCS file: /cvsroot/webtools/webservices/plugins/org.eclipse.jst.ws.axis2.creation.ui/plugin.xml,v
retrieving revision 1.1
diff -u -r1.1 plugin.xml
--- plugin.xml 24 Apr 2007 16:59:55 -0000 1.1
+++ plugin.xml 3 Jan 2009 06:57:54 -0000
@@ -56,4 +56,13 @@
+
+
+
+
+ Create a deployable axis2 archive.
+
+
+
+
Index: src/org/eclipse/jst/ws/internal/axis2/creation/ui/widgets/export/AARExportWizard.java
===================================================================
RCS file: src/org/eclipse/jst/ws/internal/axis2/creation/ui/widgets/export/AARExportWizard.java
diff -N src/org/eclipse/jst/ws/internal/axis2/creation/ui/widgets/export/AARExportWizard.java
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ src/org/eclipse/jst/ws/internal/axis2/creation/ui/widgets/export/AARExportWizard.java 1 Jan 1970 00:00:00 -0000
@@ -0,0 +1,159 @@
+/*******************************************************************************
+ * Copyright (c) 2007 WSO2 Inc. and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * WSO2 Inc. - initial API and implementation
+ * yyyymmdd bug Email and other contact information
+ * -------- -------- -----------------------------------------------------------
+ * 20090103 168938 samindaw@wso2.com - Saminda Wijeratne, Initial code to introduce aar export
+ *******************************************************************************/
+
+package org.eclipse.jst.ws.internal.axis2.creation.ui.widgets.export;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.operation.IRunnableWithProgress;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.jst.ws.axis2.core.utils.ArchiveManipulator;
+import org.eclipse.ui.IExportWizard;
+import org.eclipse.ui.IWorkbench;
+
+public class AARExportWizard extends Wizard implements IExportWizard{
+ private AARExportWizardPage mainPage;
+ private IStructuredSelection selection;
+ private IProject selectedProject;
+
+ @Override
+ public boolean performFinish() {
+ IRunnableWithProgress op = new IRunnableWithProgress() {
+ public void run(IProgressMonitor monitor) throws InvocationTargetException {
+ try {
+ doFinish(monitor);
+ } catch (Exception e) {
+ throw new InvocationTargetException(e);
+ } finally {
+ monitor.done();
+ }
+ }
+ };
+ try {
+ getContainer().run(true, false, op);
+ } catch (InterruptedException e) {
+ return false;
+ } catch (InvocationTargetException e) {
+ Throwable realException = e.getTargetException();
+ realException.printStackTrace();
+ if (realException.getMessage().trim().equalsIgnoreCase(""))
+ MessageDialog.openError(getShell(), "Error", "Error occured while service archive.");
+ else
+ MessageDialog.openError(getShell(), "Error", realException.getMessage());
+ return false;
+ }
+ MessageDialog.openInformation(getShell(), "Axis2 Archive", "Axis2 archive created successfully.");
+
+ return true;
+ }
+
+ public void init(IWorkbench arg0, IStructuredSelection arg1) {
+ this.selection=arg1;
+ if (selection.getFirstElement() instanceof IProject){
+ selectedProject=(IProject)selection.getFirstElement();
+ }
+ }
+ public void addPages() {
+ super .addPages();
+
+ mainPage = new AARExportWizardPage("AAR Export Wizard",selectedProject);
+ addPage(mainPage);
+ }
+
+ private void doFinish(IProgressMonitor monitor) throws Exception {
+
+ IFolder selectedService = mainPage.getSelectedService();
+
+ IPath selectedServicePath = selectedService.getLocation();
+
+ try {
+
+ IPath serviceArchiveLocation = new Path(mainPage.getFileLocation());
+ ArchiveManipulator archiveManipulator = new ArchiveManipulator();
+ archiveManipulator.archiveDir(serviceArchiveLocation.toOSString(), selectedServicePath.toOSString());
+
+ } catch (IOException e) {
+ throw e;
+ }
+
+
+
+
+
+//
+// int a;
+// a=10;
+// if (selectedProject!=null){
+// selectedProject=(IProject)selection.getFirstElement();
+// monitor.beginTask("Determining whether the selected is a bpel project...", 100);
+// String path = selectedProject.getLocation().toOSString();
+// monitor.worked(10);
+// monitor.setTaskName("Listing project artifacts...");
+// List allFilesPresentInFolder = FileManagementUtil.getAllFilesPresentInFolder(new File(path));
+// printList(allFilesPresentInFolder);
+// monitor.worked(25);
+// monitor.setTaskName("Filtering out non bpel artifacts...");
+// List bpelValidFileList = BpelUtils.getBpelValidFileList(path,(String[]) allFilesPresentInFolder.toArray(new String[allFilesPresentInFolder.size()]));
+// printList(bpelValidFileList);
+// monitor.worked(40);
+// File tempFolder = null;
+// try {
+// tempFolder = File.createTempFile("temp",".tmp");
+// tempFolder.delete();
+// tempFolder.mkdir();
+// File zipFolder=new File(tempFolder,selectedProject.getName());
+// File tmpZip=File.createTempFile("temp",".tmp");
+// tmpZip.delete();
+// //tmpZip.deleteOnExit();
+// System.out.println(tempFolder.getAbsolutePath());
+// System.out.println(tmpZip.getAbsolutePath());
+//
+// monitor.setTaskName("Creating tje bpel artifact...");
+// FileManagementUtil.copyDirectory(new File(path), zipFolder, bpelValidFileList);
+// monitor.worked(55);
+// FileManagementUtil.removeEmptyDirectories(zipFolder);
+// monitor.worked(60);
+// FileManagementUtil.zipFolder(tempFolder.getAbsolutePath(), tmpZip.getAbsolutePath());
+// monitor.worked(75);
+// if (tmpZip.exists()){
+// monitor.setTaskName("Exporting the artifact...");
+// String deployableZip = mainPage.getArchiveFileName(); //FileManagementUtil.addNodesToPath(PersistentWSASEmitterContext.getInstance().getWSASRuntimeLocation(),new String[]{"repository", "bpel",p.getName()+".zip"});
+// File deployedZip = new File(deployableZip);
+// FileManagementUtil.copy(tmpZip, deployedZip);
+// monitor.worked(100);
+// monitor.done();
+// if (deployedZip.exists())
+// return;
+// else
+// throw new Exception("Could export the bpel archive.");
+// }else
+// throw new Exception("Unable to create the bpel archive.");
+// } catch (IOException e) {
+// throw e;
+// }finally{
+// //FileManagementUtil.deleteDirectories(tempFolder);
+// }
+// }
+ }
+
+}
+
Index: src/org/eclipse/jst/ws/internal/axis2/creation/ui/widgets/export/AARExportWizardPage.java
===================================================================
RCS file: src/org/eclipse/jst/ws/internal/axis2/creation/ui/widgets/export/AARExportWizardPage.java
diff -N src/org/eclipse/jst/ws/internal/axis2/creation/ui/widgets/export/AARExportWizardPage.java
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ src/org/eclipse/jst/ws/internal/axis2/creation/ui/widgets/export/AARExportWizardPage.java 1 Jan 1970 00:00:00 -0000
@@ -0,0 +1,256 @@
+/*******************************************************************************
+ * Copyright (c) 2007 WSO2 Inc. and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * WSO2 Inc. - initial API and implementation
+ * yyyymmdd bug Email and other contact information
+ * -------- -------- -----------------------------------------------------------
+ * 20090103 168938 samindaw@wso2.com - Saminda Wijeratne, Initial code to introduce aar export
+ *******************************************************************************/
+
+package org.eclipse.jst.ws.internal.axis2.creation.ui.widgets.export;
+
+import java.io.File;
+import java.util.List;
+
+import org.eclipse.core.resources.IFolder;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.ResourcesPlugin;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.jst.ws.axis2.core.utils.Axis2CoreUtils;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.FileDialog;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+public class AARExportWizardPage extends WizardPage {
+ private String fileLocation;
+ private Text deployInWorkspaceText;
+ private String archiveName;
+ private Combo projectSelectionCombo;
+ private Combo serviceSelectionCombo;
+ private List servicesList;
+ private String serviceToArchive;
+ private String selectedProject="";
+
+ protected AARExportWizardPage(String pageName, IProject selectedProject) {
+ super(pageName);
+ if (selectedProject!=null)
+ this.selectedProject=selectedProject.getName();
+ setTitle("Axis2 Service Archive Exporter");
+ setDescription("Export axis2 service archive");
+ }
+
+ public void createControl(Composite parent) {
+ Composite container = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout();
+ container.setLayout(layout);
+ layout.numColumns = 3;
+ layout.verticalSpacing = 5;
+ GridData gd;
+ Label label;
+
+ label=new Label(container,SWT.NULL);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ label.setLayoutData(gd);
+ gd.horizontalSpan=1;
+ label.setText("Web project");
+
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan=2;
+ projectSelectionCombo = new Combo(container,SWT.NONE | SWT.READ_ONLY);
+ projectSelectionCombo.setLayoutData(gd);
+ projectSelectionCombo.addModifyListener(new ModifyListener(){
+ public void modifyText(ModifyEvent arg0) {
+ fillSrviceSelectionCombo();
+ }
+
+ });
+
+ label=new Label(container,SWT.NULL);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ label.setLayoutData(gd);
+ gd.horizontalSpan=1;
+ label.setText("Axis2 service");
+
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan=2;
+ serviceSelectionCombo = new Combo(container,SWT.NONE | SWT.READ_ONLY);
+ serviceSelectionCombo.setLayoutData(gd);
+ serviceSelectionCombo.addModifyListener(new ModifyListener(){
+ public void modifyText(ModifyEvent arg0) {
+ handleModify();
+ }
+
+ });
+ fillProjectSelectionCombo();
+ fillSrviceSelectionCombo();
+
+ label=new Label(container,SWT.NULL);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ label.setLayoutData(gd);
+ gd.horizontalSpan=3;
+
+ label=new Label(container,SWT.HORIZONTAL | SWT.SEPARATOR);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 3;
+ label.setLayoutData(gd);
+
+ label=new Label(container,SWT.NULL);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ label.setLayoutData(gd);
+ gd.horizontalSpan=3;
+
+ label=new Label(container,SWT.NULL);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.horizontalSpan = 1;
+ label.setLayoutData(gd);
+ label.setText("Destination");
+
+
+ deployInWorkspaceText = new Text(container, SWT.BORDER | SWT.SINGLE);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ deployInWorkspaceText.setLayoutData(gd);
+ deployInWorkspaceText.addModifyListener(new ModifyListener() {
+ public void modifyText(ModifyEvent e) {
+ handleDeployInWorkspaceText();
+ }
+ });
+
+ Button deployInWorkspaceBrowseButton = new Button(container, SWT.PUSH);
+ deployInWorkspaceBrowseButton.setText("Browse");
+ deployInWorkspaceBrowseButton.addSelectionListener(new SelectionAdapter() {
+ public void widgetSelected(SelectionEvent e) {
+ handledeployInWorkspaceBrowseButton();
+ }
+ });
+
+ deployInWorkspaceText.setText("");
+ handleDeployInWorkspaceText();
+ setControl(parent);
+ }
+
+ private void fillSrviceSelectionCombo(){
+ //Check whether there is IDE configured services in the WSAS services directory
+ IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectSelectionCombo.getText());
+ selectedProject=project.getName();
+ servicesList=Axis2CoreUtils.getServiceFoldersInProject(project);
+ serviceSelectionCombo.removeAll();
+ for(Object o:servicesList){
+ IFolder folder=(IFolder)o;
+ serviceSelectionCombo.add(folder.getName());
+ }
+ if (serviceSelectionCombo.getItemCount()>0)
+ serviceSelectionCombo.select(0);
+ }
+
+ private void handleModify(){
+ setServiceToArchive(serviceSelectionCombo.getText());
+ archiveName=getServiceToArchive()+".aar";
+ }
+
+ private void fillProjectSelectionCombo(){
+ String[] webProjects=Axis2CoreUtils.getWorkspaceWebProjectList();
+ projectSelectionCombo.removeAll();
+
+ for(String project:webProjects){
+ projectSelectionCombo.add(project);
+ if (project.equals(selectedProject))
+ projectSelectionCombo.select(projectSelectionCombo.getItemCount()-1);
+ }
+
+ if (projectSelectionCombo.getSelectionIndex()==-1 && projectSelectionCombo.getItemCount()>0)
+ projectSelectionCombo.select(0);
+ }
+
+ protected void handledeployInWorkspaceBrowseButton() {
+ String fileName=getSavePath(archiveName);
+ if (fileName!=null){
+ Path path = new Path(fileName);
+ if (path.segmentCount()>0)
+ archiveName=path.segment(path.segmentCount()-1);
+ if (fileName!=null)
+ deployInWorkspaceText.setText(fileName);
+ }
+ }
+
+ protected void handleDeployInWorkspaceText() {
+ this.setFileLocation(deployInWorkspaceText.getText());
+ String msg=null;
+ File file = new File(getFileLocation());
+ if (getFileLocation().equalsIgnoreCase("") || !file.getParentFile().exists())
+ msg="Specified path for the file should be valid";
+ else if (!file.getName().toLowerCase().endsWith(".aar"))
+ msg="The Destination archive should end with .aar";
+ else if (file.exists()) {
+ setDescription(file.getName()+" already exists in the path specified. If you continue the file will be overwritten.");
+ }else
+ setDescription("Export axis2 service archive");
+ updateStatus(msg);
+ }
+
+ private void updateStatus(String msg){
+ if (serviceSelectionCombo.getSelectionIndex()==-1)
+ msg="No valid axis2 services found";
+ setErrorMessage(msg);
+ setPageComplete(msg==null);
+ }
+
+ private String getSavePath(String archive){
+ String fileName = null;
+ FileDialog dlg = new FileDialog(getShell());
+ dlg.setFileName(archive);
+ fileName = dlg.open();
+ return fileName;
+ }
+
+ public void setFileLocation(String fileLocation) {
+ this.fileLocation = fileLocation;
+ }
+
+ public String getFileLocation() {
+ return fileLocation;
+ }
+
+ public String getArchiveFileName(){
+ return (new File(fileLocation)).getAbsolutePath();
+ }
+
+ /**
+ * @param serviceToArchive the serviceToArchive to set
+ */
+ public void setServiceToArchive(String serviceToArchive) {
+ this.serviceToArchive = serviceToArchive;
+ }
+
+ /**
+ * @return the serviceToArchive
+ */
+ public String getServiceToArchive() {
+ return serviceToArchive;
+ }
+
+ public IFolder getSelectedService(){
+ for(Object o:servicesList){
+ IFolder folder=(IFolder)o;
+ if (folder.getName().equals(getServiceToArchive())){
+ return folder;
+ }
+ }
+ return null;
+ }
+}
#P org.eclipse.jst.ws.axis2.core
Index: src/org/eclipse/jst/ws/axis2/core/utils/Axis2CoreUtils.java
===================================================================
RCS file: /cvsroot/webtools/webservices/plugins/org.eclipse.jst.ws.axis2.core/src/org/eclipse/jst/ws/axis2/core/utils/Axis2CoreUtils.java,v
retrieving revision 1.6
diff -u -r1.6 Axis2CoreUtils.java
--- src/org/eclipse/jst/ws/axis2/core/utils/Axis2CoreUtils.java 15 Oct 2008 14:47:21 -0000 1.6
+++ src/org/eclipse/jst/ws/axis2/core/utils/Axis2CoreUtils.java 3 Jan 2009 06:57:58 -0000
@@ -16,6 +16,7 @@
* 20070824 200515 sandakith@wso2.com - Lahiru Sandakith, NON-NLS move to seperate file
* 20080625 210817 samindaw@wso2.com - Saminda Wijeratne, Setting the proxyBean and proxyEndPoint values - Refactoring
* 20080924 247929 samindaw@wso2.com - Saminda Wijeratne, source folder not correctly set
+ * 20090103 168938 samindaw@wso2.com - Saminda Wijeratne, Initial code to introduce aar export
*******************************************************************************/
package org.eclipse.jst.ws.axis2.core.utils;
@@ -28,15 +29,21 @@
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
@@ -44,6 +51,7 @@
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.core.JavaProject;
import org.eclipse.jst.ws.axis2.core.constant.Axis2Constants;
+import org.eclipse.jst.ws.internal.common.J2EEUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
@@ -243,4 +251,62 @@
}
return (String[])paths.toArray(new String[0]);
}
+
+
+ public static String[] getWorkspaceWebProjectList(){
+ List webProjects=new ArrayList();
+ IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
+ for(IProject project:projects){
+ try{
+ J2EEUtils.getWebInfPath(project);
+ webProjects.add(project.getName());
+ }catch(Exception e){
+ //not a web project
+ }
+ }
+ return (String[])webProjects.toArray(new String[webProjects.size()]);
+ }
+
+ public static List getServiceFoldersInProject(IProject project){
+ List services=new ArrayList();
+ IPath webInfPath = J2EEUtils.getWebInfPath(project);
+ IFolder folder=project.getFolder(webInfPath.removeFirstSegments(1));
+ IFolder servicesFolder=folder.getFolder(new Path("services"));
+
+ ServiceFolderVisitor visitor = new ServiceFolderVisitor(false);
+ try {
+ servicesFolder.accept(visitor);
+ } catch (CoreException e1) {
+ e1.printStackTrace();
+ }
+ for(IResource resource:visitor.getResources()){
+ Path path = new Path(resource.toString().substring(servicesFolder.toString().length()));
+ if (path.segmentCount()==1 && resource instanceof IFolder){
+ IFolder folder2=(IFolder)resource;
+ services.add(folder2);
+ }
+ }
+
+ return services;
+ }
+
+ private static class ServiceFolderVisitor implements IResourceVisitor{
+ List linkedFolders;
+ boolean isGetOnlyLinkedFolders=false;
+ public ServiceFolderVisitor(boolean isGetOnlyLinkedFolders){
+ linkedFolders=new ArrayList();
+ this.isGetOnlyLinkedFolders=isGetOnlyLinkedFolders;
+ }
+ public boolean visit(IResource arg0) throws CoreException {
+ if (!isGetOnlyLinkedFolders || arg0.isLinked()){
+ if (arg0 instanceof IFolder || arg0 instanceof IFile)
+ linkedFolders.add(arg0);
+ }
+ return true;
+ }
+
+ public IResource[] getResources(){
+ return linkedFolders.toArray(new IResource[]{});
+ }
+ }
}
Index: src/org/eclipse/jst/ws/axis2/core/utils/ArchiveManipulator.java
===================================================================
RCS file: src/org/eclipse/jst/ws/axis2/core/utils/ArchiveManipulator.java
diff -N src/org/eclipse/jst/ws/axis2/core/utils/ArchiveManipulator.java
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ src/org/eclipse/jst/ws/axis2/core/utils/ArchiveManipulator.java 1 Jan 1970 00:00:00 -0000
@@ -0,0 +1,220 @@
+/*******************************************************************************
+ * Copyright (c) 2007 WSO2 Inc. and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * WSO2 Inc. - initial API and implementation
+ * yyyymmdd bug Email and other contact information
+ * -------- -------- -----------------------------------------------------------
+ * 20090103 168938 samindaw@wso2.com - Saminda Wijeratne, Initial code to introduce aar export
+ *******************************************************************************/
+
+package org.eclipse.jst.ws.axis2.core.utils;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+public class ArchiveManipulator {
+ protected String archiveSourceDir;
+
+ /**
+ * Utility method to archive the given directory
+ * @param destArchiveName
+ * @param sourceDir
+ * @throws IOException
+ */
+ public void archiveDir(String destArchiveName, String sourceDir) throws IOException {
+ File zipDir = new File(sourceDir);
+ if (!zipDir.isDirectory()) {
+ throw new RuntimeException(sourceDir + " is not a directory");
+ }
+
+ ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destArchiveName));
+ this.archiveSourceDir = sourceDir;
+ zipDir(zipDir, zos);
+ zos.close();
+ }
+
+ /**
+ * Utility method to archive the given file
+ * @param from
+ * @param to
+ * @throws IOException
+ */
+ public void archiveFile(String from, String to) throws IOException {
+ FileInputStream in = new FileInputStream(from);
+ ZipOutputStream out = new ZipOutputStream(new FileOutputStream(to));
+ byte[] buffer = new byte[40960];
+ int bytesRead;
+ while ((bytesRead = in.read(buffer)) != -1) {
+ out.write(buffer, 0, bytesRead);
+ }
+ in.close();
+ out.close();
+ }
+
+ /**
+ * List the contents of an archive
+ * @param archive
+ * @return List of Zip Entries
+ * @throws IOException
+ */
+ public String[] check(String archive) throws IOException {
+ ZipInputStream zin = null;
+ InputStream in = null;
+ Collection entries = new ArrayList();
+ try {
+ in = new FileInputStream(archive);
+ zin = new ZipInputStream(in);
+ ZipEntry entry;
+ while ((entry = zin.getNextEntry()) != null) {
+ entries.add(entry.getName());
+ }
+ return (String[]) entries.toArray(new String[entries.size()]);
+ } finally {
+ try {
+ if (zin != null) {
+ zin.close();
+ }
+ if (in != null) {
+ in.close();
+ }
+ } catch (IOException e) {
+ System.err.println("Could not close InputStream " + e);
+ }
+ }
+ }
+
+ /**
+ * Utility method to extract an archive
+ * @param archive
+ * @param extractDir
+ * @throws IOException
+ */
+ public void extract(String archive, String extractDir) throws IOException {
+ FileInputStream inputStream = new FileInputStream(archive);
+ extractFromStream(inputStream, extractDir);
+ }
+
+ /**
+ * Utility method to extract form a stream to a given directory
+ * @param inputStream
+ * @param extractDir
+ * @throws IOException
+ */
+ public void extractFromStream(InputStream inputStream, String extractDir) throws IOException {
+ ZipInputStream zin = null;
+ try {
+ File unzipped = new File(extractDir);
+ // Open the ZIP file
+ zin = new ZipInputStream(inputStream);
+ unzipped.mkdirs();
+ ZipEntry entry;
+ while ((entry = zin.getNextEntry()) != null) {
+ String entryName = entry.getName();
+ File f = new File(extractDir + File.separator + entryName);
+
+ if (entryName.endsWith("/") && !f.exists()) { // this is a
+ // directory
+ f.mkdirs();
+ continue;
+ }
+
+ // This is a file. Carry out File processing
+ int lastIndexOfSlash = entryName.lastIndexOf("/");
+ String dirPath = "";
+ if (lastIndexOfSlash != -1) {
+ dirPath = entryName.substring(0, lastIndexOfSlash);
+ File dir = new File(extractDir + File.separator + dirPath);
+ if (!dir.exists()) {
+ dir.mkdirs();
+ }
+ }
+
+ if (!f.isDirectory()) {
+ OutputStream out = new FileOutputStream(f);
+ byte[] buf = new byte[40960];
+
+ // Transfer bytes from the ZIP file to the output file
+ int len;
+ while ((len = zin.read(buf)) > 0) {
+ out.write(buf, 0, len);
+ }
+ }
+ }
+ } catch (IOException e) {
+ String msg = "Cannot unzip archive. It is probably corrupt";
+ System.err.println(msg);
+ e.printStackTrace();
+ throw e;
+ } finally {
+ try {
+ if (zin != null) {
+ zin.close();
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ /**
+ * Utility method used by archive methods
+ * @param zipDir
+ * @param zos
+ * @throws IOException
+ */
+ private void zipDir(File zipDir, ZipOutputStream zos) throws IOException {
+ //get a listing of the directory content
+ String[] dirList = zipDir.list();
+ byte[] readBuffer = new byte[40960];
+ int bytesIn = 0;
+ //loop through dirList, and zip the files
+ for (int i = 0; i < dirList.length; i++) {
+ File f = new File(zipDir, dirList[i]);
+ //place the zip entry in the ZipOutputStream object
+ zos.putNextEntry(new ZipEntry(getZipEntryPath(f)));
+ if (f.isDirectory()) {
+ //if the File object is a directory, call this
+ //function again to add its content recursively
+ zipDir(f, zos);
+ //loop again
+ continue;
+ }
+ //if we reached here, the File object f was not a directory
+ //create a FileInputStream on top of f
+ FileInputStream fis = new FileInputStream(f);
+
+ //now write the content of the file to the ZipOutputStream
+ while ((bytesIn = fis.read(readBuffer)) != -1) {
+ zos.write(readBuffer, 0, bytesIn);
+ }
+ //close the Stream
+ fis.close();
+ }
+ }
+
+ private String getZipEntryPath(File f) {
+ String entryPath = f.getPath();
+ entryPath = entryPath.substring(archiveSourceDir.length() + 1);
+ if (File.separatorChar == '\\') {
+ entryPath = entryPath.replace(File.separatorChar, '/');
+ }
+ if (f.isDirectory()) {
+ entryPath += "/";
+ }
+ return entryPath;
+ }
+}