You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@openoffice.apache.org by ar...@apache.org on 2012/01/27 02:29:58 UTC
svn commit: r1236486 [33/43] - in
/incubator/ooo/devtools/netbeansintegration: ./ build/
build/public-package-jars/ javahelp/ javahelp/org/ javahelp/org/openoffice/
javahelp/org/openoffice/extensions/
javahelp/org/openoffice/extensions/docs/ javahelp/o...
Added: incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/ProjectCreator.java
URL: http://svn.apache.org/viewvc/incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/ProjectCreator.java?rev=1236486&view=auto
==============================================================================
--- incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/ProjectCreator.java (added)
+++ incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/ProjectCreator.java Fri Jan 27 01:29:33 2012
@@ -0,0 +1,784 @@
+/*************************************************************************
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ProjectCreator.java,v $
+ *
+ * $Revision: 1.33 $
+ *
+ * last change: $Author: sg $ $Date: 2009/10/22 08:00:39 $
+ *
+ * The Contents of this file are made available subject to
+ * the terms of GNU Lesser General Public License Version 2.1.
+ *
+ *
+ * GNU Lesser General Public License Version 2.1
+ * =============================================
+ * Copyright 2005 by Sun Microsystems, Inc.
+ * 901 San Antonio Road, Palo Alto, CA 94303, USA
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1, as published by the Free Software Foundation.
+ *
+ * This library 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 for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
+ * MA 02111-1307 USA
+ *
+ ************************************************************************/
+package org.openoffice.extensions.util;
+
+import org.openoffice.extensions.config.office.PlatformInfo;
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintStream;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Map;
+import java.util.Properties;
+import java.util.StringTokenizer;
+import java.util.Vector;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import javax.swing.JOptionPane;
+import org.openide.filesystems.FileLock;
+import org.openide.util.NbBundle;
+import org.openide.util.Utilities;
+import org.netbeans.spi.project.ui.templates.support.Templates;
+import org.openide.WizardDescriptor;
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.FileUtil;
+import org.openoffice.extensions.config.ConfigurationSettings;
+import org.openoffice.extensions.config.office.OpenOfficeLocation;
+import org.openoffice.extensions.projecttemplates.actions.ProjectVersion;
+import org.openoffice.extensions.projecttemplates.addon.AddOnWizardIterator;
+import org.openoffice.extensions.projecttemplates.addon.datamodel.AddOn;
+import org.openoffice.extensions.projecttemplates.calcaddin.AddinWizardIterator;
+import org.openoffice.extensions.projecttemplates.component.ComponentWizardIterator;
+import org.openoffice.extensions.util.datamodel.NbNodeObject;
+import org.openoffice.extensions.util.datamodel.PropertyContainer;
+import org.openoffice.extensions.util.datamodel.properties.UnknownOpenOfficeOrgLanguageIDException;
+import org.openoffice.extensions.util.datamodel.properties.UnknownOpenOfficeOrgPropertyException;
+import sun.tools.jar.Main;
+
+/**
+ * Create a project from wizard, e.g. an Calc AddIn
+ */
+public class ProjectCreator {
+
+ private File m_RootDir;
+ private WizardDescriptor wiz;
+
+ private FileObject m_RootFile;
+ private static final String CR = System.getProperty("line.separator"); // NOI18N
+ private static final int UNDEFINED_TYPE = 0;
+ private static final int ADDIN_TYPE = 1;
+ private static final int CREATE_INTERFACE_TYPE = 2;
+ private static final int COMPONENT_TYPE = 3;
+ private static final int ADDON_TYPE = 4;
+ private int m_ProjectType; // for just using skeletonmaker, use undefined type
+
+ // addin templates
+ private String[] addin_template_xcu;
+ private String[] function_template_xcu;
+ private String[] parameter_template_xcu;
+
+ private String[] service_template_idl;
+ private String[] interface_template_idl;
+
+ private String[] addin_schema_xcs;
+
+ /** Creates a new instance of ProjectCreator */
+ public ProjectCreator(File rootDir, WizardDescriptor wiz) {
+ this.wiz = wiz;
+ this.m_RootDir = rootDir;
+ this.m_RootFile = FileUtil.toFileObject(rootDir);
+ }
+
+/* public String createIdlFileAndMerge(NbNodeObject idlType) {
+ projectType = CREATE_INTERFACE_TYPE;
+ Class c = ComponentWizardIterator.class;
+ withoutSkeletonMaker = true;
+ String rdbName = TypeBrowser.getTempRdbFileName();
+ if (rdbName == null) return null; // 2do: concide exception handling
+ String propsFile = "Bundle.properties"; // NOI18N
+ interface_template_idl = readFileLinesInArray(c, propsFile, "InterfaceTemplate"); // NOI18N
+
+ updateWizardDescriptor();
+ if (idlType instanceof Interface) {
+ prepareWizardDataFromInterface((Interface)idlType);
+ }
+
+ FileObject[] createdIdlFiles = null;
+ try {
+ IdlFileCreator ifcr = new IdlFileCreator(wiz, ComponentWizardIterator.class,
+ rootDir.getCanonicalPath());
+ createdIdlFiles = ifcr.createAllIdlFiles(idlType);
+/* String idlNme = (String)wiz.getProperty("idlName"); // NOI18N
+ interf = FileUtil.createData(rootFile, idlNme);
+ fillFile(interf, interface_template_idl); */
+/* skeletonmaker(createdIdlFiles);
+ } catch (IOException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ return null;
+ }
+ return createdIdlFiles==null?null:createdIdlFiles[0].getPath();
+ } */
+
+ public void createComponent() {
+ m_ProjectType = COMPONENT_TYPE;
+ Class c = ComponentWizardIterator.class;
+
+ // read template files in String arrays
+ String propsFile = "Bundle.properties"; // NOI18N
+ service_template_idl = readFileLinesInArray(c, propsFile, "ServiceTemplate"); // NOI18N
+ interface_template_idl = readFileLinesInArray(c, propsFile, "InterfaceTemplate"); // NOI18N
+
+ FileObject template = Templates.getTemplate(wiz);
+ updateWizardDescriptor();
+ try {
+ unZipFile(template.getName(), template.getInputStream());
+ createProjectStructure();
+ } catch (FileNotFoundException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ } catch (IOException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ } catch (UnknownOpenOfficeOrgLanguageIDException e) {
+ LogWriter.getLogWriter().printStackTrace(e);
+ } catch (UnknownOpenOfficeOrgPropertyException e) {
+ LogWriter.getLogWriter().printStackTrace(e);
+ }
+
+ }
+
+ public void createAddon() {
+ m_ProjectType = ADDON_TYPE;
+
+ FileObject template = Templates.getTemplate(wiz);
+ updateWizardDescriptor();
+ try {
+ unZipFile(template.getName(), template.getInputStream());
+ createProjectStructure();
+ } catch (FileNotFoundException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ } catch (IOException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ } catch (UnknownOpenOfficeOrgLanguageIDException e) {
+ LogWriter.getLogWriter().printStackTrace(e);
+ } catch (UnknownOpenOfficeOrgPropertyException e) {
+ LogWriter.getLogWriter().printStackTrace(e);
+ }
+
+ }
+
+ public void createCalcAddIn() {
+ m_ProjectType = ADDIN_TYPE;
+ Class c = AddinWizardIterator.class;
+
+ // read template files in String arrays
+ String propsFile = "Bundle.properties"; // NOI18N
+ addin_template_xcu = readFileLinesInArray(c, propsFile, "AddInTemplate"); // NOI18N
+ function_template_xcu = readFileLinesInArray(c, propsFile, "FunctionTemplate"); // NOI18N
+ parameter_template_xcu = readFileLinesInArray(c, propsFile, "ParameterTemplate"); // NOI18N
+ service_template_idl = readFileLinesInArray(c, propsFile, "ServiceTemplate"); // NOI18N
+ interface_template_idl = readFileLinesInArray(c, propsFile, "InterfaceTemplate"); // NOI18N
+ addin_schema_xcs = readFileLinesInArray(c, propsFile, "AddInSchema"); // NOI18N
+
+ try {
+ FileObject template = Templates.getTemplate(wiz);
+ updateWizardDescriptor();
+ unZipFile(template.getName(), template.getInputStream());
+ createProjectStructure();
+ } catch (FileNotFoundException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ } catch (IOException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ } catch (UnknownOpenOfficeOrgLanguageIDException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ } catch (UnknownOpenOfficeOrgPropertyException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ }
+ }
+
+ private void updateWizardDescriptor() {
+ ConfigurationSettings settings = ConfigurationSettings.getSettings();
+ wiz.putProperty("PlatformBinDir", PlatformInfo.getPlatformBinDir()); // NOI18N
+ wiz.putProperty("PlatformPackageDir", PlatformInfo.getPlatformPackageDir()); // NOI18N
+ wiz.putProperty("OfficeLibrary", settings.getLibraryName()); // NOI18N
+ wiz.putProperty("OfficePath", Utilities.replaceString(settings.getValue(ConfigurationSettings.KEY_OFFICE_INSTALLATION), "\\", "/")); // NOI18N
+ wiz.putProperty("SdkPath", Utilities.replaceString(settings.getValue(ConfigurationSettings.KEY_SDK_INSTALLATION), "\\", "/")); // NOI18N
+ wiz.putProperty("TimeStamp", ConfigurationSettings.getTimeStamp()); // NOI18N
+ wiz.putProperty("UserName", settings.getUser()); // NOI18N
+ String pkg = (String)wiz.getProperty("UnoPackage"); // NOI18N
+ StringBuffer targetFileName = new StringBuffer("src"); // NOI18Nm
+ targetFileName.append(File.separatorChar);
+ targetFileName.append(pkg.replace('.', '/'));
+ wiz.putProperty("CompleteSourcePath", targetFileName.toString()); // NOI18N
+ wiz.putProperty("CentralRegistrationClass",
+ pkg.concat(".").concat("CentralRegistrationClass")); // NOI18N
+ wiz.putProperty("BuildUnoVersion", ProjectVersion.getProjectVersion()); // NOI18N
+ }
+
+ private void unZipFile(String templateName, InputStream source) throws IOException {
+ final String[] PATH_PROPERTIES = {};
+ final String[] CONTENT_PROPERTIES = {
+ "ProjectName",
+ "OfficePath",
+ "SdkPath",
+ "OfficeLibrary",
+ "PlatformBinDir",
+ "RegistrationClass",
+ "BuildUnoVersion",
+ "UnoPackage",
+ "TimeStamp",
+ "UserName",
+ "CentralRegistrationClass",
+ "StartupOptions",
+ }; // NOI18N
+
+ Class c = null;
+ switch (m_ProjectType) {
+ case ADDIN_TYPE:
+ c = AddinWizardIterator.class;
+ break;
+ case ADDON_TYPE:
+ c = AddOnWizardIterator.class;
+ break;
+ default:
+ c = ComponentWizardIterator.class;
+ }
+ Substitutions substitutions = new Substitutions(wiz, new BufferedInputStream(
+ c.getResourceAsStream(templateName.concat(".properties"))), // NOI18N
+ PATH_PROPERTIES, CONTENT_PROPERTIES);
+ try {
+ ZipInputStream str = new ZipInputStream(source);
+ ZipEntry entry;
+ while ((entry = str.getNextEntry()) != null) {
+ if (entry.isDirectory()) {
+ // in this template we don't have to change any paths
+ continue;
+ } else {
+ String name = entry.getName();
+ FileObject fo = null;
+ fo = FileUtil.createData(m_RootFile, substitutions.substitutePath(name));
+ if (fo != null) {
+ FileLock lock = fo.lock();
+ try {
+ OutputStream out = fo.getOutputStream(lock);
+ try {
+ InputStream substituted = substitutions.substituteContent(entry.getSize(),
+ str, entry.getName());
+ FileUtil.copy(substituted, out);
+ } finally {
+ out.close();
+ }
+ } finally {
+ lock.releaseLock();
+ }
+ }
+ }
+ }
+ } finally {
+ source.close();
+ }
+ }
+
+ public static String[] readFileLinesInArray(Class baseClass, String propsFile, String key) {
+ InputStream in = new BufferedInputStream(baseClass.getResourceAsStream(propsFile));
+ Properties props = new Properties();
+ try {
+ props.load(in);
+ } catch (IOException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ }
+ String s = props.getProperty(key);
+ StringTokenizer t = new StringTokenizer(s, "\n"); // NOI18N
+ Vector<String> lines = new Vector<String>();
+ while(t.hasMoreTokens()) {
+ String line = t.nextToken();
+ lines.add(line);
+ }
+ return lines.toArray(new String[lines.size()]);
+ }
+
+ private void createProjectStructure()
+ throws IOException, UnknownOpenOfficeOrgLanguageIDException,
+ UnknownOpenOfficeOrgPropertyException {
+ FileUtil.createFolder(m_RootFile, "test"); // NOI18N
+
+ String projectPath = FileUtil.toFile(m_RootFile).getCanonicalPath();
+ FileUtil.createFolder(m_RootFile, "build"); // NOI18N
+ FileUtil.createFolder(m_RootFile, "dist"); // NOI18N
+
+ String pkg = (String)wiz.getProperty("UnoPackage"); // NOI18N
+ String pkgPath = pkg.replace('.', File.separatorChar);
+
+ File packageTree = new File(
+ new StringBuffer(projectPath).append(File.separator).append("src").append(
+ File.separator).append(pkgPath).toString()); // NOI18N
+
+ packageTree.mkdirs();
+
+ wiz.putProperty("javaOutPath", packageTree.getCanonicalPath()); // NOI18N
+
+ String projectSourceDir = new StringBuffer(projectPath).append(File.separator).append("src").toString(); // NOI18N
+
+ if (this.m_ProjectType == ADDIN_TYPE) {
+ IdlFileCreator ifcr = new IdlFileCreator(wiz, AddinWizardIterator.class,
+ projectSourceDir);
+
+ FileObject[] createdIdlFiles = ifcr.createAllIdlFiles((NbNodeObject)wiz.getProperty("ServiceObject")); // NOI18N
+
+ File f = new File(projectPath.concat(File.separator).concat("src")); // NOI18N
+ FileObject sourceFo = FileUtil.toFileObject(f);
+ FileObject xcuFile = FileUtil.createData(m_RootFile, "registry/data/org/openoffice/Office/CalcAddins.xcu"); // NOI18N
+ fillFile(xcuFile, addin_template_xcu);
+ ManifestCreator mc = new ManifestCreator(m_RootFile);
+ mc.add(ManifestCreator.configuration_data_MediaType, "registry/data/org/openoffice/Office/CalcAddins.xcu"); // NOI18N
+ mc.add(ManifestCreator.uno_typelibrary_rdb_MediaType, "types.rdb"); // NOI18N
+ mc.add(ManifestCreator.uno_component_java_MediaType, new StringBuffer((String)
+ wiz.getProperty("name")).append(".jar").toString()); // NOI18N
+
+ mc.flush();
+
+ skeletonmaker(createdIdlFiles, null);
+ } else if (this.m_ProjectType == COMPONENT_TYPE) {
+
+ IdlFileCreator ifcr = new IdlFileCreator(wiz, ComponentWizardIterator.class,
+ projectSourceDir);
+
+ Hashtable types = (Hashtable)wiz.getProperty("DesignedTypes"); // NOI18N
+ Enumeration keys = types.keys();
+ Vector<FileObject> idlFiles = new Vector<FileObject>();
+ while(keys.hasMoreElements()) {
+ FileObject[] createdIdlFiles = ifcr.createAllIdlFiles((NbNodeObject)types.get(keys.nextElement()));
+ for (int i=0; i<createdIdlFiles.length; i++) {
+ idlFiles.add(createdIdlFiles[i]);
+ }
+ }
+ @SuppressWarnings(value = "unchecked") // NOI18N
+ Vector<String> v = (Vector<String>)wiz.getProperty("DumpTypes"); // NOI18N
+
+ ManifestCreator mc = new ManifestCreator(m_RootFile);
+ if (!types.isEmpty()) // with own data types, we have a types.rdb
+ mc.add(ManifestCreator.uno_typelibrary_rdb_MediaType, "types.rdb"); // NOI18N
+ mc.add(ManifestCreator.uno_component_java_MediaType, new StringBuffer((String)
+ wiz.getProperty("name")).append(".jar").toString()); // NOI18N
+ mc.flush();
+
+ skeletonmaker(idlFiles.toArray(new FileObject[idlFiles.size()]),
+ v.toArray(new String[v.size()]));
+ }
+ else if (this.m_ProjectType == ADDON_TYPE) {
+
+ wiz.putProperty("mainClassNameSmall", ((String)wiz.getProperty("mainClassName")).toLowerCase()); // NOI18N
+
+ XcuFileCreator xcucr = new XcuFileCreator(wiz, AddOnWizardIterator.class);
+// projectSourceDir);
+
+ xcucr.createXcuFile(XcuFileCreator.XCU_ADDON_TYPE);
+ xcucr.createXcuFile(XcuFileCreator.XCU_PROTOCOL_HANDLER_TYPE);
+
+ ManifestCreator mc = new ManifestCreator(m_RootFile);
+ mc.add(ManifestCreator.configuration_data_MediaType, "registry/data/org/openoffice/Office/ProtocolHandler.xcu"); // NOI18N
+ mc.add(ManifestCreator.configuration_data_MediaType, "registry/data/org/openoffice/Office/Addons.xcu"); // NOI18N
+ mc.add(ManifestCreator.uno_component_java_MediaType, new StringBuffer((String)
+ wiz.getProperty("name")).append(".jar").toString()); // NOI18N
+ mc.flush();
+
+ skeletonmaker((AddOn)wiz.getProperty("AddOn")); // NOI18N
+ }
+ }
+
+ private void fillFile(FileObject fo, String[] data)
+ throws IOException, UnknownOpenOfficeOrgLanguageIDException, UnknownOpenOfficeOrgPropertyException {
+ FileLock lock = fo.lock();
+ try {
+ OutputStream out = fo.getOutputStream(lock);
+ OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8"); // NOI18N
+ AdvancedReplace aReplace = new AdvancedReplace(
+ wiz, function_template_xcu, parameter_template_xcu);
+ try {
+ writeStringArrayInFile(outWriter, aReplace, data);
+ } finally {
+ outWriter.close();
+ }
+ } finally {
+ lock.releaseLock();
+ }
+ }
+
+ private void writeStringArrayInFile(
+ OutputStreamWriter outWriter, AdvancedReplace aReplace, String[]data)
+ throws IOException, UnknownOpenOfficeOrgLanguageIDException, UnknownOpenOfficeOrgPropertyException {
+ for (int i=0; i<data.length; i++) {
+ String[] nextData = aReplace.replaceVariables(data[i]);
+ if (nextData.length == 1) {
+ outWriter.write(nextData[0], 0, nextData[0].length());
+ outWriter.write(CR, 0, CR.length());
+ } else if (nextData.length > 0){ // just to avoid endless recursion
+ outWriter.flush();
+ writeStringArrayInFile(outWriter, aReplace, (String[])nextData);
+ }
+ }
+ outWriter.flush();
+ }
+
+ private void skeletonmaker(AddOn addon) {
+ String platform = PlatformInfo.getPlatformBinDir();
+ String sdkPath = (String)wiz.getProperty("SdkPath"); // NOI18N
+ String sdkBinPath = sdkPath.concat(File.separator).concat(platform).concat(File.separator).concat("bin"); // NOI18N
+ // np exception? should not happen this far in the code
+ if (OpenOfficeLocation.getOpenOfficeLocation().isThreeLayerOffice()) {
+ sdkBinPath = sdkPath.concat(File.separator).concat("bin"); // NOI18N
+ }
+ String soPath = "";
+ String[] typesRdbPath = null;
+ OpenOfficeLocation loc = OpenOfficeLocation.getOpenOfficeLocation();
+ if (loc != null) {
+ soPath = loc.getPathVariable();
+ if (!PlatformInfo.isWindows()) {
+ soPath = soPath.concat(File.pathSeparator).concat("/usr/bin"); // NOI18N
+ }
+ typesRdbPath = loc.getUnoTypesPath();
+ }
+ else {
+ typesRdbPath = new String[0];
+ }
+
+ // tempdir is needed for idlc
+ Map<String,String> p = new HashMap<String,String>(5);
+ p.put(ScriptExecutor.PATH, soPath);
+ p.put(ScriptExecutor.LD_LIBRARY_PATH, soPath);
+ p.put(ScriptExecutor.DYLD_LIBRARY_PATH, soPath);
+ p.put(ScriptExecutor.TEMP, System.getProperty("java.io.tmpdir"));
+ p.put(ScriptExecutor.TMP, System.getProperty("java.io.tmpdir"));
+ ScriptExecutor.setEnv(p); // NOI18N
+
+ String outFileWithPackage = ((String)wiz.getProperty("packageName")).concat(".").concat((String)wiz.getProperty("mainClassName")); // NOI18N
+
+ try {
+ String namePrefix = ((String)wiz.getProperty("Protocol")).concat(":"); // NOI18N
+ NbNodeObject[] commands = addon.getAllCommands();
+ for (int i=0; i<commands.length; i++) {
+ if (i != 0)
+ namePrefix = namePrefix.concat(","); // NOI18N
+ namePrefix = namePrefix.concat(
+ ((PropertyContainer)commands[i]).getSimpleProperty(PropertyContainer.PROPERTY_CONTAINER_NAME));
+ }
+
+ Vector<String> commandVector = new Vector<String>();
+ commandVector.add(sdkBinPath.concat(File.separator).concat("uno-skeletonmaker")); // NOI18N
+
+ if (typesRdbPath.length > 0) {
+ String typesURLList = prepareTypesURLList(typesRdbPath);
+ commandVector.add("-env:UNO_TYPES=".concat(typesURLList)); // NOI18N
+ }
+
+ commandVector.add("add-on"); // NOI18N
+ commandVector.add("--java5"); // NOI18N
+
+ commandVector.add("-o".concat(((File)wiz.getProperty("projdir")).getCanonicalPath())
+ .concat(File.separator).concat("src")); // NOI18N
+ commandVector.add("-n".concat(outFileWithPackage)); // NOI18N
+
+ commandVector.add("-p".concat(namePrefix)); // NOI18N
+
+ String[] command = commandVector.toArray(new String[commandVector.size()]);
+ StringBuffer c = new StringBuffer();
+ for (int i=0; i<command.length; i++) {
+ c.append(command[i]).append(" "); // NOI18N
+ }
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_INFO, c.toString());
+ ScriptExecutor.executeScript(command);
+ if (ScriptExecutor.hasErrors()) { // message box with errors...
+ String message = NbBundle.getMessage(ProjectCreator.class, "ERROR_CommandExecute").concat(
+ "\n").concat(ScriptExecutor.getErrors()); // NOI18N
+ JOptionPane.showMessageDialog(null, message,
+ NbBundle.getMessage(ProjectCreator.class, "LOG_Level_critical"), JOptionPane.ERROR_MESSAGE); // NOI18N
+ }
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_INFO, ScriptExecutor.getOutput());
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_CRITICAL, ScriptExecutor.getErrors());
+ } catch (IOException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ }
+ catch (UnknownOpenOfficeOrgPropertyException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ }
+ }
+
+ // TODO: show errors on output tab!
+ private boolean skeletonmaker(FileObject[] idlFileObjects, String[] dumpTypes) throws IOException {
+ boolean executeWorked = true; // return variable; set to false in case of error
+ String projDir = ((File)wiz.getProperty("projdir")).getCanonicalPath(); // NOI18N
+ String platform = PlatformInfo.getPlatformBinDir();
+ String sdkPath = (String)wiz.getProperty("SdkPath"); // NOI18N
+ String sdkBinPath = sdkPath.concat(File.separator).concat(platform).concat(File.separator).concat("bin"); // NOI18N
+ String ureBinPath = sdkBinPath;
+ // np exception? should not happen this far in the code
+ if (OpenOfficeLocation.getOpenOfficeLocation().isThreeLayerOffice()) {
+ sdkBinPath = sdkPath.concat(File.separator).concat("bin"); // NOI18N
+ ureBinPath = OpenOfficeLocation.getOpenOfficeLocation().getUreBinPath();
+ }
+
+ // adapt path for Ubuntu script execution of sdk tools
+// String soProgramPath = ((String)wiz.getProperty("OfficePath")).concat(File.separator).concat(PlatformInfo.getOfficeProgramDir()); // NOI18N
+// String soUrl = (soProgramPath.startsWith("/") ? "file://" : "file:///").concat(soProgramPath.replace('\\', '/')); // NOI18N
+ String soPath = "";
+ String[] typesRdbPath = null;
+ OpenOfficeLocation loc = OpenOfficeLocation.getOpenOfficeLocation();
+ if (loc != null) {
+ soPath = loc.getPathVariable();
+ if (!PlatformInfo.isWindows()) {
+ soPath = soPath.concat(File.pathSeparator).concat("/usr/bin"); // NOI18N
+ }
+ typesRdbPath = loc.getUnoTypesPath();
+ }
+ else {
+ typesRdbPath = new String[0];
+ }
+
+
+ // tempdir is needed for idlc
+ Map<String,String> p = new HashMap<String,String>(5);
+ p.put(ScriptExecutor.PATH, soPath);
+ p.put(ScriptExecutor.LD_LIBRARY_PATH, soPath);
+ p.put(ScriptExecutor.DYLD_LIBRARY_PATH, soPath);
+ p.put(ScriptExecutor.TEMP, System.getProperty("java.io.tmpdir"));
+ p.put(ScriptExecutor.TMP, System.getProperty("java.io.tmpdir"));
+ ScriptExecutor.setEnv(p); // NOI18N
+
+ // don't do all this if no own idls are defined.
+ String rdbPath = null;
+ if (idlFileObjects.length != 0) {
+ // idlc
+ String srcIdlPath = projDir.concat(File.separator).concat("src"); // NOI18N
+ String sdkIdlIncludes = sdkPath.concat(File.separator).concat("idl").concat(";").concat(srcIdlPath); // NOI18N
+
+ String urdOutPath = projDir.concat(File.separator).concat("build").concat(File.separator)
+ .concat("idl").concat(File.separator).concat("urd"); // NOI18N
+
+ String[] command = new String[3 + idlFileObjects.length];
+ command[0] = sdkBinPath.concat(File.separator).concat("idlc"); // NOI18N
+ command[1] = "-I".concat(sdkIdlIncludes); // NOI18N
+ command[2] = "-O".concat(urdOutPath); // NOI18N
+ for (int i=0; i<idlFileObjects.length; i++) {
+ command[3+i] = FileUtil.toFile(idlFileObjects[i]).getCanonicalPath();
+ }
+
+ ScriptExecutor.executeScript(command, (File)wiz.getProperty("projdir")); // NOI18N
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_INFO, ScriptExecutor.getOutput());
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_CRITICAL, ScriptExecutor.getErrors());
+
+ // regmerge
+ File f = new File(projDir.concat(File.separator).concat("build").concat(File.separator)
+ .concat("idl").concat(File.separator).concat("rdb")); // NOI18N
+ f.mkdirs();
+ rdbPath = projDir.concat(File.separator).concat("build").concat(File.separator)
+ .concat("idl").concat(File.separator).concat("rdb").concat(File.separator).concat("types.rdb"); // NOI18N
+
+ command = new String[3 + idlFileObjects.length];
+ command[0] = ureBinPath.concat(File.separator).concat("regmerge"); // NOI18N
+ command[1] = rdbPath;
+ command[2] = "/UCR"; // NOI18N
+ for (int i=0; i<idlFileObjects.length; i++) {
+ command[3+i] = urdOutPath.concat(File.separator)
+ .concat(FileUtil.toFile(idlFileObjects[i]).getName().replaceAll("\\.idl", ".urd")); // NOI18N
+ }
+
+ ScriptExecutor.executeScript(command);
+ if (ScriptExecutor.hasErrors()) { // message box with errors...
+ String message = NbBundle.getMessage(ProjectCreator.class, "ERROR_CommandExecute").concat(
+ "\n").concat(ScriptExecutor.getErrors()); // NOI18N
+ JOptionPane.showMessageDialog(null, message,
+ NbBundle.getMessage(ProjectCreator.class, "LOG_Level_critical"), JOptionPane.ERROR_MESSAGE); // NOI18N
+ executeWorked = false;
+ }
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_INFO, ScriptExecutor.getOutput());
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_CRITICAL, ScriptExecutor.getErrors());
+
+ // new part for initially creating a IDL_types.rdb
+ // javamaker
+ f = new File(projDir.concat(File.separator).concat("build").concat(File.separator)
+ .concat("classes")); // NOI18N
+ String classesOutPath = f.getCanonicalPath();
+ f.mkdirs();
+ command = new String[5 + typesRdbPath.length];
+ command[0] = sdkBinPath.concat(File.separator).concat("javamaker"); // NOI18N
+ command[1] = "-BUCR"; // NOI18N
+ command[2] = "-O";
+ command[3] = classesOutPath;
+ command[4] = rdbPath;
+ for (int i = 0; i < typesRdbPath.length; i++) {
+ command[5 + i] = "-X".concat(typesRdbPath[i]);
+ }
+
+ ScriptExecutor.executeScript(command);
+ if (ScriptExecutor.hasErrors()) { // message box with errors...
+ String message = NbBundle.getMessage(ProjectCreator.class, "ERROR_CommandExecute").concat(
+ "\n").concat(ScriptExecutor.getErrors()); // NOI18N
+ JOptionPane.showMessageDialog(null, message,
+ NbBundle.getMessage(ProjectCreator.class, "LOG_Level_critical"), JOptionPane.ERROR_MESSAGE); // NOI18N
+ executeWorked = false;
+ }
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_INFO, ScriptExecutor.getOutput());
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_CRITICAL, ScriptExecutor.getErrors());
+
+ // make a jar
+ PrintStream outStream = new PrintStream(LogWriter.getLogWriter().getLogStream(LogWriter.LEVEL_INFO));
+ PrintStream errStream = new PrintStream(LogWriter.getLogWriter().getLogStream(LogWriter.LEVEL_CRITICAL));
+ Main jartool = new Main(outStream, errStream, "jar");
+
+ f = new File(projDir.concat(File.separator).concat("dist"));
+ f.mkdirs();
+ command = new String[2 + 3 * idlFileObjects.length];
+ final String IDL_JAR_NAME = (String)ProjectTypeHelper.getObjectFromUnoProperties(
+ m_RootFile, "idl_types.jar"); // NOI18N
+ String jarFile = f.getCanonicalPath().concat(File.separator).concat(IDL_JAR_NAME);
+ f = new File(jarFile);
+ if (f.exists()) {
+ command[0] = "uf";
+ }
+ else {
+ command[0] = "cf";
+ }
+ command[1] = jarFile;
+ for (int i = 0; i < idlFileObjects.length; i++) {
+ // remove first part of path to build correct directory structure in jar file
+ String fileName = FileUtil.toFile(idlFileObjects[i]).getCanonicalPath().replace(srcIdlPath, "");
+ command[2 + i * 3] = "-C";
+ command[3 + i * 3] = classesOutPath; // build/classes
+ command[4 + i * 3] = fileName.substring(1).replace(".idl", ".class"); // remove preceding "/"
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_INFO, "File: " + command[4 + i * 3]);
+ }
+
+ jartool.run(command);
+ }
+
+ // skeletonmaker
+ String outFileWithPackage = ((String)wiz.getProperty("packageName")).concat(".").concat((String)wiz.getProperty("mainClassName")); // NOI18N
+
+ Vector<String> commandVector = new Vector<String>();
+ commandVector.add(sdkBinPath.concat(File.separator).concat("uno-skeletonmaker")); // NOI18N
+
+ if (typesRdbPath.length > 0) {
+ String typesURLList = prepareTypesURLList(typesRdbPath);
+ commandVector.add("-env:UNO_TYPES=".concat(typesURLList)); // NOI18N
+ }
+
+ commandVector.add(this.m_ProjectType==ADDIN_TYPE?"calc-add-in":"component"); // NOI18N
+
+ commandVector.add("--java5"); // NOI18N
+ if (idlFileObjects.length!=0)
+ commandVector.add("-l".concat(PathExchanger.pathToOfficeFileUrl(rdbPath))); // NOI18N
+
+ // this is different for components
+ if (this.m_ProjectType==ADDIN_TYPE) {
+ commandVector.add("-t".concat(outFileWithPackage)); // NOI18N
+ }
+ else {
+ // add all the types.
+ for (int i=0; i<dumpTypes.length; i++) {
+ commandVector.add("-t".concat(dumpTypes[i])); // NOI18N
+ }
+ }
+ commandVector.add("-o".concat(projDir)
+ .concat(File.separator).concat("src")); // NOI18N
+ if (this.m_ProjectType==ADDIN_TYPE) {
+ commandVector.add("-n".concat(outFileWithPackage).concat("Impl")); // NOI18N
+ }
+ else {
+ commandVector.add("-n".concat(outFileWithPackage)); // NOI18N
+ }
+
+ String[] command = commandVector.toArray(new String[commandVector.size()]);
+ StringBuffer c = new StringBuffer();
+ for (int i=0; i<command.length; i++) {
+ c.append(command[i]).append(" "); // NOI18N
+ }
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_INFO, c.toString());
+ ScriptExecutor.executeScript(command);
+ if (ScriptExecutor.hasErrors()) { // message box with errors...
+ String message = NbBundle.getMessage(ProjectCreator.class, "ERROR_CommandExecute").concat(
+ "\n").concat(ScriptExecutor.getErrors()); // NOI18N
+ JOptionPane.showMessageDialog(null, message,
+ NbBundle.getMessage(ProjectCreator.class, "LOG_Level_critical"), JOptionPane.ERROR_MESSAGE); // NOI18N
+ executeWorked = false;
+ }
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_INFO, ScriptExecutor.getOutput());
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_CRITICAL, ScriptExecutor.getErrors());
+ return executeWorked;
+ }
+
+ /**
+ * Call this for creating an implementation object for one or more new idl file(s)
+ * @param files the idl files for creating the implementation object
+ */
+ public boolean skeletonmaker(FileObject[] files) throws IOException {
+ updateWizardDescriptor();
+ String[] localIdlFiles = new String[files.length];
+ FileObject sourceFO = m_RootFile.getFileObject("src"); // NOI18N
+ for (int i = 0; i < files.length; i++) {
+ int startPos = FileUtil.toFile(sourceFO).getCanonicalPath().length();
+ String name = FileUtil.toFile(files[i]).getCanonicalPath().substring(startPos + 1);
+ name = name.substring(0, name.lastIndexOf('.'));
+ localIdlFiles[i] = name.replace(File.separatorChar, '.');
+ }
+ return skeletonmaker(files, localIdlFiles);
+ }
+
+ /**
+ * Call this for creating an implementation object for one or more new idl file(s)
+ * from OpenOffice.org
+ * @param idlNames the idl files for creating the implementation object
+ */
+ public boolean skeletonmaker(String[] idlNames) throws IOException {
+ updateWizardDescriptor();
+ Vector<FileObject> localIdlFiles = new Vector<FileObject>();
+ FileObject sourceFO = m_RootFile.getFileObject("src");
+ for (int i = 0; i < idlNames.length; i++) {
+ String name = idlNames[i].replace('.', '/').concat(".idl"); // NOI18N
+ FileObject idlCandidate = sourceFO.getFileObject(name);
+ if (idlCandidate != null && !idlCandidate.isVirtual()) {
+ localIdlFiles.add(idlCandidate); // file exists in local path
+ }
+ }
+ return skeletonmaker(localIdlFiles.toArray(new FileObject[localIdlFiles.size()]), idlNames);
+ }
+
+ private String prepareTypesURLList(String[] typesRdbPath) {
+ String[] typeUrl = new String[typesRdbPath.length];
+ String typesURLList = "";
+ // make URL from path to types rdb
+ for (int i = 0; i < typesRdbPath.length; i++) {
+ String types = typesRdbPath[i].replace(" ", "%20"); // NOI18N
+ types = (types.startsWith("/")?"file://":"file:///").concat(types); // NOI18N
+ typeUrl[i] = types.replace("\\", "/"); // NOI18N
+ if(i > 0) {
+ typesURLList = typesURLList.concat(" ");
+ }
+ typesURLList = typesURLList.concat(typeUrl[i]);
+ }
+ return typesURLList;
+ }
+
+ // debug purpose
+ private String printCommand(String[] command) {
+ String c = ""; // NOI18N
+ for (int i=0; i<command.length; i++)
+ c = c.concat(command[i]).concat(" "); // NOI18N
+ return c;
+ }
+}
Added: incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/ProjectTypeHelper.java
URL: http://svn.apache.org/viewvc/incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/ProjectTypeHelper.java?rev=1236486&view=auto
==============================================================================
--- incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/ProjectTypeHelper.java (added)
+++ incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/ProjectTypeHelper.java Fri Jan 27 01:29:33 2012
@@ -0,0 +1,149 @@
+/*************************************************************************
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ProjectTypeHelper.java,v $
+ *
+ * $Revision: 1.12 $
+ *
+ * last change: $Author: sg $ $Date: 2008/10/07 08:59:58 $
+ *
+ * The Contents of this file are made available subject to
+ * the terms of GNU Lesser General Public License Version 2.1.
+ *
+ *
+ * GNU Lesser General Public License Version 2.1
+ * =============================================
+ * Copyright 2005 by Sun Microsystems, Inc.
+ * 901 San Antonio Road, Palo Alto, CA 94303, USA
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1, as published by the Free Software Foundation.
+ *
+ * This library 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 for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
+ * MA 02111-1307 USA
+ *
+ ************************************************************************/
+
+package org.openoffice.extensions.util;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+import java.util.PropertyResourceBundle;
+import org.netbeans.api.project.Project;
+import org.openide.filesystems.FileObject;
+
+/**
+ *
+ * @author js93811
+ */
+public class ProjectTypeHelper {
+
+ public static boolean isExtensionProject(Project p) {
+ if (p != null) {
+ FileObject f = p.getProjectDirectory();
+ return isExtensionProject(f);
+ }
+ return false;
+ }
+
+ public static boolean isExtensionProject(FileObject projDir) {
+ boolean bExtensionProject = false;
+ Object o = getObjectFromUnoProperties(projDir, "uno.project.type"); // NOI18N
+ // some resource is not there: not an extension project, then
+ if (o != null) {
+ String projectType = o.toString();
+ // i've classified the project fine grained to be flexible
+ if (projectType.equals("office.calc.addin.project")) { // NOI18N
+ bExtensionProject = true;
+ }
+ else if (projectType.equals("office.addon.project")) { // NOI18N
+ bExtensionProject = true;
+ }
+ else if (projectType.equals("office.component.project")) { // NOI18N
+ bExtensionProject = true;
+ }
+ }
+ return bExtensionProject;
+ }
+
+ public static Object getObjectFromUnoProperties(FileObject projectDir, String propName) {
+ PropertyResourceBundle unoProjectProps = getProperties(projectDir);
+ if (unoProjectProps == null) return null;
+ return unoProjectProps.handleGetObject(propName);
+ }
+
+ public static Object getObjectFromUnoProperties(Project proj, String propName) {
+ if (proj == null) return null;
+ FileObject projectDir = proj.getProjectDirectory();
+ return getObjectFromUnoProperties(projectDir, propName);
+ }
+
+ public static Properties getUnoProperties(FileObject projectRoot) {
+ Properties props = new Properties();
+ if (projectRoot != null) {
+ FileObject f = projectRoot.getFileObject("nbproject"); // NOI18N
+ if (f != null) {
+ f = f.getFileObject("project-uno", "properties"); // NOI18N
+ if (f != null) {
+ InputStream inStream = null;
+ try {
+ inStream = f.getInputStream();
+ props.load(inStream);
+ } catch (FileNotFoundException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ } catch (IOException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ } finally {
+ try {
+ if (inStream != null)
+ inStream.close();
+ } catch (IOException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ }
+ }
+ }
+ }
+ }
+ return props;
+ }
+
+ private static PropertyResourceBundle getProperties(FileObject projectRoot) {
+ PropertyResourceBundle unoProjectProps = null;
+ if (projectRoot != null) {
+ FileObject f = projectRoot.getFileObject("nbproject"); // NOI18N
+ if (f != null) {
+ f = f.getFileObject("project-uno", "properties"); // NOI18N
+ if (f != null && f.isValid()) {
+ InputStream inStream = null;
+ try {
+ inStream = f.getInputStream();
+ unoProjectProps = new PropertyResourceBundle(inStream);
+ } catch (FileNotFoundException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ } catch (IOException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ } finally {
+ try {
+ if (inStream != null)
+ inStream.close();
+ } catch (IOException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ }
+ }
+ }
+ }
+ }
+ return unoProjectProps;
+ }
+}
Added: incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/ScriptExecutor.java
URL: http://svn.apache.org/viewvc/incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/ScriptExecutor.java?rev=1236486&view=auto
==============================================================================
--- incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/ScriptExecutor.java (added)
+++ incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/ScriptExecutor.java Fri Jan 27 01:29:33 2012
@@ -0,0 +1,256 @@
+/*************************************************************************
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptExecutor.java,v $
+ *
+ * $Revision: 1.7 $
+ *
+ * last change: $Author: sg $ $Date: 2009/01/08 11:41:04 $
+ *
+ * The Contents of this file are made available subject to
+ * the terms of GNU Lesser General Public License Version 2.1.
+ *
+ *
+ * GNU Lesser General Public License Version 2.1
+ * =============================================
+ * Copyright 2005 by Sun Microsystems, Inc.
+ * 901 San Antonio Road, Palo Alto, CA 94303, USA
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1, as published by the Free Software Foundation.
+ *
+ * This library 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 for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
+ * MA 02111-1307 USA
+ *
+ ************************************************************************/
+
+package org.openoffice.extensions.util;
+
+import java.io.File;
+import java.io.InputStream;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import org.openoffice.extensions.config.office.PlatformInfo;
+
+/**
+ *
+ */
+public class ScriptExecutor {
+ public static final String PATH = "PATH";
+ public static final String LD_LIBRARY_PATH = "LD_LIBRARY_PATH";
+ public static final String DYLD_LIBRARY_PATH = "DYLD_LIBRARY_PATH";
+ public static final String TEMP = "TEMP";
+ public static final String TMP = "TMP";
+
+ static Map<String,String> envVars;
+ static String[] script;
+ static File workDir;
+ static String errorMsg;
+ private static String outMsg;
+ static int exitVal;
+
+
+ /**
+ * set the environment variables
+ */
+ public static void setEnv(Map<String,String> _envVars) {
+ envVars = correctEnvVarForWindwos(_envVars);
+ }
+
+ /**
+ * correct env variables on Windows: especially on Windows xp, PATH
+ * variable has to be set as "Path"
+ */
+ private static Map<String,String> correctEnvVarForWindwos(Map<String,String> _envVars) {
+ // fix Win XP bug: canntot set path as "PATH"
+ if (_envVars != null && PlatformInfo.isWindows()) {
+ String value = _envVars.remove(PATH);
+ if (value != null) {
+ _envVars.put("Path", value);
+ }
+ }
+ return _envVars;
+ }
+
+ private static void updateExistingEnvironment(Map<String,String> environment) {
+ if (envVars != null && environment != null) {
+ Set<String> keys = envVars.keySet();
+ for (Iterator<String> it = keys.iterator(); it.hasNext();) {
+ String key = it.next();
+ if (environment.containsKey(key)) {
+ if (key.equalsIgnoreCase(PATH) ||
+ key.equalsIgnoreCase(LD_LIBRARY_PATH)||
+ key.equalsIgnoreCase(DYLD_LIBRARY_PATH)) {
+ // append on all paths
+ String val = environment.get(key);
+ val = val.concat(File.pathSeparator).concat(envVars.get(key));
+ environment.put(key, val);
+ }
+ // keep all tem/zmp variables as they are.
+ }
+ else {
+ environment.put(key, envVars.get(key));
+ }
+ // for testing, log the stuff
+ // LogWriter.getLogWriter().log(LogWriter.LEVEL_INFO, key.concat("=").concat(environment.get(key)));
+ }
+ }
+ }
+
+ /**
+ * Look, if the momentarily executed program has already finished.
+ * @param p The momentarily running process.
+ * @return The exit value of the program.
+ */
+ private static int isRunning(Process p) {
+ int ret = -305;
+ try {
+ ret = p.exitValue();
+ }
+ catch (java.lang.Exception e) {
+ // empty by default: exception is thrown when p is still alive
+ }
+ return ret;
+ }
+
+
+ /**
+ * Execute a program and wait for the result.
+ * @param script The program including parameters.
+ * @param envVars The environment variables for the program.
+ * @param workDir The working directory of the command.
+ * @return The exit value of the program.
+ */
+ public static int executeScript(String[] script, Map<String,String> _envVars, File workDir ) {
+ StringBuffer buf = new StringBuffer();
+ for (int i=0; i<script.length; i++) {
+ buf.append(script[i]).append(" "); // NOI18N
+ }
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_INFO, buf.toString());
+ if (_envVars != null) {
+ envVars = correctEnvVarForWindwos(_envVars);
+ }
+ errorMsg = ""; // NOI18N
+ outMsg = ""; // NOI18N
+ exitVal = -305;
+ int available;
+ byte[] in = null;
+ byte[] err = null;
+ String sIn = ""; // NOI18N
+ String sErr = ""; // NOI18N
+ try {
+ ProcessBuilder pb = new ProcessBuilder(script);
+ pb = pb.directory(workDir);
+ updateExistingEnvironment(pb.environment());
+
+ Process tool = pb.start();
+// Process tool = Runtime.getRuntime().exec(script, envVars, workDir);
+ InputStream aIn = tool.getInputStream();
+ InputStream aErr = tool.getErrorStream();
+
+ while(exitVal == -305) {
+ exitVal = isRunning(tool);
+ // input stream
+ available = aIn.available();
+ if (available > 0) {
+ in = new byte[available];
+ aIn.read(in, 0, available);
+ outMsg += new String(in);
+ }
+ // error stream
+ available = aErr.available();
+ if (available > 0) {
+ err = new byte[available];
+ aErr.read(err, 0, available);
+ errorMsg += new String(err);
+ }
+ Thread.sleep(500);
+ }
+ } catch (IOException ioe) {
+ LogWriter.getLogWriter().printStackTrace(ioe);
+ }
+ catch (InterruptedException e) {
+ LogWriter.getLogWriter().printStackTrace(e);
+ }
+ return exitVal;
+ }
+
+ /**
+ * Execute a program and wait for the result.
+ * @param script The program including parameters.
+ * @param envVars The environment variables for the program.
+ * @param workDir The working directory of the command.
+ * @return The exit value of the program.
+ */
+ public static int executeScript(String[] script, Map<String,String> envVars) {
+ if (workDir == null) {
+ return executeScript(script, envVars,
+ new File(System.getProperty("user.dir"))); // NOI18N
+ }
+ return executeScript(script, envVars, workDir);
+ }
+
+ /**
+ * Execute a program and wait for the result. Use the
+ * initial set environment variables from this class.
+ * @param script The program including parameters.
+ * @return True, if the program executed correctly.
+ */
+ public static int executeScript(String[] script) {
+ return executeScript(script, envVars);
+ }
+
+ /**
+ * Execute a program and wait for the result. Use the
+ * initial set environment variables from this class.
+ * @param script The program including parameters.
+ * @return True, if the program executed correctly.
+ */
+ public static int executeScript(String[] script, File workDir) {
+ return executeScript(script, envVars, workDir);
+ }
+
+ /**
+ * Get the error messages of the last executed script.
+ * @return The message
+ */
+ public static String getErrors() {
+ return errorMsg;
+ }
+
+ /**
+ * Get the error messages of the last executed script.
+ * @return The message
+ */
+ public static boolean hasErrors() {
+ return errorMsg != null && errorMsg.length() > 0;
+ }
+
+ /**
+ * Get the output of the last executed script.
+ * @return The message
+ */
+ public static String getOutput() {
+ return outMsg;
+ }
+
+ /**
+ * Get the error messages of the last executed script.
+ * @return The message
+ */
+ public static boolean hasOutput() {
+ return outMsg != null && outMsg.length() > 0;
+ }
+
+}
\ No newline at end of file
Added: incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/Substitutions.java
URL: http://svn.apache.org/viewvc/incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/Substitutions.java?rev=1236486&view=auto
==============================================================================
--- incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/Substitutions.java (added)
+++ incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/Substitutions.java Fri Jan 27 01:29:33 2012
@@ -0,0 +1,148 @@
+/*************************************************************************
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: Substitutions.java,v $
+ *
+ * $Revision: 1.7 $
+ *
+ * last change: $Author: sg $ $Date: 2008/10/07 08:59:58 $
+ *
+ * The Contents of this file are made available subject to
+ * the terms of GNU Lesser General Public License Version 2.1.
+ *
+ *
+ * GNU Lesser General Public License Version 2.1
+ * =============================================
+ * Copyright 2005 by Sun Microsystems, Inc.
+ * 901 San Antonio Road, Palo Alto, CA 94303, USA
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1, as published by the Free Software Foundation.
+ *
+ * This library 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 for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
+ * MA 02111-1307 USA
+ *
+ ************************************************************************/
+
+package org.openoffice.extensions.util;
+
+import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.util.Iterator;
+import java.util.Properties;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.netbeans.spi.project.ui.templates.support.Templates;
+import org.openide.WizardDescriptor;
+import org.openide.filesystems.FileUtil;
+import org.openide.util.Utilities;
+
+/**
+ * Replaces strings in content being unzipped to customize the project name to
+ * match what the user entered in the wizard.
+ *
+ */
+public class Substitutions {
+ private Properties props;
+ private String[] pathProperties;
+ private String[] contentProperties;
+ private WizardDescriptor wiz;
+
+
+ /** Creates a new instance of Substitutions */
+ public Substitutions(WizardDescriptor wiz, InputStream propertyStream, String[] pathProperties, String[] contentProperties) throws IOException {
+ if (propertyStream == null) {
+ throw new IOException ("Could not find properties file"); // NOI18N
+ }
+ props = new Properties();
+ props.load(propertyStream);
+
+ this.wiz = wiz;
+ this.pathProperties = pathProperties;
+ this.contentProperties = contentProperties;
+ }
+
+ private Substitutions (InputStream stream, WizardDescriptor wiz, String[] pathProperties, String[] contentProperties) throws IOException {
+ if (stream == null) {
+ throw new IOException ("Could not find properties file"); // NOI18N
+ }
+ props = new Properties();
+ props.load(stream);
+
+ this.wiz = wiz;
+ this.pathProperties = pathProperties;
+ this.contentProperties = contentProperties;
+ }
+
+
+ public String substitutePath (String filepath) {
+ String result = null;
+ if (filepath.indexOf("CentralRegistrationClass.java") != -1) { // NOI18N
+ result = ((String)wiz.getProperty(
+ "CompleteSourcePath")).concat(
+ "/CentralRegistrationClass.java"); // NOI18N
+ }
+ else {
+ result = props.getProperty(filepath);
+ if (result != null) {
+ for (int i=0; i < pathProperties.length; i++) {
+ String propertyVariable = "%" + pathProperties[i] + "%"; // NOI18N
+ result = result.replaceAll(propertyVariable, (String) wiz.getProperty(pathProperties[i]));
+ }
+ }
+ }
+ return result == null ? filepath : result;
+ }
+
+ public InputStream substituteContent (long originalSize, InputStream input, String filename) throws IOException {
+ if (filename.endsWith (".gif") || filename.endsWith (".png") || filename.endsWith(".jar")) { // NOI18N
+ return input;
+ }
+ if (originalSize > Integer.MAX_VALUE || originalSize < 0) {
+ throw new IllegalArgumentException ("File too large: " + // NOI18N
+ originalSize);
+ }
+ ByteArrayOutputStream temp = new ByteArrayOutputStream ((int) originalSize);
+ FileUtil.copy (input, temp);
+ byte[] b = temp.toByteArray();
+
+ //XXX do we want default charset, or UTF-8 - UTF-8 I think...
+ CharBuffer cb = Charset.defaultCharset().decode(ByteBuffer.wrap(b));
+ String data = cb.toString();
+
+ for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
+ String key = (String) iter.next();
+ String val = props.getProperty(key);
+
+ for (int i=0; i < contentProperties.length; i++) {
+ String propertyVariable = "%" + contentProperties[i] + "%"; // NOI18N
+ String replacement = (String) wiz.getProperty(contentProperties[i]);
+ if (replacement == null) replacement = ""; // NOI18N
+ val = val.replaceAll(propertyVariable, replacement);
+ }
+
+ Matcher m = Pattern.compile(key).matcher(data);
+ data = m.replaceAll(val);
+ }
+
+ return new ByteArrayInputStream (data.getBytes());
+ }
+}
+
Added: incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/UnoIdlSyntax.java
URL: http://svn.apache.org/viewvc/incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/UnoIdlSyntax.java?rev=1236486&view=auto
==============================================================================
--- incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/UnoIdlSyntax.java (added)
+++ incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/UnoIdlSyntax.java Fri Jan 27 01:29:33 2012
@@ -0,0 +1,400 @@
+/*************************************************************************
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: UnoIdlSyntax.java,v $
+ *
+ * $Revision: 1.1 $
+ *
+ * last change: $Author: sg $ $Date: 2009/07/06 14:51:26 $
+ *
+ * The Contents of this file are made available subject to
+ * the terms of GNU Lesser General Public License Version 2.1.
+ *
+ *
+ * GNU Lesser General Public License Version 2.1
+ * =============================================
+ * Copyright 2005 by Sun Microsystems, Inc.
+ * 901 San Antonio Road, Palo Alto, CA 94303, USA
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1, as published by the Free Software Foundation.
+ *
+ * This library 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 for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
+ * MA 02111-1307 USA
+ *
+ ************************************************************************/
+
+package org.openoffice.extensions.util;
+
+/**
+ *
+ */
+public class UnoIdlSyntax {
+ public enum TokenID {
+ TEXT, STRING, NUMBER, COMMENT, KEYWORD, PRECOMPILE, BRACKET, CHAR, FUNCTION
+ }
+
+ private static final int INIT = 0;
+ private static final int ISI_BLOCK_COMMENT = 1;
+ private static final int ISI_COMMENT_START = 2;
+ private static final int ISI_STAR_IN_BLOCK_COMMENT = 3;
+ private static final int ISI_LINE_COMMENT = 4;
+ private static final int ISI_TEXT = 5;
+ private static final int ISI_WHITESPACE = 6;
+ private static final int ISI_KEYWORD = 7;
+ private static final int ISI_PRECOMPILER = 8;
+ private static final int ISI_OPENING_BRACKET = 9;
+ private static final int ISI_TEXT_IN_BRACKETS = 10;
+ private static final int ISI_DOUBLE_QUOTE = 11;
+ private static final int ISI_SINGLE_QUOTE = 12;
+ private static final int ISI_BACKSLASH_IN_DOUBLE_QUOTE = 13;
+ private static final int ISI_BACKSLASH_IN_SINGLE_QUOTE = 14;
+ private static final int ISI_NUMBER = 15;
+ private static final int ISI_FUNCTION = 16;
+
+ /** all recognized keywords **/
+ private static final String[] KEYWORDS = {
+ // idl file types
+ "constants", "enum", "exception", "interface", "service", "struct",
+ "singleton",
+ // data types
+ "any", "boolean", "byte", "char", "double", "float", "hyper", "long",
+ "sequence", "short", "string", "type", "void",
+ // modifiers
+ "const", "published", "unsigned",
+ // namespace
+ "module",
+ // exceptions
+ "raises",
+ }; // NOI18N
+
+ private char[] buffer;
+ private int state;
+ private int offset;
+ private int stopOffset;
+ private int startOffset;
+ private int tokenLength;
+ private String token; // only for debugging
+
+ public UnoIdlSyntax(char[] theBuffer) {
+ this.buffer = theBuffer;
+ // initialize local variables with meaningful values
+ this.state = INIT;
+ this.offset = 0;
+ this.stopOffset = buffer.length - 1;
+ this.startOffset = offset;
+ }
+
+ public TokenID parseNextToken() {
+ return doParseToken();
+ }
+
+ public int getOffset() {
+ return offset;
+ }
+
+ public int getTokenLength() {
+ return tokenLength;
+ }
+
+ @Override
+ public String toString() {
+ return token;
+ }
+
+ protected TokenID parseToken() {
+ TokenID result = doParseToken();
+// LogWriter.getLogWriter().log(LogWriter.LEVEL_INFO, "parseToken: " + result); // NOI18N
+ return result;
+ }
+
+ private TokenID doParseToken() {
+ char actChar;
+ startOffset = offset;
+ // get the state with a lookahead function
+ int[] offsetAndState = getNextState(buffer, offset, stopOffset, state);
+ // set the token for debugging purposes
+ token = new String(buffer, offset, offsetAndState[0]);
+ // add the count of chars used for determining the lookahead
+ // to the offset
+ offset += offsetAndState[0];
+ // set the state
+ state = offsetAndState[1];
+ // go to the end of the state and return a token.
+ while (offset < stopOffset) {
+ actChar = buffer[offset];
+ switch(state) {
+ case ISI_LINE_COMMENT:
+ switch (actChar) {
+ case '\n': // NOI18N
+ offset++;
+ return TokenID.COMMENT;
+ }
+ break;
+ case ISI_BLOCK_COMMENT:
+ switch (actChar) {
+ case '*': // NOI18N
+ state = ISI_STAR_IN_BLOCK_COMMENT;
+ break;
+ }
+ break;
+ case ISI_STAR_IN_BLOCK_COMMENT:
+ switch (actChar) {
+ case '/': // NOI18N
+ offset++;
+ return TokenID.COMMENT;
+ case '*': // NOI18N
+ // state stays the same; just here to show it
+ break;
+ default:
+ state = ISI_BLOCK_COMMENT;
+ }
+ break;
+ case ISI_PRECOMPILER: //have read this already
+ offset++;
+ return TokenID.PRECOMPILE;
+ case ISI_KEYWORD:
+ // offset++ is not necessary; we're one further because the length
+ // of the keyword is added to offset.
+ return TokenID.KEYWORD;
+ case ISI_TEXT:
+ int[] nextStuff = getNextState(buffer, offset, stopOffset, state);
+ int newState = nextStuff[1]; // not really interested in offset
+ // switch between text and whitespace: only in whitespace mode
+ // are numbers allowed; this way they always start with a whitespace
+ if (newState == ISI_WHITESPACE) {
+ state = ISI_WHITESPACE;
+ }
+ else if (newState != ISI_TEXT) {
+ return TokenID.TEXT;
+ }
+ break;
+ case ISI_WHITESPACE:
+ nextStuff = getNextState(buffer, offset, stopOffset, state);
+ newState = nextStuff[1]; // not really interested in offset
+ if (newState == ISI_TEXT) {
+ state = ISI_TEXT;
+ }
+ else if (newState != ISI_WHITESPACE) {
+ return TokenID.TEXT;
+ }
+ break;
+ case ISI_OPENING_BRACKET:
+ offset++;
+ state = ISI_TEXT_IN_BRACKETS;
+ return TokenID.TEXT;
+ case ISI_TEXT_IN_BRACKETS:
+ switch (actChar) {
+ case ']': // NOI18N // closing bracket found
+ state = ISI_TEXT;
+ // no offset++ because ']' is not part of the token, it's only
+ // the text inside
+ return TokenID.BRACKET;
+ // default: state stays the same...
+ }
+ break;
+ case ISI_DOUBLE_QUOTE:
+ switch (actChar) {
+ case '\"': // NOI18N // closing double quote found.
+ offset++;
+ return TokenID.STRING;
+ case '\\': // NOI18N
+ state = ISI_BACKSLASH_IN_DOUBLE_QUOTE;
+ break;
+ // default: state stays the same...
+ }
+ break;
+ case ISI_BACKSLASH_IN_DOUBLE_QUOTE: // do not react on any char
+ state = ISI_DOUBLE_QUOTE;
+ break;
+ case ISI_SINGLE_QUOTE:
+ switch (actChar) {
+ case '\'': // NOI18N // closing single quote found.
+ offset++;
+ return TokenID.CHAR;
+ case '\\': // NOI18N
+ state = ISI_BACKSLASH_IN_SINGLE_QUOTE;
+ break;
+ // default: state stays the same...
+ }
+ break;
+ case ISI_BACKSLASH_IN_SINGLE_QUOTE: // do not react on any char
+ state = ISI_SINGLE_QUOTE;
+ break;
+ case ISI_NUMBER:
+ if ((actChar > '9' || actChar < '0') && actChar != '.') {
+ // offset++ is not needed: now we're after the number
+ return TokenID.NUMBER;
+ }
+ // do nothing in every other case
+ break;
+ }
+ offset++;
+ }
+ // exit with this state
+ if (offset == stopOffset) return null;
+ // starting state sign (like /* for comment), but no end before eof.
+ switch(state) {
+ case ISI_BLOCK_COMMENT:
+ case ISI_LINE_COMMENT:
+ return TokenID.COMMENT;
+ case ISI_WHITESPACE:
+ case ISI_TEXT:
+ case ISI_FUNCTION:
+ return TokenID.TEXT;
+ case ISI_KEYWORD:
+ return TokenID.KEYWORD;
+ case ISI_PRECOMPILER:
+ return TokenID.PRECOMPILE;
+ case ISI_TEXT_IN_BRACKETS:
+ return TokenID.BRACKET;
+ case ISI_DOUBLE_QUOTE:
+ return TokenID.STRING;
+ case ISI_SINGLE_QUOTE:
+ return TokenID.CHAR;
+ case ISI_NUMBER:
+ return TokenID.NUMBER;
+ }
+ return null;
+ }
+
+ /**
+ * take the next n chars to determine the next state for reading the buffer.
+ * start with char at offset and take no more than stopOffset-offset chars from
+ * buffer.
+ * @return array of length 2; index 0 is the count which is added to offset;
+ * index 1 is the state we're now in.
+ */
+ private int[] getNextState(
+ char[] buffer, int localOffset, int stopOffset, int oldState) {
+ if (buffer==null || buffer.length==0) {
+ return new int[] {0, INIT};
+ }
+ if (oldState == ISI_BLOCK_COMMENT) {
+ return new int[]{0, oldState};
+ }
+ if (oldState == ISI_TEXT_IN_BRACKETS) {
+ return new int[]{0, oldState};
+ }
+ int newState = INIT;
+ int offsetAdd = 0;
+ char nextChar = buffer[localOffset];
+ if (nextChar == '/' && ++localOffset < stopOffset) { // one more char for a comment
+ nextChar = buffer[localOffset];
+ switch(nextChar) {
+ case '*':
+ newState = ISI_BLOCK_COMMENT;
+ offsetAdd = 2;
+ break;
+ case '/':
+ newState = ISI_LINE_COMMENT;
+ offsetAdd = 2;
+ break;
+ default:
+ newState = ISI_TEXT;
+ offsetAdd = 1;
+ }
+ }
+ else if (nextChar == '#') { // precompiler statement
+ while(!Character.isWhitespace(nextChar) && localOffset + ++offsetAdd < stopOffset) {
+ nextChar = buffer[localOffset + offsetAdd];
+ }
+ newState = ISI_PRECOMPILER;
+ }
+ else if (nextChar == '[') { // opening bracket
+ newState = ISI_OPENING_BRACKET;
+ }
+ else if (nextChar == '\\') {
+ newState = ISI_TEXT; // if this is the beginning, it's surely text
+ offsetAdd++; // jump over the next char
+ }
+ else if (nextChar == '\"') { // NOI18N // opening bracket
+ // strange stuff may happen if a file ever starts with a quote, but that's a syntax error anyway...'
+ newState = ISI_DOUBLE_QUOTE;
+ offsetAdd++;
+ }
+ else if (nextChar == '\'') { // opening bracket
+ newState = ISI_SINGLE_QUOTE;
+ offsetAdd++;
+ }
+ else if (nextChar <= '9' && nextChar >= '0') { // numeric!
+ if (oldState == ISI_WHITESPACE) {
+ newState = ISI_NUMBER;
+ }
+ else {
+ newState = ISI_TEXT;
+ }
+ }
+ else if (nextChar == '.') { // lookahead for next char to make sure it's a number
+ if (localOffset + ++offsetAdd < stopOffset) {
+ nextChar = buffer[localOffset + offsetAdd];
+ if (nextChar <= '9' && nextChar >= '0') {
+ newState = ISI_NUMBER;
+ offsetAdd++;
+ }
+ else {
+ newState = ISI_TEXT;
+ }
+ }
+ }
+ else {
+ if (oldState != ISI_TEXT) {
+ String keyword = getKeyword(buffer, localOffset, stopOffset);
+ if (keyword == null) {
+ if (Character.isWhitespace(nextChar)) {
+ newState = ISI_WHITESPACE;
+ }
+ else {
+ newState = ISI_TEXT;
+ }
+ }
+ else {
+ newState = ISI_KEYWORD;
+ this.tokenLength = keyword.length();
+ offsetAdd = tokenLength;
+ }
+ }
+ else {
+ if (Character.isWhitespace(nextChar)) {
+ newState = ISI_WHITESPACE;
+ }
+ else {
+ newState = ISI_TEXT;
+ }
+ }
+ }
+ return new int[] {offsetAdd, newState};
+ }
+
+ /**
+ * returns the keyword if it was found in the buffer
+ */
+ private static String getKeyword(char[]buffer, int offset, int stopOffset) {
+ for (int i=0; i<KEYWORDS.length; i++) {
+ String keyword = KEYWORDS[i];
+ if (keyword.length() + offset < stopOffset) {
+ String match = String.copyValueOf(
+ buffer, offset, keyword.length());
+ // check if after the keyword's a whitespace!
+ if (match.equals(keyword)) {
+ if (buffer.length > offset + keyword.length()) {
+ if (Character.isWhitespace(buffer[offset + keyword.length()]))
+ return keyword;
+ }
+ }
+ }
+ }
+ return null;
+ }
+}
+
+
Added: incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/XcuFileCreator.java
URL: http://svn.apache.org/viewvc/incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/XcuFileCreator.java?rev=1236486&view=auto
==============================================================================
--- incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/XcuFileCreator.java (added)
+++ incubator/ooo/devtools/netbeansintegration/src/org/openoffice/extensions/util/XcuFileCreator.java Fri Jan 27 01:29:33 2012
@@ -0,0 +1,183 @@
+/*************************************************************************
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: XcuFileCreator.java,v $
+ *
+ * $Revision: 1.9 $
+ *
+ * last change: $Author: sg $ $Date: 2008/10/07 08:59:58 $
+ *
+ * The Contents of this file are made available subject to
+ * the terms of GNU Lesser General Public License Version 2.1.
+ *
+ *
+ * GNU Lesser General Public License Version 2.1
+ * =============================================
+ * Copyright 2005 by Sun Microsystems, Inc.
+ * 901 San Antonio Road, Palo Alto, CA 94303, USA
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1, as published by the Free Software Foundation.
+ *
+ * This library 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 for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
+ * MA 02111-1307 USA
+ *
+ ************************************************************************/
+
+package org.openoffice.extensions.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import org.openide.WizardDescriptor;
+import org.openide.filesystems.FileLock;
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.FileUtil;
+import org.openoffice.extensions.projecttemplates.addon.datamodel.AddOn;
+import org.openoffice.extensions.util.datamodel.PropertyContainer;
+import org.openoffice.extensions.util.datamodel.properties.UnknownOpenOfficeOrgLanguageIDException;
+import org.openoffice.extensions.util.datamodel.properties.UnknownOpenOfficeOrgPropertyException;
+
+/**
+ *
+ * @author sg128468
+ */
+public class XcuFileCreator {
+
+ private final String PROTOCOL_HANDLER_TEMPLATE_NAME = "ProtocolHandlerTemplate"; // NOI18N
+ private final String ADDON_TEMPLATE_NAME = "AddonTemplate"; // NOI18N
+ private final String TOOLBAR_TEMPLATE_NAME = "ToolBarTemplate"; // NOI18N
+ private final String MENUBAR_TEMPLATE_NAME = "MenuBarTemplate"; // NOI18N
+ private final String PROPS_FILE = "Bundle.properties"; // NOI18N
+
+ private WizardDescriptor m_wizard;
+ private Class m_templateBaseClass;
+// private String m_baseDir;
+
+ public static final int XCU_ADDON_TYPE = 0;
+ public static final int XCU_PROTOCOL_HANDLER_TYPE = 1;
+ public static final int XCU_ADDIN_TYPE = 2; // 2do: use this
+
+ /** Creates a new instance of XcuFileCreator */
+ public XcuFileCreator(WizardDescriptor wiz,
+ Class templateBaseClass) {
+ this.m_wizard = wiz;
+ this.m_templateBaseClass = templateBaseClass;
+// this.m_baseDir = baseDir;
+ }
+
+ public void createXcuFile(int type) {
+ switch(type) {
+ case XCU_ADDON_TYPE:
+ // add templates for menus and toolbars as wizard props
+ m_wizard.putProperty("OfficeMenuBar", // NOI18N
+ ProjectCreator.readFileLinesInArray(
+ m_templateBaseClass, PROPS_FILE, MENUBAR_TEMPLATE_NAME));
+ m_wizard.putProperty("OfficeToolBar", // NOI18N
+ ProjectCreator.readFileLinesInArray(
+ m_templateBaseClass, PROPS_FILE, TOOLBAR_TEMPLATE_NAME));
+ // additional templates: better idea than this?
+ createFile("org/openoffice/Office/Addons.xcu", new AdvancedReplace(m_wizard, (AddOn)m_wizard.getProperty("AddOn")), ADDON_TEMPLATE_NAME); // NOI18N
+ break;
+ case XCU_PROTOCOL_HANDLER_TYPE:
+ createFile("org/openoffice/Office/ProtocolHandler.xcu", new AdvancedReplace(m_wizard, (AddOn)m_wizard.getProperty("AddOn")), PROTOCOL_HANDLER_TEMPLATE_NAME); // NOI18N
+ break;
+ case XCU_ADDIN_TYPE:
+ // 2do
+ break;
+ default:
+ LogWriter.getLogWriter().log(LogWriter.LEVEL_CRITICAL, "Illegal xcu type."); // NOI18N
+ return; // do nothing
+ }
+ }
+
+ private void createFile(String fileName, AdvancedReplace aReplace, String templateName) {
+ // get the template
+ String[] template_xcu = ProjectCreator.readFileLinesInArray(
+ m_templateBaseClass, PROPS_FILE, templateName);
+ try {
+ FileObject projDir = FileUtil.toFileObject((File)m_wizard.getProperty("projdir")); // NOI18N
+ String registryDir = (String)ProjectTypeHelper.getObjectFromUnoProperties(projDir, "registry.dir"); // NOI18N
+ if (registryDir == null) {
+ registryDir = "registry"; // NOI18N
+ }
+ FileObject registryData = projDir.getFileObject(registryDir.concat("/data")); // NOI18N
+ if (registryData == null) {
+ registryData = FileUtil.createFolder(projDir, registryDir.concat("/data")); // NOI18N
+ }
+
+ FileObject ifcObject = FileUtil.createData(
+ registryData, fileName);
+ fillFile(aReplace, ifcObject, template_xcu);
+ }
+ catch(IOException e) {
+ LogWriter.getLogWriter().printStackTrace(e);
+ } catch (UnknownOpenOfficeOrgLanguageIDException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ } catch (UnknownOpenOfficeOrgPropertyException ex) {
+ LogWriter.getLogWriter().printStackTrace(ex);
+ }
+ }
+
+ private void fillFile(AdvancedReplace aReplace, FileObject fo, String[] data)
+ throws IOException, UnknownOpenOfficeOrgLanguageIDException, UnknownOpenOfficeOrgPropertyException {
+ FileLock lock = fo.lock();
+ try {
+ OutputStream out = fo.getOutputStream(lock);
+ OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8"); // NOI18N
+ try {
+ writeStringArrayInFile(outWriter, aReplace, data);
+ }
+ finally {
+ outWriter.close();
+ }
+ } finally {
+ lock.releaseLock();
+ }
+ }
+
+ private void writeStringArrayInFile(
+ OutputStreamWriter outWriter, AdvancedReplace aReplace, String[]data)
+ throws IOException, UnknownOpenOfficeOrgLanguageIDException, UnknownOpenOfficeOrgPropertyException {
+ for (int i=0; i<data.length; i++) {
+ String[] nextData = aReplace.replaceVariables(data[i]);
+ if (nextData.length == 1) {
+ outWriter.write(nextData[0], 0, nextData[0].length());
+ outWriter.write("\n", 0, 1); // NOI18N
+ }
+ else if (nextData.length > 0){ // just to avoid endless recursion
+ outWriter.flush();
+ writeStringArrayInFile(outWriter, aReplace, (String[])nextData);
+ }
+ }
+ outWriter.flush();
+ }
+
+ public static String getXcuContext(String[] string) {
+ if (string == null || string.length == 0)
+ return "<value/>"; // NOI18N
+ StringBuffer retValue = new StringBuffer("<value>"); // NOI18N
+ for (int i = 0; i < string.length; i++) {
+ if (i > 0) {
+ retValue.append(","); // NOI18N
+ }
+ // replace short form of contexts with proper entries for the Office
+ for (int j = 0; j < PropertyContainer.PROPERTY_CONTAINER_CONTEXTS.length; j++) {
+ if (string[i].equals(PropertyContainer.PROPERTY_CONTAINER_CONTEXTS[j])) {
+ retValue.append(PropertyContainer.PROPERTY_CONTAINER_CONTEXT_REPRESENTATIONS[j]); // NOI18N
+ }
+ }
+ }
+ return retValue.append("</value>").toString(); // NOI18N
+ }
+}