diff options
Diffstat (limited to 'scripting/java/org/openoffice/idesupport')
19 files changed, 2970 insertions, 0 deletions
diff --git a/scripting/java/org/openoffice/idesupport/CommandLineTools.java b/scripting/java/org/openoffice/idesupport/CommandLineTools.java new file mode 100644 index 000000000000..29d3b704f0a6 --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/CommandLineTools.java @@ -0,0 +1,350 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.Enumeration; +import java.util.StringTokenizer; + +import com.sun.star.script.framework.container.ScriptEntry; +import com.sun.star.script.framework.container.ParcelDescriptor; + +import org.openoffice.idesupport.zip.ParcelZipper; +import org.openoffice.idesupport.filter.AllFilesFilter; +import com.sun.star.script.framework.container.XMLParserFactory; +import org.openoffice.idesupport.*; + +public class CommandLineTools { + private static final String PARCEL_XML_FILE = + ParcelZipper.PARCEL_DESCRIPTOR_XML; + + private static String officePath = null; + + public static void main(String[] args) { + CommandLineTools driver = new CommandLineTools(); + Command command = driver.parseArgs(args); + + // Get the URL for the Office DTD directory and pass it to the + // XMLParserFactory so that Office xml files can be parsed + if (officePath == null) + { + try { + SVersionRCFile sv = SVersionRCFile.createInstance(); + if (sv.getDefaultVersion() != null) + { + officePath = sv.getDefaultVersion().getPath(); + } + } + catch (IOException ioe) { + System.err.println("Error getting Office directory"); + } + } + + if (officePath == null) + { + driver.fatalUsage("Error: Office Installation path not set"); + } + + File officeDir = new File(officePath); + if (officeDir.exists() == false || officeDir.isDirectory() == false) + { + driver.fatalUsage( + "Error: Office Installation path not valid: " + officePath); + } + + OfficeInstallation oi = new OfficeInstallation(officePath); + String url = oi.getURL("share/dtd/officedocument/1_0/"); + XMLParserFactory.setOfficeDTDURL(url); + + if (command == null) + driver.printUsage(); + else { + try { + command.execute(); + } + catch (Exception e) { + driver.fatal("Error: " + e.getMessage()); + } + } + } + + private interface Command { + public void execute() throws Exception; + } + + private void printUsage() { + System.out.println("java " + getClass().getName() + " -h " + + "prints this message"); + System.out.println("java " + getClass().getName() + + " [-o Path to Office Installation] " + + "-d <script parcel zip file> " + + "<destination document or directory>"); + System.out.println("java " + getClass().getName() + + " [-o Path to Office Installation] " + + "-g [parcel root directory] [options] [script names]"); + System.out.println("options:"); + System.out.println("\t[-l language[=supported extension 1[" + + File.pathSeparator + "supported extension 2]]]"); + System.out.println("\t[-p name=value]"); + System.out.println("\t[-v]"); + } + + private void fatal(String message) { + System.err.println(message); + System.exit(-1); + } + + private void fatalUsage(String message) { + System.err.println(message); + System.err.println(); + printUsage(); + System.exit(-1); + } + private Command parseArgs(String[] args) { + + if (args.length < 1) { + return null; + } + else if (args[0].equals("-h")) { + return new Command() { + public void execute() { + printUsage(); + } + }; + } + + int i = 0; + + if(args[0].equals("-o")) { + officePath = args[i+1]; + i += 2; + } + + if(args[i].equals("-d")) { + if ((args.length - i) != 3) + return null; + else + return new DeployCommand(args[i+1], args[i+2]); + } + else if(args[i].equals("-g")) { + + if ((args.length - i) == 1) + return new GenerateCommand(System.getProperty("user.dir")); + + GenerateCommand command; + i++; + if (!args[i].startsWith("-")) + command = new GenerateCommand(args[i++]); + else + command = new GenerateCommand(System.getProperty("user.dir")); + + for (; i < args.length; i++) { + if (args[i].equals("-l")) { + command.setLanguage(args[++i]); + } + else if (args[i].equals("-p")) { + command.addProperty(args[++i]); + } + else if (args[i].equals("-v")) { + command.setVerbose(); + } + else { + command.addScript(args[i]); + } + } + return command; + } + return null; + } + + private static class GenerateCommand implements Command { + + private File basedir, contents, parcelxml; + private boolean verbose = false; + private String language = null; + private MethodFinder finder = null; + private ArrayList scripts = null; + private Hashtable properties = new Hashtable(3); + + public GenerateCommand(String basedir) { + this.basedir = new File(basedir); + this.contents = new File(basedir, ParcelZipper.CONTENTS_DIRNAME); + this.parcelxml = new File(contents, PARCEL_XML_FILE); + } + + public void setLanguage(String language) { + StringTokenizer tokenizer = new StringTokenizer(language, "="); + this.language = tokenizer.nextToken(); + + if (this.language.toLowerCase().equals("java")) { + this.finder = JavaFinder.getInstance(); + return; + } + + if (tokenizer.hasMoreTokens()) { + String ext = (String)tokenizer.nextToken(); + String[] extensions; + + if (ext.indexOf(File.pathSeparator) != -1) { + tokenizer = new StringTokenizer(ext, File.pathSeparator); + extensions = new String[tokenizer.countTokens()]; + int i = 0; + + while(tokenizer.hasMoreTokens()) + extensions[i++] = (String)tokenizer.nextToken(); + } + else { + extensions = new String[1]; + extensions[0] = ext; + } + this.finder = new ExtensionFinder(this.language, extensions); + } + } + + public void addProperty(String prop) { + StringTokenizer tok = new StringTokenizer(prop, "="); + + if (tok.countTokens() != 2) + return; + + String name = tok.nextToken(); + String value = tok.nextToken(); + + properties.put(name, value); + } + + public void setVerbose() { + verbose = true; + } + + public void addScript(String script) { + if (language == null) + return; + + addScript(new ScriptEntry(language, script, script, basedir.getName())); + } + + public void addScript(ScriptEntry entry) { + if (scripts == null) + scripts = new ArrayList(3); + scripts.add(entry); + } + + public void execute() throws Exception { + + if (basedir.isDirectory() != true) { + throw new Exception(basedir.getName() + " is not a directory"); + } + else if (contents.exists() != true) { + throw new Exception(basedir.getName() + + " does not contain a Contents directory"); + } + + if (language == null && parcelxml.exists() == false) { + throw new Exception(parcelxml.getName() + " not found and language " + + "not specified"); + } + + if (language != null && parcelxml.exists() == true) { + ParcelDescriptor desc; + String desclang = ""; + + desc = new ParcelDescriptor(parcelxml); + desclang = desc.getLanguage().toLowerCase(); + + if (!desclang.equals(language.toLowerCase())) + throw new Exception(parcelxml.getName() + " already exists, " + + "and has a different language attribute: " + + desc.getLanguage()); + } + + if (language != null && scripts == null) { + if (finder == null) + throw new Exception("Extension list not specified for this language"); + + log("Searching for " + language + " scripts"); + + ScriptEntry[] entries = finder.findMethods(contents); + for (int i = 0; i < entries.length; i++) { + addScript(entries[i]); + log("Found: " + entries[i].getLogicalName()); + } + } + + if (scripts != null) { + if (scripts.size() == 0) + throw new Exception("No valid scripts found"); + + ParcelDescriptor desc = new ParcelDescriptor(parcelxml, language); + desc.setScriptEntries((ScriptEntry[])scripts.toArray(new ScriptEntry[0])); + if (properties.size() != 0) { + Enumeration enumer = properties.keys(); + + while (enumer.hasMoreElements()) { + String name = (String)enumer.nextElement(); + String value = (String)properties.get(name); + log("Setting property: " + name + " to " + value); + + desc.setLanguageProperty(name, value); + } + } + desc.write(); + } + else { + if (parcelxml.exists() == false) + throw new Exception("No valid scripts found"); + } + + contents = new File(contents.getAbsolutePath()); + String name = ParcelZipper.getParcelZipper().zipParcel(contents, AllFilesFilter.getInstance()); + System.out.println(name + " generated"); + } + + private void log(String message) { + if (verbose) + System.out.println(message); + } + } + + private static class DeployCommand implements Command { + + File source, target; + + public DeployCommand(String source, String target) { + this.source = new File(source); + this.target = new File(target); + } + + public void execute() throws Exception { + ParcelZipper.getParcelZipper().deployParcel(source, target); + System.out.println(source.getName() + + " successfully deployed to " + target.getAbsolutePath()); + } + } +} diff --git a/scripting/java/org/openoffice/idesupport/ExtensionFinder.java b/scripting/java/org/openoffice/idesupport/ExtensionFinder.java new file mode 100644 index 000000000000..8a0a10196a73 --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/ExtensionFinder.java @@ -0,0 +1,60 @@ +package org.openoffice.idesupport; + +import java.io.File; +import java.util.ArrayList; +import org.openoffice.idesupport.zip.ParcelZipper; + +import com.sun.star.script.framework.container.ScriptEntry; + +public class ExtensionFinder implements MethodFinder { + + private String[] extensions; + private String language; + + public ExtensionFinder(String language, String[] extensions) { + this.language = language; + this.extensions = extensions; + } + + public ScriptEntry[] findMethods(File basedir) { + String parcelName; + ArrayList files = new ArrayList(10); + ScriptEntry[] empty = new ScriptEntry[0]; + + if (basedir == null || basedir.exists() == false || + basedir.isDirectory() == false) + return empty; + + parcelName = basedir.getName(); + if (parcelName.equals(ParcelZipper.CONTENTS_DIRNAME)) + parcelName = basedir.getParentFile().getName(); + + findFiles(files, basedir, parcelName); + + if (files.size() != 0) + return (ScriptEntry[])files.toArray(empty); + return empty; + } + + private void findFiles(ArrayList list, File basedir, String parcelName) { + File[] children = basedir.listFiles(); + File f; + + for (int i = 0; i < children.length; i++) { + f = children[i]; + + if (f.isDirectory()) + findFiles(list, f, parcelName); + else { + for (int j = 0; j < extensions.length; j++) { + if (f.getName().endsWith(extensions[j])) { + ScriptEntry entry = new ScriptEntry(language, + f.getName(), f.getName(), parcelName); + list.add(entry); + break; + } + } + } + } + } +} diff --git a/scripting/java/org/openoffice/idesupport/JavaFinder.java b/scripting/java/org/openoffice/idesupport/JavaFinder.java new file mode 100644 index 000000000000..cf077b6b2c08 --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/JavaFinder.java @@ -0,0 +1,227 @@ +package org.openoffice.idesupport; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Vector; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.net.URLClassLoader; +import java.net.MalformedURLException; +import org.openoffice.idesupport.zip.ParcelZipper; + +import com.sun.star.script.framework.container.ScriptEntry; + +public class JavaFinder implements MethodFinder { + + private static JavaFinder finder; + private static final String JAVA_SUFFIX = ".java"; + private static final String CLASS_SUFFIX = ".class"; + private static final String LANGUAGE = "Java"; + private static final String FIRST_PARAM = + "drafts.com.sun.star.script.framework.runtime.XScriptContext"; + + private Vector classpath = null; + + private JavaFinder() {} + + private JavaFinder(Vector classpath) { + this.classpath = classpath; + } + + public static JavaFinder getInstance() { + if (finder == null) { + synchronized(JavaFinder.class) { + if (finder == null) + finder = new JavaFinder(); + } + } + return finder; + } + + public static JavaFinder getInstance(Vector classpath) { + return new JavaFinder(classpath); + } + + public ScriptEntry[] findMethods(File basedir) { + String parcelName; + ArrayList result = new ArrayList(10); + ScriptEntry[] empty = new ScriptEntry[0]; + + if (basedir == null || basedir.exists() == false || + basedir.isDirectory() == false) + return empty; + + parcelName = basedir.getName(); + if (parcelName.equals(ParcelZipper.CONTENTS_DIRNAME)) + parcelName = basedir.getParentFile().getName(); + + String[] classNames = findClassNames(basedir); + if (classNames != null && classNames.length != 0) { + + ClassLoader classloader; + + if (classpath == null) + classloader = getClassLoader(basedir); + else + classloader = getClassLoader(); + + for (int i = 0; i < classNames.length; i++) + { + try + { + Class clazz = classloader.loadClass(classNames[i]); + Method[] methods = clazz.getDeclaredMethods(); + for (int k = 0; k < methods.length; k++) + { + if (Modifier.isPublic(methods[k].getModifiers())) + { + Class[] params = methods[k].getParameterTypes(); + if(params.length > 0) + { + if(params[0].getName().equals(FIRST_PARAM)) + { + ScriptEntry entry = + new ScriptEntry(classNames[i] + "." + + methods[k].getName(), parcelName); + result.add(entry); + } + } + } + } + } + catch (ClassNotFoundException e) + { + System.err.println("Caught ClassNotFoundException loading: " + + classNames[i]); + continue; + } + catch (NoClassDefFoundError nc) + { + System.err.println("Caught NoClassDefFoundErr loading: " + + classNames[i]); + continue; + } + } + } + + if (result.size() != 0) + return (ScriptEntry[])result.toArray(empty); + return empty; + } + + private ClassLoader getClassLoader() { + int len = classpath.size(); + ArrayList urls = new ArrayList(len); + + for (int i = 0; i < len; i++) { + try { + String s = (String)classpath.elementAt(i); + s = SVersionRCFile.toFileURL(s); + + if (s != null) + urls.add(new URL(s)); + } + catch (MalformedURLException mue) { + } + } + + return new URLClassLoader((URL[])urls.toArray(new URL[0])); + } + + private ClassLoader getClassLoader(File basedir) { + ArrayList files = findFiles(basedir, ".jar"); + files.add(basedir); + + try { + Enumeration offices = SVersionRCFile.createInstance().getVersions(); + + while (offices.hasMoreElements()) { + OfficeInstallation oi = (OfficeInstallation)offices.nextElement(); + String unoil = SVersionRCFile.getPathForUnoil(oi.getPath()); + + if (unoil != null) { + files.add(new File(unoil, "unoil.jar")); + break; + } + } + } + catch (IOException ioe) { + return null; + } + + URL[] urls = new URL[files.size()]; + String urlpath; + File f; + for (int i = 0; i < urls.length; i++) { + try { + f = (File)files.get(i); + urlpath = SVersionRCFile.toFileURL(f.getAbsolutePath()); + + if (urlpath != null) + urls[i] = new URL(urlpath); + } + catch (MalformedURLException mue) { + // do nothing, go on to next file + } + } + + return new URLClassLoader(urls); + } + + private ArrayList findFiles(File basedir, String suffix) { + ArrayList result = new ArrayList(); + File[] children = basedir.listFiles(); + + for (int i = 0; i < children.length; i++) { + if (children[i].isDirectory()) + result.addAll(findFiles(children[i], suffix)); + else if (children[i].getName().endsWith(suffix)) + result.add(children[i]); + } + return result; + } + + private String[] findClassNames(File basedir) + { + ArrayList classFiles = findFiles(basedir, CLASS_SUFFIX); + if(classFiles == null || classFiles.size() == 0) + return null; + + ArrayList javaFiles = findFiles(basedir, JAVA_SUFFIX); + if(javaFiles == null || javaFiles.size() == 0) + return null; + + ArrayList result = new ArrayList(); + for (int i = 0; i < classFiles.size(); i++) + { + File classFile = (File)classFiles.get(i); + String className = classFile.getName(); + className = className.substring(0, className.lastIndexOf(CLASS_SUFFIX)); + boolean finished = false; + + + for (int j = 0; j < javaFiles.size() && finished == false; j++) + { + File javaFile = (File)javaFiles.get(j); + String javaName = javaFile.getName(); + javaName = javaName.substring(0, javaName.lastIndexOf(JAVA_SUFFIX)); + + if (javaName.equals(className)) + { + String path = classFile.getAbsolutePath(); + path = path.substring(basedir.getAbsolutePath().length() + 1); + path = path.replace(File.separatorChar, '.'); + path = path.substring(0, path.lastIndexOf(CLASS_SUFFIX)); + + result.add(path); + javaFiles.remove(j); + finished = true; + } + } + } + return (String[])result.toArray(new String[0]); + } +} diff --git a/scripting/java/org/openoffice/idesupport/LocalOffice.java b/scripting/java/org/openoffice/idesupport/LocalOffice.java new file mode 100644 index 000000000000..73f319a87269 --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/LocalOffice.java @@ -0,0 +1,109 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package org.openoffice.idesupport; + +import java.io.File; +import java.net.ConnectException; +import java.util.Vector; + +/** + * LocalOffice represents a connection to the local office. + * + * This class allows to get access to some scripting framework + * releated functionality of the locally running office. The + * office has to be started with options appropriate for establishing + * local connection. + * + * @author misha <misha@openoffice.org> + */ +public class LocalOffice +{ + /** + * Creates an instance of the local office connection. + * + * @param parent is an application specific class loader. + * @param officePath is a platform specific path string + * to the office distribution. + * @param port is a communication port. + */ + public static final LocalOffice create( + ClassLoader parent, String officePath, int port) + { + Vector path = new Vector(); + path.addElement(officePath + "/program/classes/ridl.jar"); + path.addElement(officePath + "/program/classes/jurt.jar"); + path.addElement(officePath + "/program/classes/unoil.jar"); + path.addElement(officePath + "/program/classes/juh.jar"); + path.addElement(System.getProperties().getProperty("netbeans.home") + + File.separator + "modules" + + File.separator + "ext" + + File.separator + "localoffice.jar"); + // commented out so code will compile + // ClassLoader appcl = new DefaultScriptClassLoader(parent, path); + ClassLoader appcl = path.getClass().getClassLoader(); + Class clazz = null; + LocalOffice office = null; + try { + clazz = appcl.loadClass( + "org.openoffice.idesupport.localoffice.LocalOfficeImpl"); + office = (LocalOffice)clazz.newInstance(); + office.connect(officePath, port); + } catch (java.lang.Exception exp) { + office = null; + } + return office; + } + + /** + * Connects to the running office. + * + * @param officePath is a platform specific path string + * to the office distribution. + * @param port is a communication port. + */ + protected void connect(String officePath, int port) + throws ConnectException + { + } + + /** + * Closes the connection to the running office. + */ + public void disconnect() + { + } + + /** + * Refresh the script storage. + * + * @param uri is an identifier of storage has to be refreshed. + */ + public void refreshStorage(String uri) + { + } +} diff --git a/scripting/java/org/openoffice/idesupport/MethodFinder.java b/scripting/java/org/openoffice/idesupport/MethodFinder.java new file mode 100644 index 000000000000..3bf85e323566 --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/MethodFinder.java @@ -0,0 +1,8 @@ +package org.openoffice.idesupport; + +import java.io.File; +import com.sun.star.script.framework.container.ScriptEntry; + +public interface MethodFinder { + public ScriptEntry[] findMethods(File basedir); +} diff --git a/scripting/java/org/openoffice/idesupport/OfficeDocument.java b/scripting/java/org/openoffice/idesupport/OfficeDocument.java new file mode 100644 index 000000000000..9f75c57be867 --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/OfficeDocument.java @@ -0,0 +1,120 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package org.openoffice.idesupport; + +import java.io.*; +import java.util.zip.*; +import java.util.Vector; +import java.util.Enumeration; +import java.util.StringTokenizer; + +import org.openoffice.idesupport.filter.FileFilter; +import org.openoffice.idesupport.filter.BinaryOnlyFilter; +import org.openoffice.idesupport.zip.ParcelZipper; + +public class OfficeDocument +{ + public static final String PARCEL_PREFIX_DIR = + ParcelZipper.PARCEL_PREFIX_DIR; + + public static final String[] OFFICE_EXTENSIONS = + {".sxc" , ".sxw", ".sxi", ".sxd"}; + public static final String OFFICE_PRODUCT_NAME = "OpenOffice.org"; + + private File file = null; + + public OfficeDocument(File file) throws IllegalArgumentException + { + if (!file.exists() || file.isDirectory() || !isOfficeFile(file)) { + throw new IllegalArgumentException("This is not a valid " + + OFFICE_PRODUCT_NAME + " document."); + } + this.file = file; + } + + private boolean isOfficeFile(File file) { + for (int i = 0; i < OFFICE_EXTENSIONS.length; i++) + if (file.getName().endsWith(OFFICE_EXTENSIONS[i])) + return true; + return false; + } + + public Enumeration getParcels() { + + Vector parcels = new Vector(); + ZipFile zp = null; + + try + { + zp = new ZipFile(this.file); + + for (Enumeration enumer = zp.entries(); enumer.hasMoreElements(); ) + { + ZipEntry ze = (ZipEntry)enumer.nextElement(); + if (ze.getName().endsWith(ParcelZipper.PARCEL_DESCRIPTOR_XML)) + { + String tmp = ze.getName(); + int end = tmp.lastIndexOf("/"); + tmp = tmp.substring(0, end); + + String parcelName = ze.getName().substring(0, end); + parcels.add(parcelName); + } + } + } + catch(ZipException ze) { + ze.printStackTrace(); + } + catch(IOException ioe) { + ioe.printStackTrace(); + } + finally { + if (zp != null) { + try { + zp.close(); + } + catch (IOException asdf) { + } + } + } + + return parcels.elements(); + } + + public boolean removeParcel(String parcelName) { + + try { + ParcelZipper.getParcelZipper().removeParcel(file, parcelName); + } + catch (IOException ioe) { + ioe.printStackTrace(); + return false; + } + return true; + } +} diff --git a/scripting/java/org/openoffice/idesupport/OfficeInstallation.java b/scripting/java/org/openoffice/idesupport/OfficeInstallation.java new file mode 100644 index 000000000000..66bb8a6ccf29 --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/OfficeInstallation.java @@ -0,0 +1,110 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ +package org.openoffice.idesupport; + +import java.io.File; +import java.net.URLDecoder; + +public class OfficeInstallation implements java.io.Serializable { + + private String name; + private String path; + private String url; + private boolean hasFW = false; + private boolean supportsFW = false; + + public static final String FILE_URL_PREFIX = SVersionRCFile.FILE_URL_PREFIX; + + public OfficeInstallation(String path) { + this(path, path); + } + + public OfficeInstallation(String name, String path) { + + this.name = name; + + if (path.startsWith(FILE_URL_PREFIX)) { + this.url = path; + path = URLDecoder.decode(path); + path = path.substring(FILE_URL_PREFIX.length()); + + if (System.getProperty("os.name").startsWith("Windows")) + path = path.replace('/', File.separatorChar); + + this.path = path; + } + else { + this.path = path; + + if (System.getProperty("os.name").startsWith("Windows")) + path = path.replace(File.separatorChar, '/'); + + this.url = FILE_URL_PREFIX + path; + } + } + + public String getName() { + return name; + } + + public String getPath() { + return path; + } + + public String getPath(String name) { + if (!name.startsWith(File.separator)) + name = File.separator + name; + + return path + name; + } + + public String getURL() { + return url; + } + + public String getURL(String name) { + if (System.getProperty("os.name").startsWith("Windows")) + name = name.replace(File.separatorChar, '/'); + + if (!name.startsWith("/")) + name = "/" + name; + + return url + name; + } + + public boolean hasFramework() { + return hasFW; + } + + public boolean supportsFramework() { + return true; + } + + public String toString() { + return getName(); + } +} diff --git a/scripting/java/org/openoffice/idesupport/SVersionRCFile.java b/scripting/java/org/openoffice/idesupport/SVersionRCFile.java new file mode 100644 index 000000000000..0df5d4a61169 --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/SVersionRCFile.java @@ -0,0 +1,237 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package org.openoffice.idesupport; + +import java.io.File; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.FileNotFoundException; +import java.util.Vector; +import java.util.HashMap; +import java.util.Enumeration; +import java.util.StringTokenizer; + +public class SVersionRCFile { + + public static final String DEFAULT_NAME = + System.getProperty("os.name").startsWith("Windows") == true ? + System.getProperty("user.home") + File.separator + + "Application Data" + File.separator + "sversion.ini" : + System.getProperty("user.home") + File.separator + + ".sversionrc"; + + public static final String FILE_URL_PREFIX = + System.getProperty("os.name").startsWith("Windows") == true ? + "file:///" : "file://"; + + public static final String PKGCHK = + System.getProperty("os.name").startsWith("Windows") == true ? + "pkgchk.exe" : "pkgchk"; + + private static final String VERSIONS_LINE = "[Versions]"; + + private static final String UNOILJAR = + "skip_registration" + File.separator + "unoil.jar"; + + private static final String UNOPACKAGEDIR = + File.separator + "user" + File.separator + "uno_packages" + + File.separator + "cache" + File.separator + "uno_packages"; + + /* Make sure this is in LowerCase !!!!! */ + private static final String SCRIPTF = "scriptf"; + + private static final HashMap files = new HashMap(3); + + private File sversionrc = null; + private OfficeInstallation defaultversion = null; + private Vector versions = null; + private long lastModified = 0; + + public SVersionRCFile() { + this(DEFAULT_NAME); + } + + public SVersionRCFile(String name) { + sversionrc = new File(name); + versions = new Vector(5); + } + + public static SVersionRCFile createInstance() { + return(createInstance(DEFAULT_NAME)); + } + + public static SVersionRCFile createInstance(String name) { + SVersionRCFile result = null; + + synchronized(SVersionRCFile.class) { + result = (SVersionRCFile)files.get(name); + + if (result == null) { + result = new SVersionRCFile(name); + files.put(name, result); + } + } + return result; + } + + public OfficeInstallation getDefaultVersion() throws IOException { + if (defaultversion == null) { + getVersions(); + } + + return defaultversion; + } + + public Enumeration getVersions() throws IOException { + + long l = sversionrc.lastModified(); + + if (l > lastModified) { + BufferedReader br = null; + + try { + br = new BufferedReader(new FileReader(sversionrc)); + load(br); + lastModified = l; + } + catch (FileNotFoundException fnfe) { + throw new IOException(fnfe.getMessage()); + } + finally { + if (br != null) + br.close(); + } + } + return versions.elements(); + } + + private void load(BufferedReader br) throws IOException { + String s; + + while ((s = br.readLine()) != null && + (s.equals(VERSIONS_LINE)) != true); + + while ((s = br.readLine()) != null && + (s.equals("")) != true) { + StringTokenizer tokens = new StringTokenizer(s, "="); + int count = tokens.countTokens(); + + if (count != 2) + continue; + + String name = tokens.nextToken(); + String path = tokens.nextToken(); + OfficeInstallation oi = new OfficeInstallation(name, path); + if (oi.supportsFramework()) { + versions.add(oi); + defaultversion = oi; + } + } + } + + public static String toFileURL(String path) { + File f = new File(path); + + if (!f.exists()) + return null; + + try { + path = f.getCanonicalPath(); + } + catch (IOException ioe) { + return null; + } + + if (System.getProperty("os.name").startsWith("Windows")) + path = path.replace(File.separatorChar, '/'); + + StringBuffer buf = new StringBuffer(FILE_URL_PREFIX); + buf.append(path); + + if (f.isDirectory()) + buf.append("/"); + + return buf.toString(); + } + + public static String getPathForUnoil(String officeInstall) + { + File unopkgdir = new File(officeInstall, UNOPACKAGEDIR); + if(!unopkgdir.exists()) + { + return null; + } + File scriptf = null; + String[] listunopkg = unopkgdir.list(); + int size = listunopkg.length; + for(int i=0; i<size; i++) + { + if (listunopkg[i].toLowerCase().indexOf(SCRIPTF)>-1) + { + scriptf = new File(unopkgdir, listunopkg[i]); + } + } + if(scriptf != null) + { + File unoil = new File(scriptf, UNOILJAR); + if(unoil.exists()) + { + String path = unoil.getParent(); + path = path.substring(path.indexOf(UNOPACKAGEDIR)); + return officeInstall + path; + } + } + return null; + } + + public static void main(String[] args) { + SVersionRCFile ov; + + if (args.length == 0) + ov = new SVersionRCFile(); + else + ov = new SVersionRCFile(args[0]); + + Enumeration enumer; + + try { + enumer = ov.getVersions(); + } + catch (IOException ioe) { + System.err.println("Error getting versions: " + ioe.getMessage()); + return; + } + + while (enumer.hasMoreElements()) { + OfficeInstallation oi = (OfficeInstallation)enumer.nextElement(); + System.out.println("Name: " + oi.getName() + ", Path: " + oi.getPath() + + ", URL: " + oi.getURL()); + } + } +} diff --git a/scripting/java/org/openoffice/idesupport/filter/AllFilesFilter.java b/scripting/java/org/openoffice/idesupport/filter/AllFilesFilter.java new file mode 100644 index 000000000000..c27886d8f9c5 --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/filter/AllFilesFilter.java @@ -0,0 +1,47 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package org.openoffice.idesupport.filter; + +public class AllFilesFilter implements FileFilter { + private static final AllFilesFilter filter = new AllFilesFilter(); + + private AllFilesFilter() { + } + + public static AllFilesFilter getInstance() { + return filter; + } + + public boolean validate(String name) { + return true; + } + + public String toString() { + return "<all files>"; + } +} diff --git a/scripting/java/org/openoffice/idesupport/filter/BinaryOnlyFilter.java b/scripting/java/org/openoffice/idesupport/filter/BinaryOnlyFilter.java new file mode 100644 index 000000000000..ba670705566c --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/filter/BinaryOnlyFilter.java @@ -0,0 +1,58 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package org.openoffice.idesupport.filter; + +public class BinaryOnlyFilter implements FileFilter { + private static final String[] EXTENSIONS = {".class", ".jar", ".bsh"}; + private static final String DESCRIPTION = "Executable Files Only"; + private static final BinaryOnlyFilter filter = new BinaryOnlyFilter(); + + private BinaryOnlyFilter() { + } + + public static BinaryOnlyFilter getInstance() { + return filter; + } + public boolean validate(String name) { + for (int i = 0; i < EXTENSIONS.length; i++) + if (name.endsWith(EXTENSIONS[i])) + return true; + return false; + } + + public String toString() { + /* StringBuffer buf = new StringBuffer(DESCRIPTION + ": "); + + for (int i = 0; i < EXTENSIONS.length - 1; i++) + buf.append("<" + EXTENSIONS[i] + "> "); + buf.append("<" + EXTENSIONS[EXTENSIONS.length - 1] + ">"); + + return buf.toString(); */ + return DESCRIPTION; + } +} diff --git a/scripting/java/org/openoffice/idesupport/filter/ExceptParcelFilter.java b/scripting/java/org/openoffice/idesupport/filter/ExceptParcelFilter.java new file mode 100644 index 000000000000..9de3acfb3ee5 --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/filter/ExceptParcelFilter.java @@ -0,0 +1,59 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package org.openoffice.idesupport.filter; + +public class ExceptParcelFilter implements FileFilter { + private static final String DESCRIPTION = "Remove specified Parcel"; + private static final ExceptParcelFilter filter = new ExceptParcelFilter(); + private static String parcelName = null; + + private ExceptParcelFilter() { + } + + public void setParcelToRemove(String parcelName) + { + this.parcelName = parcelName; + } + + public static ExceptParcelFilter getInstance() { + return filter; + } + public boolean validate(String name) { + if (name.startsWith(this.parcelName)) + return true; + return false; + } + + public String toString() { + StringBuffer buf = new StringBuffer(DESCRIPTION + ": "); + + buf.append("<" + this.parcelName + ">"); + + return buf.toString(); + } +} diff --git a/scripting/java/org/openoffice/idesupport/filter/FileFilter.java b/scripting/java/org/openoffice/idesupport/filter/FileFilter.java new file mode 100644 index 000000000000..52ad72c4753c --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/filter/FileFilter.java @@ -0,0 +1,32 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package org.openoffice.idesupport.filter; + +public interface FileFilter { + public boolean validate(String name); +} diff --git a/scripting/java/org/openoffice/idesupport/localoffice/LocalOfficeImpl.java b/scripting/java/org/openoffice/idesupport/localoffice/LocalOfficeImpl.java new file mode 100644 index 000000000000..491aa61cb052 --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/localoffice/LocalOfficeImpl.java @@ -0,0 +1,154 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package org.openoffice.idesupport.localoffice; + +import java.net.ConnectException; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XComponent; +import com.sun.star.bridge.UnoUrlResolver; +import com.sun.star.bridge.XUnoUrlResolver; +import com.sun.star.beans.XPropertySet; +import com.sun.star.comp.helper.Bootstrap; +import com.sun.star.uno.XComponentContext; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.Exception; + +import drafts.com.sun.star.script.framework.storage.XScriptStorageManager; + +import org.openoffice.idesupport.LocalOffice; + +/** + * LocalOfficeImpl represents a connection to the local office. + * + * This class is an implementation of LocalOffice ane allows to + * get access to some scripting framework releated functionality + * of the locally running office. The office has to be started + * with options appropriate for establishing local connection. + * + * @author misha <misha@openoffice.org> + */ +public final class LocalOfficeImpl + extends LocalOffice +{ + private final static String STORAGE_MRG_SINGLETON = + "/singletons/drafts.com.sun.star.script.framework.storage.theScriptStorageManager"; + + private transient String mOfficePath; + private transient XMultiComponentFactory mComponentFactory; + private transient XComponentContext mComponentContext; + private transient XMultiServiceFactory mServiceFactory; + /** + * Constructor. + */ + public LocalOfficeImpl() + { + } + + /** + * Connects to the running office. + * + * @param officePath is a platform specific path string + * to the office distribution. + * @param port is a communication port. + */ + protected void connect(String officePath, int port) + throws ConnectException + { + mOfficePath = officePath; + try { + bootstrap(port); + } catch (java.lang.Exception ex) { + throw new ConnectException(ex.getMessage()); + } + } + + /** + * Refresh the script storage. + * + * @param uri is an identifier of storage has to be refreshed. + */ + public void refreshStorage(String uri) + { + try { + Object object = null; + object = mComponentContext.getValueByName(STORAGE_MRG_SINGLETON); + XScriptStorageManager storageMgr; + storageMgr = (XScriptStorageManager)UnoRuntime.queryInterface( + XScriptStorageManager.class, object); + storageMgr.refreshScriptStorage(uri); + } catch (java.lang.Exception ex) { +System.out.println("*** LocalOfficeImpl.refreshStorage: FAILED " + ex.getMessage()); +System.out.println("*** LocalOfficeImpl.refreshStorage: FAILED " + ex.getClass().getName()); + } +System.out.println("*** LocalOfficeImpl.refreshStorage: DONE"); + } + + /** + * Closes the connection to the running office. + */ + public void disconnect() + { +/* + if(mComponentFactory != null) { + XComponent comp = (XComponent)UnoRuntime.queryInterface( + XComponent.class, mComponentFactory); + comp.dispose(); + } +*/ + } + + /** + * Boot straps UNO. + * + * The office has to be started with following string: + * "-accept=socket,host=localhost,port=<PORT>;urp;StarOffice.ServiceManager" + * + * @param port is a communication port. + */ + private void bootstrap(int port) + throws java.lang.Exception + { + Object object; + mComponentContext = Bootstrap.createInitialComponentContext(null); + XUnoUrlResolver urlresolver = UnoUrlResolver.create(mComponentContext); + object = urlresolver.resolve( + "uno:socket,host=localhost,port=" + + port + + ";urp;StarOffice.ServiceManager"); + mComponentFactory = (XMultiComponentFactory)UnoRuntime.queryInterface( + XMultiComponentFactory.class, object); + XPropertySet factoryProps; + factoryProps = (XPropertySet)UnoRuntime.queryInterface( + XPropertySet.class, mComponentFactory); + object = factoryProps.getPropertyValue("DefaultContext"); + mComponentContext = (XComponentContext)UnoRuntime.queryInterface( + XComponentContext.class, object); + } +} diff --git a/scripting/java/org/openoffice/idesupport/ui/ConfigurePanel.java b/scripting/java/org/openoffice/idesupport/ui/ConfigurePanel.java new file mode 100644 index 000000000000..b4bfd6266dac --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/ui/ConfigurePanel.java @@ -0,0 +1,236 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package org.openoffice.idesupport.ui; + +import java.io.File; +import java.io.IOException; + +import java.util.Vector; +import java.util.Enumeration; + +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JButton; +import javax.swing.AbstractButton; +import javax.swing.ImageIcon; +import javax.swing.border.LineBorder; + +import java.awt.BorderLayout; +import java.awt.GridBagLayout; +import java.awt.GridBagConstraints; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import org.w3c.dom.Document; + +import com.sun.star.script.framework.container.ScriptEntry; +import com.sun.star.script.framework.container.ParcelDescriptor; + +import org.openoffice.idesupport.zip.ParcelZipper; + +public class ConfigurePanel extends JPanel { + + private File basedir; + private Vector classpath; + private ParcelDescriptor descriptor; + + private MethodPanel methodPanel; + private ScriptPanel scriptPanel; + + public static final String DIALOG_TITLE = + "Choose What to Export as Scripts"; + + public ConfigurePanel(String basedir, Vector classpath, + ParcelDescriptor descriptor) { + + this.basedir = new File(basedir); + this.classpath = classpath; + this.descriptor = descriptor; + initUI(); + } + + public ConfigurePanel(String basedir, Vector classpath) + throws IOException { + + this.basedir = new File(basedir); + this.classpath = classpath; + this.descriptor = new ParcelDescriptor(new File(this.basedir, + ParcelZipper.PARCEL_DESCRIPTOR_XML)); + initUI(); + } + + public void reload(String basedir, Vector classpath, + ParcelDescriptor descriptor) { + + if (basedir != null) + this.basedir = new File(basedir); + + if (classpath != null) + this.classpath = classpath; + + if (descriptor != null) { + descriptor = descriptor; + } + + methodPanel.reload(this.basedir, this.classpath, + descriptor.getLanguage()); + scriptPanel.reload(descriptor.getScriptEntries()); + } + + public void reload(String basedir, Vector classpath) + throws IOException { + + if (basedir != null) + this.basedir = new File(basedir); + + if (classpath != null) + this.classpath = classpath; + + this.descriptor = new ParcelDescriptor(new File(this.basedir, + ParcelZipper.PARCEL_DESCRIPTOR_XML)); + + methodPanel.reload(this.basedir, this.classpath, + descriptor.getLanguage()); + scriptPanel.reload(descriptor.getScriptEntries()); + } + + public ParcelDescriptor getConfiguration() throws Exception { + Enumeration scripts = scriptPanel.getScriptEntries(); + descriptor.setScriptEntries(scripts); + return descriptor; + } + + private void initUI() { + + JPanel leftPanel = new JPanel(); + JPanel methodButtons = initMethodButtons(); + methodPanel = new MethodPanel(basedir, classpath, descriptor.getLanguage()); + + leftPanel.setLayout(new BorderLayout()); + leftPanel.add(methodPanel, BorderLayout.CENTER); + + JPanel rightPanel = new JPanel(); + JPanel scriptButtons = initScriptButtons(); + scriptPanel = new ScriptPanel(descriptor.getScriptEntries()); + + rightPanel.setLayout(new BorderLayout()); + rightPanel.add(scriptPanel, BorderLayout.CENTER); + rightPanel.add(scriptButtons, BorderLayout.SOUTH); + + setLayout(new GridBagLayout()); + setPreferredSize(new java.awt.Dimension(700, 300)); + setBorder(LineBorder.createBlackLineBorder()); + + GridBagConstraints gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 0; + gbc.fill = java.awt.GridBagConstraints.BOTH; + gbc.ipadx = 40; + gbc.anchor = java.awt.GridBagConstraints.WEST; + gbc.insets = new Insets(10, 5, 5, 5); + gbc.weightx = 0.75; + add(leftPanel, gbc); + + gbc = new java.awt.GridBagConstraints(); + gbc.gridx = 1; + gbc.gridy = 0; + add(methodButtons, gbc); + + gbc = new java.awt.GridBagConstraints(); + gbc.gridx = 2; + gbc.gridy = 0; + gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER; + gbc.fill = java.awt.GridBagConstraints.BOTH; + gbc.anchor = java.awt.GridBagConstraints.EAST; + gbc.insets = new Insets(10, 5, 5, 5); + gbc.weightx = 1.0; + gbc.weighty = 1.0; + add(rightPanel, gbc); + } + + private JPanel initMethodButtons() { + JPanel panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + ImageIcon icon = new ImageIcon(getClass().getResource("/org/openoffice/idesupport/ui/add.gif")); + JButton addButton = new JButton("Add", icon); + addButton.setHorizontalTextPosition(AbstractButton.LEFT); + + addButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + scriptPanel.addScriptEntries(methodPanel.getSelectedEntries()); + } + } + ); + + GridBagConstraints gbc = new java.awt.GridBagConstraints(); + gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER; + gbc.fill = java.awt.GridBagConstraints.HORIZONTAL; + gbc.insets = new Insets(5, 5, 5, 5); + panel.add(addButton, gbc); + + JPanel dummyPanel = new JPanel(); + gbc = new java.awt.GridBagConstraints(); + gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER; + gbc.gridheight = java.awt.GridBagConstraints.REMAINDER; + gbc.fill = java.awt.GridBagConstraints.BOTH; + gbc.weightx = 1.0; + gbc.weighty = 1.0; + panel.add(dummyPanel, gbc); + + return panel; + } + + private JPanel initScriptButtons() { + JPanel panel = new JPanel(); + JButton removeButton = new JButton("Remove"); + JButton removeAllButton = new JButton("Remove All"); + + removeButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + scriptPanel.removeSelectedRows(); + } + } + ); + + removeAllButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + scriptPanel.removeAllRows(); + } + } + ); + + panel.add(removeButton); + panel.add(removeAllButton); + + return panel; + } +} diff --git a/scripting/java/org/openoffice/idesupport/ui/MethodPanel.java b/scripting/java/org/openoffice/idesupport/ui/MethodPanel.java new file mode 100644 index 000000000000..a65c9556d131 --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/ui/MethodPanel.java @@ -0,0 +1,186 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package org.openoffice.idesupport.ui; + +import java.io.File; +import java.util.Vector; +import java.util.ArrayList; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JList; +import javax.swing.JTable; +import javax.swing.table.AbstractTableModel; +import javax.swing.JLabel; +import java.awt.BorderLayout; +import java.net.URL; +import java.net.URLClassLoader; +import java.net.MalformedURLException; + +import com.sun.star.script.framework.container.ScriptEntry; +import org.openoffice.idesupport.MethodFinder; +import org.openoffice.idesupport.ExtensionFinder; +import org.openoffice.idesupport.JavaFinder; + +public class MethodPanel extends JPanel { + + private File basedir; + private Vector classpath; + private final static String FIRST_PARAM = + "drafts.com.sun.star.script.framework.runtime.XScriptContext"; + + // private JTable table; + // private MethodTableModel model; + private JList list; + private ScriptEntry[] values; + + public MethodPanel(File basedir, Vector classpath, String language) { + this.basedir = basedir; + this.classpath = classpath; + + initValues(language); + initUI(); + } + + public void reload(File basedir, Vector classpath, String language) { + this.basedir = basedir; + this.classpath = classpath; + + initValues(language); + list.setListData(values); + } + + public ScriptEntry[] getSelectedEntries() { + Object[] selections = list.getSelectedValues(); + ScriptEntry[] entries = new ScriptEntry[selections.length]; + + for (int i = 0; i < selections.length; i++) { + entries[i] = (ScriptEntry)selections[i]; + } + + return entries; + } + + private void initUI() { + JLabel label = new JLabel("Available Methods:"); + // table = new JTable(model); + list = new JList(values); + + JScrollPane pane = new JScrollPane(list); + label.setLabelFor(pane); + + BorderLayout layout = new BorderLayout(); + setLayout(layout); + layout.setVgap(5); + + add(label, BorderLayout.NORTH); + add(pane, BorderLayout.CENTER); + } + + private void initValues(String language) { + MethodFinder finder; + + if (language == null) + finder = JavaFinder.getInstance(classpath); + else if (language.toLowerCase().equals("beanshell")) + finder = new ExtensionFinder(language, new String[] {".bsh"}); + else + finder = JavaFinder.getInstance(classpath); + + values = finder.findMethods(basedir); + } + + /* + private class MethodTableModel extends AbstractTableModel { + final String[] columnNames = {"Method", + "Language"}; + + private Vector methods; + private int nextRow; + + public MethodTableModel() { + methods = new Vector(11); + } + + public int getColumnCount() { + return columnNames.length; + } + + public int getRowCount() { + return methods.size(); + } + + public String getColumnName(int col) { + return columnNames[col]; + } + + public void add(ScriptEntry entry) { + methods.addElement(entry); + fireTableRowsInserted(nextRow, nextRow); + nextRow++; + } + + public void remove(int row) { + methods.removeElementAt(row); + fireTableRowsDeleted(row, row); + nextRow--; + } + + public void removeAll() { + methods.removeAllElements(); + fireTableRowsDeleted(0, nextRow); + nextRow = 0; + } + + public Object getValueAt(int row) { + return methods.elementAt(row); + } + + public Object getValueAt(int row, int col) { + String result = ""; + ScriptEntry entry; + + entry = (ScriptEntry)methods.elementAt(row); + + if (col == 0) + result = entry.getLanguageName(); + else if (col == 1) + result = entry.getLanguage(); + + return result; + } + + public boolean isCellEditable(int row, int col) { + return false; + } + } + */ +} diff --git a/scripting/java/org/openoffice/idesupport/ui/ScriptPanel.java b/scripting/java/org/openoffice/idesupport/ui/ScriptPanel.java new file mode 100644 index 000000000000..98a6ac50e22d --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/ui/ScriptPanel.java @@ -0,0 +1,206 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package org.openoffice.idesupport.ui; + +import java.io.File; +import java.util.Vector; +import java.util.Enumeration; + +import java.awt.BorderLayout; +import java.awt.event.FocusEvent; +import java.awt.event.FocusAdapter; + +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JLabel; +import javax.swing.JTextField; +import javax.swing.JTable; +import javax.swing.DefaultCellEditor; +import javax.swing.table.TableCellEditor; +import javax.swing.table.TableColumn; +import javax.swing.table.AbstractTableModel; + +import com.sun.star.script.framework.container.ScriptEntry; + +public class ScriptPanel extends JPanel { + private ScriptTableModel model; + private JTable table; + + public ScriptPanel(ScriptEntry[] scripts) { + model = new ScriptTableModel(scripts); + initUI(); + } + + public void reload(ScriptEntry[] entries) { + model.removeAll(); + addScriptEntries(entries); + } + + public void addScriptEntries(ScriptEntry[] entries) { + for (int i = 0; i < entries.length; i++) { + ScriptEntry entry; + + try { + entry = (ScriptEntry) entries[i].clone(); + } + catch (CloneNotSupportedException cnse) { + entry = new ScriptEntry(entries[i].getLanguage(), + entries[i].getLanguageName(), + entries[i].getLogicalName(), + entries[i].getLocation()); + } + + model.add(entry); + } + } + + public void removeSelectedRows() { + int[] selections = table.getSelectedRows(); + + for (int i = selections.length - 1; i >= 0; i--) { + model.remove(selections[i]); + } + } + + public void removeAllRows() { + model.removeAll(); + } + + public Enumeration getScriptEntries() { + return model.getScriptEntries(); + } + + private void initUI() { + table = new JTable(model); + TableColumn column = table.getColumnModel().getColumn(1); + column.setCellEditor(new DefaultCellEditor(new JTextField())); + + table.addFocusListener(new FocusAdapter() { + public void focusLost(FocusEvent evt) { + tableFocusLost(evt); + } + }); + + JScrollPane pane = new JScrollPane(table); + JLabel label = new JLabel("Scripts:"); + label.setLabelFor(pane); + + BorderLayout layout = new BorderLayout(); + setLayout(layout); + layout.setVgap(5); + add(label, BorderLayout.NORTH); + add(pane, BorderLayout.CENTER); + } + + private void tableFocusLost(FocusEvent evt) { + TableCellEditor editor = table.getCellEditor(); + if (editor != null) { + Object value = editor.getCellEditorValue(); + if (value != null) + model.setValueAt(value, + table.getEditingRow(), table.getEditingColumn()); + } + } + + private class ScriptTableModel extends AbstractTableModel { + final String[] columnNames = {"Exported Method", + "Script Name"}; + + private Vector scripts; + private int nextRow; + + public ScriptTableModel(ScriptEntry[] entries) { + scripts = new Vector(entries.length + 11); + for (int i = 0; i < entries.length; i++) { + scripts.addElement(entries[i]); + } + nextRow = entries.length; + } + + public int getColumnCount() { + return columnNames.length; + } + + public int getRowCount() { + return scripts.size(); + } + + public String getColumnName(int col) { + return columnNames[col]; + } + + public void add(ScriptEntry entry) { + scripts.addElement(entry); + fireTableRowsInserted(nextRow, nextRow); + nextRow++; + } + + public void remove(int row) { + scripts.removeElementAt(row); + fireTableRowsDeleted(row, row); + nextRow--; + } + + public void removeAll() { + scripts.removeAllElements(); + fireTableRowsDeleted(0, nextRow); + nextRow = 0; + } + + public Enumeration getScriptEntries() { + return scripts.elements(); + } + + public Object getValueAt(int row, int col) { + String result = ""; + ScriptEntry entry; + + entry = (ScriptEntry)scripts.elementAt(row); + + if (col == 0) + result = entry.getLanguageName(); + else if (col == 1) + result = entry.getLogicalName(); + + return result; + } + + public boolean isCellEditable(int row, int col) { + if (col == 0) + return false; + else + return true; + } + + public void setValueAt(Object value, int row, int col) { + ScriptEntry entry = (ScriptEntry)scripts.elementAt(row); + entry.setLogicalName((String)value); + fireTableCellUpdated(row, col); + } + } +} diff --git a/scripting/java/org/openoffice/idesupport/ui/add.gif b/scripting/java/org/openoffice/idesupport/ui/add.gif Binary files differnew file mode 100644 index 000000000000..e47c986ccf1f --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/ui/add.gif diff --git a/scripting/java/org/openoffice/idesupport/xml/Manifest.java b/scripting/java/org/openoffice/idesupport/xml/Manifest.java new file mode 100644 index 000000000000..74b5bc8f22bc --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/xml/Manifest.java @@ -0,0 +1,171 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package org.openoffice.idesupport.xml; + +import java.io.InputStream; +import java.io.OutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.IOException; + +import java.util.Enumeration; +import java.util.ArrayList; +import java.util.Iterator; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.w3c.dom.Element; + +import com.sun.star.script.framework.container.XMLParserFactory; + +public class Manifest { + + private Document document = null; + private boolean baseElementsExist = false; + + public Manifest(InputStream inputStream) throws IOException { + document = XMLParserFactory.getParser().parse(inputStream); + } + + public void add(String entry) { + add(entry, ""); + } + + private void add(String entry, String type) { + Element root, el; + + ensureBaseElementsExist(); + + try { + root = (Element) + document.getElementsByTagName("manifest:manifest").item(0); + + el = document.createElement("manifest:file-entry"); + el.setAttribute("manifest:media-type", type); + el.setAttribute("manifest:full-path", entry); + // System.out.println("added: " + el.toString()); + root.appendChild(el); + } + catch (Exception e) { + System.err.println("Error adding entry: " + e.getMessage()); + } + } + + private void ensureBaseElementsExist() { + if (baseElementsExist == false) { + baseElementsExist = true; + add("Scripts/", "application/script-parcel"); + } + } + + public void remove(String entry) { + Element root, el; + int len; + + try { + root = (Element) + document.getElementsByTagName("manifest:manifest").item(0); + + NodeList nl = root.getElementsByTagName("manifest:file-entry"); + if (nl == null || (len = nl.getLength()) == 0) + return; + + ArrayList list = new ArrayList(); + for (int i = 0; i < len; i++) { + el = (Element)nl.item(i); + if (el.getAttribute("manifest:full-path").startsWith(entry)) { + // System.out.println("found: " + el.toString()); + list.add(el); + } + } + + Iterator iter = list.iterator(); + while (iter.hasNext()) + root.removeChild((Element)iter.next()); + + // System.out.println("and after root is: " + root.toString()); + } + catch (Exception e) { + System.err.println("Error removing entry: " + e.getMessage()); + } + } + + public InputStream getInputStream() throws IOException { + InputStream result = null; + ByteArrayOutputStream out = null; + + try { + out = new ByteArrayOutputStream(); + write(out); + result = new ByteArrayInputStream(out.toByteArray()); + // result = replaceNewlines(out.toByteArray()); + } + finally { + if (out != null) + out.close(); + } + + return result; + } + + private InputStream replaceNewlines(byte[] bytes) throws IOException { + InputStream result; + ByteArrayOutputStream out; + BufferedReader reader; + + reader = new BufferedReader(new InputStreamReader( + new ByteArrayInputStream(bytes))); + out = new ByteArrayOutputStream(); + + int previous = reader.read(); + out.write(previous); + int current; + + while ((current = reader.read()) != -1) { + if (((char)current == '\n' || (char)current == ' ') && + (char)previous == '\n') + continue; + else { + out.write(current); + previous = current; + } + } + result = new ByteArrayInputStream(out.toByteArray()); + + return result; + } + + public void write(OutputStream out) throws IOException { + XMLParserFactory.getParser().write(document, out); + } +} diff --git a/scripting/java/org/openoffice/idesupport/zip/ParcelZipper.java b/scripting/java/org/openoffice/idesupport/zip/ParcelZipper.java new file mode 100644 index 000000000000..f0bfb52ecfe6 --- /dev/null +++ b/scripting/java/org/openoffice/idesupport/zip/ParcelZipper.java @@ -0,0 +1,600 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +package org.openoffice.idesupport.zip; + +import java.io.*; +import java.util.Enumeration; +import java.util.zip.*; +import java.beans.PropertyVetoException; + +import org.openoffice.idesupport.filter.FileFilter; +import org.openoffice.idesupport.filter.BinaryOnlyFilter; +import org.openoffice.idesupport.filter.ExceptParcelFilter; + +import com.sun.star.script.framework.container.ParcelDescriptor; +import org.openoffice.idesupport.xml.Manifest; + +public class ParcelZipper +{ + public static final String PARCEL_PREFIX_DIR = "Scripts/"; + public static final String PARCEL_EXTENSION = "sxp"; + public static final String CONTENTS_DIRNAME = "Contents"; + public static final String PARCEL_DESCRIPTOR_XML = "parcel-descriptor.xml"; + + private static ParcelZipper zipper = null; + + private static final FileFilter DEFAULT_FILTER = + BinaryOnlyFilter.getInstance(); + + private ParcelZipper() { + } + + public static ParcelZipper getParcelZipper() { + if (zipper == null) { + synchronized(ParcelZipper.class) { + if (zipper == null) + zipper = new ParcelZipper(); + } + } + return zipper; + } + + public String zipParcel(File basedir) throws IOException { + File targetfile, targetdir; + + if (basedir.getName().equals(CONTENTS_DIRNAME)) + targetdir = basedir.getParentFile(); + else + targetdir = basedir; + + targetfile = new File(targetdir, targetdir.getName() + "." + PARCEL_EXTENSION); + + return zipParcel(basedir, targetfile, DEFAULT_FILTER); + } + + public String zipParcel(File basedir, File targetfile) throws IOException { + return zipParcel(basedir, targetfile, DEFAULT_FILTER); + } + + public String zipParcel(File basedir, FileFilter filter) throws IOException { + File targetfile, targetdir; + + if (basedir.getName().equals(CONTENTS_DIRNAME)) + targetdir = basedir.getParentFile(); + else + targetdir = basedir; + + targetfile = new File(targetdir, targetdir.getName() + "." + PARCEL_EXTENSION); + + return zipParcel(basedir, targetfile, filter); + } + + public String zipParcel(File basedir, File targetfile, FileFilter filter) + throws IOException { + String realpath, tmppath; + + realpath = targetfile.getPath(); + tmppath = realpath + ".tmp"; + + File tmpfile = new File(tmppath); + ZipOutputStream out = null; + try { + if (tmpfile.exists() == true) + tmpfile.delete(); + + out = new ZipOutputStream(new FileOutputStream(tmpfile)); + + File[] children = basedir.listFiles(); + for (int i = 0; i < children.length; i++) + addFileToParcel(children[i], "", out, filter); + } + catch (IOException ioe) { + out.close(); + tmpfile.delete(); + throw ioe; + } + finally { + if (out != null) + out.close(); + } + + if (targetfile.exists() == true) + targetfile.delete(); + tmpfile.renameTo(targetfile); + + return targetfile.getAbsolutePath(); + } + + private void addFileToParcel(File root, String path, ZipOutputStream out, FileFilter filter) + throws IOException { + ZipEntry ze; + + if (root.isDirectory() == true) { + ze = new ZipEntry(/* PARCEL_PREFIX_DIR + */ path + root.getName() + "/"); + out.putNextEntry(ze); + out.closeEntry(); + File[] children = root.listFiles(); + + for (int i = 0; i < children.length; i++) + addFileToParcel(children[i], path + root.getName() + "/", out, filter); + } + else { + if (filter.validate(root.getName()) == false && + root.getName().equals("parcel-descriptor.xml") == false) + return; + + ze = new ZipEntry(/* PARCEL_PREFIX_DIR + */ path + root.getName()); + out.putNextEntry(ze); + + byte[] bytes = new byte[1024]; + int len; + + FileInputStream fis = null; + try { + fis = new FileInputStream(root); + + while ((len = fis.read(bytes)) != -1) + out.write(bytes, 0, len); + } + finally { + if (fis != null) fis.close(); + } + out.closeEntry(); + } + } + + public boolean isOverwriteNeeded(File parcel, File target) + throws IOException + { + boolean result; + + if (target.isDirectory()) + result = isDirectoryOverwriteNeeded(parcel, target); + else + result = isDocumentOverwriteNeeded(parcel, target); + + return result; + } + + private boolean isDirectoryOverwriteNeeded(File parcel, File target) { + String parcelDir = getParcelDirFromParcelZip(parcel.getName()); + + File langdir; + try { + langdir = new File(target, getParcelLanguage(parcel)); + } + catch (IOException ioe) { + return false; + } + + if (langdir.exists() == false) + return false; + + File[] children = langdir.listFiles(); + + for (int i = 0; i < children.length; i++) + if (children[i].getName().equals(parcelDir)) + return true; + + return false; + } + + private boolean isDocumentOverwriteNeeded(File parcel, File document) + throws IOException + { + ZipFile documentZip = null; + boolean result = false; + + try { + documentZip = new ZipFile(document); + + String name = + PARCEL_PREFIX_DIR + getParcelLanguage(parcel) + + "/" + getParcelDirFromParcelZip(parcel.getName()) + + "/" + PARCEL_DESCRIPTOR_XML; + + if (documentZip.getEntry(name) != null) + result = true; + } + catch (IOException ioe) { + return false; + } + finally { + if (documentZip != null) documentZip.close(); + } + + return result; + } + + public String deployParcel(File parcel, File target) + throws IOException { + + String output = null; + if (target.isDirectory()) + output = unzipToDirectory(parcel, target); + else + output = unzipToZip(parcel, target); + return output; + } + + private String getParcelDirFromParcelZip(String zipname) { + String result = zipname.substring(0, zipname.lastIndexOf(".")); + return result; + } + + private String unzipToDirectory(File parcel, File targetDirectory) + throws IOException { + + ZipInputStream in = null; + File parcelDir = new File(targetDirectory, + getParcelLanguage(parcel) + File.separator + + getParcelDirFromParcelZip(parcel.getName())); + + if (isDirectoryOverwriteNeeded(parcel, targetDirectory)) { + if (deleteDir(parcelDir) == false) { + throw new IOException("Could not overwrite: " + + parcelDir.getAbsolutePath()); + } + } + + try { + in = new ZipInputStream(new FileInputStream(parcel)); + + File outFile; + ZipEntry inEntry = in.getNextEntry(); + byte[] bytes = new byte[1024]; + int len; + + while (inEntry != null) { + outFile = new File(parcelDir, inEntry.getName()); + if (inEntry.isDirectory()) { + outFile.mkdir(); + } + else { + if (outFile.getParentFile().exists() != true) + outFile.getParentFile().mkdirs(); + + FileOutputStream out = null; + try { + out = new FileOutputStream(outFile); + + while ((len = in.read(bytes)) != -1) + out.write(bytes, 0, len); + } + finally { + if (out != null) out.close(); + } + } + inEntry = in.getNextEntry(); + } + } + finally { + if (in != null) in.close(); + } + + return parcelDir.getAbsolutePath(); + } + + private boolean deleteDir(File basedir) { + if (basedir.isDirectory()) { + String[] children = basedir.list(); + for (int i=0; i<children.length; i++) { + boolean success = deleteDir(new File(basedir, children[i])); + if (!success) { + return false; + } + } + } + return basedir.delete(); + } + + private String unzipToZip(File parcel, File targetDocument) + throws IOException { + + ZipInputStream documentStream = null; + ZipInputStream parcelStream = null; + ZipOutputStream outStream = null; + Manifest manifest; + + String language = getParcelLanguage(parcel); + + if (isDocumentOverwriteNeeded(parcel, targetDocument)) { + String parcelName = language + "/" + + getParcelDirFromParcelZip(parcel.getName()); + removeParcel(targetDocument, parcelName); + } + + // first write contents of document to tmpfile + File tmpfile = new File(targetDocument.getAbsolutePath() + ".tmp"); + + manifest = addParcelToManifest(targetDocument, parcel); + + try { + documentStream = + new ZipInputStream(new FileInputStream(targetDocument)); + parcelStream = new ZipInputStream(new FileInputStream(parcel)); + outStream = new ZipOutputStream(new FileOutputStream(tmpfile)); + + copyParcelToZip(parcelStream, outStream, PARCEL_PREFIX_DIR + + language + "/" + getParcelDirFromParcelZip(parcel.getName())); + copyDocumentToZip(documentStream, outStream, manifest); + } + catch (IOException ioe) { + tmpfile.delete(); + throw ioe; + } + finally { + if (documentStream != null) documentStream.close(); + if (parcelStream != null) parcelStream.close(); + if (outStream != null) outStream.close(); + } + + if (targetDocument.delete() == false) { + tmpfile.delete(); + throw new IOException("Could not overwrite " + targetDocument); + } + else + tmpfile.renameTo(targetDocument); + + return targetDocument.getAbsolutePath(); + } + + private void copyParcelToZip(ZipInputStream in, ZipOutputStream out, + String parcelName) throws IOException { + + ZipEntry outEntry; + ZipEntry inEntry = in.getNextEntry(); + byte[] bytes = new byte[1024]; + int len; + + while (inEntry != null) { + if(parcelName!=null) + outEntry = new ZipEntry(parcelName + "/" + inEntry.getName()); + else + outEntry = new ZipEntry(inEntry); + out.putNextEntry(outEntry); + + if (inEntry.isDirectory() == false) + while ((len = in.read(bytes)) != -1) + out.write(bytes, 0, len); + + out.closeEntry(); + inEntry = in.getNextEntry(); + } + } + + private void copyDocumentToZip(ZipInputStream in, ZipOutputStream out, + Manifest manifest) throws IOException { + + ZipEntry outEntry; + ZipEntry inEntry; + byte[] bytes = new byte[1024]; + int len; + + while ((inEntry = in.getNextEntry()) != null) { + + outEntry = new ZipEntry(inEntry); + out.putNextEntry(outEntry); + + if(inEntry.getName().equals("META-INF/manifest.xml") && + manifest != null) { + InputStream manifestStream = null; + try { + manifestStream = manifest.getInputStream(); + while ((len = manifestStream.read(bytes)) != -1) + out.write(bytes, 0, len); + } + finally { + if (manifestStream != null) + manifestStream.close(); + } + } + else if (inEntry.isDirectory() == false) { + while ((len = in.read(bytes)) != -1) + out.write(bytes, 0, len); + } + + out.closeEntry(); + } + } + + public String removeParcel(File document, String parcelName) + throws IOException { + + ZipInputStream documentStream = null; + ZipOutputStream outStream = null; + Manifest manifest = null; + + if (!parcelName.startsWith(PARCEL_PREFIX_DIR)) + parcelName = PARCEL_PREFIX_DIR + parcelName; + manifest = removeParcelFromManifest(document, parcelName); + + // first write contents of document to tmpfile + File tmpfile = new File(document.getAbsolutePath() + ".tmp"); + + try { + ZipEntry outEntry; + ZipEntry inEntry; + byte[] bytes = new byte[1024]; + int len; + + documentStream = new ZipInputStream(new FileInputStream(document)); + outStream = new ZipOutputStream(new FileOutputStream(tmpfile)); + + while ((inEntry = documentStream.getNextEntry()) != null) { + + if(inEntry.getName().startsWith(parcelName)) + continue; + + outEntry = new ZipEntry(inEntry); + outStream.putNextEntry(outEntry); + + if(inEntry.getName().equals("META-INF/manifest.xml") && + manifest != null) { + InputStream manifestStream = null; + try { + manifestStream = manifest.getInputStream(); + while ((len = manifestStream.read(bytes)) != -1) + outStream.write(bytes, 0, len); + } + finally { + if (manifestStream != null) + manifestStream.close(); + } + } + else if (inEntry.isDirectory() == false) { + while ((len = documentStream.read(bytes)) != -1) + outStream.write(bytes, 0, len); + } + + outStream.closeEntry(); + } + } + catch (IOException ioe) { + tmpfile.delete(); + throw ioe; + } + finally { + if (documentStream != null) + documentStream.close(); + + if (outStream != null) + outStream.close(); + } + + if (document.delete() == false) { + tmpfile.delete(); + throw new IOException("Could not overwrite " + document); + } + else + tmpfile.renameTo(document); + + return document.getAbsolutePath(); + } + + private Manifest getManifestFromDocument(File document) { + ZipFile documentZip = null; + Manifest result = null; + + try { + documentZip = new ZipFile(document); + ZipEntry original = documentZip.getEntry("META-INF/manifest.xml"); + if (original != null) { + result = new Manifest(documentZip.getInputStream(original)); + } + } + catch (IOException ioe) { + result = null; + } + finally { + try { + if (documentZip != null) + documentZip.close(); + } + catch (IOException ioe) {} + } + + return result; + } + + private Manifest addParcelToManifest(File document, File parcel) + throws IOException { + + ZipFile parcelZip = null; + Manifest result = null; + + result = getManifestFromDocument(document); + if (result == null) + return null; + + String language = getParcelLanguage(parcel); + + try { + parcelZip = new ZipFile(parcel); + + String prefix = PARCEL_PREFIX_DIR + language + "/" + + getParcelDirFromParcelZip(parcel.getName()) + "/"; + + Enumeration entries = parcelZip.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = (ZipEntry)entries.nextElement(); + result.add(prefix + entry.getName()); + } + } + catch (IOException ioe) { + return null; + } + finally { + try { + if (parcelZip != null) + parcelZip.close(); + } + catch (IOException ioe) {} + } + + return result; + } + + private Manifest removeParcelFromManifest(File document, String name) { + Manifest result = null; + + result = getManifestFromDocument(document); + if (result == null) + return null; + + result.remove(name); + return result; + } + + public String getParcelLanguage(File file) throws IOException { + ZipFile zf = null; + ZipEntry ze = null; + InputStream is = null; + ParcelDescriptor pd; + + try { + zf = new ZipFile(file); + ze = zf.getEntry(PARCEL_DESCRIPTOR_XML); + + if (ze == null) + throw new IOException("Could not find Parcel Descriptor in parcel"); + + is = zf.getInputStream(ze); + pd = new ParcelDescriptor(is); + } + finally { + if (zf != null) + zf.close(); + + if (is != null) + is.close(); + } + + return pd.getLanguage().toLowerCase(); + } +} |