diff options
Diffstat (limited to 'bundles/org.eclipse.equinox.p2.metadata.generator/src')
24 files changed, 0 insertions, 7469 deletions
diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/Activator.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/Activator.java deleted file mode 100644 index 5c2cb2cac..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/Activator.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.generator; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; - -public class Activator implements BundleActivator { - public static BundleContext context = null; - public static String ID = "org.eclipse.equinox.p2.metadata.generator"; //$NON-NLS-1$ - - public static BundleContext getContext() { - return context; - } - - public void start(BundleContext context) throws Exception { - Activator.context = context; - } - - public void stop(BundleContext context) throws Exception { - Activator.context = null; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java deleted file mode 100644 index 3d2dd9f6f..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/EclipseGeneratorApplication.java +++ /dev/null @@ -1,422 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.generator; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.app.IApplication; -import org.eclipse.equinox.app.IApplicationContext; -import org.eclipse.equinox.internal.provisional.p2.metadata.generator.EclipseInstallGeneratorInfoProvider; -import org.eclipse.equinox.internal.provisional.p2.metadata.generator.Generator; -import org.eclipse.equinox.p2.core.*; -import org.eclipse.equinox.p2.repository.IRepository; -import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; -import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; -import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; -import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; -import org.eclipse.osgi.util.NLS; -import org.osgi.framework.ServiceReference; - -public class EclipseGeneratorApplication implements IApplication { - - // The mapping rules for in-place generation need to construct paths into the structure - // of an eclipse installation; in the future the default artifact mapping declared in - // SimpleArtifactRepository may change, for example, to not have a 'bundles' directory - // instead of a 'plugins' directory, so a separate constant is defined and used here. - static final private String[][] INPLACE_MAPPING_RULES = { {"(& (classifier=osgi.bundle) (format=packed)", "${repoUrl}/features/${id}_${version}.jar.pack.gz"}, //$NON-NLS-1$//$NON-NLS-2$ - {"(& (classifier=org.eclipse.update.feature))", "${repoUrl}/features/${id}_${version}.jar"}, //$NON-NLS-1$//$NON-NLS-2$ - {"(& (classifier=osgi.bundle))", "${repoUrl}/plugins/${id}_${version}.jar"}, //$NON-NLS-1$//$NON-NLS-2$ - {"(& (classifier=binary))", "${repoUrl}/binary/${id}_${version}"}}; //$NON-NLS-1$//$NON-NLS-2$ - - static final public String PUBLISH_PACK_FILES_AS_SIBLINGS = "publishPackFilesAsSiblings"; //$NON-NLS-1$ - - private Generator.GeneratorResult incrementalResult = null; - private boolean generateRootIU = true; - private URI metadataLocation; - private String metadataRepoName; - private URI artifactLocation; - private String artifactRepoName; - private String operation; - private String argument; - private String features; - private String bundles; - private String base; - //whether repository xml files should be compressed - private String compress = "false"; //$NON-NLS-1$ - - private ServiceReference agentRef; - private IProvisioningAgent agent; - - private File getExecutableName(String base, EclipseInstallGeneratorInfoProvider provider) { - File location = provider.getExecutableLocation(); - if (location == null) - return new File(base, EclipseInstallGeneratorInfoProvider.getDefaultExecutableName(null)); - if (location.isAbsolute()) - return location; - return new File(base, location.getPath()); - } - - private void initialize(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException { - if ("-source".equalsIgnoreCase(operation)) //$NON-NLS-1$ - provider.initialize(new File(argument)); - else if ("-inplace".equalsIgnoreCase(operation)) { //$NON-NLS-1$ - provider.initialize(new File(argument)); - initializeForInplace(provider); - } else if ("-config".equalsIgnoreCase(operation)) { //$NON-NLS-1$ - provider.initialize(new File(argument), new File(argument, "configuration"), getExecutableName(argument, provider), null, null); //$NON-NLS-1$ - } else if ("-updateSite".equalsIgnoreCase(operation)) { //$NON-NLS-1$ - provider.setAddDefaultIUs(false); - provider.initialize(new File(argument), null, null, new File[] {new File(argument, "plugins")}, new File(argument, "features")); //$NON-NLS-1$ //$NON-NLS-2$ - initializeForInplace(provider); - } else { - // base is set but we expect everything else to have been set using - // explicit args. Note that if we are coming in via an Ant task, we have - // to ensure all the values are passed in - if (base != null) { - File[] bundlesLocation = bundles == null ? null : new File[] {new File(bundles)}; - File featuresLocation = features == null ? null : new File(features); - provider.initialize(new File(base), null, null, bundlesLocation, featuresLocation); - } - } - initializeRepositories(provider); - } - - private void initializeArtifactRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException { - if (artifactLocation == null) - return; - IArtifactRepositoryManager manager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME); - URI location = artifactLocation; - - String repositoryName = (artifactRepoName != null && artifactRepoName.length() > 0) ? artifactRepoName : artifactLocation + " - artifacts"; //$NON-NLS-1$ - Map properties = new HashMap(1); - properties.put(IRepository.PROP_COMPRESSED, compress); - if (provider.reuseExistingPack200Files()) - properties.put(PUBLISH_PACK_FILES_AS_SIBLINGS, Boolean.TRUE.toString()); - IArtifactRepository result = null; - try { - result = manager.createRepository(location, repositoryName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); - manager.removeRepository(location); - provider.setArtifactRepository(result); - return; - } catch (ProvisionException e) { - //fall through a load existing repo - } - - IArtifactRepository repository = manager.loadRepository(location, null); - if (repository != null) { - manager.removeRepository(location); - if (!repository.isModifiable()) - throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoNotWritable, location)); - provider.setArtifactRepository(repository); - if (provider.reuseExistingPack200Files()) - repository.setProperty(PUBLISH_PACK_FILES_AS_SIBLINGS, "true"); //$NON-NLS-1$ - if (!provider.append()) { - File repoLocation = URIUtil.toFile(location); - if (repoLocation.isFile()) - repoLocation = repoLocation.getParentFile(); - if (repoLocation.equals(provider.getBaseLocation())) - throw new IllegalArgumentException(NLS.bind(Messages.exception_artifactRepoNoAppendDestroysInput, location)); - - repository.removeAll(); - } - } - return; - } - - public void initializeForInplace(EclipseInstallGeneratorInfoProvider provider) { - File location = provider.getBaseLocation(); - if (location == null) - location = provider.getBundleLocations()[0]; - metadataLocation = location.toURI(); - artifactLocation = location.toURI(); - provider.setPublishArtifactRepository(true); - provider.setPublishArtifacts(false); - provider.setAppend(true); - provider.setMappingRules(INPLACE_MAPPING_RULES); - } - - private void initializeMetadataRepository(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException { - if (metadataLocation == null) - return; - URI location = metadataLocation; - - // First try to create a simple repo, this will fail if one already exists - // We try creating a repo first instead of just loading what is there because we don't want a repo based - // on a site.xml if there is one there. - - String repositoryName = (metadataRepoName == null || metadataRepoName.length() == 0) ? metadataLocation + " - metadata" : metadataRepoName; //$NON-NLS-1$ - Map properties = new HashMap(1); - properties.put(IRepository.PROP_COMPRESSED, compress); - - IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME); - try { - IMetadataRepository result = manager.createRepository(location, repositoryName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, properties); - manager.removeRepository(location); - provider.setMetadataRepository(result); - return; - } catch (ProvisionException e) { - //fall through and load the existing repo - } - - IMetadataRepository repository = manager.loadRepository(location, null); - if (repository != null) { - manager.removeRepository(location); - // don't set the compress flag here because we don't want to change the format - // of an already existing repository - if (!repository.isModifiable()) - throw new IllegalArgumentException(NLS.bind(Messages.exception_metadataRepoNotWritable, location)); - provider.setMetadataRepository(repository); - if (!provider.append()) - repository.removeAll(); - return; - } - } - - private void initializeRepositories(EclipseInstallGeneratorInfoProvider provider) throws ProvisionException { - initializeArtifactRepository(provider); - initializeMetadataRepository(provider); - } - - public void setCompress(String value) { - if (Boolean.valueOf(value).booleanValue()) - compress = "true"; //$NON-NLS-1$ - } - - public void processCommandLineArguments(String[] args, EclipseInstallGeneratorInfoProvider provider) throws Exception { - if (args == null) - return; - for (int i = 0; i < args.length; i++) { - // check for args without parameters (i.e., a flag arg) - - if (args[i].equalsIgnoreCase("-publishArtifacts") || args[i].equalsIgnoreCase("-pa")) //$NON-NLS-1$ //$NON-NLS-2$ - provider.setPublishArtifacts(true); - - if (args[i].equalsIgnoreCase("-publishArtifactRepository") || args[i].equalsIgnoreCase("-par")) //$NON-NLS-1$ //$NON-NLS-2$ - provider.setPublishArtifactRepository(true); - - if (args[i].equalsIgnoreCase("-append")) //$NON-NLS-1$ - provider.setAppend(true); - - if (args[i].equalsIgnoreCase("-noDefaultIUs")) //$NON-NLS-1$ - provider.setAddDefaultIUs(false); - - if (args[i].equalsIgnoreCase("-compress")) //$NON-NLS-1$ - compress = "true"; //$NON-NLS-1$ - - if (args[i].equalsIgnoreCase("-reusePack200Files")) //$NON-NLS-1$ - provider.reuseExistingPack200Files(true); - - // check for args with parameters. If we are at the last argument or if the next one - // has a '-' as the first character, then we can't have an arg with a parm so continue. - if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$ - continue; - String arg = args[++i]; - - if (args[i - 1].equalsIgnoreCase("-source")) { //$NON-NLS-1$ - operation = args[i - 1]; - argument = arg; - } - - if (args[i - 1].equalsIgnoreCase("-inplace")) { //$NON-NLS-1$ - operation = args[i - 1]; - argument = arg; - } - - if (args[i - 1].equalsIgnoreCase("-config")) { //$NON-NLS-1$ - operation = args[i - 1]; - argument = arg; - } - if (args[i - 1].equalsIgnoreCase("-updateSite")) { //$NON-NLS-1$ - operation = args[i - 1]; - argument = arg; - } - - if (args[i - 1].equalsIgnoreCase("-exe")) //$NON-NLS-1$ - provider.setExecutableLocation(arg); - - if (args[i - 1].equalsIgnoreCase("-launcherConfig")) //$NON-NLS-1$ - provider.setLauncherConfig(arg); - - if (args[i - 1].equalsIgnoreCase("-metadataRepositoryName")) //$NON-NLS-1$ - metadataRepoName = arg; - - try { - if (args[i - 1].equalsIgnoreCase("-metadataRepository") || args[i - 1].equalsIgnoreCase("-mr")) //$NON-NLS-1$ //$NON-NLS-2$ - metadataLocation = URIUtil.fromString(arg); - - if (args[i - 1].equalsIgnoreCase("-artifactRepository") | args[i - 1].equalsIgnoreCase("-ar")) //$NON-NLS-1$ //$NON-NLS-2$ - artifactLocation = URIUtil.fromString(arg); - - if (args[i - 1].equalsIgnoreCase("-site")) //$NON-NLS-1$ - provider.setSiteLocation(URIUtil.fromString(arg)); - } catch (URISyntaxException e) { - throw new IllegalArgumentException("Repository location (" + arg + ") must be a URL."); //$NON-NLS-1$ //$NON-NLS-2$ - } - - if (args[i - 1].equalsIgnoreCase("-artifactRepositoryName")) //$NON-NLS-1$ - artifactRepoName = arg; - - if (args[i - 1].equalsIgnoreCase("-flavor")) //$NON-NLS-1$ - provider.setFlavor(arg); - - if (args[i - 1].equalsIgnoreCase("-productFile")) //$NON-NLS-1$ - provider.setProductFile(arg); - - if (args[i - 1].equalsIgnoreCase("-features")) //$NON-NLS-1$ - features = arg; - - if (args[i - 1].equalsIgnoreCase("-bundles")) //$NON-NLS-1$ - bundles = arg; - - if (args[i - 1].equalsIgnoreCase("-base")) //$NON-NLS-1$ - base = arg; - - if (args[i - 1].equalsIgnoreCase("-root")) //$NON-NLS-1$ - provider.setRootId(arg); - - if (args[i - 1].equalsIgnoreCase("-rootVersion")) //$NON-NLS-1$ - provider.setRootVersion(arg); - - if (args[i - 1].equalsIgnoreCase("-p2.os")) //$NON-NLS-1$ - provider.setOS(arg); - - } - } - - public Object run(String args[]) throws Exception { - EclipseInstallGeneratorInfoProvider provider = new EclipseInstallGeneratorInfoProvider(); - processCommandLineArguments(args, provider); - Object result = run(provider); - if (result != IApplication.EXIT_OK) - for (int i = 0; i < args.length; i++) - System.out.println(args[i]); - return result; - } - - public Object run(EclipseInstallGeneratorInfoProvider provider) throws Exception { - initializeAgent(); - initialize(provider); - - if (provider.getBaseLocation() == null && provider.getProductFile() == null && !generateRootIU) { - System.out.println(Messages.exception_baseLocationNotSpecified); - return new Integer(-1); - } - - // if we asked for artifacts to be published in some form, there must be a repo given - if ((provider.publishArtifactRepository() || provider.publishArtifacts()) && provider.getArtifactRepository() == null) { - System.out.println(Messages.exception_artifactRepoNotSpecified); - return new Integer(-1); - } - - if (provider.getMetadataRepository() == null) { - System.out.println(Messages.exception_metadataRepoNotSpecified); - return new Integer(-1); - } - - System.out.println(NLS.bind(Messages.message_generatingMetadata, provider.getBaseLocation())); - - long before = System.currentTimeMillis(); - IStatus result = generate(provider); - - long after = System.currentTimeMillis(); - if (result.isOK()) { - System.out.println(NLS.bind(Messages.message_generationCompleted, String.valueOf((after - before) / 1000))); - return IApplication.EXIT_OK; - } - System.out.println(result); - return new Integer(1); - } - - private void initializeAgent() throws ProvisionException { - agentRef = Activator.getContext().getServiceReference(IProvisioningAgent.SERVICE_NAME); - if (agentRef != null) { - agent = (IProvisioningAgent) Activator.getContext().getService(agentRef); - if (agent != null) - return; - } - ServiceReference providerRef = Activator.getContext().getServiceReference(IProvisioningAgentProvider.SERVICE_NAME); - if (providerRef == null) - throw new RuntimeException("No provisioning agent provider is available"); //$NON-NLS-1$ - IProvisioningAgentProvider provider = (IProvisioningAgentProvider) Activator.getContext().getService(providerRef); - if (provider == null) - throw new RuntimeException("No provisioning agent provider is available"); //$NON-NLS-1$ - //obtain agent for currently running system - agent = provider.createAgent(null); - Activator.getContext().ungetService(providerRef); - } - - protected IStatus generate(EclipseInstallGeneratorInfoProvider provider) { - Generator generator = new Generator(provider); - if (incrementalResult != null) - generator.setIncrementalResult(incrementalResult); - generator.setGenerateRootIU(generateRootIU); - IStatus result = generator.generate(); - incrementalResult = null; - return result; - } - - public Object start(IApplicationContext context) throws Exception { - return run((String[]) context.getArguments().get("application.args")); //$NON-NLS-1$ - } - - public void stop() { - if (agentRef != null) { - Activator.getContext().ungetService(agentRef); - agentRef = null; - } - } - - public void setBase(String base) { - this.base = base; - } - - public void setArtifactLocation(URI location) { - this.artifactLocation = location; - } - - public void setBundles(String bundles) { - this.bundles = bundles; - } - - public void setOperation(String operation, String argument) { - this.operation = operation; - this.argument = argument; - } - - public void setFeatures(String features) { - this.features = features; - } - - public void setMetadataLocation(URI location) { - this.metadataLocation = location; - } - - public void setMetadataRepositoryName(String name) { - this.metadataRepoName = name; - } - - public void setArtifactRepositoryName(String name) { - this.artifactRepoName = name; - } - - public void setIncrementalResult(Generator.GeneratorResult ius) { - this.incrementalResult = ius; - } - - public void setGeneratorRootIU(boolean b) { - this.generateRootIU = b; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/LocalizationHelper.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/LocalizationHelper.java deleted file mode 100644 index deeae27c0..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/LocalizationHelper.java +++ /dev/null @@ -1,200 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.generator; - -import java.io.*; -import java.net.URL; -import java.net.URLConnection; -import java.util.*; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -/** - * Helper functions supporting the processing of localized - * property files. - * - */ -public final class LocalizationHelper { - - private static final String PROPERTIES_FILE_EXTENSION = ".properties"; //$NON-NLS-1$ - private static final Locale DEFAULT_LOCALE = new Locale("df", "LT"); //$NON-NLS-1$//$NON-NLS-2$ - private static LocalizationHelper instance = new LocalizationHelper(); - - // Extract the locale string from the properties file with the given filename - // where the locale string follows the given prefix. For example, return "zh_HK" - // from filename == "plugin_zh_HK.properties" and prefix == "plugin". - static public String getLocaleString(String filename, String prefix) { - String localeString = null; - if (filename.startsWith(prefix) && filename.endsWith(PROPERTIES_FILE_EXTENSION)) { - if (filename.length() > prefix.length() + PROPERTIES_FILE_EXTENSION.length()) { - localeString = filename.substring(prefix.length() + 1, filename.length() - PROPERTIES_FILE_EXTENSION.length()); - } else { - localeString = ""; //$NON-NLS-1$ - } - } - return localeString; - } - - // Get the locale corresponding to the given locale string - static public Locale getLocale(String localeString) { - Locale locale = DEFAULT_LOCALE; - if (localeString.length() == 5 && localeString.indexOf('_') == 2) { - locale = new Locale(localeString.substring(0, 2), localeString.substring(3, 5)); - } else if (localeString.length() == 2) { - locale = new Locale(localeString.substring(0, 2)); - } - return locale; - } - - // For the given root directory and path to localization files within that directory - // get a map from locale to property set for the localization property files. - public static Map getDirPropertyLocalizations(File root, String localizationPath, Locale defaultLocale, String[] propertyKeys) { - File fullPath = new File(root, localizationPath); - File localizationDir = fullPath.getParentFile(); - final String localizationFile = fullPath.getName(); - String[] localizationFiles = LocalizationHelper.getLocalizationFiles(localizationDir, localizationFile); - - HashMap localizations = null; - - if (localizationFiles != null) { - localizations = new HashMap(localizationFiles.length); - for (int i = 0; i < localizationFiles.length; i++) { - String nextFile = localizationFiles[i]; - Locale nextLocale = getLocale(LocalizationHelper.getLocaleString(nextFile, localizationFile)); - - try { - Properties properties = loadProperties(root, nextFile); - Properties localizedStrings = getLocalizedProperties(propertyKeys, properties); - if (localizedStrings.size() > 0) { - localizations.put(nextLocale, localizedStrings); - if (DEFAULT_LOCALE.equals(nextLocale) && defaultLocale != null) { - localizations.put(nextLocale, localizedStrings); - } - } - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - } - - return localizations; - } - - public static Map getJarPropertyLocalizations(File root, String localizationPath, Locale defaultLocale, String[] propertyKeys) { - ZipFile jarFile = null; - Map localizations = new HashMap(4); - try { - jarFile = new ZipFile(root, ZipFile.OPEN_READ); - for (Enumeration entries = jarFile.entries(); entries.hasMoreElements();) { - ZipEntry nextEntry = (ZipEntry) entries.nextElement(); - String nextName = nextEntry.getName(); - String localeString = LocalizationHelper.getLocaleString(nextName, localizationPath); - - if (!nextEntry.isDirectory() && localeString != null) { - Locale nextLocale = LocalizationHelper.getLocale(localeString); - InputStream stream = null; - try { - stream = jarFile.getInputStream(nextEntry); - Properties properties = new Properties(); - properties.load(stream); - Properties localizedStrings = LocalizationHelper.getLocalizedProperties(propertyKeys, properties); - if (localizedStrings.size() > 0) { - localizations.put(nextLocale, localizedStrings); - if (DEFAULT_LOCALE.equals(nextLocale) && defaultLocale != null) { - localizations.put(nextLocale, localizedStrings); - } - } - } finally { - if (stream != null) - stream.close(); - } - } - } - } catch (IOException ioe) { - ioe.printStackTrace(); - } finally { - if (jarFile != null) { - try { - jarFile.close(); - } catch (IOException ioe) { - // do nothing - } - } - } - - return localizations; - } - - // Load a property set from given root and file with the given name - private static Properties loadProperties(File root, String propertyFilename) throws IOException { - Properties result = new Properties(); - InputStream propertyStream = null; - try { - try { - if (root.isDirectory()) - propertyStream = new FileInputStream(new File(root, propertyFilename)); - else { - URLConnection connection = new URL("jar:" + root.toURL().toExternalForm() + "!/" + propertyFilename).openConnection(); //$NON-NLS-1$ //$NON-NLS-2$ - connection.setUseCaches(false); - propertyStream = connection.getInputStream(); - } - } catch (FileNotFoundException e) { - // if there is no messages file then just return; - return result; - } - result.load(propertyStream); - } finally { - if (propertyStream != null) - propertyStream.close(); - } - return result; - } - - // Given a list of keys and the corresponding localized property set, - // return a new property set with those keys and the localized values. - static public Properties getLocalizedProperties(String[] propertyKeys, Properties properties) { - Properties localizedProperties = new Properties(); - for (int i = 0; i < propertyKeys.length; i++) { - String key = propertyKeys[i]; - if (key != null) { - String localizedValue = properties.getProperty(key); - if (localizedValue != null) - localizedProperties.put(key, localizedValue); - } - } - return localizedProperties; - } - - public static String[] getLocalizationFiles(File localizationDir, final String filenamePrefix) { - return localizationDir.list(instance.new FileFilter() { - public boolean accept(File directory, String filename) { - return (getLocaleString(filename, filenamePrefix) != null ? true : false); - } - }); - } - - private abstract class FileFilter implements FilenameFilter { - - public FileFilter() { - // Nothing to do - } - - /* (non-Javadoc) - * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String) - */ - public abstract boolean accept(File directory, String filename); - } - - private LocalizationHelper() { - // - } - -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/Messages.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/Messages.java deleted file mode 100644 index 8663c54ed..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/Messages.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. All rights reserved. This - * program and the accompanying materials are made available under the terms of - * the Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: IBM Corporation - initial API and implementation - ******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.generator; - -import org.eclipse.osgi.util.NLS; - -public class Messages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.equinox.internal.p2.metadata.generator.messages";//$NON-NLS-1$ - - public static String exception_errorConverting; - public static String exception_errorParsingUpdateSite; - public static String exception_stateAddition; - public static String exception_sourceDirectoryInvalid; - public static String exception_artifactRepoNotWritable; - public static String exception_artifactRepoNotSpecified; - public static String exception_metadataRepoNotWritable; - public static String exception_metadataRepoNotSpecified; - public static String exception_baseLocationNotSpecified; - public static String exception_artifactRepoNoAppendDestroysInput; - - public static String message_generatingMetadata; - public static String message_generationCompleted; - - static { - // load message values from bundle file - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/ProductQuery.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/ProductQuery.java deleted file mode 100644 index 6e9a293e5..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/ProductQuery.java +++ /dev/null @@ -1,133 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.generator; - -import java.io.*; -import java.util.*; -import org.eclipse.equinox.internal.p2.metadata.generator.features.ProductFile; -import org.eclipse.equinox.internal.provisional.p2.metadata.generator.Generator.GeneratorResult; -import org.eclipse.equinox.internal.provisional.p2.metadata.generator.MetadataGeneratorHelper; -import org.eclipse.equinox.p2.metadata.*; -import org.eclipse.equinox.p2.query.MatchQuery; - -public class ProductQuery extends MatchQuery { - private static final String EQUINOX_LAUNCHER = "org.eclipse.equinox.launcher"; //$NON-NLS-1$ - - private final ProductFile product; - private final String flavor; - private final Map children = new HashMap(); - private final String versionAdvice; - - public ProductQuery(ProductFile product, String flavor, Map configIUs, String versionAdvice) { - this.product = product; - this.flavor = flavor; - this.versionAdvice = versionAdvice; - initialize(configIUs); - } - - private Properties loadVersions(String location) { - Properties properties = new Properties(); - if (location == null) - return properties; - File file = new File(location); - if (file.exists()) { - InputStream stream = null; - try { - stream = new BufferedInputStream(new FileInputStream(file)); - properties.load(stream); - } catch (IOException e) { - // nothing - } finally { - if (stream != null) - try { - stream.close(); - } catch (IOException e) { - //nothing - } - } - } - return properties; - } - - private void initialize(Map configIUs) { - boolean features = product.useFeatures(); - Properties versions = loadVersions(versionAdvice); - - List contents = features ? product.getFeatures() : product.getPlugins(); - for (Iterator iterator = contents.iterator(); iterator.hasNext();) { - String item = (String) iterator.next(); - - VersionRange range = VersionRange.emptyRange; - if (versions.containsKey(item)) { - Version value = Version.create(versions.getProperty(item)); - range = new VersionRange(value, true, value, true); - } - - if (features) // for features we want the group - item = MetadataGeneratorHelper.getTransformedId(item, false, true); - - children.put(item, range); - if (configIUs.containsKey(item)) { - for (Iterator ius = ((Set) configIUs.get(item)).iterator(); ius.hasNext();) { - IInstallableUnit object = (IInstallableUnit) ius.next(); - children.put(object.getId(), new VersionRange(object.getVersion(), true, object.getVersion(), true)); - } - } - } - - //also include the launcher CU fragments as a workaround to bug 218890 - String launcherPrefix = product.getId() + ".launcher"; //$NON-NLS-1$ - if (configIUs.containsKey(launcherPrefix)) { - for (Iterator ius = ((Set) configIUs.get(launcherPrefix)).iterator(); ius.hasNext();) { - IInstallableUnit object = (IInstallableUnit) ius.next(); - children.put(object.getId(), new VersionRange(object.getVersion(), true, object.getVersion(), true)); - } - } - - //also add the launcher.jar - if (!children.containsKey(EQUINOX_LAUNCHER)) { - children.put(EQUINOX_LAUNCHER, VersionRange.emptyRange); - children.put(flavor + EQUINOX_LAUNCHER, VersionRange.emptyRange); - } - - // and launcher fragment CUs - if (configIUs.containsKey(EQUINOX_LAUNCHER)) { - for (Iterator ius = ((Set) configIUs.get(EQUINOX_LAUNCHER)).iterator(); ius.hasNext();) { - IInstallableUnit object = (IInstallableUnit) ius.next(); - children.put(object.getId(), new VersionRange(object.getVersion(), true, object.getVersion(), true)); - } - } - - // feature based product, individual bundle config CUs are under CONFIGURATION_CUS for convenience - if (features && configIUs.containsKey(GeneratorResult.CONFIGURATION_CUS)) { - for (Iterator ius = ((Set) configIUs.get(GeneratorResult.CONFIGURATION_CUS)).iterator(); ius.hasNext();) { - IInstallableUnit object = (IInstallableUnit) ius.next(); - children.put(object.getId(), new VersionRange(object.getVersion(), true, object.getVersion(), true)); - } - } - } - - /* (non-Javadoc) - * @see org.eclipse.equinox.internal.provisional.p2.query.Query#isMatch(java.lang.Object) - */ - public boolean isMatch(Object object) { - if (!(object instanceof IInstallableUnit)) - return false; - - IInstallableUnit candidate = (IInstallableUnit) object; - VersionRange range = (VersionRange) children.get(candidate.getId()); - if (range != null) { - return range.isIncluded(candidate.getVersion()); - } - - return false; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/DefaultSiteParser.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/DefaultSiteParser.java deleted file mode 100644 index 6552f5629..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/DefaultSiteParser.java +++ /dev/null @@ -1,731 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.generator.features; - -import java.io.IOException; -import java.io.InputStream; -import java.util.*; -import javax.xml.parsers.*; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.core.helpers.Tracing; -import org.eclipse.equinox.internal.p2.metadata.repository.Activator; -import org.eclipse.equinox.internal.provisional.p2.metadata.generator.URLEntry; -import org.eclipse.osgi.util.NLS; -import org.w3c.dom.*; -import org.xml.sax.*; -import org.xml.sax.helpers.DefaultHandler; - -/** - * Parses a site.xml file. - * This class was initially copied from org.eclipse.update.core.model.DefaultSiteParser. - */ -public class DefaultSiteParser extends DefaultHandler { - - private static final String ARCHIVE = "archive"; //$NON-NLS-1$ - private static final String CATEGORY = "category"; //$NON-NLS-1$ - private static final String CATEGORY_DEF = "category-def"; //$NON-NLS-1$ - - private static final String ASSOCIATE_SITES_URL = "associateSitesURL"; //$NON-NLS-1$ - private static final String ASSOCIATE_SITE = "associateSite"; //$NON-NLS-1$ - private static final String DEFAULT_INFO_URL = "index.html"; //$NON-NLS-1$ - private static final String DESCRIPTION = "description"; //$NON-NLS-1$ - private static final String FEATURE = "feature"; //$NON-NLS-1$ - private static final String FEATURES = "features/"; //$NON-NLS-1$ - private final static SAXParserFactory parserFactory = SAXParserFactory.newInstance(); - private static final String PLUGIN_ID = Activator.ID; - private static final String SITE = "site"; //$NON-NLS-1$ - - private static final int STATE_ARCHIVE = 3; - private static final int STATE_CATEGORY = 4; - private static final int STATE_CATEGORY_DEF = 5; - private static final int STATE_DESCRIPTION_CATEGORY_DEF = 7; - private static final int STATE_DESCRIPTION_SITE = 6; - private static final int STATE_FEATURE = 2; - private static final int STATE_IGNORED_ELEMENT = -1; - private static final int STATE_INITIAL = 0; - private static final int STATE_SITE = 1; - - private int currentState; - - private boolean DESCRIPTION_SITE_ALREADY_SEEN = false; - // Current object stack (used to hold the current object we are - // populating in this plugin descriptor - Stack objectStack = new Stack(); - - private SAXParser parser; - - // Current State Information - Stack stateStack = new Stack(); - - // List of string keys for translated strings - private final List messageKeys = new ArrayList(4); - - private MultiStatus status; - - /* - * - */ - private static void debug(String s) { - Tracing.debug("DefaultSiteParser: " + s); //$NON-NLS-1$ - } - - private static URLEntry[] getAssociateSites(String associateSitesURL) { - - try { - DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = domFactory.newDocumentBuilder(); - Document document = builder.parse(associateSitesURL); - if (document == null) - return null; - NodeList mirrorNodes = document.getElementsByTagName(ASSOCIATE_SITE); - URLEntry[] mirrors = new URLEntry[mirrorNodes.getLength()]; - for (int i = 0; i < mirrorNodes.getLength(); i++) { - Element mirrorNode = (Element) mirrorNodes.item(i); - mirrors[i] = new URLEntry(); - String infoURL = mirrorNode.getAttribute("url"); //$NON-NLS-1$ - String label = mirrorNode.getAttribute("label"); //$NON-NLS-1$ - mirrors[i].setURL(infoURL); - mirrors[i].setAnnotation(label); - - if (Tracing.DEBUG_GENERATOR_PARSING) - debug("Processed mirror: url:" + infoURL + " label:" + label); //$NON-NLS-1$ //$NON-NLS-2$ - } - return mirrors; - } catch (Exception e) { - // log if absolute url - if (associateSitesURL != null && (associateSitesURL.startsWith("http://") //$NON-NLS-1$ - || associateSitesURL.startsWith("https://") //$NON-NLS-1$ - || associateSitesURL.startsWith("file://") //$NON-NLS-1$ - || associateSitesURL.startsWith("ftp://") //$NON-NLS-1$ - || associateSitesURL.startsWith("jar://"))) //$NON-NLS-1$ - log(Messages.DefaultSiteParser_mirrors, e); - return null; - } - } - - static void log(Exception e) { - LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "Internal Error", e)); //$NON-NLS-1$ - } - - static void log(String message) { - LogHelper.log(new Status(IStatus.WARNING, Activator.ID, message, null)); - } - - static void log(String message, Exception e) { - LogHelper.log(new Status(IStatus.WARNING, Activator.ID, message, e)); - } - - /** - * Constructs a site parser. - */ - public DefaultSiteParser() { - super(); - stateStack = new Stack(); - objectStack = new Stack(); - status = null; - DESCRIPTION_SITE_ALREADY_SEEN = false; - try { - parserFactory.setNamespaceAware(true); - this.parser = parserFactory.newSAXParser(); - } catch (ParserConfigurationException e) { - log(e); - } catch (SAXException e) { - log(e); - } - - if (Tracing.DEBUG_GENERATOR_PARSING) - debug("Created"); //$NON-NLS-1$ - } - - /** - * Handle character text - * @see DefaultHandler#characters(char[], int, int) - * @since 2.0 - */ - public void characters(char[] ch, int start, int length) { - String text = new String(ch, start, length); - //only push if description - int state = ((Integer) stateStack.peek()).intValue(); - if (state == STATE_DESCRIPTION_SITE || state == STATE_DESCRIPTION_CATEGORY_DEF) - objectStack.push(text); - - } - - /** - * Handle end of element tags - * @see DefaultHandler#endElement(String, String, String) - * @since 2.0 - */ - public void endElement(String uri, String localName, String qName) { - - String text = null; - URLEntry info = null; - - int state = ((Integer) stateStack.peek()).intValue(); - switch (state) { - case STATE_IGNORED_ELEMENT : - case STATE_ARCHIVE : - case STATE_CATEGORY : - stateStack.pop(); - break; - - case STATE_INITIAL : - internalError(Messages.DefaultSiteParser_ParsingStackBackToInitialState); - break; - - case STATE_SITE : - stateStack.pop(); - if (objectStack.peek() instanceof String) { - text = (String) objectStack.pop(); - SiteModel site = (SiteModel) objectStack.peek(); - site.getDescription().setAnnotation(text); - } - //do not pop the object - break; - - case STATE_FEATURE : - stateStack.pop(); - objectStack.pop(); - break; - - case STATE_CATEGORY_DEF : - stateStack.pop(); - if (objectStack.peek() instanceof String) { - text = (String) objectStack.pop(); - SiteCategory category = (SiteCategory) objectStack.peek(); - category.setDescription(text); - } - objectStack.pop(); - break; - - case STATE_DESCRIPTION_SITE : - stateStack.pop(); - text = ""; //$NON-NLS-1$ - while (objectStack.peek() instanceof String) { - // add text, preserving at most one space between text fragments - String newText = (String) objectStack.pop(); - if (trailingSpace(newText) && !leadingSpace(text)) { - text = " " + text; //$NON-NLS-1$ - } - text = newText.trim() + text; - if (leadingSpace(newText) && !leadingSpace(text)) { - text = " " + text; //$NON-NLS-1$ - } - } - text = text.trim(); - - info = (URLEntry) objectStack.pop(); - if (text != null) - info.setAnnotation(text); - - SiteModel siteModel = (SiteModel) objectStack.peek(); - // override description. - // do not raise error as previous description may be default one - // when parsing site tag - if (DESCRIPTION_SITE_ALREADY_SEEN) - debug(NLS.bind(Messages.DefaultSiteParser_ElementAlreadySet, (new String[] {getState(state)}))); - siteModel.setDescription(info); - DESCRIPTION_SITE_ALREADY_SEEN = true; - break; - - case STATE_DESCRIPTION_CATEGORY_DEF : - stateStack.pop(); - text = ""; //$NON-NLS-1$ - while (objectStack.peek() instanceof String) { - // add text, preserving at most one space between text fragments - String newText = (String) objectStack.pop(); - if (trailingSpace(newText) && !leadingSpace(text)) { - text = " " + text; //$NON-NLS-1$ - } - text = newText.trim() + text; - if (leadingSpace(newText) && !leadingSpace(text)) { - text = " " + text; //$NON-NLS-1$ - } - } - text = text.trim(); - - info = (URLEntry) objectStack.pop(); - if (text != null) - info.setAnnotation(text); - - SiteCategory category = (SiteCategory) objectStack.peek(); - if (category.getDescription() != null) - internalError(NLS.bind(Messages.DefaultSiteParser_ElementAlreadySet, (new String[] {getState(state), category.getLabel()}))); - else - category.setDescription(info.getAnnotation()); - break; - - default : - internalError(NLS.bind(Messages.DefaultSiteParser_UnknownEndState, (new String[] {getState(state)}))); - break; - } - - if (Tracing.DEBUG_GENERATOR_PARSING) - debug("End Element:" + uri + ":" + localName + ":" + qName);//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - - /* - * Handles an error state specified by the status. The collection of all logged status - * objects can be accessed using <code>getStatus()</code>. - * - * @param error a status detailing the error condition - */ - private void error(IStatus error) { - - if (status == null) { - status = new MultiStatus(PLUGIN_ID, 0, Messages.DefaultSiteParser_ErrorParsingSite, null); - } - - status.add(error); - if (Tracing.DEBUG_GENERATOR_PARSING) - LogHelper.log(error); - } - - /** - * Handle errors - * @see DefaultHandler#error(SAXParseException) - * @since 2.0 - */ - public void error(SAXParseException ex) { - logStatus(ex); - } - - /** - * Handle fatal errors - * @see DefaultHandler#fatalError(SAXParseException) - * @exception SAXException - * @since 2.0 - */ - public void fatalError(SAXParseException ex) throws SAXException { - logStatus(ex); - throw ex; - } - - /* - * return the state as String - */ - private String getState(int state) { - - switch (state) { - case STATE_IGNORED_ELEMENT : - return "Ignored"; //$NON-NLS-1$ - - case STATE_INITIAL : - return "Initial"; //$NON-NLS-1$ - - case STATE_SITE : - return "Site"; //$NON-NLS-1$ - - case STATE_FEATURE : - return "Feature"; //$NON-NLS-1$ - - case STATE_ARCHIVE : - return "Archive"; //$NON-NLS-1$ - - case STATE_CATEGORY : - return "Category"; //$NON-NLS-1$ - - case STATE_CATEGORY_DEF : - return "Category Def"; //$NON-NLS-1$ - - case STATE_DESCRIPTION_CATEGORY_DEF : - return "Description / Category Def"; //$NON-NLS-1$ - - case STATE_DESCRIPTION_SITE : - return "Description / Site"; //$NON-NLS-1$ - - default : - return Messages.DefaultSiteParser_UnknownState; - } - } - - /** - * Returns all status objects accumulated by the parser. - * - * @return multi-status containing accumulated status, or <code>null</code>. - * @since 2.0 - */ - public MultiStatus getStatus() { - return status; - } - - private void handleCategoryDefState(String elementName, Attributes attributes) { - if (elementName.equals(FEATURE)) { - stateStack.push(new Integer(STATE_FEATURE)); - processFeature(attributes); - } else if (elementName.equals(ARCHIVE)) { - stateStack.push(new Integer(STATE_ARCHIVE)); - processArchive(attributes); - } else if (elementName.equals(CATEGORY_DEF)) { - stateStack.push(new Integer(STATE_CATEGORY_DEF)); - processCategoryDef(attributes); - } else if (elementName.equals(DESCRIPTION)) { - stateStack.push(new Integer(STATE_DESCRIPTION_CATEGORY_DEF)); - processInfo(attributes); - } else - internalErrorUnknownTag(NLS.bind(Messages.DefaultSiteParser_UnknownElement, (new String[] {elementName, getState(currentState)}))); - } - - private void handleCategoryState(String elementName, Attributes attributes) { - if (elementName.equals(DESCRIPTION)) { - stateStack.push(new Integer(STATE_DESCRIPTION_SITE)); - processInfo(attributes); - } else if (elementName.equals(FEATURE)) { - stateStack.push(new Integer(STATE_FEATURE)); - processFeature(attributes); - } else if (elementName.equals(ARCHIVE)) { - stateStack.push(new Integer(STATE_ARCHIVE)); - processArchive(attributes); - } else if (elementName.equals(CATEGORY_DEF)) { - stateStack.push(new Integer(STATE_CATEGORY_DEF)); - processCategoryDef(attributes); - } else if (elementName.equals(CATEGORY)) { - stateStack.push(new Integer(STATE_CATEGORY)); - processCategory(attributes); - } else - internalErrorUnknownTag(NLS.bind(Messages.DefaultSiteParser_UnknownElement, (new String[] {elementName, getState(currentState)}))); - } - - private void handleFeatureState(String elementName, Attributes attributes) { - if (elementName.equals(DESCRIPTION)) { - stateStack.push(new Integer(STATE_DESCRIPTION_SITE)); - processInfo(attributes); - } else if (elementName.equals(FEATURE)) { - stateStack.push(new Integer(STATE_FEATURE)); - processFeature(attributes); - } else if (elementName.equals(ARCHIVE)) { - stateStack.push(new Integer(STATE_ARCHIVE)); - processArchive(attributes); - } else if (elementName.equals(CATEGORY_DEF)) { - stateStack.push(new Integer(STATE_CATEGORY_DEF)); - processCategoryDef(attributes); - } else if (elementName.equals(CATEGORY)) { - stateStack.push(new Integer(STATE_CATEGORY)); - processCategory(attributes); - } else - internalErrorUnknownTag(NLS.bind(Messages.DefaultSiteParser_UnknownElement, (new String[] {elementName, getState(currentState)}))); - } - - private void handleInitialState(String elementName, Attributes attributes) throws SAXException { - if (elementName.equals(SITE)) { - stateStack.push(new Integer(STATE_SITE)); - processSite(attributes); - } else { - internalErrorUnknownTag(NLS.bind(Messages.DefaultSiteParser_UnknownElement, (new String[] {elementName, getState(currentState)}))); - // what we received was not a site.xml, no need to continue - throw new SAXException(Messages.DefaultSiteParser_InvalidXMLStream); - } - - } - - private void handleSiteState(String elementName, Attributes attributes) { - if (elementName.equals(DESCRIPTION)) { - stateStack.push(new Integer(STATE_DESCRIPTION_SITE)); - processInfo(attributes); - } else if (elementName.equals(FEATURE)) { - stateStack.push(new Integer(STATE_FEATURE)); - processFeature(attributes); - } else if (elementName.equals(ARCHIVE)) { - stateStack.push(new Integer(STATE_ARCHIVE)); - processArchive(attributes); - } else if (elementName.equals(CATEGORY_DEF)) { - stateStack.push(new Integer(STATE_CATEGORY_DEF)); - processCategoryDef(attributes); - } else - internalErrorUnknownTag(NLS.bind(Messages.DefaultSiteParser_UnknownElement, (new String[] {elementName, getState(currentState)}))); - } - - /* - * - */ - private void internalError(String message) { - error(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, message, null)); - } - - /* - * - */ - private void internalErrorUnknownTag(String msg) { - stateStack.push(new Integer(STATE_IGNORED_ELEMENT)); - internalError(msg); - } - - private boolean leadingSpace(String str) { - if (str.length() <= 0) { - return false; - } - return Character.isWhitespace(str.charAt(0)); - } - - /* - * - */ - private void logStatus(SAXParseException ex) { - String name = ex.getSystemId(); - if (name == null) - name = ""; //$NON-NLS-1$ - else - name = name.substring(1 + name.lastIndexOf("/")); //$NON-NLS-1$ - - String msg; - if (name.equals("")) //$NON-NLS-1$ - msg = NLS.bind(Messages.DefaultSiteParser_ErrorParsing, (new String[] {ex.getMessage()})); - else { - String[] values = new String[] {name, Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber()), ex.getMessage()}; - msg = NLS.bind(Messages.DefaultSiteParser_ErrorlineColumnMessage, values); - } - error(new Status(IStatus.ERROR, PLUGIN_ID, msg, ex)); - } - - /** - * Parses the specified input steam and constructs a site model. - * The input stream is not closed as part of this operation. - * - * @param in input stream - * @return site model - * @exception SAXException - * @exception IOException - * @since 2.0 - */ - public SiteModel parse(InputStream in) throws SAXException, IOException { - stateStack.push(new Integer(STATE_INITIAL)); - currentState = ((Integer) stateStack.peek()).intValue(); - parser.parse(new InputSource(in), this); - if (objectStack.isEmpty()) - throw new SAXException(Messages.DefaultSiteParser_NoSiteTag); - if (objectStack.peek() instanceof SiteModel) { - SiteModel site = (SiteModel) objectStack.pop(); - site.setMessageKeys(messageKeys); - return site; - } - String stack = ""; //$NON-NLS-1$ - Iterator iter = objectStack.iterator(); - while (iter.hasNext()) { - stack = stack + iter.next().toString() + "\r\n"; //$NON-NLS-1$ - } - throw new SAXException(NLS.bind(Messages.DefaultSiteParser_WrongParsingStack, (new String[] {stack}))); - } - - /* - * process archive info - */ - private void processArchive(Attributes attributes) { - URLEntry archive = new URLEntry(); - String id = attributes.getValue("path"); //$NON-NLS-1$ - if (id == null || id.trim().equals("")) { //$NON-NLS-1$ - internalError(NLS.bind(Messages.DefaultSiteParser_Missing, (new String[] {"path", getState(currentState)}))); //$NON-NLS-1$ - } - - archive.setAnnotation(id); - - String url = attributes.getValue("url"); //$NON-NLS-1$ - if (url == null || url.trim().equals("")) { //$NON-NLS-1$ - internalError(NLS.bind(Messages.DefaultSiteParser_Missing, (new String[] {"archive", getState(currentState)}))); //$NON-NLS-1$ - } else { - archive.setURL(url); - - SiteModel site = (SiteModel) objectStack.peek(); - site.addArchive(archive); - } - if (Tracing.DEBUG_GENERATOR_PARSING) - debug("End processing Archive: path:" + id + " url:" + url);//$NON-NLS-1$ //$NON-NLS-2$ - - } - - /* - * process the Category info - */ - private void processCategory(Attributes attributes) { - String category = attributes.getValue("name"); //$NON-NLS-1$ - SiteFeature feature = (SiteFeature) objectStack.peek(); - feature.addCategoryName(category); - - if (Tracing.DEBUG_GENERATOR_PARSING) - debug("End processing Category: name:" + category); //$NON-NLS-1$ - } - - /* - * process category def info - */ - private void processCategoryDef(Attributes attributes) { - SiteCategory category = new SiteCategory(); - String name = attributes.getValue("name"); //$NON-NLS-1$ - String label = attributes.getValue("label"); //$NON-NLS-1$ - checkTranslated(label); - category.setName(name); - category.setLabel(label); - - SiteModel site = (SiteModel) objectStack.peek(); - site.addCategory(category); - objectStack.push(category); - - if (Tracing.DEBUG_GENERATOR_PARSING) - debug("End processing CategoryDef: name:" + name + " label:" + label); //$NON-NLS-1$ //$NON-NLS-2$ - } - - /* - * process feature info - */ - private void processFeature(Attributes attributes) { - SiteFeature feature = new SiteFeature(); - - // feature location on the site - String urlInfo = attributes.getValue("url"); //$NON-NLS-1$ - // identifier and version - String id = attributes.getValue("id"); //$NON-NLS-1$ - String ver = attributes.getValue("version"); //$NON-NLS-1$ - - boolean noURL = (urlInfo == null || urlInfo.trim().equals("")); //$NON-NLS-1$ - boolean noId = (id == null || id.trim().equals("")); //$NON-NLS-1$ - boolean noVersion = (ver == null || ver.trim().equals("")); //$NON-NLS-1$ - - // We need to have id and version, or the url, or both. - if (noURL) { - if (noId || noVersion) - internalError(NLS.bind(Messages.DefaultSiteParser_Missing, (new String[] {"url", getState(currentState)}))); //$NON-NLS-1$ - else - // default url - urlInfo = FEATURES + id + '_' + ver; // - } - - feature.setURLString(urlInfo); - - // if one is null, and not the other - if (noId ^ noVersion) { - String[] values = new String[] {id, ver, getState(currentState)}; - log(NLS.bind(Messages.DefaultFeatureParser_IdOrVersionInvalid, values)); - } else { - feature.setFeatureIdentifier(id); - feature.setFeatureVersion(ver); - } - - SiteModel site = (SiteModel) objectStack.peek(); - site.addFeature(feature); - - objectStack.push(feature); - - if (Tracing.DEBUG_GENERATOR_PARSING) - debug("End Processing DefaultFeature Tag: url:" + urlInfo); //$NON-NLS-1$ - - } - - /* - * process URL info with element text - */ - private void processInfo(Attributes attributes) { - URLEntry inf = new URLEntry(); - String infoURL = attributes.getValue("url"); //$NON-NLS-1$ - inf.setURL(infoURL); - - if (Tracing.DEBUG_GENERATOR_PARSING) - debug("Processed Info: url:" + infoURL); //$NON-NLS-1$ - - objectStack.push(inf); - } - - /* - * process site info - */ - private void processSite(Attributes attributes) { - // create site map - SiteModel site = new SiteModel(); - - // provide default description URL - // If <description> is specified, for the site, it takes precedence - URLEntry description = new URLEntry(); - description.setURL(DEFAULT_INFO_URL); - site.setDescription(description); - - // get mirrors, if any - String mirrorsURL = attributes.getValue("mirrorsURL"); //$NON-NLS-1$ - if (mirrorsURL != null && mirrorsURL.trim().length() > 0) { - site.setMirrorsURLString(mirrorsURL); - } - - if (attributes.getValue(ASSOCIATE_SITES_URL) != null) - site.setAssociateSites(getAssociateSites(attributes.getValue(ASSOCIATE_SITES_URL))); - - objectStack.push(site); - } - - /** - * Handle start of element tags - * @see DefaultHandler#startElement(String, String, String, Attributes) - * @since 2.0 - */ - public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { - - if (Tracing.DEBUG_GENERATOR_PARSING) { - debug("State: " + currentState); //$NON-NLS-1$ - debug("Start Element: uri:" + uri + " local Name:" + localName + " qName:" + qName);//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - - switch (currentState) { - case STATE_IGNORED_ELEMENT : - internalErrorUnknownTag(NLS.bind(Messages.DefaultSiteParser_UnknownElement, (new String[] {localName, getState(currentState)}))); - break; - case STATE_INITIAL : - handleInitialState(localName, attributes); - break; - - case STATE_SITE : - handleSiteState(localName, attributes); - break; - - case STATE_FEATURE : - handleFeatureState(localName, attributes); - break; - - case STATE_ARCHIVE : - handleSiteState(localName, attributes); - break; - - case STATE_CATEGORY : - handleCategoryState(localName, attributes); - break; - - case STATE_CATEGORY_DEF : - handleCategoryDefState(localName, attributes); - break; - - case STATE_DESCRIPTION_SITE : - handleSiteState(localName, attributes); - break; - - case STATE_DESCRIPTION_CATEGORY_DEF : - handleSiteState(localName, attributes); - break; - - default : - internalErrorUnknownTag(NLS.bind(Messages.DefaultSiteParser_UnknownStartState, (new String[] {getState(currentState)}))); - break; - } - int newState = ((Integer) stateStack.peek()).intValue(); - if (newState != STATE_IGNORED_ELEMENT) - currentState = newState; - - } - - private boolean trailingSpace(String str) { - if (str.length() <= 0) { - return false; - } - return Character.isWhitespace(str.charAt(str.length() - 1)); - } - - // Add translatable strings from the site.xml - // to the list of message keys. - private void checkTranslated(String value) { - if (value != null && value.length() > 1 && value.startsWith("%")) //$NON-NLS-1$ - messageKeys.add(value.substring(1)); - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/FeatureParser.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/FeatureParser.java deleted file mode 100644 index c6a06273e..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/FeatureParser.java +++ /dev/null @@ -1,363 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.generator.features; - -import java.io.*; -import java.net.URL; -import java.util.*; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import javax.xml.parsers.*; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.metadata.generator.Activator; -import org.eclipse.equinox.internal.p2.metadata.generator.LocalizationHelper; -import org.eclipse.equinox.internal.provisional.p2.metadata.generator.Feature; -import org.eclipse.equinox.internal.provisional.p2.metadata.generator.FeatureEntry; -import org.eclipse.osgi.util.NLS; -import org.xml.sax.*; -import org.xml.sax.helpers.DefaultHandler; - -/** - * Default feature parser. - * Parses the feature manifest file as defined by the platform. - * - * @since 3.0 - */ -public class FeatureParser extends DefaultHandler { - - private final static SAXParserFactory parserFactory = SAXParserFactory.newInstance(); - private SAXParser parser; - protected Feature result; - private URL url; - private StringBuffer characters = null; - - private Properties messages = null; - private List messageKeys = null; - - public FeatureParser() { - this(true); - } - - protected FeatureParser(boolean createParser) { - super(); - if (!createParser) - return; - try { - parserFactory.setNamespaceAware(true); - this.parser = parserFactory.newSAXParser(); - } catch (ParserConfigurationException e) { - System.out.println(e); - } catch (SAXException e) { - System.out.println(e); - } - } - - public void characters(char[] ch, int start, int length) throws SAXException { - if (characters == null) - return; - characters.append(ch, start, length); - } - - protected Feature createFeature(String id, String version) { - return new Feature(id, version); - } - - public void endElement(String uri, String localName, String qName) throws SAXException { - if (characters == null) - return; - if ("description".equals(localName)) { //$NON-NLS-1$ - result.setDescription(localize(characters.toString().trim())); - } else if ("license".equals(localName)) { //$NON-NLS-1$ - result.setLicense(localize(characters.toString().trim())); - } else if ("copyright".equals(localName)) { //$NON-NLS-1$ - result.setCopyright(localize(characters.toString().trim())); - } - characters = null; - } - - private void loadProperties(File directory, Properties properties) { - //skip directories that don't contain a feature.properties file - File file = new File(directory, "feature.properties"); //$NON-NLS-1$ - if (!file.exists()) - return; - try { - InputStream input = new BufferedInputStream(new FileInputStream(file)); - try { - properties.load(input); - } finally { - if (input != null) - input.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - private void loadProperties(JarFile jar, Properties properties) { - JarEntry entry = jar.getJarEntry("feature.properties"); //$NON-NLS-1$ - if (entry == null) - return; - try { - InputStream input = new BufferedInputStream(jar.getInputStream(entry)); - try { - properties.load(input); - } finally { - if (input != null) - input.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - private String localize(String value) { - if (messages == null || value == null) - return value; - if (!value.startsWith("%")) //$NON-NLS-1$ - return value; - String key = value.substring(1); - messageKeys.add(key); - return value; - } - - /** - * Parses the specified location and constructs a feature. The given location - * should be either the location of the feature JAR or the directory containing - * the feature. - * - * @param location the location of the feature to parse. - */ - public Feature parse(File location) { - if (!location.exists()) - return null; - - Feature feature = null; - Properties properties = new Properties(); - - if (location.isDirectory()) { - //skip directories that don't contain a feature.xml file - File file = new File(location, "feature.xml"); //$NON-NLS-1$ - if (!file.exists()) - return null; - loadProperties(location, properties); - try { - InputStream input = new BufferedInputStream(new FileInputStream(file)); - feature = parse(input, properties); - if (feature != null) { - String[] keyStrings = (String[]) messageKeys.toArray(new String[messageKeys.size()]); - feature.setLocalizations(LocalizationHelper.getDirPropertyLocalizations(location, "feature", null, keyStrings)); //$NON-NLS-1$ - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } else if (location.getName().endsWith(".jar")) { //$NON-NLS-1$ - JarFile jar = null; - try { - jar = new JarFile(location); - loadProperties(jar, properties); - JarEntry entry = jar.getJarEntry("feature.xml"); //$NON-NLS-1$ - if (entry == null) - return null; - InputStream input = new BufferedInputStream(jar.getInputStream(entry)); - feature = parse(input, properties); - if (feature != null) { - String[] keyStrings = (String[]) messageKeys.toArray(new String[messageKeys.size()]); - feature.setLocalizations(LocalizationHelper.getJarPropertyLocalizations(location, "feature", null, keyStrings)); //$NON-NLS-1$ - } - } catch (IOException e) { - e.printStackTrace(); - } catch (SecurityException e) { - LogHelper.log(new Status(IStatus.WARNING, Activator.ID, "Exception parsing feature: " + location.getAbsolutePath(), e)); //$NON-NLS-1$ - } finally { - try { - if (jar != null) - jar.close(); - } catch (IOException e) { - // - } - } - } - return feature; - } - - /** - * Parse the given input stream and return a feature object - * or null. This method closes the input stream. - */ - public Feature parse(InputStream in, Properties messages) { - this.messages = messages; - this.messageKeys = new ArrayList(messages.size()); - result = null; - try { - parser.parse(new InputSource(in), this); - } catch (SAXException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - in.close(); - } catch (IOException e1) { - // Utils.log(e1.getLocalizedMessage()); - } - } - return result; - } - - private void processCopyright(Attributes attributes) { - result.setCopyrightURL(attributes.getValue("url")); //$NON-NLS-1$ - characters = new StringBuffer(); - } - - private void processDescription(Attributes attributes) { - result.setDescriptionURL(attributes.getValue("url")); //$NON-NLS-1$ - characters = new StringBuffer(); - } - - private void processDiscoverySite(Attributes attributes) { - //ignore discovery sites of type 'web' - if ("web".equals(attributes.getValue("type"))) //$NON-NLS-1$ //$NON-NLS-2$ - return; - result.addDiscoverySite(attributes.getValue("label"), attributes.getValue("url")); //$NON-NLS-1$ //$NON-NLS-2$ - } - - protected void processFeature(Attributes attributes) { - String id = attributes.getValue("id"); //$NON-NLS-1$ - String ver = attributes.getValue("version"); //$NON-NLS-1$ - - if (id == null || id.trim().equals("") //$NON-NLS-1$ - || ver == null || ver.trim().equals("")) { //$NON-NLS-1$ - // System.out.println(NLS.bind(Messages.FeatureParser_IdOrVersionInvalid, (new String[] { id, ver}))); - } else { - result = createFeature(id, ver); - result.setApplication(attributes.getValue("application")); //$NON-NLS-1$ - result.setPlugin(attributes.getValue("plugin")); //$NON-NLS-1$ - result.setExclusive(Boolean.valueOf(attributes.getValue("exclusive")).booleanValue()); //$NON-NLS-1$ - result.setPrimary(Boolean.valueOf(attributes.getValue("primary")).booleanValue()); //$NON-NLS-1$ - - //TODO rootURLs - if (url != null && "file".equals(url.getProtocol())) { //$NON-NLS-1$ - File f = new File(url.getFile().replace('/', File.separatorChar)); - result.setURL("features" + "/" + f.getParentFile().getName() + "/");// + f.getName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } else { - // externalized URLs might be in relative form, ensure they are absolute - // feature.setURL(Utils.makeAbsolute(Utils.getInstallURL(), url).toExternalForm()); - } - - result.setProviderName(localize(attributes.getValue("provider-name"))); //$NON-NLS-1$ - result.setLabel(localize(attributes.getValue("label"))); //$NON-NLS-1$ - - // Utils.debug("End process DefaultFeature tag: id:" +id + " ver:" +ver + " url:" + feature.getURL()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - } - - private void processImport(Attributes attributes) { - String id = attributes.getValue("feature"); //$NON-NLS-1$ - FeatureEntry entry = null; - if (id != null) { - if ("true".equalsIgnoreCase(attributes.getValue("patch"))) { //$NON-NLS-1$ //$NON-NLS-2$ - entry = FeatureEntry.createRequires(id, attributes.getValue("version"), "perfect", attributes.getValue("filter"), false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - entry.setPatch(true); - } else { - entry = FeatureEntry.createRequires(id, attributes.getValue("version"), attributes.getValue("match"), attributes.getValue("filter"), false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - } else { - id = attributes.getValue("plugin"); //$NON-NLS-1$ - entry = FeatureEntry.createRequires(id, attributes.getValue("version"), attributes.getValue("match"), attributes.getValue("filter"), true); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - result.addEntry(entry); - } - - private void processIncludes(Attributes attributes) { - FeatureEntry entry = new FeatureEntry(attributes.getValue("id"), attributes.getValue("version"), false); //$NON-NLS-1$ //$NON-NLS-2$ - String flag = attributes.getValue("optional"); //$NON-NLS-1$ - if (flag != null) - entry.setOptional(Boolean.valueOf(flag).booleanValue()); - setEnvironment(attributes, entry); - result.addEntry(entry); - } - - private void processInstallHandler(Attributes attributes) { - result.setInstallHandler(attributes.getValue("handler")); //$NON-NLS-1$ - result.setInstallHandlerLibrary(attributes.getValue("library")); //$NON-NLS-1$ - result.setInstallHandlerURL(attributes.getValue("url")); //$NON-NLS-1$ - } - - private void processLicense(Attributes attributes) { - result.setLicenseURL(attributes.getValue("url")); //$NON-NLS-1$ - characters = new StringBuffer(); - } - - private void processPlugin(Attributes attributes) { - String id = attributes.getValue("id"); //$NON-NLS-1$ - String version = attributes.getValue("version"); //$NON-NLS-1$ - - if (id == null || id.trim().equals("") || version == null || version.trim().equals("")) { //$NON-NLS-1$ //$NON-NLS-2$ - System.out.println(NLS.bind("FeatureParser#processPlugin, ID {0} or version {1} invalid", (new String[] {id, version}))); //$NON-NLS-1$ - } else { - FeatureEntry plugin = new FeatureEntry(id, version, true); - setEnvironment(attributes, plugin); - String unpack = attributes.getValue("unpack"); //$NON-NLS-1$ - if (unpack != null) - plugin.setUnpack(Boolean.valueOf(unpack).booleanValue()); - String fragment = attributes.getValue("fragment"); //$NON-NLS-1$ - if (fragment != null) - plugin.setFragment(Boolean.valueOf(fragment).booleanValue()); - String filter = attributes.getValue("filter"); //$NON-NLS-1$ - if (filter != null) - plugin.setFilter(filter); - result.addEntry(plugin); - - // Utils.debug("End process DefaultFeature tag: id:" + id + " ver:" + ver + " url:" + feature.getURL()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - } - - private void processUpdateSite(Attributes attributes) { - result.setUpdateSiteLabel(attributes.getValue("label")); //$NON-NLS-1$ - result.setUpdateSiteURL(attributes.getValue("url")); //$NON-NLS-1$ - } - - private void setEnvironment(Attributes attributes, FeatureEntry entry) { - String os = attributes.getValue("os"); //$NON-NLS-1$ - String ws = attributes.getValue("ws"); //$NON-NLS-1$ - String nl = attributes.getValue("nl"); //$NON-NLS-1$ - String arch = attributes.getValue("arch"); //$NON-NLS-1$ - entry.setEnvironment(os, ws, arch, nl); - } - - public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { - // Utils.debug("Start Element: uri:" + uri + " local Name:" + localName + " qName:" + qName); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if ("plugin".equals(localName)) { //$NON-NLS-1$ - processPlugin(attributes); - } else if ("description".equals(localName)) { //$NON-NLS-1$ - processDescription(attributes); - } else if ("license".equals(localName)) { //$NON-NLS-1$ - processLicense(attributes); - } else if ("copyright".equals(localName)) { //$NON-NLS-1$ - processCopyright(attributes); - } else if ("feature".equals(localName)) { //$NON-NLS-1$ - processFeature(attributes); - } else if ("import".equals(localName)) { //$NON-NLS-1$ - processImport(attributes); - } else if ("includes".equals(localName)) { //$NON-NLS-1$ - processIncludes(attributes); - } else if ("install-handler".equals(localName)) { //$NON-NLS-1$ - processInstallHandler(attributes); - } else if ("update".equals(localName)) { //$NON-NLS-1$ - processUpdateSite(attributes); - } else if ("discovery".equals(localName)) { //$NON-NLS-1$ - processDiscoverySite(attributes); - } - } - -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/Messages.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/Messages.java deleted file mode 100644 index dce8bba54..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/Messages.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.generator.features; - -import org.eclipse.osgi.util.NLS; - -public final class Messages extends NLS { - - private static final String BUNDLE_NAME = "org.eclipse.equinox.internal.p2.metadata.generator.features.messages";//$NON-NLS-1$ - - public static String DefaultFeatureParser_IdOrVersionInvalid; - public static String DefaultSiteParser_NoSiteTag; - public static String DefaultSiteParser_WrongParsingStack; - public static String DefaultSiteParser_UnknownElement; - public static String DefaultSiteParser_UnknownStartState; - public static String DefaultSiteParser_Missing; - public static String DefaultSiteParser_ParsingStackBackToInitialState; - public static String DefaultSiteParser_ElementAlreadySet; - public static String DefaultSiteParser_UnknownEndState; - public static String DefaultSiteParser_ErrorParsing; - public static String DefaultSiteParser_ErrorlineColumnMessage; - public static String DefaultSiteParser_ErrorParsingSite; - public static String DefaultSiteParser_UnknownState; - public static String DefaultSiteParser_InvalidXMLStream; - public static String DefaultSiteParser_mirrors; - static { - NLS.initializeMessages(BUNDLE_NAME, Messages.class); - } - - private Messages() { - // Do not instantiate - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/ProductFile.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/ProductFile.java deleted file mode 100644 index fd1e55017..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/ProductFile.java +++ /dev/null @@ -1,514 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.p2.metadata.generator.features; - -import java.io.*; -import java.util.*; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import org.xml.sax.Attributes; -import org.xml.sax.InputSource; -import org.xml.sax.helpers.DefaultHandler; - -/** - * - * @since 3.1 - */ -public class ProductFile extends DefaultHandler { - private final static SAXParserFactory parserFactory = SAXParserFactory.newInstance(); - - private static final String PROGRAM_ARGS = "programArgs"; //$NON-NLS-1$ - private static final String PROGRAM_ARGS_LINUX = "programArgsLin"; //$NON-NLS-1$ - private static final String PROGRAM_ARGS_MAC = "programArgsMac"; //$NON-NLS-1$ - private static final String PROGRAM_ARGS_SOLARIS = "programArgsSol"; //$NON-NLS-1$ - private static final String PROGRAM_ARGS_WIN = "programArgsWin"; //$NON-NLS-1$ - private static final String VM_ARGS = "vmArgs"; //$NON-NLS-1$ - private static final String VM_ARGS_LINUX = "vmArgsLin"; //$NON-NLS-1$ - private static final String VM_ARGS_MAC = "vmArgsMac"; //$NON-NLS-1$ - private static final String VM_ARGS_SOLARIS = "vmArgsSol"; //$NON-NLS-1$ - private static final String VM_ARGS_WIN = "vmArgsWin"; //$NON-NLS-1$ - - private static final String SOLARIS_LARGE = "solarisLarge"; //$NON-NLS-1$ - private static final String SOLARIS_MEDIUM = "solarisMedium"; //$NON-NLS-1$ - private static final String SOLARIS_SMALL = "solarisSmall"; //$NON-NLS-1$ - private static final String SOLARIS_TINY = "solarisTiny"; //$NON-NLS-1$ - private static final String WIN32_16_LOW = "winSmallLow"; //$NON-NLS-1$ - private static final String WIN32_16_HIGH = "winSmallHigh"; //$NON-NLS-1$ - private static final String WIN32_24_LOW = "win24Low"; //$NON-NLS-1$ - private static final String WIN32_32_LOW = "winMediumLow"; //$NON-NLS-1$ - private static final String WIN32_32_HIGH = "winMediumHigh"; //$NON-NLS-1$ - private static final String WIN32_48_LOW = "winLargeLow"; //$NON-NLS-1$ - private static final String WIN32_48_HIGH = "winLargeHigh"; //$NON-NLS-1$ - - private static final String OS_WIN32 = "win32";//$NON-NLS-1$ - private static final String OS_LINUX = "linux";//$NON-NLS-1$ - private static final String OS_SOLARIS = "solaris";//$NON-NLS-1$ - private static final String OS_MACOSX = "macosx";//$NON-NLS-1$ - - private static final String PRODUCT = "product"; //$NON-NLS-1$ - private static final String CONFIG_INI = "configIni"; //$NON-NLS-1$ - private static final String LAUNCHER = "launcher"; //$NON-NLS-1$ - private static final String LAUNCHER_ARGS = "launcherArgs"; //$NON-NLS-1$ - private static final String PLUGINS = "plugins"; //$NON-NLS-1$ - private static final String FEATURES = "features"; //$NON-NLS-1$ - private static final String P_USE_ICO = "useIco"; //$NON-NLS-1$ - - //These constants form a small state machine to parse the .product file - private static final int STATE_START = 0; - private static final int STATE_PRODUCT = 1; - private static final int STATE_LAUNCHER = 2; - private static final int STATE_LAUNCHER_ARGS = 3; - private static final int STATE_PLUGINS = 4; - private static final int STATE_FEATURES = 5; - private static final int STATE_PROGRAM_ARGS = 6; - private static final int STATE_PROGRAM_ARGS_LINUX = 7; - private static final int STATE_PROGRAM_ARGS_MAC = 8; - private static final int STATE_PROGRAM_ARGS_SOLARIS = 9; - private static final int STATE_PROGRAM_ARGS_WIN = 10; - private static final int STATE_VM_ARGS = 11; - private static final int STATE_VM_ARGS_LINUX = 12; - private static final int STATE_VM_ARGS_MAC = 13; - private static final int STATE_VM_ARGS_SOLARIS = 14; - private static final int STATE_VM_ARGS_WIN = 15; - private static final int STATE_CONFIG_INI = 16; - - private int state = STATE_START; - - private final SAXParser parser; - private String currentOS = null; - private boolean useIco = false; - private final ArrayList result = new ArrayList(6); - private final Map platformSpecificConfigPaths = new HashMap(); - private String configPlatform = null; - private String platformConfigPath = null; - private String launcherName = null; - private String id = null; - private String uid = null; - private boolean useFeatures = false; - private List plugins = null; - private List fragments = null; - private List features = null; - private String productName = null; - private String version = null; - - private Properties launcherArgs = new Properties(); - - private static String normalize(String text) { - if (text == null || text.trim().length() == 0) - return ""; //$NON-NLS-1$ - - text = text.replaceAll("\\r|\\n|\\f|\\t", " "); //$NON-NLS-1$ //$NON-NLS-2$ - return text.replaceAll("\\s+", " "); //$NON-NLS-1$ //$NON-NLS-2$ - } - - /** - * Constructs a feature parser. - */ - public ProductFile(String location, String os) throws Exception { - super(); - this.currentOS = os; - - parserFactory.setNamespaceAware(true); - parser = parserFactory.newSAXParser(); - InputStream in = new BufferedInputStream(new FileInputStream(location)); - try { - parser.parse(new InputSource(in), this); - } finally { - if (in != null) - in.close(); - } - } - - public List getPlugins() { - return getPlugins(true); - } - - public List getPlugins(boolean includeFragments) { - List p = plugins != null ? plugins : Collections.EMPTY_LIST; - if (!includeFragments) - return p; - - List f = fragments != null ? fragments : Collections.EMPTY_LIST; - int size = p.size() + f.size(); - if (size == 0) - return Collections.EMPTY_LIST; - - List both = new ArrayList(size); - both.addAll(p); - both.addAll(f); - return both; - } - - public List getFeatures() { - if (features == null) - return Collections.EMPTY_LIST; - return features; - } - - public String getId() { - if (uid != null) - return uid; - return id; - } - - public String getProductId() { - return id; - } - - public String getProductName() { - return productName; - } - - public boolean useFeatures() { - return useFeatures; - } - - public String getVersion() { - return (version == null || version.length() == 0) ? "0.0.0" : version; //$NON-NLS-1$ - } - - public String getLauncherName() { - return launcherName; - } - - public String getVMArguments(String os) { - String key = null; - if (os.equals(OS_WIN32)) { - key = VM_ARGS_WIN; - } else if (os.equals(OS_LINUX)) { - key = VM_ARGS_LINUX; - } else if (os.equals(OS_MACOSX)) { - key = VM_ARGS_MAC; - } else if (os.equals(OS_SOLARIS)) { - key = VM_ARGS_SOLARIS; - } - - String prefix = launcherArgs.getProperty(VM_ARGS); - String platform = null, args = null; - if (key != null) - platform = launcherArgs.getProperty(key); - if (prefix != null) - args = platform != null ? prefix + " " + platform : prefix; //$NON-NLS-1$ - else - args = platform != null ? platform : ""; //$NON-NLS-1$ - return normalize(args); - } - - public String getProgramArguments(String os) { - String key = null; - if (os.equals(OS_WIN32)) { - key = PROGRAM_ARGS_WIN; - } else if (os.equals(OS_LINUX)) { - key = PROGRAM_ARGS_LINUX; - } else if (os.equals(OS_MACOSX)) { - key = PROGRAM_ARGS_MAC; - } else if (os.equals(OS_SOLARIS)) { - key = PROGRAM_ARGS_SOLARIS; - } - - String prefix = launcherArgs.getProperty(PROGRAM_ARGS); - String platform = null, args = null; - if (key != null) - platform = launcherArgs.getProperty(key); - if (prefix != null) - args = platform != null ? prefix + " " + platform : prefix; //$NON-NLS-1$ - else - args = platform != null ? platform : ""; //$NON-NLS-1$ - return normalize(args); - } - - public void startElement(String uri, String localName, String qName, Attributes attributes) { - switch (state) { - case STATE_START : - if (PRODUCT.equals(localName)) { - processProduct(attributes); - state = STATE_PRODUCT; - } - break; - - case STATE_PRODUCT : - if (CONFIG_INI.equals(localName)) { - processConfigIni(attributes); - state = STATE_CONFIG_INI; - } else if (LAUNCHER.equals(localName)) { - processLauncher(attributes); - state = STATE_LAUNCHER; - } else if (PLUGINS.equals(localName)) { - state = STATE_PLUGINS; - } else if (FEATURES.equals(localName)) { - state = STATE_FEATURES; - } else if (LAUNCHER_ARGS.equals(localName)) { - state = STATE_LAUNCHER_ARGS; - } - break; - - case STATE_CONFIG_INI : - processConfigIniPlatform(localName, true); - break; - - case STATE_LAUNCHER : - if (OS_SOLARIS.equals(localName)) { - processSolaris(attributes); - } else if ("win".equals(localName)) { //$NON-NLS-1$ - processWin(attributes); - } else if (OS_LINUX.equals(localName)) { - processLinux(attributes); - } else if (OS_MACOSX.equals(localName)) { - processMac(attributes); - } - if ("ico".equals(localName)) { //$NON-NLS-1$ - processIco(attributes); - } else if ("bmp".equals(localName)) { //$NON-NLS-1$ - processBmp(attributes); - } - break; - - case STATE_LAUNCHER_ARGS : - if (PROGRAM_ARGS.equals(localName)) { - state = STATE_PROGRAM_ARGS; - } else if (PROGRAM_ARGS_LINUX.equals(localName)) { - state = STATE_PROGRAM_ARGS_LINUX; - } else if (PROGRAM_ARGS_MAC.equals(localName)) { - state = STATE_PROGRAM_ARGS_MAC; - } else if (PROGRAM_ARGS_SOLARIS.equals(localName)) { - state = STATE_PROGRAM_ARGS_SOLARIS; - } else if (PROGRAM_ARGS_WIN.equals(localName)) { - state = STATE_PROGRAM_ARGS_WIN; - } else if (VM_ARGS.equals(localName)) { - state = STATE_VM_ARGS; - } else if (VM_ARGS_LINUX.equals(localName)) { - state = STATE_VM_ARGS_LINUX; - } else if (VM_ARGS_MAC.equals(localName)) { - state = STATE_VM_ARGS_MAC; - } else if (VM_ARGS_SOLARIS.equals(localName)) { - state = STATE_VM_ARGS_SOLARIS; - } else if (VM_ARGS_WIN.equals(localName)) { - state = STATE_VM_ARGS_WIN; - } - break; - - case STATE_PLUGINS : - if ("plugin".equals(localName)) { //$NON-NLS-1$ - processPlugin(attributes); - } - break; - - case STATE_FEATURES : - if ("feature".equals(localName)) { //$NON-NLS-1$ - processFeature(attributes); - } - break; - } - } - - public void endElement(String uri, String localName, String qName) { - switch (state) { - case STATE_PLUGINS : - if (PLUGINS.equals(localName)) - state = STATE_PRODUCT; - break; - case STATE_FEATURES : - if (FEATURES.equals(localName)) - state = STATE_PRODUCT; - break; - case STATE_LAUNCHER_ARGS : - if (LAUNCHER_ARGS.equals(localName)) - state = STATE_PRODUCT; - break; - case STATE_LAUNCHER : - if (LAUNCHER.equals(localName)) - state = STATE_PRODUCT; - break; - - case STATE_PROGRAM_ARGS : - case STATE_PROGRAM_ARGS_LINUX : - case STATE_PROGRAM_ARGS_MAC : - case STATE_PROGRAM_ARGS_SOLARIS : - case STATE_PROGRAM_ARGS_WIN : - case STATE_VM_ARGS : - case STATE_VM_ARGS_LINUX : - case STATE_VM_ARGS_MAC : - case STATE_VM_ARGS_SOLARIS : - case STATE_VM_ARGS_WIN : - state = STATE_LAUNCHER_ARGS; - break; - - case STATE_CONFIG_INI : - if (CONFIG_INI.equals(localName)) - state = STATE_PRODUCT; - else - processConfigIniPlatform(localName, false); - break; - } - } - - public void characters(char[] ch, int start, int length) { - switch (state) { - case STATE_PROGRAM_ARGS : - addLaunchArgumentToMap(PROGRAM_ARGS, String.valueOf(ch, start, length)); - break; - case STATE_PROGRAM_ARGS_LINUX : - addLaunchArgumentToMap(PROGRAM_ARGS_LINUX, String.valueOf(ch, start, length)); - break; - case STATE_PROGRAM_ARGS_MAC : - addLaunchArgumentToMap(PROGRAM_ARGS_MAC, String.valueOf(ch, start, length)); - break; - case STATE_PROGRAM_ARGS_SOLARIS : - addLaunchArgumentToMap(PROGRAM_ARGS_SOLARIS, String.valueOf(ch, start, length)); - break; - case STATE_PROGRAM_ARGS_WIN : - addLaunchArgumentToMap(PROGRAM_ARGS_WIN, String.valueOf(ch, start, length)); - break; - case STATE_VM_ARGS : - addLaunchArgumentToMap(VM_ARGS, String.valueOf(ch, start, length)); - break; - case STATE_VM_ARGS_LINUX : - addLaunchArgumentToMap(VM_ARGS_LINUX, String.valueOf(ch, start, length)); - break; - case STATE_VM_ARGS_MAC : - addLaunchArgumentToMap(VM_ARGS_MAC, String.valueOf(ch, start, length)); - break; - case STATE_VM_ARGS_SOLARIS : - addLaunchArgumentToMap(VM_ARGS_SOLARIS, String.valueOf(ch, start, length)); - break; - case STATE_VM_ARGS_WIN : - addLaunchArgumentToMap(VM_ARGS_WIN, String.valueOf(ch, start, length)); - break; - case STATE_CONFIG_INI : - if (platformConfigPath != null) - platformConfigPath += String.valueOf(ch, start, length); - break; - } - } - - private void addLaunchArgumentToMap(String key, String value) { - if (launcherArgs == null) - launcherArgs = new Properties(); - - String oldValue = launcherArgs.getProperty(key); - if (oldValue != null) - launcherArgs.setProperty(key, oldValue + value); - else - launcherArgs.setProperty(key, value); - } - - private void processPlugin(Attributes attributes) { - String fragment = attributes.getValue("fragment"); //$NON-NLS-1$ - if (fragment != null && new Boolean(fragment).booleanValue()) { - if (fragments == null) - fragments = new ArrayList(); - fragments.add(attributes.getValue("id")); //$NON-NLS-1$ - } else { - if (plugins == null) - plugins = new ArrayList(); - plugins.add(attributes.getValue("id")); //$NON-NLS-1$ - } - } - - private void processFeature(Attributes attributes) { - if (features == null) - features = new ArrayList(); - features.add(attributes.getValue("id")); //$NON-NLS-1$ - } - - private void processProduct(Attributes attributes) { - id = attributes.getValue("id"); //$NON-NLS-1$ - uid = attributes.getValue("uid"); //$NON-NLS-1$ - productName = attributes.getValue("name"); //$NON-NLS-1$ - String use = attributes.getValue("useFeatures"); //$NON-NLS-1$ - if (use != null) - useFeatures = Boolean.valueOf(use).booleanValue(); - version = attributes.getValue("version"); //$NON-NLS-1$ - } - - private void processConfigIni(Attributes attributes) { - String path = null; - if ("custom".equals(attributes.getValue("use"))) { //$NON-NLS-1$//$NON-NLS-2$ - path = attributes.getValue("path"); //$NON-NLS-1$ - } - String os = attributes.getValue("os"); //$NON-NLS-1$ - if (os != null && os.length() > 0) { - // TODO should we allow a platform-specific default to over-ride a custom generic path? - if (path != null) - platformSpecificConfigPaths.put(os, path); - } else if (path != null) { - // configPath = path; - } - } - - private void processConfigIniPlatform(String key, boolean begin) { - if (begin) { - configPlatform = key; - platformConfigPath = ""; //$NON-NLS-1$ - } else if (configPlatform.equals(key) && platformConfigPath.length() > 0) { - platformSpecificConfigPaths.put(key, platformConfigPath); - platformConfigPath = null; - } - } - - private void processLauncher(Attributes attributes) { - launcherName = attributes.getValue("name"); //$NON-NLS-1$ - } - - private boolean osMatch(String os) { - if (os == currentOS) - return true; - if (os == null) - return false; - return os.equals(currentOS); - } - - private void processSolaris(Attributes attributes) { - if (!osMatch(OS_SOLARIS)) - return; - result.add(attributes.getValue(SOLARIS_LARGE)); - result.add(attributes.getValue(SOLARIS_MEDIUM)); - result.add(attributes.getValue(SOLARIS_SMALL)); - result.add(attributes.getValue(SOLARIS_TINY)); - } - - private void processWin(Attributes attributes) { - if (!osMatch(OS_WIN32)) - return; - useIco = Boolean.valueOf(attributes.getValue(P_USE_ICO)).booleanValue(); - } - - private void processIco(Attributes attributes) { - if (!osMatch(OS_WIN32) || !useIco) - return; - result.add(attributes.getValue("path")); //$NON-NLS-1$ - } - - private void processBmp(Attributes attributes) { - if (!osMatch(OS_WIN32) || useIco) - return; - result.add(attributes.getValue(WIN32_16_HIGH)); - result.add(attributes.getValue(WIN32_16_LOW)); - result.add(attributes.getValue(WIN32_24_LOW)); - result.add(attributes.getValue(WIN32_32_HIGH)); - result.add(attributes.getValue(WIN32_32_LOW)); - result.add(attributes.getValue(WIN32_48_HIGH)); - result.add(attributes.getValue(WIN32_48_LOW)); - } - - private void processLinux(Attributes attributes) { - if (!osMatch(OS_LINUX)) - return; - result.add(attributes.getValue("icon")); //$NON-NLS-1$ - } - - private void processMac(Attributes attributes) { - if (!osMatch(OS_MACOSX)) - return; - result.add(attributes.getValue("icon")); //$NON-NLS-1$ - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/SiteCategory.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/SiteCategory.java deleted file mode 100644 index 8acf12360..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/SiteCategory.java +++ /dev/null @@ -1,146 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.generator.features; - -import java.util.Map; - -/** - * A category in an update site. - * - * Based on org.eclipse.update.core.model.CategoryModel. - */ -public class SiteCategory { - - private String description; - private String label; - private String name; - private Map localizations; - - /** - * Creates an uninitialized model object. - * - * @since 2.0 - */ - public SiteCategory() { - super(); - } - - /** - * Compare two category models for equality. - * - * @see Object#equals(Object) - * @since 2.0 - */ - public boolean equals(Object obj) { - boolean result = false; - if (obj instanceof SiteCategory) { - SiteCategory otherCategory = (SiteCategory) obj; - result = getName().equalsIgnoreCase(otherCategory.getName()); - } - return result; - } - - /** - * Retrieve the detailed category description - * - * @return category description, or <code>null</code>. - * @since 2.0 - */ - public String getDescription() { - return description; - } - - /** - * Retrieve the non-localized displayable label for the category. - * - * @return non-localized displayable label, or <code>null</code>. - * @since 2.0 - */ - public String getLabel() { - return label; - } - - /** - * Gets the localizations for the site as a map from locale - * to the set of translated properties for that locale. - * - * @return a map from locale to property set - * @since 3.4 - */ - public Map getLocalizations() { - return this.localizations; - } - - /** - * Retrieve the name of the category. - * - * @return category name, or <code>null</code>. - * @since 2.0 - */ - public String getName() { - return name; - } - - /** - * Compute hash code for category model. - * - * @see Object#hashCode() - * @since 2.0 - */ - public int hashCode() { - return getName().hashCode(); - } - - /** - * Sets the category description. - * Throws a runtime exception if this object is marked read-only. - * - * @param description category description - * @since 2.0 - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Sets the category displayable label. - * Throws a runtime exception if this object is marked read-only. - * - * @param label displayable label, or resource key - * @since 2.0 - */ - public void setLabel(String label) { - this.label = label; - } - - /** - * Sets the localizations for the site as a map from locale - * to the set of translated properties for that locale. - * - * @param localizations as a map from locale to property set - * @since 3.4 - */ - public void setLocalizations(Map localizations) { - this.localizations = localizations; - } - - /** - * Sets the category name. - * Throws a runtime exception if this object is marked read-only. - * - * @param name category name - * @since 2.0 - */ - public void setName(String name) { - this.name = name; - } - -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/SiteFeature.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/SiteFeature.java deleted file mode 100644 index 589788197..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/SiteFeature.java +++ /dev/null @@ -1,245 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * James D Miles (IBM Corp.) - bug 191783, NullPointerException in FeatureDownloader - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.generator.features; - -import java.io.File; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -/** - * A reference to a feature in an update site.xml file. - * - * Based on org.eclipse.update.core.model.FeatureReferenceModel. - */ -public class SiteFeature { - - // performance - private URL base; - private List /* of String*/categoryNames; - private String featureId; - private String featureVersion; - - private final boolean resolved = false; - private URL url; - private String urlString; - - /* - * Compares two URL for equality - * Return false if one of them is null - */ - public static boolean sameURL(URL url1, URL url2) { - if (url1 == url2) - return true; - if (url1 == null ^ url2 == null) - return false; - - // check if URL are file: URL as we may - // have 2 URL pointing to the same featureReference - // but with different representation - // (i.e. file:/C;/ and file:C:/) - final boolean isFile1 = "file".equalsIgnoreCase(url1.getProtocol());//$NON-NLS-1$ - final boolean isFile2 = "file".equalsIgnoreCase(url2.getProtocol());//$NON-NLS-1$ - if (isFile1 && isFile2) { - File file1 = new File(url1.getFile()); - File file2 = new File(url2.getFile()); - return file1.equals(file2); - } - // URL1 xor URL2 is a file, return false. (They either both need to be files, or neither) - if (isFile1 ^ isFile2) - return false; - return getExternalForm(url1).equals(getExternalForm(url2)); - } - - /** - * Gets the external form of this URL. In particular, it trims any white space, - * removes a trailing slash and creates a lower case string. - */ - private static String getExternalForm(URL url) { - String externalForm = url.toExternalForm(); - if (externalForm == null) - return ""; //$NON-NLS-1$ - externalForm = externalForm.trim(); - if (externalForm.endsWith("/")) { //$NON-NLS-1$ - // Remove the trailing slash - externalForm = externalForm.substring(0, externalForm.length() - 1); - } - return externalForm.toLowerCase(); - } - - /** - * Creates an uninitialized feature reference model object. - */ - public SiteFeature() { - super(); - } - - /** - * Adds the name of a category this feature belongs to. - * Throws a runtime exception if this object is marked read-only. - * - * @param categoryName category name - */ - public void addCategoryName(String categoryName) { - if (this.categoryNames == null) - this.categoryNames = new ArrayList(); - if (!this.categoryNames.contains(categoryName)) - this.categoryNames.add(categoryName); - } - - private void delayedResolve() { - - // PERF: delay resolution - if (resolved) - return; - - // resolve local elements - try { - url = new URL(base, urlString); - } catch (MalformedURLException e) { - // UpdateCore.warn("", e); //$NON-NLS-1$ - } - } - - /** - * Compares 2 feature reference models for equality - * - * @param object feature reference model to compare with - * @return <code>true</code> if the two models are equal, - * <code>false</code> otherwise - */ - public boolean equals(Object object) { - if (object == null) - return false; - if (!(object instanceof SiteFeature)) - return false; - SiteFeature that = (SiteFeature) object; - if (this.featureId == null) { - if (that.featureId != null) - return false; - } else if (!this.featureId.equals(that.featureId)) - return false; - if (this.featureVersion == null) { - if (that.featureVersion != null) - return false; - } else if (!this.featureVersion.equals(that.featureVersion)) - return false; - return sameURL(this.getURL(), that.getURL()); - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (featureId == null ? 0 : featureId.hashCode()); - result = prime * result + (featureVersion == null ? 0 : featureVersion.hashCode()); - if (this.getURL() == null) - return result; - - if ("file".equalsIgnoreCase(getURL().getProtocol())) {//$NON-NLS-1$ - // If the URL is a file, then create the HashCode from the file - File f = new File(getURL().getFile()); - if (f != null) - result = prime * result + f.hashCode(); - } else - // Otherwise create it from the External form of the URL (in lower case) - result = prime * result + getExternalForm(this.getURL()).hashCode(); - return result; - } - - /** - * Returns the names of categories the referenced feature belongs to. - * - * @return an array of names, or an empty array. - */ - public String[] getCategoryNames() { - if (categoryNames == null) - return new String[0]; - - return (String[]) categoryNames.toArray(new String[0]); - } - - /** - * Returns the feature identifier as a string - * - * @return feature identifier - */ - public String getFeatureIdentifier() { - return featureId; - } - - /** - * Returns the feature version as a string - * - * @return feature version - */ - public String getFeatureVersion() { - return featureVersion; - } - - /** - * Returns the resolved URL for the feature reference. - * - * @return url string - */ - public URL getURL() { - delayedResolve(); - return url; - } - - /** - * Sets the feature identifier. - * Throws a runtime exception if this object is marked read-only. - * - * @param featureId feature identifier - */ - public void setFeatureIdentifier(String featureId) { - this.featureId = featureId; - } - - /** - * Sets the feature version. - * Throws a runtime exception if this object is marked read-only. - * - * @param featureVersion feature version - */ - public void setFeatureVersion(String featureVersion) { - this.featureVersion = featureVersion; - } - - /** - * Sets the unresolved URL for the feature reference. - * Throws a runtime exception if this object is marked read-only. - * - * @param urlString unresolved URL string - */ - public void setURLString(String urlString) { - this.urlString = urlString; - this.url = null; - } - - /** - * @see Object#toString() - */ - public String toString() { - StringBuffer buffer = new StringBuffer(); - buffer.append(getClass().toString() + " :"); //$NON-NLS-1$ - buffer.append(" at "); //$NON-NLS-1$ - if (url != null) - buffer.append(url.toExternalForm()); - return buffer.toString(); - } - -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/SiteModel.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/SiteModel.java deleted file mode 100644 index 8b784ea3b..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/SiteModel.java +++ /dev/null @@ -1,197 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.p2.metadata.generator.features; - -import java.util.*; -import org.eclipse.equinox.internal.provisional.p2.metadata.generator.URLEntry; - -/** - * A model of an update site. - * - * Copied from org.eclipse.update.core.model.SiteModel. - */ -public class SiteModel { - - private List /*of ArchiveReferenceModel*/archiveReferences; - /** - * Map of String (category id) -> SiteCategory - */ - private Map categories; - private URLEntry description; - /** - * Map of String (feature id) -> SiteFeature - */ - private List features; - private String mirrorsURLString; - private URLEntry[] associateSites; - private List messageKeys; - private Map localizations; - - /** - * Creates an uninitialized site model object. - * - * @since 2.0 - */ - public SiteModel() { - super(); - } - - /** - * Adds an archive reference model to site. - * Throws a runtime exception if this object is marked read-only. - * - * @param archiveReference archive reference model - * @since 2.0 - */ - public void addArchive(URLEntry archiveReference) { - if (this.archiveReferences == null) - this.archiveReferences = new ArrayList(); - if (!this.archiveReferences.contains(archiveReference)) - this.archiveReferences.add(archiveReference); - } - - /** - * Adds a category to the site. - * - * @param category category model - */ - public void addCategory(SiteCategory category) { - if (categories == null) - categories = new HashMap(); - if (!categories.containsKey(category.getName())) { - categories.put(category.getName(), category); - if (localizations != null && !localizations.isEmpty()) - category.setLocalizations(localizations); - } - } - - /** - * Adds a feature reference model to site. - * - * @param featureReference feature reference model - */ - public void addFeature(SiteFeature featureReference) { - if (this.features == null) - this.features = new ArrayList(); - this.features.add(featureReference); - } - - public URLEntry[] getAssociatedSites() { - return associateSites; - } - - /** - * Returns the category with the given name. - * @return the category with the given name, or <code>null</code> - */ - public SiteCategory getCategory(String name) { - return (SiteCategory) (categories == null ? null : categories.get(name)); - } - - /** - * Returns the site description. - * - * @return site description, or <code>null</code>. - */ - public URLEntry getDescription() { - return description; - } - - /** - * Returns an array of feature reference models on this site. - * - * @return an array of feature reference models, or an empty array. - */ - public SiteFeature[] getFeatures() { - if (features == null || features.size() == 0) - return new SiteFeature[0]; - return (SiteFeature[]) features.toArray(new SiteFeature[0]); - } - - /** - * Return the keys for translatable strings - * - * @return the list of keys for translatable strings; may be null - * @since 3.4 - */ - public List getMessageKeys() { - return messageKeys; - } - - /** - * Returns the URL from which the list of mirrors of this site can be retrieved. - * - * @since org.eclipse.equinox.p2.metadata.generator 1.0 - */ - public String getMirrorsURL() { - return mirrorsURLString; - } - - /** - * Sets the site description. - * - * @param description site description - * @since 2.0 - */ - public void setDescription(URLEntry description) { - this.description = description; - } - - /** - * Sets the localizations for the site as a map from locale - * to the set of translated properties for that locale. - * - * @param localizations as a map from locale to property set - * @since 3.4 - */ - public void setLocalizations(Map localizations) { - this.localizations = localizations; - if (localizations != null && !localizations.isEmpty() && // - categories != null && !categories.isEmpty()) { - for (Iterator catIter = categories.entrySet().iterator(); catIter.hasNext();) { - Map.Entry entry = (Map.Entry) catIter.next(); - SiteCategory category = (SiteCategory) entry.getValue(); - category.setLocalizations(localizations); - } - } - } - - /** - * Sets keys for translatable strings - * - * @param keys for translatable strings - * @since 3.4 - */ - public void setMessageKeys(List keys) { - this.messageKeys = keys; - } - - /** - * Sets the mirrors url. Mirror sites will then be obtained from this mirror url later. - * This method is complementary to setMirrorsiteEntryModels(), and only one of these - * methods should be called. - * - * @param mirrorsURL additional update site mirrors - * @since 3.1 - */ - public void setMirrorsURLString(String mirrorsURL) { - this.mirrorsURLString = mirrorsURL; - } - - /** - * Sets the associated sites for this update site. - * - * @param associateSites the associated sites - */ - public void setAssociateSites(URLEntry[] associateSites) { - this.associateSites = associateSites; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/messages.properties b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/messages.properties deleted file mode 100644 index 78bd8ff21..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/messages.properties +++ /dev/null @@ -1,28 +0,0 @@ -############################################################################### -# Copyright (c) 2000, 2008 IBM Corporation and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# IBM Corporation - initial API and implementation -############################################################################### -# Install Update Core Properties File -# - -DefaultFeatureParser_IdOrVersionInvalid= Error parsing feature stream. The unique identifier or the version is null or empty for the State: \"{2}\": unique identifier=\"{0}\" version=\"{1}\". -DefaultSiteParser_NoSiteTag= Error parsing site stream. Unable to find root element \"site\" in the stream. -DefaultSiteParser_WrongParsingStack= Internal Error parsing site stream. Unexpected Parsing Stack: \"{0}\" -DefaultSiteParser_UnknownElement= Error parsing site stream. Unknown element \"{0}\" in parsing state \"{1}\". Check the validity of the XML file. -DefaultSiteParser_UnknownStartState= Internal Error parsing site stream. Unknown start state \"{0}\". -DefaultSiteParser_Missing= Error parsing site stream. The \"{0}\" tag of the element \"{1}\" is null or empty. Value is required. -DefaultSiteParser_ParsingStackBackToInitialState= Internal Error parsing site stream. Parsing stack back to Initial State. -DefaultSiteParser_ElementAlreadySet= Error parsing site stream. Element: \"{0}\" already set for the Site. -DefaultSiteParser_UnknownEndState= Internal Error parsing site stream. Unknown end state \"{0}\". -DefaultSiteParser_ErrorParsing= Error Parsing site stream. Error: \"{0}\" -DefaultSiteParser_ErrorlineColumnMessage= Error Parsing site stream. Element \"{0}\" line: \"{1}\" column:\"{2}\". Error: \"{3}\". -DefaultSiteParser_ErrorParsingSite= Error Parsing site stream. -DefaultSiteParser_UnknownState= Unknown State \"{0}\". -DefaultSiteParser_InvalidXMLStream= The XML stream is not a valid default \"site.xml\" file. The root tag is not site. -DefaultSiteParser_mirrors = Error processing update site mirror. diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/messages.properties b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/messages.properties deleted file mode 100644 index 348bc1ed8..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/messages.properties +++ /dev/null @@ -1,22 +0,0 @@ -############################################################################### -# Copyright (c) 2007, 2008 IBM Corporation and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# IBM Corporation - initial API and implementation -############################################################################### -exception_errorConverting = An error occurred while generating manifest for {0}. -exception_errorParsingUpdateSite = Error parsing update site: {0}. -exception_stateAddition = An error has occurred while adding the bundle {0}. -exception_sourceDirectoryInvalid = Source directory is invalid: {0}. -exception_artifactRepoNotWritable = Artifact repository is not writable: {0}. -exception_artifactRepoNotSpecified = An artifact repository was not specified. -exception_metadataRepoNotWritable = Metadata repository not writable: {0}. -exception_metadataRepoNotSpecified = A metadata repository location was not specified. -exception_baseLocationNotSpecified = Eclipse base location not specified. -exception_artifactRepoNoAppendDestroysInput = Not appending to artifact repository ({0}) will destroy input files. -message_generatingMetadata = Generating metadata for {0}. -message_generationCompleted = Generation completed with success [{0} seconds]. diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/BundleDescriptionFactory.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/BundleDescriptionFactory.java deleted file mode 100644 index 218c6fe6e..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/BundleDescriptionFactory.java +++ /dev/null @@ -1,180 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.generator; - -import java.io.*; -import java.util.*; -import java.util.jar.JarFile; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.metadata.generator.Activator; -import org.eclipse.equinox.internal.p2.metadata.generator.Messages; -import org.eclipse.osgi.service.pluginconversion.PluginConversionException; -import org.eclipse.osgi.service.pluginconversion.PluginConverter; -import org.eclipse.osgi.service.resolver.*; -import org.eclipse.osgi.util.ManifestElement; -import org.eclipse.osgi.util.NLS; -import org.osgi.framework.BundleException; - -/** - * @deprecated All of the function here has moved to BundlesAction static methods - */ -public class BundleDescriptionFactory { - static final String DIR = "dir"; //$NON-NLS-1$ - static final String JAR = "jar"; //$NON-NLS-1$ - private static final String FEATURE_FILENAME_DESCRIPTOR = "feature.xml"; //$NON-NLS-1$ - private static final String PLUGIN_FILENAME_DESCRIPTOR = "plugin.xml"; //$NON-NLS-1$ - private static final String FRAGMENT_FILENAME_DESCRIPTOR = "fragment.xml"; //$NON-NLS-1$ - - static String BUNDLE_FILE_KEY = "eclipse.p2.bundle.format"; //$NON-NLS-1$ - - // static final String DEFAULT_BUNDLE_LOCALIZATION = "plugin"; //$NON-NLS-1$ - // static final String PROPERTIES_FILE_EXTENSION = ".properties"; //$NON-NLS-1$ - // static final String MANIFEST_LOCALIZATIONS = "eclipse.p2.manifest.localizations"; //$NON-NLS-1$ - // - // static final Locale DEFAULT_LOCALE = new Locale("df", "LT"); //$NON-NLS-1$//$NON-NLS-2$ - // static final Locale PSEUDO_LOCALE = new Locale("zz", "ZZ"); //$NON-NLS-1$//$NON-NLS-2$ - - StateObjectFactory factory; - State state; - - public BundleDescriptionFactory(StateObjectFactory factory, State state) { - this.factory = factory; - this.state = state; - //TODO find a state and a factory when not provided - } - - private PluginConverter acquirePluginConverter() { - return (PluginConverter) ServiceHelper.getService(Activator.getContext(), PluginConverter.class.getName()); - } - - private Dictionary convertPluginManifest(File bundleLocation, boolean logConversionException) { - PluginConverter converter; - try { - converter = acquirePluginConverter(); - if (converter == null) { - LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "Unable to aquire PluginConverter service during generation for: " + bundleLocation)); - return null; - } - return converter.convertManifest(bundleLocation, false, null, true, null); - } catch (PluginConversionException convertException) { - // only log the exception if we had a plugin.xml or fragment.xml and we failed conversion - if (bundleLocation.getName().equals(FEATURE_FILENAME_DESCRIPTOR)) - return null; - if (!new File(bundleLocation, PLUGIN_FILENAME_DESCRIPTOR).exists() && !new File(bundleLocation, FRAGMENT_FILENAME_DESCRIPTOR).exists()) - return null; - if (logConversionException) { - IStatus status = new Status(IStatus.WARNING, Activator.ID, 0, NLS.bind(Messages.exception_errorConverting, bundleLocation.getAbsolutePath()), convertException); - LogHelper.log(status); - } - return null; - } - } - - public BundleDescription getBundleDescription(Dictionary enhancedManifest, File bundleLocation) { - try { - BundleDescription descriptor = factory.createBundleDescription(state, enhancedManifest, bundleLocation != null ? bundleLocation.getAbsolutePath() : null, 1); //TODO Do we need to have a real bundle id - descriptor.setUserObject(enhancedManifest); - return descriptor; - } catch (BundleException e) { - String message = NLS.bind(Messages.exception_stateAddition, bundleLocation == null ? null : bundleLocation.getAbsoluteFile()); - IStatus status = new Status(IStatus.WARNING, Activator.ID, message, e); - LogHelper.log(status); - return null; - } - } - - public BundleDescription getBundleDescription(File bundleLocation) { - Dictionary manifest = loadManifest(bundleLocation); - if (manifest == null) - return null; - return getBundleDescription(manifest, bundleLocation); - } - - public BundleDescription getBundleDescription(InputStream manifestStream, File bundleLocation) { - Hashtable entries = new Hashtable(); - try { - ManifestElement.parseBundleManifest(manifestStream, entries); - return getBundleDescription(entries, bundleLocation); - } catch (IOException e) { - String message = "An error occurred while reading the bundle description " + (bundleLocation == null ? "" : bundleLocation.getAbsolutePath() + '.'); //$NON-NLS-1$ //$NON-NLS-2$ - IStatus status = new Status(IStatus.ERROR, Activator.ID, message, e); - LogHelper.log(status); - } catch (BundleException e) { - String message = "An error occurred while reading the bundle description " + (bundleLocation == null ? "" : bundleLocation.getAbsolutePath() + '.'); //$NON-NLS-1$ //$NON-NLS-2$ - IStatus status = new Status(IStatus.ERROR, Activator.ID, message, e); - LogHelper.log(status); - } - return null; - } - - public Dictionary loadManifest(File bundleLocation) { - InputStream manifestStream = null; - ZipFile jarFile = null; - try { - if ("jar".equalsIgnoreCase(new Path(bundleLocation.getName()).getFileExtension()) && bundleLocation.isFile()) { //$NON-NLS-1$ - jarFile = new ZipFile(bundleLocation, ZipFile.OPEN_READ); - ZipEntry manifestEntry = jarFile.getEntry(JarFile.MANIFEST_NAME); - if (manifestEntry != null) { - manifestStream = jarFile.getInputStream(manifestEntry); - } - } else { - File manifestFile = new File(bundleLocation, JarFile.MANIFEST_NAME); - if (manifestFile.exists()) - manifestStream = new BufferedInputStream(new FileInputStream(manifestFile)); - } - } catch (IOException e) { - //ignore but log - LogHelper.log(new Status(IStatus.WARNING, Activator.ID, "An error occurred while loading the bundle manifest " + bundleLocation, e)); //$NON-NLS-1$ - } - - Dictionary manifest = null; - if (manifestStream != null) { - try { - Map manifestMap = ManifestElement.parseBundleManifest(manifestStream, null); - // TODO temporary hack. We are reading a Map but everyone wants a Dictionary so convert. - // real answer is to have people expect a Map but that is a wider change. - manifest = new Hashtable(manifestMap); - } catch (IOException e) { - LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "An error occurred while loading the bundle manifest " + bundleLocation, e)); //$NON-NLS-1$ - return null; - } catch (BundleException e) { - LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "An error occurred while loading the bundle manifest " + bundleLocation, e)); //$NON-NLS-1$ - return null; - } finally { - try { - if (jarFile != null) - jarFile.close(); - } catch (IOException e2) { - //Ignore - } - } - } else { - manifest = convertPluginManifest(bundleLocation, true); - } - - if (manifest == null) - return null; - - //Deal with the pre-3.0 plug-in shape who have a default jar manifest.mf - if (manifest.get(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME) == null) - manifest = convertPluginManifest(bundleLocation, true); - - if (manifest == null) - return null; - - manifest.put(BUNDLE_FILE_KEY, bundleLocation.isDirectory() ? DIR : JAR); - return manifest; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/EclipseInstallGeneratorInfoProvider.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/EclipseInstallGeneratorInfoProvider.java deleted file mode 100644 index 12a891c55..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/EclipseInstallGeneratorInfoProvider.java +++ /dev/null @@ -1,538 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.generator; - -import java.io.File; -import java.io.IOException; -import java.net.*; -import java.util.*; -import org.eclipse.equinox.frameworkadmin.BundleInfo; -import org.eclipse.equinox.internal.frameworkadmin.equinox.EquinoxFwConfigFileParser; -import org.eclipse.equinox.internal.frameworkadmin.equinox.EquinoxManipulatorImpl; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.metadata.generator.Activator; -import org.eclipse.equinox.internal.p2.metadata.generator.Messages; -import org.eclipse.equinox.internal.provisional.frameworkadmin.*; -import org.eclipse.equinox.p2.metadata.IInstallableUnit; -import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; -import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; -import org.eclipse.equinox.simpleconfigurator.manipulator.SimpleConfiguratorManipulator; -import org.eclipse.osgi.service.environment.EnvironmentInfo; -import org.eclipse.osgi.util.NLS; -import org.osgi.framework.*; -import org.osgi.util.tracker.ServiceTracker; - -/** - * @deprecated The function in this class has been refactored into more focused locations - * such as IPublisherAction and IPublishingAdvice classes. See the individual method deprecations - * for more information on where the code has moved. - */ -public class EclipseInstallGeneratorInfoProvider implements IGeneratorInfo { - private final static String FILTER_OBJECTCLASS = "(" + Constants.OBJECTCLASS + "=" + FrameworkAdmin.class.getName() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - - private final static String filterFwName = "(" + FrameworkAdmin.SERVICE_PROP_KEY_FW_NAME + "=Equinox)"; //$NON-NLS-1$ //$NON-NLS-2$ - //String filterFwVersion = "(" + FrameworkAdmin.SERVICE_PROP_KEY_FW_VERSION + "=" + props.getProperty("equinox.fw.version") + ")"; - private final static String filterLauncherName = "(" + FrameworkAdmin.SERVICE_PROP_KEY_LAUNCHER_NAME + "=Eclipse.exe)"; //$NON-NLS-1$ //$NON-NLS-2$ - //String filterLauncherVersion = "(" + FrameworkAdmin.SERVICE_PROP_KEY_LAUNCHER_VERSION + "=" + props.getProperty("equinox.launcher.version") + ")"; - private final static String frameworkAdminFillter = "(&" + FILTER_OBJECTCLASS + filterFwName + filterLauncherName + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - private static final String ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR = "org.eclipse.equinox.simpleconfigurator"; //$NON-NLS-1$ - private static final String ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_CONFIGURL = "org.eclipse.equinox.simpleconfigurator.configUrl"; //$NON-NLS-1$ - private static final String ORG_ECLIPSE_EQUINOX_P2_RECONCILER_DROPINS = "org.eclipse.equinox.p2.reconciler.dropins"; //$NON-NLS-1$ - - private String os; - - /** - * Returns a default name for the executable. - * @param providedOS The operating system to return the executable for. If null, - * the operating system is determined from the current runtime environment. - */ - public static String getDefaultExecutableName(String providedOS) { - String theOS = providedOS; - if (theOS == null) { - EnvironmentInfo info = (EnvironmentInfo) ServiceHelper.getService(Activator.getContext(), EnvironmentInfo.class.getName()); - theOS = info.getOS(); - } - if (theOS.equalsIgnoreCase("win32")) //$NON-NLS-1$ - return "eclipse.exe"; //$NON-NLS-1$ - if (theOS.equalsIgnoreCase("macosx")) //$NON-NLS-1$ - return "Eclipse.app"; //$NON-NLS-1$ - //FIXME Is this a reasonable default for all non-Windows platforms? - return "eclipse"; //$NON-NLS-1$ - } - - private boolean addDefaultIUs = true; - - private boolean append = false; - private IArtifactRepository artifactRepository; - private File baseLocation; - private File[] bundleLocations; - private File configLocation; - private ArrayList defaultIUs; - private List otherIUs; - private File executableLocation; - private File featuresLocation; - private String flavor; - private ServiceTracker frameworkAdminTracker; - private Manipulator manipulator; - private IMetadataRepository metadataRepository; - private boolean publishArtifactRepo = false; - private boolean publishArtifacts = false; - private String rootId; - private String rootVersion; - private String productFile = null; - private String launcherConfig; - private String versionAdvice; - - private URI siteLocation; - - private boolean reuseExistingPack200Files = false; - - public EclipseInstallGeneratorInfoProvider() { - super(); - } - - public boolean addDefaultIUs() { - return addDefaultIUs; - } - - public boolean append() { - return append; - } - - /** - * @deprecated moved to DefaultCUsAction - */ - protected GeneratorBundleInfo createDefaultConfigurationBundleInfo() { - GeneratorBundleInfo result = new GeneratorBundleInfo(); - result.setSymbolicName("defaultConfigure"); //$NON-NLS-1$ - result.setVersion("1.0.0"); //$NON-NLS-1$ - result.setStartLevel(4); - // These should just be in the install section now - // result.setSpecialConfigCommands("installBundle(bundle:${artifact});"); - return result; - } - - /** - * @deprecated moved to DefaultCUsAction - */ - protected GeneratorBundleInfo createDefaultUnconfigurationBundleInfo() { - GeneratorBundleInfo result = new GeneratorBundleInfo(); - result.setSymbolicName("defaultUnconfigure"); //$NON-NLS-1$ - result.setVersion("1.0.0"); //$NON-NLS-1$ - // These should just be in the uninstall section now - // result.setSpecialConfigCommands("uninstallBundle(bundle:${artifact});"); - return result; - } - - /** - * Obtains the framework manipulator instance. Throws an exception - * if it could not be created. - * @deprecated see DataLoader - */ - private void createFrameworkManipulator() { - FrameworkAdmin admin = getFrameworkAdmin(); - if (admin == null) - throw new RuntimeException("Framework admin service not found"); //$NON-NLS-1$ - manipulator = admin.getManipulator(); - if (manipulator == null) - throw new RuntimeException("Framework manipulator not found"); //$NON-NLS-1$ - } - - /** - * @deprecated moved to EquinoxLauncherData - */ - public static GeneratorBundleInfo createLauncher() { - GeneratorBundleInfo result = new GeneratorBundleInfo(); - result.setSymbolicName("org.eclipse.equinox.launcher"); //$NON-NLS-1$ - result.setVersion("0.0.0"); //$NON-NLS-1$ - //result.setSpecialConfigCommands("manipulator.addProgramArgument('-startup'); manipulator.addProgramArgument(artifact);"); - result.setSpecialConfigCommands("addProgramArg(programArg:-startup);addProgramArg(programArg:@artifact);"); //$NON-NLS-1$ - result.setSpecialUnconfigCommands("removeProgramArg(programArg:-startup);removeProgramArg(programArg:@artifact);"); //$NON-NLS-1$ - return result; - } - - /** - * @deprecated moved to EquinoxLauncherCUAction - */ - private Collection createLauncherBundleInfo(Set ius) { - Collection result = new HashSet(); - Collection launchers = getIUs(ius, "org.eclipse.equinox.launcher."); //$NON-NLS-1$ - if (launchers.size() > 0) { - for (Iterator iterator = launchers.iterator(); iterator.hasNext();) { - IInstallableUnit object = (IInstallableUnit) iterator.next(); - if (object.getId().endsWith(".source")) //$NON-NLS-1$ - continue; - GeneratorBundleInfo temp = new GeneratorBundleInfo(); - temp.setSymbolicName(object.getId()); - temp.setVersion(object.getVersion().toString()); - temp.setSpecialConfigCommands("addProgramArg(programArg:--launcher.library);addProgramArg(programArg:@artifact);"); //$NON-NLS-1$ - temp.setSpecialUnconfigCommands("removeProgramArg(programArg:--launcher.library);removeProgramArg(programArg:@artifact);"); //$NON-NLS-1$ - result.add(temp); - } - } else if (launcherConfig != null) { - String[] config = Generator.parseConfigSpec(launcherConfig); - //we want ws.os.arch - GeneratorBundleInfo temp = new GeneratorBundleInfo(); - temp.setSymbolicName("org.eclipse.equinox.launcher." + config[1] + '.' + config[0] + '.' + config[2]); //$NON-NLS-1$ - temp.setSpecialConfigCommands("addProgramArg(programArg:--launcher.library);addProgramArg(programArg:@artifact);"); //$NON-NLS-1$ - temp.setSpecialUnconfigCommands("removeProgramArg(programArg:--launcher.library);removeProgramArg(programArg:@artifact);"); //$NON-NLS-1$ - result.add(temp); - } - return result; - } - - /** - * @deprecated moved to EclipseInstallAction (perhaps it will be somewhere more general...) - */ - private GeneratorBundleInfo createSimpleConfiguratorBundleInfo() { - GeneratorBundleInfo result = new GeneratorBundleInfo(); - result.setSymbolicName(ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR); - result.setVersion("0.0.0"); //$NON-NLS-1$ - result.setStartLevel(1); - result.setMarkedAsStarted(true); - return result; - } - - /** - * @deprecated moved to EclipseInstallAction (perhaps it will be somewhere more general...) - */ - private GeneratorBundleInfo createDropinsReconcilerBundleInfo() { - GeneratorBundleInfo result = new GeneratorBundleInfo(); - result.setSymbolicName(ORG_ECLIPSE_EQUINOX_P2_RECONCILER_DROPINS); - result.setVersion("0.0.0"); //$NON-NLS-1$ - result.setMarkedAsStarted(true); - result.setSpecialConfigCommands("mkdir(path:${installFolder}/dropins)"); //$NON-NLS-1$ - return result; - } - - /** - * @deprecated moved to BundlesAction - */ - private void expandBundleLocations() { - if (bundleLocations == null) { - bundleLocations = new File[] {}; - return; - } - ArrayList result = new ArrayList(); - for (int i = 0; i < bundleLocations.length; i++) { - File location = bundleLocations[i]; - if (location.isDirectory()) { - File[] list = location.listFiles(); - for (int j = 0; j < list.length; j++) - result.add(list[j]); - } else { - result.add(location); - } - } - bundleLocations = (File[]) result.toArray(new File[result.size()]); - } - - public IArtifactRepository getArtifactRepository() { - return artifactRepository; - } - - public File getBaseLocation() { - return baseLocation; - } - - public File[] getBundleLocations() { - return bundleLocations; - } - - public ConfigData getConfigData() { - return manipulator == null ? null : manipulator.getConfigData(); - } - - /** - * @deprecated moved to DataLoader - */ - public ConfigData loadConfigData(File location) { - if (manipulator == null) - return null; - - EquinoxFwConfigFileParser parser = new EquinoxFwConfigFileParser(Activator.getContext()); - try { - parser.readFwConfig(manipulator, location); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (URISyntaxException e) { - e.printStackTrace(); - } - - ConfigData data = manipulator.getConfigData(); - String value = data.getProperty(ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_CONFIGURL); - if (value != null) { - try { - //config.ini uses simpleconfigurator, read the bundles.info and replace the bundle infos - SimpleConfiguratorManipulator simpleManipulator = (SimpleConfiguratorManipulator) ServiceHelper.getService(Activator.getContext(), SimpleConfiguratorManipulator.class.getName()); - BundleInfo[] bundleInfos = simpleManipulator.loadConfiguration(new URL(value).openStream(), null); - data.setBundles(bundleInfos); - } catch (MalformedURLException e1) { - // ignore - } catch (IOException e1) { - // ignore - } - - try { - data.setProperty(ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR_CONFIGURL, EquinoxManipulatorImpl.makeRelative(value, configLocation.toURL())); - } catch (MalformedURLException e) { - //ignore - } - } - - return data; - } - - /** - * @deprecated logic moved to EclipseInstallAction (and related actions) - */ - public ArrayList getDefaultIUs(Set ius) { - if (defaultIUs != null) - return defaultIUs; - defaultIUs = new ArrayList(5); - if (addDefaultIUs) { - defaultIUs.addAll(createLauncherBundleInfo(ius)); - defaultIUs.add(createLauncher()); - defaultIUs.add(createSimpleConfiguratorBundleInfo()); - defaultIUs.add(createDropinsReconcilerBundleInfo()); - // defaultIUs.add(createDefaultConfigurationBundleInfo()); - // defaultIUs.add(createDefaultUnconfigurationBundleInfo()); - } - return defaultIUs; - } - - // TODO: This is kind of ugly. It's purpose is to allow us to craft CUs that we know about and need for our build - // We should try to replace this with something more generic prior to release - /** - * @deprecated this has been replaced with RootIUAdvice and related things - */ - public Collection getOtherIUs() { - if (otherIUs != null) - return otherIUs; - otherIUs = new ArrayList(); - otherIUs.add(createDropinsReconcilerBundleInfo()); - return otherIUs; - } - - public File getExecutableLocation() { - return executableLocation; - } - - public File getFeaturesLocation() { - return featuresLocation; - } - - public String getFlavor() { - //use 'tooling' as default flavor since we are not actively using flavors yet - return flavor == null ? "tooling" : flavor; //$NON-NLS-1$ - } - - /** - * @deprecated moved to DataLoader - */ - private FrameworkAdmin getFrameworkAdmin() { - if (frameworkAdminTracker == null) { - try { - Filter filter = Activator.getContext().createFilter(frameworkAdminFillter); - frameworkAdminTracker = new ServiceTracker(Activator.getContext(), filter, null); - frameworkAdminTracker.open(); - } catch (InvalidSyntaxException e) { - // never happens - e.printStackTrace(); - } - } - - return (FrameworkAdmin) frameworkAdminTracker.getService(); - } - - private Collection getIUs(Set ius, String prefix) { - Set result = new HashSet(); - for (Iterator iterator = ius.iterator(); iterator.hasNext();) { - IInstallableUnit tmp = (IInstallableUnit) iterator.next(); - if (tmp.getId().startsWith(prefix)) - result.add(tmp); - } - return result; - } - - public File getJRELocation() { - //assume JRE is relative to install location - if (executableLocation == null) - return null; - return new File(executableLocation.getParentFile(), "jre"); //$NON-NLS-1$ - } - - public String getLauncherConfig() { - return launcherConfig; - } - - public LauncherData getLauncherData() { - return manipulator == null ? null : manipulator.getLauncherData(); - } - - public IMetadataRepository getMetadataRepository() { - return metadataRepository; - } - - public String getRootId() { - return rootId; - } - - public String getRootVersion() { - if (rootVersion == null || rootVersion.length() == 0) - return "0.0.0"; //$NON-NLS-1$ - return rootVersion; - } - - public String getProductFile() { - return productFile; - } - - public URI getSiteLocation() { - return siteLocation; - } - - public void initialize(File base) { - // if the various locations are set in self, use them. Otherwise compute defaults - File[] bundles = bundleLocations == null ? new File[] {new File(base, "plugins")} : bundleLocations; //$NON-NLS-1$ - File features = featuresLocation == null ? new File(base, "features") : featuresLocation; //$NON-NLS-1$ - File executable = executableLocation == null ? new File(base, getDefaultExecutableName(os)) : executableLocation; - File configuration = configLocation == null ? new File(base, "configuration") : configLocation; //$NON-NLS-1$ - - initialize(base, configuration, executable, bundles, features); - } - - public void initialize(File base, File config, File executable, File[] bundles, File features) { - if (base == null || !base.exists()) - throw new RuntimeException(NLS.bind(Messages.exception_sourceDirectoryInvalid, base == null ? "null" : base.getAbsolutePath())); //$NON-NLS-1$ - this.baseLocation = base; - if (config == null || config.exists()) - this.configLocation = config; - if (executable == null || executable.exists()) - this.executableLocation = executable; - if (bundles != null) - bundleLocations = bundles; - if (features != null) - featuresLocation = features; - expandBundleLocations(); - - // if the config or exe are not set then we cannot be generating any data related to the config so - // don't bother setting up the manipulator. In fact, the manipulator will likely be invalid without - // these locations. - if (configLocation == null || executableLocation == null) - return; - - createFrameworkManipulator(); - - LauncherData launcherData = manipulator.getLauncherData(); - launcherData.setFwPersistentDataLocation(configLocation, true); - launcherData.setLauncher(executableLocation); - try { - manipulator.load(); - } catch (IllegalStateException e2) { - // TODO Auto-generated catch block - e2.printStackTrace(); - } catch (FrameworkAdminRuntimeException e2) { - // TODO Auto-generated catch block - e2.printStackTrace(); - } catch (IOException e2) { - // TODO Auto-generated catch block - e2.printStackTrace(); - } - } - - public boolean publishArtifactRepository() { - return publishArtifactRepo; - } - - public boolean publishArtifacts() { - return publishArtifacts; - } - - public boolean reuseExistingPack200Files() { - return reuseExistingPack200Files; - } - - public void reuseExistingPack200Files(boolean publishPack) { - reuseExistingPack200Files = publishPack; - } - - public void setAddDefaultIUs(boolean value) { - addDefaultIUs = value; - } - - public void setAppend(boolean value) { - append = value; - } - - public void setArtifactRepository(IArtifactRepository value) { - artifactRepository = value; - } - - public void setExecutableLocation(String value) { - executableLocation = new File(value); - } - - public void setFlavor(String value) { - flavor = value; - } - - public void setLauncherConfig(String value) { - launcherConfig = value; - } - - public void setMappingRules(String[][] value) { - } - - public void setMetadataRepository(IMetadataRepository value) { - metadataRepository = value; - } - - public void setOS(String os) { - this.os = os; - } - - public void setPublishArtifactRepository(boolean value) { - publishArtifactRepo = value; - } - - public void setPublishArtifacts(boolean value) { - publishArtifacts = value; - } - - public void setRootId(String value) { - rootId = value; - } - - public void setRootVersion(String value) { - rootVersion = value; - } - - public void setProductFile(String file) { - productFile = file; - } - - /** - * Sets the location of site.xml if applicable. - */ - public void setSiteLocation(URI location) { - this.siteLocation = location; - } - - public String getVersionAdvice() { - return versionAdvice; - } - - public void setVersionAdvice(String advice) { - this.versionAdvice = advice; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/Feature.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/Feature.java deleted file mode 100644 index e27ff87dd..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/Feature.java +++ /dev/null @@ -1,278 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.generator; - -import java.util.ArrayList; -import java.util.Map; - -/** - * - * Feature information - */ -public class Feature { - - private final String id; - private final String version; - private String label; - private String pluginId; - private boolean primary = false; - private boolean exclusive = false; - private String application; - - private URLEntry description; - private URLEntry license; - private URLEntry copyright; - - private String installHandler; - private String installHandlerURL; - private String installHandlerLibrary; - - private URLEntry updateSite; - private ArrayList discoverySites; - - private ArrayList entries; - private String providerName; - - private String location; - - private Map localizations; - - public Feature(String id, String version) { - if (id == null) - throw new IllegalArgumentException(); - this.id = id; - this.version = version; - } - - public void addDiscoverySite(String siteLabel, String url) { - if (siteLabel == null && url == null) - return; - - if (this.discoverySites == null) - this.discoverySites = new ArrayList(); - - URLEntry entry = new URLEntry(url, siteLabel); - this.discoverySites.add(entry); - } - - public void addEntry(FeatureEntry plugin) { - if (entries == null) - entries = new ArrayList(); - entries.add(plugin); - } - - public String getApplication() { - return application; - } - - public String getCopyright() { - if (copyright != null) - return copyright.getAnnotation(); - return null; - } - - public String getCopyrightURL() { - if (copyright != null) - return copyright.getURL(); - return null; - } - - public String getDescription() { - if (description != null) - return description.getAnnotation(); - return null; - } - - public String getDescriptionURL() { - if (description != null) - return description.getURL(); - return null; - } - - public URLEntry[] getDiscoverySites() { - if (discoverySites == null) - return new URLEntry[0]; - return (URLEntry[]) discoverySites.toArray(new URLEntry[discoverySites.size()]); - } - - public FeatureEntry[] getEntries() { - if (entries == null) - return new FeatureEntry[0]; - return (FeatureEntry[]) entries.toArray(new FeatureEntry[entries.size()]); - } - - public String getId() { - return id; - } - - public String getInstallHandler() { - return installHandler; - } - - public String getInstallHandlerLibrary() { - return installHandlerLibrary; - } - - public String getInstallHandlerURL() { - return installHandlerURL; - } - - public String getLabel() { - return label; - } - - public String getLicense() { - if (license != null) - return license.getAnnotation(); - return null; - } - - public String getLicenseURL() { - if (license != null) - return license.getURL(); - return null; - } - - public Map getLocalizations() { - return this.localizations; - } - - public String getLocation() { - return this.location; - } - - public String getPlugin() { - return pluginId; - } - - public String getProviderName() { - return providerName; - } - - public URLEntry getUpdateSite() { - return updateSite; - } - - public String getVersion() { - return version; - } - - public boolean isExclusive() { - return exclusive; - } - - public boolean isPrimary() { - return primary; - } - - public void setApplication(String application) { - this.application = application; - } - - public void setCopyright(String copyright) { - if (this.copyright == null) - this.copyright = new URLEntry(); - this.copyright.setAnnotation(copyright); - } - - public void setCopyrightURL(String copyrightURL) { - if (this.copyright == null) - this.copyright = new URLEntry(); - this.copyright.setURL(copyrightURL); - } - - public void setDescription(String description) { - if (this.description == null) - this.description = new URLEntry(); - this.description.setAnnotation(description); - } - - public void setDescriptionURL(String descriptionURL) { - if (this.description == null) - this.description = new URLEntry(); - this.description.setURL(descriptionURL); - } - - public void setExclusive(boolean exclusive) { - this.exclusive = exclusive; - } - - public void setInstallHandler(String installHandler) { - this.installHandler = installHandler; - } - - public void setInstallHandlerLibrary(String installHandlerLibrary) { - this.installHandlerLibrary = installHandlerLibrary; - } - - public void setInstallHandlerURL(String installHandlerURL) { - this.installHandlerURL = installHandlerURL; - } - - public void setLabel(String label) { - this.label = label; - } - - public void setLicense(String license) { - if (this.license == null) - this.license = new URLEntry(); - this.license.setAnnotation(license); - } - - public void setLicenseURL(String licenseURL) { - if (this.license == null) - this.license = new URLEntry(); - this.license.setURL(licenseURL); - } - - public void setLocalizations(Map localizations) { - this.localizations = localizations; - } - - public void setLocation(String location) { - this.location = location; - } - - public void setPlugin(String pluginId) { - this.pluginId = pluginId; - } - - public void setPrimary(boolean primary) { - this.primary = primary; - } - - public void setProviderName(String value) { - providerName = value; - } - - public void setUpdateSiteLabel(String updateSiteLabel) { - if (this.updateSite == null) - this.updateSite = new URLEntry(); - this.updateSite.setAnnotation(updateSiteLabel); - } - - public void setUpdateSiteURL(String updateSiteURL) { - if (this.updateSite == null) - this.updateSite = new URLEntry(); - this.updateSite.setURL(updateSiteURL); - } - - public void setURL(String value) { - // - } - - /** - * For debugging purposes only. - */ - public String toString() { - return "Feature " + id + " version: " + version; //$NON-NLS-1$ //$NON-NLS-2$ - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/FeatureEntry.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/FeatureEntry.java deleted file mode 100644 index 870a3b6f2..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/FeatureEntry.java +++ /dev/null @@ -1,179 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.generator; - -import org.eclipse.equinox.p2.metadata.Version; - -/** - */ -public class FeatureEntry { - private final String id; - private final String version; - private String os; - private String ws; - private String arch; - private String nl; - private String match; - private final boolean isPlugin; - private boolean isFragment = false; - private boolean isRequires = false; - private boolean unpack = true; - private boolean optional = false; - private boolean isPatch = false; - - /** - * Temporary field to add provisioning filters to features - */ - private String filter; - - public static FeatureEntry createRequires(String id, String version, String match, String filter, boolean isPlugin) { - FeatureEntry result = new FeatureEntry(id, version, isPlugin); - result.match = match; - result.isRequires = true; - if (filter != null) - result.setFilter(filter); - return result; - } - - public FeatureEntry(String id, String version, boolean isPlugin) { - this.id = id; - this.version = Version.parseVersion(version).toString(); - this.isPlugin = isPlugin; - } - - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final FeatureEntry other = (FeatureEntry) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - return true; - } - - public String getArch() { - return arch; - } - - /** - * Temporary method to add provisioning filters to features - */ - public String getFilter() { - return filter; - } - - public String getId() { - return id; - } - - public String getMatch() { - return match; - } - - public String getNL() { - return nl; - } - - public String getOS() { - return os; - } - - public String getVersion() { - return version; - } - - public String getWS() { - return ws; - } - - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - return result; - } - - public boolean isFragment() { - return isFragment; - } - - public boolean isOptional() { - return optional; - } - - public boolean isPlugin() { - return isPlugin; - } - - public boolean isRequires() { - return isRequires; - } - - public boolean isUnpack() { - return unpack; - } - - public void setEnvironment(String os, String ws, String arch, String nl) { - this.os = os; - this.ws = ws; - this.arch = arch; - this.nl = nl; - } - - /** - * Temporary method to add provisioning filters to features - */ - public void setFilter(String filter) { - this.filter = filter; - - } - - public void setFragment(boolean value) { - isFragment = value; - } - - public void setOptional(boolean value) { - optional = value; - } - - public void setUnpack(boolean value) { - unpack = value; - } - - public String toString() { - StringBuffer result = new StringBuffer(); - - result.append(isPlugin ? "Plugin: " : "Feature: "); //$NON-NLS-1$ //$NON-NLS-2$ - result.append(id != null ? id.toString() : ""); //$NON-NLS-1$ - result.append(version != null ? " " + version.toString() : ""); //$NON-NLS-1$ //$NON-NLS-2$ - return result.toString(); - } - - public boolean isPatch() { - return isPatch; - } - - public void setPatch(boolean patch) { - this.isPatch = patch; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/Generator.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/Generator.java deleted file mode 100644 index f40635685..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/Generator.java +++ /dev/null @@ -1,1402 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.generator; - -import java.io.*; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; -import java.util.Map.Entry; -import org.eclipse.core.runtime.*; -import org.eclipse.equinox.frameworkadmin.BundleInfo; -import org.eclipse.equinox.internal.frameworkadmin.equinox.EquinoxConstants; -import org.eclipse.equinox.internal.p2.core.helpers.*; -import org.eclipse.equinox.internal.p2.core.helpers.FileUtils.IPathComputer; -import org.eclipse.equinox.internal.p2.metadata.ArtifactKey; -import org.eclipse.equinox.internal.p2.metadata.InstallableUnit; -import org.eclipse.equinox.internal.p2.metadata.generator.*; -import org.eclipse.equinox.internal.p2.metadata.generator.Messages; -import org.eclipse.equinox.internal.p2.metadata.generator.features.*; -import org.eclipse.equinox.internal.provisional.frameworkadmin.ConfigData; -import org.eclipse.equinox.internal.provisional.frameworkadmin.LauncherData; -import org.eclipse.equinox.p2.core.ProvisionException; -import org.eclipse.equinox.p2.metadata.*; -import org.eclipse.equinox.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.p2.metadata.MetadataFactory.InstallableUnitFragmentDescription; -import org.eclipse.equinox.p2.metadata.VersionRange; -import org.eclipse.equinox.p2.metadata.expression.IMatchExpression; -import org.eclipse.equinox.p2.query.*; -import org.eclipse.equinox.p2.repository.IRepository; -import org.eclipse.equinox.p2.repository.artifact.*; -import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; -import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; -import org.eclipse.equinox.p2.repository.spi.RepositoryReference; -import org.eclipse.osgi.service.environment.Constants; -import org.eclipse.osgi.service.resolver.*; -import org.eclipse.osgi.util.NLS; - -public class Generator { - /** - * Captures the output of an execution of the generator. - */ - public static class GeneratorResult { - public static final String CONFIGURATION_CUS = "CONFIGURATION_CUS"; //$NON-NLS-1$ - - final public Map pluginShape = new HashMap(); - - /** - * The set of generated IUs that will be children of the root IU - */ - final public Set rootIUs = new HashSet(); - /** - * The set of generated IUs that will not be children of the root IU - */ - final public Set nonRootIUs = new HashSet(); - - /** - * Map of symbolic name to a set of generated CUs for that IU - */ - final public Map configurationIUs = new HashMap(); - - /** - * Map launcherConfig to config.ini ConfigData - */ - final public Map configData = new HashMap(); - - /** - * Returns all IUs generated during this execution of the generator. - */ - public Set allGeneratedIUs() { - HashSet all = new HashSet(); - all.addAll(rootIUs); - all.addAll(nonRootIUs); - return all; - } - - /** - * Returns the IU in this result with the given id. - */ - public IInstallableUnit getInstallableUnit(String id) { - for (Iterator iterator = rootIUs.iterator(); iterator.hasNext();) { - IInstallableUnit tmp = (IInstallableUnit) iterator.next(); - if (tmp.getId().equals(id)) - return tmp; - } - for (Iterator iterator = nonRootIUs.iterator(); iterator.hasNext();) { - IInstallableUnit tmp = (IInstallableUnit) iterator.next(); - if (tmp.getId().equals(id)) - return tmp; - } - return null; - - } - - public Map getPluginShapeInfo() { - return pluginShape; - } - } - - private static final String ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR = "org.eclipse.equinox.simpleconfigurator"; //$NON-NLS-1$ - private static final String ORG_ECLIPSE_UPDATE_CONFIGURATOR = "org.eclipse.update.configurator"; //$NON-NLS-1$ - private static final String ORG_ECLIPSE_EQUINOX_LAUNCHER = "org.eclipse.equinox.launcher"; //$NON-NLS-1$ - - private static final String PRODUCT_CONFIG_SUFFIX = ".config"; //$NON-NLS-1$ - private static final String PRODUCT_INI_SUFFIX = ".ini"; //$NON-NLS-1$ - private static final String PRODUCT_LAUCHER_SUFFIX = ".launcher"; //$NON-NLS-1$ - private static final String CONFIG_ANY = "ANY"; //$NON-NLS-1$ - - private static final String PROTOCOL_FILE = "file"; //$NON-NLS-1$ - - protected final IGeneratorInfo info; - - private GeneratorResult incrementalResult = null; - private ProductFile productFile = null; - private boolean generateRootIU = true; - - /** - * Short term fix to ensure IUs that have no corresponding category are not lost. - * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=211521. - */ - protected final Set rootCategory = new HashSet(); - - private StateObjectFactory stateObjectFactory; - - /** - * Convert a list of tokens into an array. The list separator has to be - * specified. - */ - public static String[] getArrayFromString(String list, String separator) { - if (list == null || list.trim().equals("")) //$NON-NLS-1$ - return new String[0]; - List result = new ArrayList(); - for (StringTokenizer tokens = new StringTokenizer(list, separator); tokens.hasMoreTokens();) { - String token = tokens.nextToken().trim(); - if (!token.equals("")) //$NON-NLS-1$ - result.add(token); - } - return (String[]) result.toArray(new String[result.size()]); - } - - public static String[] parseConfigSpec(String config) { - String[] parsed = getArrayFromString(config, "_"); //$NON-NLS-1$ - for (int i = 0; i < parsed.length; i++) { - if (parsed[i].equals("*")) //$NON-NLS-1$ - parsed[i] = "ANY"; //$NON-NLS-1$ - } - if (parsed.length > 3) { - String[] adjusted = new String[] {parsed[0], parsed[1], parsed[2] + '_' + parsed[3]}; - return adjusted; - } - return parsed; - } - - public Generator(IGeneratorInfo infoProvider) { - this.info = infoProvider; - // TODO need to figure a better way of configuring the generator... - PlatformAdmin platformAdmin = (PlatformAdmin) ServiceHelper.getService(Activator.getContext(), PlatformAdmin.class.getName()); - if (platformAdmin != null) { - stateObjectFactory = platformAdmin.getFactory(); - } - } - - public void setIncrementalResult(GeneratorResult result) { - this.incrementalResult = result; - } - - private String getProductVersion() { - String version = "1.0.0"; //$NON-NLS-1$ - if (productFile != null && !productFile.getVersion().equals("0.0.0")) //$NON-NLS-1$ - version = productFile.getVersion(); - else if (!info.getRootVersion().equals("0.0.0")) //$NON-NLS-1$ - version = info.getRootVersion(); - return version; - } - - /** - * @deprecated moved to ProductAction - */ - protected IInstallableUnit createProductIU(GeneratorResult result) { - generateProductConfigCUs(result); - - GeneratorResult productContents = new GeneratorResult(); - - ProductQuery productQuery = new ProductQuery(productFile, info.getFlavor(), result.configurationIUs, info.getVersionAdvice()); - IQuery query = QueryUtil.createLatestQuery(productQuery); - IQueryResult queryResult = info.getMetadataRepository().query(query, null); - for (Iterator iterator = queryResult.iterator(); iterator.hasNext();) { - productContents.rootIUs.add(iterator.next()); - } - - String version = getProductVersion(); - VersionRange range = new VersionRange(Version.create(version), true, Version.create(version), true); - ArrayList requires = new ArrayList(1); - requires.add(MetadataFactory.createRequirement(info.getFlavor() + productFile.getId(), productFile.getId() + PRODUCT_LAUCHER_SUFFIX, range, null, false, true)); - requires.add(MetadataFactory.createRequirement(info.getFlavor() + productFile.getId(), productFile.getId() + PRODUCT_INI_SUFFIX, range, null, false, false)); - requires.add(MetadataFactory.createRequirement(info.getFlavor() + productFile.getId(), productFile.getId() + PRODUCT_CONFIG_SUFFIX, range, null, false, false)); - - //default CUs - requires.add(MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, MetadataGeneratorHelper.createDefaultConfigUnitId(MetadataGeneratorHelper.OSGI_BUNDLE_CLASSIFIER, info.getFlavor()), VersionRange.emptyRange, null, false, false)); - requires.add(MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, MetadataGeneratorHelper.createDefaultConfigUnitId("source", info.getFlavor()), VersionRange.emptyRange, null, false, false)); //$NON-NLS-1$ - if (productFile.useFeatures()) - requires.add(MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, MetadataGeneratorHelper.createDefaultConfigUnitId(MetadataGeneratorHelper.ECLIPSE_FEATURE_CLASSIFIER, info.getFlavor()), VersionRange.emptyRange, MetadataGeneratorHelper.INSTALL_FEATURES_FILTER, true, false)); - - InstallableUnitDescription root = createTopLevelIUDescription(productContents, productFile.getId(), version, productFile.getProductName(), requires, false); - return MetadataFactory.createInstallableUnit(root); - } - - /** - * @deprecated moved to RootIUAction - */ - protected IInstallableUnit createTopLevelIU(GeneratorResult result, String configurationIdentification, String configurationVersion) { - // TODO, bit of a hack but for now set the name of the IU to the ID. - InstallableUnitDescription root = createTopLevelIUDescription(result, configurationIdentification, configurationVersion, configurationIdentification, null, true); - return MetadataFactory.createInstallableUnit(root); - } - - /** - * @deprecated moved to RootIUAction - */ - protected InstallableUnitDescription createTopLevelIUDescription(GeneratorResult result, String configurationIdentification, String configurationVersion, String configurationName, List requires, boolean configureLauncherData) { - InstallableUnitDescription root = new MetadataFactory.InstallableUnitDescription(); - root.setSingleton(true); - root.setId(configurationIdentification); - root.setVersion(Version.create(configurationVersion)); - root.setProperty(IInstallableUnit.PROP_NAME, configurationName); - - ArrayList reqsConfigurationUnits = new ArrayList(result.rootIUs.size()); - for (Iterator iterator = result.rootIUs.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); - VersionRange range = new VersionRange(iu.getVersion(), true, iu.getVersion(), true); - // boolean isOptional = checkOptionalRootDependency(iu); - reqsConfigurationUnits.add(MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, iu.getId(), range, iu.getFilter(), false, false)); - } - if (requires != null) - reqsConfigurationUnits.addAll(requires); - root.setRequirements((IRequirement[]) reqsConfigurationUnits.toArray(new IRequirement[reqsConfigurationUnits.size()])); - root.setArtifacts(new IArtifactKey[0]); - - root.setProperty("lineUp", "true"); //$NON-NLS-1$ //$NON-NLS-2$ - root.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor(configurationIdentification, VersionRange.emptyRange, IUpdateDescriptor.NORMAL, null)); - root.setProperty(InstallableUnitDescription.PROP_TYPE_GROUP, Boolean.TRUE.toString()); - root.setCapabilities(new IProvidedCapability[] {MetadataGeneratorHelper.createSelfCapability(configurationIdentification, Version.create(configurationVersion))}); - root.setTouchpointType(MetadataGeneratorHelper.TOUCHPOINT_OSGI); - Map touchpointData = new HashMap(); - - // Publisher refactor - the configdata stuff moved to a distinct IU added by the ConfigCUsAction - String configurationData = ""; //$NON-NLS-1$ - String unconfigurationData = ""; //$NON-NLS-1$ - - ConfigData configData = info.getConfigData(); - if (configData != null) { - String[] dataStrings = getConfigurationStrings(configData); - configurationData += dataStrings[0]; - unconfigurationData += dataStrings[1]; - } - - if (configureLauncherData) { - LauncherData launcherData = info.getLauncherData(); - if (launcherData != null) { - String[] dataStrings = getLauncherConfigStrings(launcherData.getJvmArgs(), launcherData.getProgramArgs()); - configurationData += dataStrings[0]; - unconfigurationData += dataStrings[1]; - } - } - touchpointData.put("configure", configurationData); //$NON-NLS-1$ - touchpointData.put("unconfigure", unconfigurationData); //$NON-NLS-1$ - //look for additional touchpoint instructions in a p2.inf file - final String productFileLocation = info.getProductFile(); - if (productFileLocation != null) { - File productFilePath = new File(productFileLocation); - if (productFilePath.exists()) { - Map advice = MetadataGeneratorHelper.getBundleAdvice(productFilePath.getParent(), "p2.inf");//$NON-NLS-1$ - if (advice != null) - MetadataGeneratorHelper.mergeInstructionsAdvice(touchpointData, advice); - } - } - - root.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - return root; - } - - /** - * @deprecated moved to ConfigCUsAction - */ - private String[] getConfigurationStrings(ConfigData configData) { - String configurationData = ""; //$NON-NLS-1$ - String unconfigurationData = ""; //$NON-NLS-1$ - for (Iterator iterator = configData.getProperties().entrySet().iterator(); iterator.hasNext();) { - Entry aProperty = (Entry) iterator.next(); - String key = ((String) aProperty.getKey()); - if (key.equals("osgi.frameworkClassPath") || key.equals("osgi.framework") || key.equals("osgi.bundles") || key.equals("eof")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - continue; - configurationData += "setProgramProperty(propName:" + key + ", propValue:" + ((String) aProperty.getValue()) + ");"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - unconfigurationData += "setProgramProperty(propName:" + key + ", propValue:);"; //$NON-NLS-1$ //$NON-NLS-2$ - } - for (Iterator iterator = configData.getProperties().entrySet().iterator(); iterator.hasNext();) { - Entry aProperty = (Entry) iterator.next(); - String key = ((String) aProperty.getKey()); - if (key.equals("osgi.frameworkClassPath") || key.equals("osgi.framework") || key.equals("osgi.bundles") || key.equals("eof")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - continue; - configurationData += "setProgramProperty(propName:" + key + ", propValue:" + ((String) aProperty.getValue()) + ");"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - unconfigurationData += "setProgramProperty(propName:" + key + ", propValue:);"; //$NON-NLS-1$ //$NON-NLS-2$ - } - - return new String[] {configurationData, unconfigurationData}; - } - - /** - * @deprecated moved to ConfigCUsAction - */ - private String[] getLauncherConfigStrings(final String[] jvmArgs, final String[] programArgs) { - String configurationData = ""; //$NON-NLS-1$ - String unconfigurationData = ""; //$NON-NLS-1$ - - for (int i = 0; i < jvmArgs.length; i++) { - configurationData += "addJvmArg(jvmArg:" + jvmArgs[i] + ");"; //$NON-NLS-1$ //$NON-NLS-2$ - unconfigurationData += "removeJvmArg(jvmArg:" + jvmArgs[i] + ");"; //$NON-NLS-1$ //$NON-NLS-2$ - } - - for (int i = 0; i < programArgs.length; i++) { - String programArg = programArgs[i]; - if (programArg.equals("--launcher.library") || programArg.equals("-startup") || programArg.equals("-configuration")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - i++; - configurationData += "addProgramArg(programArg:" + programArg + ");"; //$NON-NLS-1$ //$NON-NLS-2$ - unconfigurationData += "removeProgramArg(programArg:" + programArg + ");"; //$NON-NLS-1$ //$NON-NLS-2$ - } - return new String[] {configurationData, unconfigurationData}; - } - - public IStatus generate() { - GeneratorResult result = incrementalResult != null ? incrementalResult : new GeneratorResult(); - - if (info.getProductFile() != null) { - try { - productFile = new ProductFile(info.getProductFile(), null); - } catch (Exception e) { - //TODO - } - } - - Feature[] features = getFeatures(info.getFeaturesLocation()); - generateFeatureIUs(features, result, info.getArtifactRepository()); - - BundleDescription[] bundles = getBundleDescriptions(info.getBundleLocations()); - generateBundleIUs(bundles, result, info.getArtifactRepository()); - - generateNativeIUs(info.getExecutableLocation(), result, info.getArtifactRepository()); - - generateConfigIUs(result); - - if (info.addDefaultIUs()) - generateDefaultConfigIU(result.rootIUs); - - if (generateRootIU) - generateRootIU(result, info.getRootId(), info.getRootVersion()); - - // persistence.setMappingRules(info.getMappingRules() == null ? defaultMappingRules : info.getMappingRules()); - // if (info.publishArtifacts() || info.publishArtifactRepository()) { - // persistence.saveArtifactRepository(); - // } - IMetadataRepository metadataRepository = info.getMetadataRepository(); - if (metadataRepository != null) { - Set allGeneratedUnits = result.allGeneratedIUs(); - metadataRepository.addInstallableUnits(allGeneratedUnits); - } - - return Status.OK_STATUS; - } - - /** - * @deprecated moved to BundlesAction - */ - protected void generateBundleIUs(BundleDescription[] bundles, GeneratorResult result, IArtifactRepository destination) { - // Computing the path for localized property files in a NL fragment bundle - // requires the BUNDLE_LOCALIZATION property from the manifest of the host bundle, - // so a first pass is done over all the bundles to cache this value as well as the tags - // from the manifest for the localizable properties. - final int CACHE_PHASE = 0; - final int GENERATE_PHASE = 1; - Map bundleLocalizationMap = new HashMap(bundles.length); - Set localizationIUs = new HashSet(32); - for (int phase = CACHE_PHASE; phase <= GENERATE_PHASE; phase++) { - for (int i = 0; i < bundles.length; i++) { - BundleDescription bd = bundles[i]; - // A bundle may be null if the associated plug-in does not have a manifest file - - // for example, org.eclipse.jdt.launching.j9 - if (bd != null && bd.getSymbolicName() != null && bd.getVersion() != null) { - Map bundleManifest = (Map) bd.getUserObject(); - - if (phase == CACHE_PHASE) { - if (bundleManifest != null) { - String[] cachedValues = MetadataGeneratorHelper.getManifestCachedValues(bundleManifest); - bundleLocalizationMap.put(makeSimpleKey(bd), cachedValues); - } - } else { - String format = (String) result.getPluginShapeInfo().get(bd.getSymbolicName() + '_' + bd.getVersion()); - if (format == null) - format = (String) bundleManifest.get(BundleDescriptionFactory.BUNDLE_FILE_KEY); - boolean isDir = (format != null && format.equals(BundleDescriptionFactory.DIR) ? true : false); - - IArtifactKey key = new ArtifactKey(MetadataGeneratorHelper.OSGI_BUNDLE_CLASSIFIER, bd.getSymbolicName(), Version.create(bd.getVersion().toString())); - IArtifactDescriptor ad = MetadataGeneratorHelper.createArtifactDescriptor(key, new File(bd.getLocation()), true, false); - ((ArtifactDescriptor) ad).setProperty(IArtifactDescriptor.DOWNLOAD_CONTENTTYPE, IArtifactDescriptor.TYPE_ZIP); - File bundleFile = new File(bd.getLocation()); - if (bundleFile.isDirectory()) - publishArtifact(ad, bundleFile.listFiles(), destination, false, bundleFile); - else - publishArtifact(ad, new File[] {bundleFile}, destination, true); - if (info.reuseExistingPack200Files() && !info.publishArtifacts()) { - File packFile = new Path(bd.getLocation()).addFileExtension("pack.gz").toFile(); //$NON-NLS-1$ - if (packFile.exists()) { - IArtifactDescriptor ad200 = MetadataGeneratorHelper.createPack200ArtifactDescriptor(key, packFile, ad.getProperty(IArtifactDescriptor.ARTIFACT_SIZE)); - publishArtifact(ad200, new File[] {packFile}, destination, true); - } - } - - IInstallableUnit bundleIU = MetadataGeneratorHelper.createBundleIU(bd, bundleManifest, isDir, key, true); - - if (isFragment(bd)) { - // TODO: Can NL fragments be multi-host? What special handling - // is required for multi-host fragments in general? - String hostId = bd.getHost().getName(); - String hostKey = makeSimpleKey(hostId); - String[] cachedValues = (String[]) bundleLocalizationMap.get(hostKey); - - if (cachedValues != null) { - MetadataGeneratorHelper.createHostLocalizationFragment(bundleIU, bd, hostId, cachedValues, localizationIUs); - } - } - - result.rootIUs.add(bundleIU); - result.nonRootIUs.addAll(localizationIUs); - localizationIUs.clear(); - } - } - } - } - } - - private static boolean isFragment(BundleDescription bd) { - return (bd.getHost() != null ? true : false); - } - - private static String makeSimpleKey(BundleDescription bd) { - // TODO: can't use the bundle version in the key for the BundleLocalization - // property map since the host specification for a fragment has a - // version range, not a version. Hence, this mechanism for finding - // manifest localization property files may break under changes - // to the BundleLocalization property of a bundle. - return makeSimpleKey(bd.getSymbolicName() /*, bd.getVersion() */); - } - - private static String makeSimpleKey(String id /*, Version version */) { - return id; // + '_' + version.toString(); - } - - /** - * Generates IUs corresponding to update site categories. - * @param categoriesToFeatures Map of SiteCategory ->Set (Feature IUs in that category). - * @param result The generator result being built - * @deprecated moved to SiteXMLAction - */ - protected void generateCategoryIUs(Map categoriesToFeatures, GeneratorResult result) { - for (Iterator it = categoriesToFeatures.keySet().iterator(); it.hasNext();) { - SiteCategory category = (SiteCategory) it.next(); - result.nonRootIUs.add(MetadataGeneratorHelper.createCategoryIU(category, (Set) categoriesToFeatures.get(category), null)); - } - } - - /** - * @deprecated moved to ConfigCUsAction - */ - private void storeConfigData(GeneratorResult result) { - if (result.configData.containsKey(info.getLauncherConfig())) - return; //been here, done this - - LauncherData launcherData = info.getLauncherData(); - if (launcherData == null) - return; - - File fwConfigFile = new File(launcherData.getFwConfigLocation(), EquinoxConstants.CONFIG_INI); - if (fwConfigFile.exists()) { - if (info instanceof EclipseInstallGeneratorInfoProvider) { - ((EclipseInstallGeneratorInfoProvider) info).loadConfigData(fwConfigFile); - ConfigData data = info.getConfigData(); - result.configData.put(info.getLauncherConfig(), data); - } - } - } - - /** - * @deprecated moved to ConfigCUsAction - */ - protected GeneratorBundleInfo createGeneratorBundleInfo(BundleInfo bundleInfo, GeneratorResult result) { - if (bundleInfo.getLocation() != null) - return new GeneratorBundleInfo(bundleInfo); - - String name = bundleInfo.getSymbolicName(); - - //easy case: do we have a matching IU? - IInstallableUnit iu = result.getInstallableUnit(name); - if (iu != null) { - bundleInfo.setVersion(iu.getVersion().toString()); - return new GeneratorBundleInfo(bundleInfo); - } - - //harder: try id_version - int i = name.indexOf('_'); - while (i > -1) { - Version version = null; - try { - version = Version.create(name.substring(i)); - bundleInfo.setSymbolicName(name.substring(0, i)); - bundleInfo.setVersion(version.toString()); - return new GeneratorBundleInfo(bundleInfo); - } catch (IllegalArgumentException e) { - // the '_' found was probably part of the symbolic id - i = name.indexOf('_', i); - } - } - - //Query the repo - IQuery query = QueryUtil.createIUQuery(name); - Iterator matches = info.getMetadataRepository().query(query, null).iterator(); - //pick the newest match - IInstallableUnit newest = null; - while (matches.hasNext()) { - IInstallableUnit candidate = (IInstallableUnit) matches.next(); - if (newest == null || (newest.getVersion().compareTo(candidate.getVersion()) < 0)) - newest = candidate; - } - if (newest != null) { - bundleInfo.setVersion(newest.getVersion().toString()); - return new GeneratorBundleInfo(bundleInfo); - } - - return null; - } - - /** - * @deprecated moved to ConfigCUsAction - */ - protected void generateBundleConfigIUs(BundleInfo[] infos, GeneratorResult result, String launcherConfig, int defaultStartLevel) { - if (infos == null) - return; - - String cuIdPrefix = ""; //$NON-NLS-1$ - String filter = null; - if (launcherConfig != null) { - //launcher config is os_ws_arch, we want suffix ws.os.arch - String[] config = parseConfigSpec(launcherConfig); - cuIdPrefix = config[1] + '.' + config[0] + '.' + config[2]; - - filter = "(& (osgi.ws=" + config[1] + ") (osgi.os=" + config[0] + ") (osgi.arch=" + config[2] + "))"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - } - - List allCUs = new ArrayList(); - for (int i = 0; i < infos.length; i++) { - GeneratorBundleInfo bundle = createGeneratorBundleInfo(infos[i], result); - if (bundle == null) - continue; - - if (bundle.getSymbolicName().equals(ORG_ECLIPSE_EQUINOX_LAUNCHER)) { - bundle = EclipseInstallGeneratorInfoProvider.createLauncher(); - } else if (bundle.getSymbolicName().startsWith(ORG_ECLIPSE_EQUINOX_LAUNCHER + '.')) { - //launcher fragments will be handled by generateDefaultConfigIU(Set) for --launcher.library. - //they don't need to be started so skip them here to avoid having to merge config commands - continue; - } - if (bundle.getSymbolicName().equals(ORG_ECLIPSE_UPDATE_CONFIGURATOR)) { - bundle.setStartLevel(BundleInfo.NO_LEVEL); - bundle.setMarkedAsStarted(false); - bundle.setSpecialConfigCommands("setProgramProperty(propName:org.eclipse.update.reconcile, propValue:false);"); //$NON-NLS-1$ - bundle.setSpecialUnconfigCommands("setProgramProperty(propName:org.eclipse.update.reconcile, propValue:);"); //$NON-NLS-1$ - } else if ((bundle.getStartLevel() == BundleInfo.NO_LEVEL || bundle.getStartLevel() == defaultStartLevel) && !bundle.isMarkedAsStarted()) { - // this bundle does not require any particular configuration, the plug-in default IU will handle installing it - continue; - } - - IInstallableUnit cu = MetadataGeneratorHelper.createBundleConfigurationUnit(bundle.getSymbolicName(), Version.create(bundle.getVersion()), false, bundle, info.getFlavor() + cuIdPrefix, filter); - if (cu != null) { - allCUs.add(cu); - result.rootIUs.add(cu); - String key = (productFile != null && productFile.useFeatures()) ? GeneratorResult.CONFIGURATION_CUS : bundle.getSymbolicName(); - if (result.configurationIUs.containsKey(key)) { - ((Set) result.configurationIUs.get(key)).add(cu); - } else { - Set set = new HashSet(); - set.add(cu); - result.configurationIUs.put(key, set); - } - } - } - IMetadataRepository metadataRepository = info.getMetadataRepository(); - if (metadataRepository != null && !allCUs.isEmpty()) { - // Product Query will run against the repo later in createProductIU, make sure these CUs are in before then - metadataRepository.addInstallableUnits(allCUs); - } - - } - - /** - * @deprecated moved to ConfigCUsAction (and perhaps a couple other places...) - */ - protected void generateConfigIUs(GeneratorResult result) { - ConfigData data = info.getConfigData(); - if ((data == null || data.getBundles().length == 0) && info.getLauncherConfig() != null) { - //We have the config.ini but not necessarily all the needed bundle IUs, remember for later - storeConfigData(result); - } else if (data != null) { - // generation against an eclipse install (config.ini + bundles) - generateBundleConfigIUs(data.getBundles(), result, info.getLauncherConfig(), data.getInitialBundleStartLevel()); - } else if (result.configData.size() > 0 && generateRootIU) { - // generation from remembered config.ini's - // we have N platforms, generate a CU for each - // TODO try and find common properties across platforms - for (Iterator iterator = result.configData.keySet().iterator(); iterator.hasNext();) { - String launcherConfig = (String) iterator.next(); - data = (ConfigData) result.configData.get(launcherConfig); - generateBundleConfigIUs(data.getBundles(), result, launcherConfig, data.getInitialBundleStartLevel()); - } - } - - List bundleInfoList = new ArrayList(); - List defaults = new ArrayList(); - if (info.addDefaultIUs()) - bundleInfoList.addAll(info.getDefaultIUs(result.rootIUs)); - - bundleInfoList.addAll(info.getOtherIUs()); - - for (Iterator iterator = bundleInfoList.iterator(); iterator.hasNext();) { - GeneratorBundleInfo bundle = (GeneratorBundleInfo) iterator.next(); - IInstallableUnit configuredIU = result.getInstallableUnit(bundle.getSymbolicName()); - if (configuredIU == null) { - if (!generateRootIU && data == null) - continue; - IQuery query = QueryUtil.createIUQuery(bundle.getSymbolicName()); - IMetadataRepository metadataRepository = info.getMetadataRepository(); - if (metadataRepository == null) - continue; - Iterator matches = metadataRepository.query(query, null).iterator(); - //pick the newest match - IInstallableUnit newest = null; - while (matches.hasNext()) { - IInstallableUnit candidate = (IInstallableUnit) matches.next(); - if (newest == null || (newest.getVersion().compareTo(candidate.getVersion()) < 0)) - newest = candidate; - } - if (newest != null) { - configuredIU = newest; - } else { - continue; - } - } - bundle.setVersion(configuredIU.getVersion().toString()); - IMatchExpression filter = configuredIU == null ? null : configuredIU.getFilter(); - IInstallableUnit cu = MetadataGeneratorHelper.createBundleConfigurationUnit(bundle.getSymbolicName(), Version.create(bundle.getVersion()), false, bundle, info.getFlavor(), filter); - //the configuration unit should share the same platform filter as the IU being configured. - if (cu != null) { - result.rootIUs.add(cu); - defaults.add(cu); - } - String key = null; - if (productFile != null && productFile.useFeatures()) - key = GeneratorResult.CONFIGURATION_CUS; - else if (bundle.getSymbolicName().startsWith(ORG_ECLIPSE_EQUINOX_LAUNCHER + '.')) - key = ORG_ECLIPSE_EQUINOX_LAUNCHER; - else - key = bundle.getSymbolicName(); - if (result.configurationIUs.containsKey(key)) { - ((Set) result.configurationIUs.get(key)).add(cu); - } else { - Set set = new HashSet(); - set.add(cu); - result.configurationIUs.put(key, set); - } - } - - IMetadataRepository metadataRepository = info.getMetadataRepository(); - if (metadataRepository != null && !defaults.isEmpty()) { - // Product Query will run against the repo later in createProductIU, make sure these CUs are in before then - metadataRepository.addInstallableUnits(defaults); - } - } - - /** - * Short term fix to ensure IUs that have no corresponding category are not lost. - * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=211521. - * @deprecated moved to RootIUAction - */ - private IInstallableUnit generateDefaultCategory(IInstallableUnit rootIU) { - rootCategory.add(rootIU); - - InstallableUnitDescription cat = new MetadataFactory.InstallableUnitDescription(); - cat.setSingleton(true); - String categoryId = rootIU.getId() + ".categoryIU"; //$NON-NLS-1$ - cat.setId(categoryId); - cat.setVersion(Version.emptyVersion); - cat.setProperty(IInstallableUnit.PROP_NAME, rootIU.getProperty(IInstallableUnit.PROP_NAME)); - cat.setProperty(IInstallableUnit.PROP_DESCRIPTION, rootIU.getProperty(IInstallableUnit.PROP_DESCRIPTION)); - - ArrayList required = new ArrayList(rootCategory.size()); - for (Iterator iterator = rootCategory.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); - required.add(MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, iu.getId(), VersionRange.emptyRange, iu.getFilter(), false, false)); - } - cat.setRequirements((IRequirement[]) required.toArray(new IRequirement[required.size()])); - cat.setCapabilities(new IProvidedCapability[] {MetadataFactory.createProvidedCapability(IInstallableUnit.NAMESPACE_IU_ID, categoryId, Version.emptyVersion)}); - cat.setArtifacts(new IArtifactKey[0]); - cat.setProperty(InstallableUnitDescription.PROP_TYPE_CATEGORY, "true"); //$NON-NLS-1$ - return MetadataFactory.createInstallableUnit(cat); - } - - /** - * @deprecated moved to DefaultCUsAction - */ - private void generateDefaultConfigIU(Set ius) { - // TODO this is a bit of a hack. We need to have the default IU fragment generated with code that configures - // and unconfigures. The Generator should be decoupled from any particular provider but it is not clear - // that we should add the create* methods to IGeneratorInfo... - // MockBundleDescription bd1 = new MockBundleDescription("defaultConfigure"); - // MockBundleDescription bd2 = new MockBundleDescription("defaultUnconfigure"); - EclipseInstallGeneratorInfoProvider provider = (EclipseInstallGeneratorInfoProvider) info; - ius.add(MetadataGeneratorHelper.createDefaultBundleConfigurationUnit(provider.createDefaultConfigurationBundleInfo(), provider.createDefaultUnconfigurationBundleInfo(), info.getFlavor())); - ius.add(MetadataGeneratorHelper.createDefaultFeatureConfigurationUnit(info.getFlavor())); - ius.add(MetadataGeneratorHelper.createDefaultConfigurationUnitForSourceBundles(info.getFlavor())); - } - - /** - * This method generates IUs for the launchers found in the org.eclipse.executable feature, if present. - * @return <code>true</code> if the executable feature was processed successfully, - * and <code>false</code> otherwise. - * @deprecated moved to ExecutablesDescriptor and EquinoxExecutableAction - */ - private boolean generateExecutableFeatureIUs(GeneratorResult result, IArtifactRepository destination) { - File parentDir = info.getFeaturesLocation(); - if (parentDir == null || !parentDir.exists()) - return false; - File[] featureDirs = parentDir.listFiles(); - if (featureDirs == null) - return false; - File executableFeatureDir = null; - final String featurePrefix = "org.eclipse.equinox.executable_"; //$NON-NLS-1$ - for (int i = 0; i < featureDirs.length; i++) { - if (featureDirs[i].getName().startsWith(featurePrefix)) { - executableFeatureDir = featureDirs[i]; - break; - } - } - if (executableFeatureDir == null) - return false; - File binDir = new File(executableFeatureDir, "bin"); //$NON-NLS-1$ - if (!binDir.exists()) - return false; - //the bin directory is dividing into a directory tree of the form /bin/ws/os/arch - File[] wsDirs = binDir.listFiles(); - if (wsDirs == null) - return false; - String versionString = executableFeatureDir.getName().substring(featurePrefix.length()); - for (int wsIndex = 0; wsIndex < wsDirs.length; wsIndex++) { - String ws = wsDirs[wsIndex].getName(); - File[] osDirs = wsDirs[wsIndex].listFiles(); - if (osDirs == null) - continue; - for (int osIndex = 0; osIndex < osDirs.length; osIndex++) { - String os = osDirs[osIndex].getName(); - File[] archDirs = osDirs[osIndex].listFiles(); - if (archDirs == null) - continue; - for (int archIndex = 0; archIndex < archDirs.length; archIndex++) { - String arch = archDirs[archIndex].getName(); - generateExecutableIUs(ws, os, arch, versionString, archDirs[archIndex], result, destination); - } - } - } - return true; - } - - /** - * Generates IUs and CUs for the files that make up the launcher for a given - * ws/os/arch combination. - * @deprecated moved to EquinoxExecutableAction - */ - private void generateExecutableIUs(String ws, String os, final String arch, String version, File root, GeneratorResult result, IArtifactRepository destination) { - if (root == null) - return; - - //Create the IU - InstallableUnitDescription iu = new MetadataFactory.InstallableUnitDescription(); - iu.setSingleton(true); - String productNamespace = (productFile != null) ? productFile.getId() : "org.eclipse"; //$NON-NLS-1$ - String launcherIdPrefix = productNamespace + PRODUCT_LAUCHER_SUFFIX; - String launcherId = launcherIdPrefix + '.' + ws + '.' + os + '.' + arch; - iu.setId(launcherId); - Version launcherVersion = Version.create(version); - iu.setVersion(launcherVersion); - iu.setSingleton(true); - IMatchExpression filter = null; - if (!ws.equals(CONFIG_ANY) && !os.equals(CONFIG_ANY) && !arch.equals(CONFIG_ANY)) { - filter = InstallableUnit.parseFilter("(& (osgi.ws=" + ws + ") (osgi.os=" + os + ") (osgi.arch=" + arch + "))"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - iu.setFilter(filter); - } - - IArtifactKey key = MetadataGeneratorHelper.createLauncherArtifactKey(launcherId, launcherVersion); - iu.setArtifacts(new IArtifactKey[] {key}); - iu.setTouchpointType(MetadataGeneratorHelper.TOUCHPOINT_NATIVE); - IProvidedCapability launcherCapability = MetadataFactory.createProvidedCapability(info.getFlavor() + productNamespace, launcherIdPrefix, launcherVersion); - iu.setCapabilities(new IProvidedCapability[] {MetadataGeneratorHelper.createSelfCapability(launcherId, launcherVersion), launcherCapability}); - - String launcherFragment = ORG_ECLIPSE_EQUINOX_LAUNCHER + '.' + ws + '.' + os; - if (!(Constants.OS_MACOSX.equals(os) && !Constants.ARCH_X86_64.equals(arch))) - launcherFragment += '.' + arch; - iu.setRequirements(new IRequirement[] {MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, launcherFragment, VersionRange.emptyRange, filter, false, false)}); - result.rootIUs.add(MetadataFactory.createInstallableUnit(iu)); - - //Create the CU - InstallableUnitFragmentDescription cu = new InstallableUnitFragmentDescription(); - String configUnitId = info.getFlavor() + launcherId; - cu.setId(configUnitId); - cu.setVersion(launcherVersion); - if (filter != null) - cu.setFilter(filter); - cu.setHost(new IRequirement[] {MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, launcherId, new VersionRange(launcherVersion, true, launcherVersion, true), null, false, false)}); - cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); - //TODO bug 218890, would like the fragment to provide the launcher capability as well, but can't right now. - cu.setCapabilities(new IProvidedCapability[] {MetadataGeneratorHelper.createSelfCapability(configUnitId, launcherVersion)}); - - mungeLauncherFileNames(root); - - cu.setTouchpointType(MetadataGeneratorHelper.TOUCHPOINT_NATIVE); - Map touchpointData = new HashMap(); - String configurationData = "unzip(source:@artifact, target:${installFolder});"; //$NON-NLS-1$ - - IInstallableUnit launcherNameIU = null; - - File executableLocation = info.getExecutableLocation(); - if (executableLocation != null) { - if (!executableLocation.exists()) { - if (Constants.OS_WIN32.equals(os) && !executableLocation.getName().endsWith(".exe")) { //$NON-NLS-1$ - executableLocation = new File(executableLocation.getParentFile(), executableLocation.getName() + ".exe"); //$NON-NLS-1$ - } else if (Constants.OS_MACOSX.equals(os)) { - String name = executableLocation.getName(); - File parent = executableLocation.getParentFile(); - executableLocation = new File(parent, name + ".app/Contents/MacOS/" + name); //$NON-NLS-1$ - } - } - - if (executableLocation.exists() && executableLocation.isFile()) - launcherNameIU = MetadataGeneratorHelper.generateLauncherSetter(executableLocation.getName(), launcherId, launcherVersion, os, ws, arch, result.rootIUs); - } - - if (launcherNameIU == null && productFile != null && productFile.getLauncherName() != null) { - launcherNameIU = MetadataGeneratorHelper.generateLauncherSetter(productFile.getLauncherName(), launcherId, launcherVersion, os, ws, arch, result.rootIUs); - } - - if (Constants.OS_MACOSX.equals(os)) { - File[] appFolders = root.listFiles(new FilenameFilter() { - public boolean accept(File dir, String name) { - return name.substring(name.length() - 4, name.length()).equalsIgnoreCase(".app"); //$NON-NLS-1$ - } - }); - for (int i = 0; appFolders != null && i < appFolders.length; i++) { - File macOSFolder = new File(appFolders[i], "Contents/MacOS"); //$NON-NLS-1$ - if (macOSFolder.exists()) { - File[] launcherFiles = macOSFolder.listFiles(); - for (int j = 0; j < launcherFiles.length; j++) { - configurationData += " chmod(targetDir:${installFolder}/" + appFolders[i].getName() + "/Contents/MacOS/, targetFile:" + launcherFiles[j].getName() + ", permissions:755);"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (launcherNameIU == null && launcherFiles[i].isFile() && new Path(launcherFiles[j].getName()).getFileExtension() == null) - launcherNameIU = MetadataGeneratorHelper.generateLauncherSetter(launcherFiles[j].getName(), launcherId, launcherVersion, os, ws, arch, result.rootIUs); - } - } - } - } else if (!Constants.OS_WIN32.equals(os)) { - File[] launcherFiles = root.listFiles(); - for (int i = 0; launcherFiles != null && i < launcherFiles.length; i++) { - configurationData += " chmod(targetDir:${installFolder}, targetFile:" + launcherFiles[i].getName() + ", permissions:755);"; //$NON-NLS-1$ //$NON-NLS-2$ - if (launcherNameIU == null && launcherFiles[i].isFile() && new Path(launcherFiles[i].getName()).getFileExtension() == null) - launcherNameIU = MetadataGeneratorHelper.generateLauncherSetter(launcherFiles[i].getName(), launcherId, launcherVersion, os, ws, arch, result.rootIUs); - } - } else if (launcherNameIU == null) { - //windows - File[] launcherFiles = root.listFiles(new FilenameFilter() { - public boolean accept(File parent, String name) { - return name.endsWith(".exe"); //$NON-NLS-1$ - } - }); - if (launcherFiles != null && launcherFiles.length > 0) - launcherNameIU = MetadataGeneratorHelper.generateLauncherSetter(launcherFiles[0].getName(), launcherId, launcherVersion, os, ws, arch, result.rootIUs); - } - touchpointData.put("install", configurationData); //$NON-NLS-1$ - String unConfigurationData = "cleanupzip(source:@artifact, target:${installFolder});"; //$NON-NLS-1$ - touchpointData.put("uninstall", unConfigurationData); //$NON-NLS-1$ - cu.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - IInstallableUnit unit = MetadataFactory.createInstallableUnit(cu); - result.rootIUs.add(unit); - //The Product Query will need to include the launcher CU fragments as a workaround to bug 218890 - if (result.configurationIUs.containsKey(launcherIdPrefix)) { - ((Set) result.configurationIUs.get(launcherIdPrefix)).add(unit); - if (launcherNameIU != null) - ((Set) result.configurationIUs.get(launcherIdPrefix)).add(launcherNameIU); - } else { - Set set = new HashSet(); - set.add(unit); - if (launcherNameIU != null) - set.add(launcherNameIU); - result.configurationIUs.put(launcherIdPrefix, set); - } - - //Create the artifact descriptor - IArtifactDescriptor descriptor = MetadataGeneratorHelper.createArtifactDescriptor(key, root, false, true); - publishArtifact(descriptor, root.listFiles(), destination, false, root); - } - - /** - * For each platform, generate a CU containing the information for the config.ini - * @deprecated moved to ProductAction and ConfigCUsAction - */ - private void generateProductConfigCUs(GeneratorResult result) { - for (Iterator iterator = result.configData.keySet().iterator(); iterator.hasNext();) { - String launcherConfig = (String) iterator.next(); - String[] config = parseConfigSpec(launcherConfig); - String ws = config[1]; - String os = config[0]; - String arch = config[2]; - - ConfigData data = (ConfigData) result.configData.get(launcherConfig); - - InstallableUnitDescription cu = new MetadataFactory.InstallableUnitDescription(); - String configUnitId = info.getFlavor() + productFile.getId() + ".config." + ws + '.' + os + '.' + arch; //$NON-NLS-1$ - - String version = getProductVersion(); - Version cuVersion = Version.create(version); - cu.setId(configUnitId); - cu.setVersion(cuVersion); - cu.setSingleton(true); - cu.setFilter("(& (osgi.ws=" + ws + ") (osgi.os=" + os + ") (osgi.arch=" + arch + "))"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - - IProvidedCapability productConfigCapability = MetadataFactory.createProvidedCapability(info.getFlavor() + productFile.getId(), productFile.getId() + PRODUCT_CONFIG_SUFFIX, cuVersion); - IProvidedCapability selfCapability = MetadataGeneratorHelper.createSelfCapability(configUnitId, cuVersion); - cu.setCapabilities(new IProvidedCapability[] {selfCapability, productConfigCapability}); - - cu.setTouchpointType(MetadataGeneratorHelper.TOUCHPOINT_OSGI); - Map touchpointData = new HashMap(); - String[] dataStrings = getConfigurationStrings(data); - touchpointData.put("configure", dataStrings[0]); //$NON-NLS-1$ - touchpointData.put("unconfigure", dataStrings[1]); //$NON-NLS-1$ - cu.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - - result.rootIUs.add(MetadataFactory.createInstallableUnit(cu)); - } - } - - /** - * For the given platform (ws, os, arch) generate the CU that will populate the product.ini file - * @deprecated moved to ProductAction and ConfigCUsAction - */ - private void generateProductIniCU(String ws, String os, String arch, String version, GeneratorResult result) { - if (productFile == null) - return; - - //attempt to merge arguments from the launcher data and the product file - Set jvmArgs = new LinkedHashSet(); - Set progArgs = new LinkedHashSet(); - LauncherData launcherData = info.getLauncherData(); - if (launcherData != null) { - jvmArgs.addAll(Arrays.asList(launcherData.getJvmArgs())); - progArgs.addAll(Arrays.asList(launcherData.getProgramArgs())); - } - progArgs.addAll(Arrays.asList(getArrayFromString(productFile.getProgramArguments(os), " "))); //$NON-NLS-1$ - jvmArgs.addAll(Arrays.asList(getArrayFromString(productFile.getVMArguments(os), " "))); //$NON-NLS-1$ - - String[] dataStrings = getLauncherConfigStrings((String[]) jvmArgs.toArray(new String[jvmArgs.size()]), (String[]) progArgs.toArray(new String[progArgs.size()])); - String configurationData = dataStrings[0]; - String unconfigurationData = dataStrings[1]; - - InstallableUnitDescription cu = new MetadataFactory.InstallableUnitDescription(); - String configUnitId = info.getFlavor() + productFile.getId() + ".ini." + ws + '.' + os + '.' + arch; //$NON-NLS-1$ - Version cuVersion = Version.create(version); - cu.setId(configUnitId); - cu.setVersion(cuVersion); - cu.setSingleton(true); - cu.setFilter("(& (osgi.ws=" + ws + ") (osgi.os=" + os + ") (osgi.arch=" + arch + "))"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - - IProvidedCapability productIniCapability = MetadataFactory.createProvidedCapability(info.getFlavor() + productFile.getId(), productFile.getId() + PRODUCT_INI_SUFFIX, cuVersion); - IProvidedCapability selfCapability = MetadataGeneratorHelper.createSelfCapability(configUnitId, cuVersion); - cu.setCapabilities(new IProvidedCapability[] {selfCapability, productIniCapability}); - - cu.setTouchpointType(MetadataGeneratorHelper.TOUCHPOINT_OSGI); - Map touchpointData = new HashMap(); - touchpointData.put("configure", configurationData); //$NON-NLS-1$ - touchpointData.put("unconfigure", unconfigurationData); //$NON-NLS-1$ - cu.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - - result.rootIUs.add(MetadataFactory.createInstallableUnit(cu)); - - } - - /** - * Generates metadata for the given features. - * @deprecated moved to FeaturesAction - */ - protected void generateFeatureIUs(Feature[] features, GeneratorResult result, IArtifactRepository destination) { - Map categoriesToFeatureIUs = new HashMap(); - Map featuresToCategories = getFeatureToCategoryMappings(); - //Build Feature IUs, and add them to any corresponding categories - for (int i = 0; i < features.length; i++) { - Feature feature = features[i]; - //publish feature site references - URLEntry updateURL = feature.getUpdateSite(); - //don't enable feature update sites by default since this results in too many - //extra sites being loaded and searched (Bug 234177) - if (updateURL != null) - generateSiteReference(updateURL.getURL(), updateURL.getAnnotation(), feature.getId(), false); - URLEntry[] discoverySites = feature.getDiscoverySites(); - for (int j = 0; j < discoverySites.length; j++) - generateSiteReference(discoverySites[j].getURL(), discoverySites[j].getAnnotation(), feature.getId(), false); - - //generate feature IU - String location = feature.getLocation(); - boolean isExploded = (location.endsWith(".jar") ? false : true); //$NON-NLS-1$ - IInstallableUnit featureIU = MetadataGeneratorHelper.createFeatureJarIU(feature, true); - Collection artifacts = featureIU.getArtifacts(); - storePluginShape(feature, result); - for (Iterator iterator = artifacts.iterator(); iterator.hasNext();) { - IArtifactDescriptor ad = MetadataGeneratorHelper.createArtifactDescriptor((IArtifactKey) iterator.next(), new File(location), true, false); - if (isExploded) - publishArtifact(ad, new File(location).listFiles(), destination, false, new File(location)); - else - publishArtifact(ad, new File[] {new File(location)}, destination, true); - } - IInstallableUnit generated = MetadataGeneratorHelper.createGroupIU(feature, featureIU); - result.rootIUs.add(generated); - result.rootIUs.add(featureIU); - - // @deprecated moved to SiteXMLAction - Set categories = getCategories(feature, featuresToCategories); - if (categories != null) { - for (Iterator it = categories.iterator(); it.hasNext();) { - SiteCategory category = (SiteCategory) it.next(); - Set featureIUs = (Set) categoriesToFeatureIUs.get(category); - if (featureIUs == null) { - featureIUs = new HashSet(); - categoriesToFeatureIUs.put(category, featureIUs); - } - featureIUs.add(generated); - } - } else { - rootCategory.add(generated); - } - } - generateCategoryIUs(categoriesToFeatureIUs, result); - } - - /** - * @deprecated moved to FeaturesAction - */ - private void storePluginShape(Feature feature, GeneratorResult result) { - FeatureEntry[] entries = feature.getEntries(); - for (int i = 0; i < entries.length; i++) { - if (entries[i].isPlugin() || entries[i].isFragment()) { - result.getPluginShapeInfo().put(entries[i].getId() + '_' + entries[i].getVersion(), entries[i].isUnpack() ? BundleDescriptionFactory.DIR : BundleDescriptionFactory.JAR); - } - } - } - - /** - * @deprecated moved to various other places. mainly the aggregator actions (e.g., EclipseInstallAction) - */ - protected void generateNativeIUs(File executableLocation, GeneratorResult result, IArtifactRepository destination) { - //generate data for JRE - File jreLocation = info.getJRELocation(); - IArtifactDescriptor artifact = MetadataGeneratorHelper.createJREData(jreLocation, result.rootIUs); - publishArtifact(artifact, new File[] {jreLocation}, destination, false); - - if (info.getLauncherConfig() != null) { - String[] config = parseConfigSpec(info.getLauncherConfig()); - String version = getProductVersion(); - File root = null; - if (executableLocation != null) - root = executableLocation.getParentFile(); - else if (info instanceof EclipseInstallGeneratorInfoProvider) - root = ((EclipseInstallGeneratorInfoProvider) info).getBaseLocation(); - generateExecutableIUs(config[1], config[0], config[2], version, root, result, destination); - generateProductIniCU(config[1], config[0], config[2], version, result); - return; - } - - //If the executable feature is present, use it to generate IUs for launchers - if (generateExecutableFeatureIUs(result, destination) || executableLocation == null) - return; - - //generate data for executable launcher - artifact = MetadataGeneratorHelper.createLauncherIU(executableLocation, info.getFlavor(), result.rootIUs); - File[] launcherFiles = null; - //hard-coded name is ok, since console launcher is not branded, and appears on Windows only - File consoleLauncher = new File(executableLocation.getParentFile(), "eclipsec.exe"); //$NON-NLS-1$ - if (consoleLauncher.exists()) - launcherFiles = new File[] {executableLocation, consoleLauncher}; - else - launcherFiles = new File[] {executableLocation}; - publishArtifact(artifact, launcherFiles, destination, false); - } - - /** - * @deprecated moved to various other places. mainly the aggregator actions (e.g., EclipseInstallAction) - */ - protected void generateRootIU(GeneratorResult result, String rootIUId, String rootIUVersion) { - IInstallableUnit rootIU = null; - - if (info.getProductFile() != null) - rootIU = createProductIU(result); - else if (rootIUId != null) - rootIU = createTopLevelIU(result, rootIUId, rootIUVersion); - - if (rootIU == null) - return; - - result.nonRootIUs.add(rootIU); - result.nonRootIUs.add(generateDefaultCategory(rootIU)); - } - - /** - * Generates and publishes a reference to an update site location - * @param location The update site location - * @param featureId the identifier of the feature where the error occurred, or null - * @param isEnabled Whether the site should be enabled by default - * @deprecated moved to FeaturesAction - */ - private void generateSiteReference(String location, String name, String featureId, boolean isEnabled) { - IMetadataRepository metadataRepo = info.getMetadataRepository(); - try { - URI associateLocation = URIUtil.fromString(location); - int flags = isEnabled ? IRepository.ENABLED : IRepository.NONE; - ArrayList refs = new ArrayList(); - refs.add(new RepositoryReference(associateLocation, name, IRepository.TYPE_METADATA, flags)); - refs.add(new RepositoryReference(associateLocation, name, IRepository.TYPE_ARTIFACT, flags)); - metadataRepo.addReferences(refs); - } catch (URISyntaxException e) { - String message = "Invalid site reference: " + location; //$NON-NLS-1$ - if (featureId != null) - message = message + " in feature: " + featureId; //$NON-NLS-1$ - LogHelper.log(new Status(IStatus.ERROR, Activator.ID, message)); - } - } - - /** - * @deprecated moved to BundlesAction - */ - protected BundleDescription[] getBundleDescriptions(File[] bundleLocations) { - if (bundleLocations == null) - return new BundleDescription[0]; - boolean addSimpleConfigurator = false; - boolean scIn = false; - for (int i = 0; i < bundleLocations.length; i++) { - if (!addSimpleConfigurator) - addSimpleConfigurator = bundleLocations[i].toString().indexOf(ORG_ECLIPSE_UPDATE_CONFIGURATOR) > 0; - if (!scIn) { - scIn = bundleLocations[i].toString().indexOf(ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR) > 0; - if (scIn) - break; - } - } - if (scIn) - addSimpleConfigurator = false; - BundleDescription[] result = new BundleDescription[bundleLocations.length + (addSimpleConfigurator ? 1 : 0)]; - BundleDescriptionFactory factory = getBundleFactory(); - for (int i = 0; i < bundleLocations.length; i++) { - BundleDescription desc = factory.getBundleDescription(bundleLocations[i]); - if (desc != null) - result[i] = desc; - } - if (addSimpleConfigurator) { - //Add simple configurator to the list of bundles - try { - File location = new File(FileLocator.toFileURL(Activator.getContext().getBundle().getEntry(ORG_ECLIPSE_EQUINOX_SIMPLECONFIGURATOR + ".jar")).getFile()); //$NON-NLS-1$ - result[result.length - 1] = factory.getBundleDescription(location); - } catch (IOException e) { - e.printStackTrace(); - } - } - return result; - } - - /** - * @deprecated moved to BundlesAction - */ - protected BundleDescriptionFactory getBundleFactory() { - return new BundleDescriptionFactory(stateObjectFactory, null); - } - - /** - * Returns the categories corresponding to the given feature, or null if there - * are no applicable categories. - * @param feature The feature to return categories for - * @param featuresToCategories A map of SiteFeature->Set<SiteCategory> - * @return A Set<SiteCategory> of the categories corresponding to the feature, or <code>null</code> - * @deprecated moved to SiteXMLAction - */ - private Set getCategories(Feature feature, Map featuresToCategories) { - //find the SiteFeature corresponding to the given feature - for (Iterator it = featuresToCategories.keySet().iterator(); it.hasNext();) { - SiteFeature siteFeature = (SiteFeature) it.next(); - String siteVersion = siteFeature.getFeatureVersion(); - if (!siteFeature.getFeatureIdentifier().equals(feature.getId())) - continue; - if (siteVersion.endsWith("qualifier")) { //$NON-NLS-1$ - String withoutQualifier = siteVersion.substring(0, siteVersion.lastIndexOf("qualifier")); //$NON-NLS-1$ - String featureVersion = feature.getVersion(); - if (featureVersion.length() >= withoutQualifier.length() && featureVersion.substring(0, withoutQualifier.length()).equals(withoutQualifier)) - return (Set) featuresToCategories.get(siteFeature); - } else if (siteFeature.getFeatureVersion().equals(feature.getVersion())) { - return (Set) featuresToCategories.get(siteFeature); - } - } - return null; - } - - /** - * @deprecated moved to FeaturesAction - */ - protected Feature[] getFeatures(File folder) { - if (folder == null || !folder.exists()) - return new Feature[0]; - File[] locations = folder.listFiles(); - ArrayList result = new ArrayList(locations.length); - for (int i = 0; i < locations.length; i++) { - Feature feature = new FeatureParser().parse(locations[i]); - if (feature != null) { - feature.setLocation(locations[i].getAbsolutePath()); - result.add(feature); - } - } - return (Feature[]) result.toArray(new Feature[result.size()]); - } - - /** - * Computes the mapping of features to categories as defined in the site.xml, - * if available. Returns an empty map if there is not site.xml, or no categories. - * @return A map of SiteFeature -> Set<SiteCategory>. - */ - protected Map getFeatureToCategoryMappings() { - HashMap mappings = new HashMap(); - URI siteLocation = info.getSiteLocation(); - if (siteLocation == null) - return mappings; - InputStream input; - SiteModel site = null; - try { - input = new BufferedInputStream(URIUtil.toURL(siteLocation).openStream()); - site = new DefaultSiteParser().parse(input); - } catch (FileNotFoundException e) { - //don't complain if the update site is not present - } catch (Exception e) { - LogHelper.log(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.exception_errorParsingUpdateSite, siteLocation), e)); - } - if (site == null) - return mappings; - - //copy mirror information from update site to p2 repositories - String mirrors = site.getMirrorsURL(); - if (mirrors != null) { - //remove site.xml file reference - int index = mirrors.indexOf("site.xml"); //$NON-NLS-1$ - if (index != -1) - mirrors = mirrors.substring(0, index) + mirrors.substring(index + "site.xml".length()); //$NON-NLS-1$ - info.getMetadataRepository().setProperty(IRepository.PROP_MIRRORS_URL, mirrors); - info.getArtifactRepository().setProperty(IRepository.PROP_MIRRORS_URL, mirrors); - } - - //publish associate sites as repository references - URLEntry[] associatedSites = site.getAssociatedSites(); - if (associatedSites != null) - for (int i = 0; i < associatedSites.length; i++) - generateSiteReference(associatedSites[i].getURL(), associatedSites[i].getAnnotation(), null, true); - - if (PROTOCOL_FILE.equals(siteLocation.getScheme())) { - File siteFile = URIUtil.toFile(siteLocation); - if (siteFile.exists()) { - File siteParent = siteFile.getParentFile(); - - List messageKeys = site.getMessageKeys(); - if (siteParent.isDirectory()) { - String[] keyStrings = (String[]) messageKeys.toArray(new String[messageKeys.size()]); - site.setLocalizations(LocalizationHelper.getDirPropertyLocalizations(siteParent, "site", null, keyStrings)); //$NON-NLS-1$ - } else if (siteFile.getName().endsWith(".jar")) { //$NON-NLS-1$ - String[] keyStrings = (String[]) messageKeys.toArray(new String[messageKeys.size()]); - site.setLocalizations(LocalizationHelper.getJarPropertyLocalizations(siteParent, "site", null, keyStrings)); //$NON-NLS-1$ - } - } - } - - SiteFeature[] features = site.getFeatures(); - for (int i = 0; i < features.length; i++) { - //add a mapping for each category this feature belongs to - String[] categoryNames = features[i].getCategoryNames(); - for (int j = 0; j < categoryNames.length; j++) { - SiteCategory category = site.getCategory(categoryNames[j]); - if (category != null) { - Set categories = (Set) mappings.get(features[i]); - if (categories == null) { - categories = new HashSet(); - mappings.put(features[i], categories); - } - categories.add(category); - } - } - } - return mappings; - } - - /** - * @TODO This method is a temporary hack to rename the launcher.exe files - * to eclipse.exe (or "launcher" to "eclipse"). Eventually we will either hand-craft - * metadata/artifacts for launchers, or alter the delta pack to contain eclipse-branded - * launchers. - * @deprecated moved to EquinoxExecutableAction - */ - private void mungeLauncherFileNames(File root) { - if (root.isDirectory()) { - File[] children = root.listFiles(); - for (int i = 0; i < children.length; i++) { - mungeLauncherFileNames(children[i]); - } - } else if (root.isFile()) { - if (root.getName().equals("launcher")) //$NON-NLS-1$ - root.renameTo(new File(root.getParentFile(), "eclipse")); //$NON-NLS-1$ - else if (root.getName().equals("launcher.exe")) //$NON-NLS-1$ - root.renameTo(new File(root.getParentFile(), "eclipse.exe")); //$NON-NLS-1$ - } - } - - protected void publishArtifact(IArtifactDescriptor descriptor, File[] files, IArtifactRepository destination, boolean asIs) { - publishArtifact(descriptor, files, destination, asIs, null); - } - - // Put the artifact on the server - /** - * @deprecated moved to AbstractPublishingAction - */ - protected void publishArtifact(IArtifactDescriptor descriptor, File[] files, IArtifactRepository destination, boolean asIs, File root) { - if (descriptor == null || destination == null) - return; - if (!info.publishArtifacts()) { - destination.addDescriptor(descriptor); - return; - } - if (asIs && files.length == 1) { - try { - if (!destination.contains(descriptor)) { - if (destination instanceof IFileArtifactRepository) { - //if the file is already in the same location the repo will put it, just add the descriptor and exit - File descriptorFile = ((IFileArtifactRepository) destination).getArtifactFile(descriptor); - if (files[0].equals(descriptorFile)) { - destination.addDescriptor(descriptor); - return; - } - } - OutputStream output = new BufferedOutputStream(destination.getOutputStream(descriptor)); - FileUtils.copyStream(new BufferedInputStream(new FileInputStream(files[0])), true, output, true); - } - } catch (ProvisionException e) { - LogHelper.log(e.getStatus()); - } catch (IOException e) { - LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "Error publishing artifacts", e)); //$NON-NLS-1$ - } - } else { - File tempFile = null; - try { - tempFile = File.createTempFile("p2.generator", ""); //$NON-NLS-1$ //$NON-NLS-2$ - IPathComputer computer = null; - if (root != null) - computer = FileUtils.createRootPathComputer(root); - else - computer = FileUtils.createDynamicPathComputer(1); - FileUtils.zip(files, null, tempFile, computer); - if (!destination.contains(descriptor)) { - destination.setProperty(IArtifactDescriptor.DOWNLOAD_CONTENTTYPE, IArtifactDescriptor.TYPE_ZIP); - OutputStream output = new BufferedOutputStream(destination.getOutputStream(descriptor)); - FileUtils.copyStream(new BufferedInputStream(new FileInputStream(tempFile)), true, output, true); - } - } catch (ProvisionException e) { - LogHelper.log(e.getStatus()); - } catch (IOException e) { - LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "Error publishing artifacts", e)); //$NON-NLS-1$ - } finally { - if (tempFile != null) - tempFile.delete(); - } - } - } - - public void setGenerateRootIU(boolean generateRootIU) { - this.generateRootIU = generateRootIU; - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/GeneratorBundleInfo.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/GeneratorBundleInfo.java deleted file mode 100644 index fdfef7d10..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/GeneratorBundleInfo.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.generator; - -import org.eclipse.equinox.frameworkadmin.BundleInfo; - -public class GeneratorBundleInfo extends BundleInfo { - // public static final int NO_LEVEL = -1; - - // private String symbolicName; - // private String version; - // private String location; - // private int expectedState; - // private int startLevel = NO_LEVEL; - // private String manifest; - - private String specialConfigCommands; - private String specialUnconfigCommands; - - public GeneratorBundleInfo(BundleInfo bInfo) { - super.setBundleId(bInfo.getBundleId()); - super.setLocation(bInfo.getLocation()); - super.setManifest(bInfo.getManifest()); - super.setMarkedAsStarted(bInfo.isMarkedAsStarted()); - super.setResolved(bInfo.isResolved()); - super.setStartLevel(bInfo.getStartLevel()); - super.setSymbolicName(bInfo.getSymbolicName()); - super.setVersion(bInfo.getVersion()); - } - - public GeneratorBundleInfo() { - // TODO Auto-generated constructor stub - } - - // /* (non-Javadoc) - // * @see java.lang.Object#hashCode() - // */ - // public int hashCode() { - // int result = symbolicName == null ? 0 : symbolicName.hashCode(); - // result = result + (version == null ? 0 : version.hashCode()); - // result = result + (location == null ? 0 : location.hashCode()); - // return result; - // } - // - // public String getSymbolicName() { - // return symbolicName; - // } - // - // public String getVersion() { - // return version; - // } - // - // public int expectedState() { - // return expectedState; - // } - // - // public int getStartLevel() { - // return startLevel; - // } - // - // public String getLocation() { - // return location; - // } - // - // public void setSymbolicName(String id) { - // symbolicName = id; - // } - // - // public void setVersion(String version) { - // this.version = version; - // } - // - // public void setExpectedState(int state) { - // expectedState = state; - // } - // - // public void setStartLevel(int level) { - // this.startLevel = level; - // } - // - // public void setLocation(String location) { - // this.location = location; - // } - // - // public void setManifest(String manifest) { - // this.manifest = manifest; - // } - // - // public String getManifest() { - // return manifest; - // } - // - public String getSpecialConfigCommands() { - return specialConfigCommands; - } - - public void setSpecialConfigCommands(String specialConfigCommands) { - this.specialConfigCommands = specialConfigCommands; - } - - public String getSpecialUnconfigCommands() { - return specialUnconfigCommands; - } - - public void setSpecialUnconfigCommands(String specialUnconfigCommands) { - this.specialUnconfigCommands = specialUnconfigCommands; - } - - // /* (non-Javadoc) - // * @see java.lang.Object#equals(java.lang.Object) - // */ - // public boolean equals(Object toCompare) { - // if (toCompare instanceof GeneratorBundleInfo) { - // GeneratorBundleInfo info = (GeneratorBundleInfo) toCompare; - // if (info.symbolicName.equals(symbolicName) && info.version.equals(version) && (info.location == null || location == null ? true : info.location.equals(location))) - // return true; - // } - // return false; - // } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - public String toString() { - StringBuffer buffer = new StringBuffer(); - String superSt = super.toString(); - if (superSt.length() > 0) - buffer.append(superSt.substring(0, superSt.length() - 1)); - buffer.append(", this.specialConfigCommands="); //$NON-NLS-1$ - buffer.append(this.specialConfigCommands); - buffer.append(')'); - return buffer.toString(); - } -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/IGeneratorInfo.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/IGeneratorInfo.java deleted file mode 100644 index 21dd8e27a..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/IGeneratorInfo.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.generator; - -import java.io.File; -import java.net.URI; -import java.util.*; -import org.eclipse.equinox.internal.provisional.frameworkadmin.ConfigData; -import org.eclipse.equinox.internal.provisional.frameworkadmin.LauncherData; -import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; -import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; - -public interface IGeneratorInfo { - - /** - * Returns whether or not to add the default IUs to the published result. - * The default IUs are typically used to configure bundles, features and - * source bundles. - * @return whether or not to publish default IUs - */ - public boolean addDefaultIUs(); - - /** - * Returns whether or not to append to existing repositories or overwrite. - * @return whether or not to append to existing repositories or overwrite. - */ - public boolean append(); - - /** - * Returns the artifact repository into which any publishable artifacts are published - * or <code>null</code> if none. - * @return a destination artifact repository or <code>null</code> - */ - public IArtifactRepository getArtifactRepository(); - - /** - * Returns a list of locations in which bundles may be found. The locations may - * be directories to search or actual bundle files. - * @return the list of locations holding bundles to process. - */ - public File[] getBundleLocations(); - - /** - * Return the configuration data to use during publishing or <code>null</code> - * if none. The configuration data details the framework and launcher setup. - * - * @return the configuration data or <code>null</code> - */ - public ConfigData getConfigData(); - - public ArrayList getDefaultIUs(Set ius); - - public File getExecutableLocation(); - - public File getFeaturesLocation(); - - public String getFlavor(); - - public File getJRELocation(); - - /** - * The platform for the data this location - * @return Returns a pde.build style platform config in the form os_ws_arch - */ - public String getLauncherConfig(); - - public LauncherData getLauncherData(); - - public IMetadataRepository getMetadataRepository(); - - public String getRootId(); - - public String getRootVersion(); - - public String getProductFile(); - - public String getVersionAdvice(); - - /** - * Returns the location of the site.xml file, or <code>null</code> if not - * generating for an update site. - * @return The location of site.xml, or <code>null</code> - */ - public URI getSiteLocation(); - - public boolean publishArtifactRepository(); - - public boolean publishArtifacts(); - - public boolean reuseExistingPack200Files(); - - public void reuseExistingPack200Files(boolean publishPack); - - public void setArtifactRepository(IArtifactRepository value); - - public void setFlavor(String value); - - public void setMetadataRepository(IMetadataRepository value); - - public void setPublishArtifacts(boolean value); - - public void setRootId(String value); - - public void setVersionAdvice(String advice); - - // TODO: This is kind of ugly. It's purpose is to allow us to craft CUs that we know about and need for our build - // We should try to replace this with something more generic prior to release - public Collection getOtherIUs(); -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/IncrementalGenerator.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/IncrementalGenerator.java deleted file mode 100644 index cb90025f1..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/IncrementalGenerator.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.metadata.generator; - -import org.eclipse.equinox.internal.p2.metadata.generator.EclipseGeneratorApplication; -import org.eclipse.equinox.internal.provisional.p2.metadata.generator.Generator.GeneratorResult; - -/** - * A class to enable carrying GeneratorResults across multiple invocations of the Generator. - * Done here in the bundle instead of in GeneratorTask because of the way org.eclipse.ant.core.AntRunner uses class loaders. - * @since 1.0 - */ - -public class IncrementalGenerator { - private static String MODE_INCREMENTAL = "incremental"; //$NON-NLS-1$ - private String mode = null; - static private GeneratorResult result = null; - - public void setMode(String mode) { - this.mode = mode; - } - - public void run(EclipseGeneratorApplication generator, EclipseInstallGeneratorInfoProvider provider) throws Exception { - if (MODE_INCREMENTAL.equals(mode)) { - if (result == null) - result = new GeneratorResult(); - generator.setIncrementalResult(result); - generator.setGeneratorRootIU(false); - } else if ("final".equals(mode) && result != null) { //$NON-NLS-1$ - generator.setIncrementalResult(result); - generator.setGeneratorRootIU(true); - } - - generator.run(provider); - - if (!MODE_INCREMENTAL.equals(mode)) { - result = null; - } - } - -} diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/MetadataGeneratorHelper.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/MetadataGeneratorHelper.java deleted file mode 100644 index 53efbdb07..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/MetadataGeneratorHelper.java +++ /dev/null @@ -1,1434 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Genuitec, LLC - added license support - *******************************************************************************/ -package org.eclipse.equinox.internal.provisional.p2.metadata.generator; - -import java.io.*; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.*; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.URIUtil; -import org.eclipse.equinox.frameworkadmin.BundleInfo; -import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; -import org.eclipse.equinox.internal.p2.metadata.*; -import org.eclipse.equinox.internal.p2.metadata.generator.Activator; -import org.eclipse.equinox.internal.p2.metadata.generator.LocalizationHelper; -import org.eclipse.equinox.internal.p2.metadata.generator.features.SiteCategory; -import org.eclipse.equinox.p2.metadata.*; -import org.eclipse.equinox.p2.metadata.MetadataFactory.InstallableUnitDescription; -import org.eclipse.equinox.p2.metadata.MetadataFactory.InstallableUnitFragmentDescription; -import org.eclipse.equinox.p2.metadata.MetadataFactory.InstallableUnitPatchDescription; -import org.eclipse.equinox.p2.metadata.VersionRange; -import org.eclipse.equinox.p2.metadata.expression.IMatchExpression; -import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor; -import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor; -import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor; -import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor; -import org.eclipse.osgi.service.environment.EnvironmentInfo; -import org.eclipse.osgi.service.resolver.*; -import org.eclipse.osgi.util.ManifestElement; -import org.osgi.framework.BundleException; -import org.osgi.framework.Constants; - -/** - * @deprecated this class has been renamed to PublisherHelper and the vast majority - * of the function has been deprecated and moved elsewhere. See the deprecation notices there - * for more information. - */ -public class MetadataGeneratorHelper { - /** - * A capability namespace representing the type of Eclipse resource (bundle, feature, source bundle, etc) - * @see IProvidedCapability#getNamespace() - */ - public static final String NAMESPACE_ECLIPSE_TYPE = "org.eclipse.equinox.p2.eclipse.type"; //$NON-NLS-1$ - - /** - * A capability name in the {@link #NAMESPACE_ECLIPSE_TYPE} namespace - * representing and OSGi bundle resource - * @see IProvidedCapability#getName() - */ - public static final String TYPE_ECLIPSE_BUNDLE = "bundle"; //$NON-NLS-1$ - /** - * A capability name in the {@link #NAMESPACE_ECLIPSE_TYPE} namespace - * representing a feature - */ - public static final String TYPE_ECLIPSE_FEATURE = "feature"; //$NON-NLS-1$ - - /** - * A capability name in the {@link #NAMESPACE_ECLIPSE_TYPE} namespace - * representing a source bundle - */ - public static final String TYPE_ECLIPSE_SOURCE = "source"; //$NON-NLS-1$ - - /** - * A capability namespace representing the localization (translation) - * of strings from a specified IU in a specified locale - * @see IProvidedCapability#getNamespace() - * TODO: this should be in API, probably in IInstallableUnit - */ - public static final String NAMESPACE_IU_LOCALIZATION = "org.eclipse.equinox.p2.localization"; //$NON-NLS-1$ - - // Only certain properties in the bundle manifest are assumed to be localized. - public static final String[] BUNDLE_LOCALIZED_PROPERTIES = {Constants.BUNDLE_NAME, Constants.BUNDLE_DESCRIPTION, Constants.BUNDLE_VENDOR, Constants.BUNDLE_CONTACTADDRESS, Constants.BUNDLE_DOCURL, Constants.BUNDLE_UPDATELOCATION}; - public static final int BUNDLE_LOCALIZATION_INDEX = BUNDLE_LOCALIZED_PROPERTIES.length; - - private static final String[] BUNDLE_IU_PROPERTY_MAP = {Constants.BUNDLE_NAME, IInstallableUnit.PROP_NAME, Constants.BUNDLE_DESCRIPTION, IInstallableUnit.PROP_DESCRIPTION, Constants.BUNDLE_VENDOR, IInstallableUnit.PROP_PROVIDER, Constants.BUNDLE_CONTACTADDRESS, IInstallableUnit.PROP_CONTACT, Constants.BUNDLE_DOCURL, IInstallableUnit.PROP_DOC_URL}; - - private static final String CAPABILITY_NS_JAVA_PACKAGE = "java.package"; //$NON-NLS-1$ - private static final String CAPABILITY_NS_OSGI_BUNDLE = "osgi.bundle"; //$NON-NLS-1$ - private static final String CAPABILITY_NS_OSGI_FRAGMENT = "osgi.fragment"; //$NON-NLS-1$ - - private static final String CAPABILITY_NS_UPDATE_FEATURE = "org.eclipse.update.feature"; //$NON-NLS-1$ - - private static final Version DEFAULT_JRE_VERSION = Version.create("1.6"); //$NON-NLS-1$ - - public static final String ECLIPSE_FEATURE_CLASSIFIER = "org.eclipse.update.feature"; //$NON-NLS-1$ - public static final String OSGI_BUNDLE_CLASSIFIER = "osgi.bundle"; //$NON-NLS-1$ - public static final String BINARY_ARTIFACT_CLASSIFIER = "binary"; //$NON-NLS-1$ - - public static final IMatchExpression INSTALL_FEATURES_FILTER = InstallableUnit.parseFilter("(org.eclipse.update.install.features=true)"); //$NON-NLS-1$ - - private static final String IU_NAMESPACE = IInstallableUnit.NAMESPACE_IU_ID; - - private static final String LAUNCHER_ID_PREFIX = "org.eclipse.launcher"; //$NON-NLS-1$ - - private static final String ECLIPSE_INSTALL_HANDLER_PROP = "org.eclipse.update.installHandler"; //$NON-NLS-1$ - private static final String UPDATE_FEATURE_APPLICATION_PROP = "org.eclipse.update.feature.application"; //$NON-NLS-1$ - private static final String UPDATE_FEATURE_PLUGIN_PROP = "org.eclipse.update.feature.plugin"; //$NON-NLS-1$ - private static final String UPDATE_FEATURE_EXCLUSIVE_PROP = "org.eclipse.update.feature.exclusive"; //$NON-NLS-1$ - private static final String UPDATE_FEATURE_PRIMARY_PROP = "org.eclipse.update.feature.primary"; //$NON-NLS-1$ - - //TODO - need to come up with a way to infer launcher version - private static final Version LAUNCHER_VERSION = Version.createOSGi(1, 0, 0); - - public static final ITouchpointType TOUCHPOINT_NATIVE = MetadataFactory.createTouchpointType("org.eclipse.equinox.p2.native", Version.createOSGi(1, 0, 0)); //$NON-NLS-1$ - public static final ITouchpointType TOUCHPOINT_OSGI = MetadataFactory.createTouchpointType("org.eclipse.equinox.p2.osgi", Version.createOSGi(1, 0, 0)); //$NON-NLS-1$ - - public static final IProvidedCapability BUNDLE_CAPABILITY = MetadataFactory.createProvidedCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_BUNDLE, Version.createOSGi(1, 0, 0)); - public static final IProvidedCapability FEATURE_CAPABILITY = MetadataFactory.createProvidedCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_FEATURE, Version.createOSGi(1, 0, 0)); - public static final IProvidedCapability SOURCE_BUNDLE_CAPABILITY = MetadataFactory.createProvidedCapability(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_SOURCE, Version.createOSGi(1, 0, 0)); - - static final String DEFAULT_BUNDLE_LOCALIZATION = "plugin"; //$NON-NLS-1$ - - static final String BUNDLE_ADVICE_FILE = "META-INF/p2.inf"; //$NON-NLS-1$ - static final String ADVICE_INSTRUCTIONS_PREFIX = "instructions."; //$NON-NLS-1$ - - static final String NAMESPACE_FLAVOR = "org.eclipse.equinox.p2.flavor"; //$NON-NLS-1$" - - public static IArtifactDescriptor createArtifactDescriptor(IArtifactKey key, File pathOnDisk, boolean asIs, boolean recur) { - //TODO this size calculation is bogus - ArtifactDescriptor result = new ArtifactDescriptor(key); - if (pathOnDisk != null) { - result.setProperty(IArtifactDescriptor.ARTIFACT_SIZE, Long.toString(pathOnDisk.length())); - // TODO - this is wrong but I'm testing a work-around for bug 205842 - result.setProperty(IArtifactDescriptor.DOWNLOAD_SIZE, Long.toString(pathOnDisk.length())); - } - if (asIs) { - String md5 = computeMD5(pathOnDisk); - if (md5 != null) - result.setProperty(IArtifactDescriptor.DOWNLOAD_MD5, md5); - } - return result; - } - - private static String computeMD5(File file) { - if (file == null || file.isDirectory() || !file.exists()) - return null; - MessageDigest md5Checker; - try { - md5Checker = MessageDigest.getInstance("MD5"); //$NON-NLS-1$ - } catch (NoSuchAlgorithmException e) { - return null; - } - InputStream fis = null; - try { - fis = new BufferedInputStream(new FileInputStream(file)); - int read = -1; - while ((read = fis.read()) != -1) { - md5Checker.update((byte) read); - } - byte[] digest = md5Checker.digest(); - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < digest.length; i++) { - if ((digest[i] & 0xFF) < 0x10) - buf.append('0'); - buf.append(Integer.toHexString(digest[i] & 0xFF)); - } - return buf.toString(); - } catch (FileNotFoundException e) { - return null; - } catch (IOException e) { - return null; - } finally { - if (fis != null) - try { - fis.close(); - } catch (IOException e) { - // ignore - } - } - } - - /** - * @deprecated moved to AbstractPublishingAction - */ - public static IArtifactDescriptor createPack200ArtifactDescriptor(IArtifactKey key, File pathOnDisk, String installSize) { - //TODO this size calculation is bogus - ArtifactDescriptor result = new ArtifactDescriptor(key); - if (pathOnDisk != null) { - result.setProperty(IArtifactDescriptor.ARTIFACT_SIZE, installSize); - // TODO - this is wrong but I'm testing a work-around for bug 205842 - result.setProperty(IArtifactDescriptor.DOWNLOAD_SIZE, Long.toString(pathOnDisk.length())); - } - IProcessingStepDescriptor[] steps = new IProcessingStepDescriptor[] {new ProcessingStepDescriptor("org.eclipse.equinox.p2.processing.Pack200Unpacker", null, true)}; //$NON-NLS-1$ - result.setProcessingSteps(steps); - result.setProperty(IArtifactDescriptor.FORMAT, IArtifactDescriptor.FORMAT_PACKED); - return result; - } - - /** - * @deprecated moved to BundlesAction - */ - public static IInstallableUnit createBundleConfigurationUnit(String iuId, Version iuVersion, boolean isBundleFragment, GeneratorBundleInfo configInfo, String configurationFlavor, String ldapFilter) { - IMatchExpression filter = ldapFilter == null ? null : InstallableUnit.parseFilter(ldapFilter); - return createBundleConfigurationUnit(iuId, iuVersion, isBundleFragment, configInfo, configurationFlavor, filter); - } - - public static IInstallableUnit createBundleConfigurationUnit(String iuId, Version iuVersion, boolean isBundleFragment, GeneratorBundleInfo configInfo, String configurationFlavor, IMatchExpression filter) { - if (configInfo == null) - return null; - - InstallableUnitFragmentDescription cu = new InstallableUnitFragmentDescription(); - String configUnitId = configurationFlavor + iuId; - cu.setId(configUnitId); - cu.setVersion(iuVersion); - - //Indicate the IU to which this CU apply - cu.setHost(new IRequirement[] { // - MetadataFactory.createRequirement(CAPABILITY_NS_OSGI_BUNDLE, iuId, new VersionRange(iuVersion, true, Version.MAX_VERSION, true), null, false, false, true), // - MetadataFactory.createRequirement(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_BUNDLE, new VersionRange(Version.createOSGi(1, 0, 0), true, Version.createOSGi(2, 0, 0), false), null, false, false, false)}); - - //Adds capabilities for fragment, self, and describing the flavor supported - cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); - cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, iuVersion), MetadataFactory.createProvidedCapability(NAMESPACE_FLAVOR, configurationFlavor, Version.createOSGi(1, 0, 0))}); - - Map touchpointData = new HashMap(); - touchpointData.put("install", "installBundle(bundle:${artifact})"); //$NON-NLS-1$ //$NON-NLS-2$ - touchpointData.put("uninstall", "uninstallBundle(bundle:${artifact})"); //$NON-NLS-1$ //$NON-NLS-2$ - touchpointData.put("configure", createConfigScript(configInfo, isBundleFragment)); //$NON-NLS-1$ - touchpointData.put("unconfigure", createUnconfigScript(configInfo, isBundleFragment)); //$NON-NLS-1$ - cu.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - cu.setFilter(filter); - return MetadataFactory.createInstallableUnit(cu); - } - - /** - * @deprecated moved to BundlesAction - */ - public static IInstallableUnit createBundleIU(BundleDescription bd, Map manifest, boolean isFolderPlugin, IArtifactKey key, boolean useNestedAdvice) { - Map manifestLocalizations = null; - if (manifest != null && bd.getLocation() != null) { - manifestLocalizations = getManifestLocalizations(manifest, new File(bd.getLocation())); - } - - return createBundleIU(bd, manifest, isFolderPlugin, key, manifestLocalizations, useNestedAdvice); - } - - private static VersionRange computeUpdateRange(org.osgi.framework.Version base) { - VersionRange updateRange = null; - if (!base.equals(org.osgi.framework.Version.emptyVersion)) { - updateRange = new VersionRange(Version.emptyVersion, true, fromOSGiVersion(base), false); - } else { - updateRange = VersionRange.emptyRange; - } - return updateRange; - } - - /** - * @deprecated moved to BundlesAction - */ - public static IInstallableUnit createBundleIU(BundleDescription bd, Map manifest, boolean isFolderPlugin, IArtifactKey key, Map manifestLocalizations, boolean useNestedAdvice) { - boolean isBinaryBundle = true; - if (manifest != null && manifest.containsKey("Eclipse-SourceBundle")) { //$NON-NLS-1$ - isBinaryBundle = false; - } - InstallableUnitDescription iu = new MetadataFactory.InstallableUnitDescription(); - iu.setSingleton(bd.isSingleton()); - iu.setId(bd.getSymbolicName()); - iu.setVersion(fromOSGiVersion(bd.getVersion())); - iu.setFilter(bd.getPlatformFilter()); - - iu.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor(bd.getSymbolicName(), computeUpdateRange(bd.getVersion()), IUpdateDescriptor.NORMAL, null)); - - boolean isFragment = bd.getHost() != null; - // boolean requiresAFragment = isFragment ? false : requireAFragment(bd, manifest); - - //Process the required bundles - BundleSpecification requiredBundles[] = bd.getRequiredBundles(); - ArrayList reqsDeps = new ArrayList(); - // if (requiresAFragment) - // reqsDeps.add(MetadataFactory.createRequiredCapability(CAPABILITY_TYPE_OSGI_FRAGMENTS, bd.getSymbolicName(), VersionRange.emptyRange, null, false, false)); - if (isFragment) - reqsDeps.add(MetadataFactory.createRequirement(CAPABILITY_NS_OSGI_BUNDLE, bd.getHost().getName(), fromOSGiVersionRange(bd.getHost().getVersionRange()), null, false, false)); - for (int j = 0; j < requiredBundles.length; j++) - reqsDeps.add(MetadataFactory.createRequirement(CAPABILITY_NS_OSGI_BUNDLE, requiredBundles[j].getName(), fromOSGiVersionRange(requiredBundles[j].getVersionRange()), null, requiredBundles[j].isOptional(), false)); - - // Process the import packages - ImportPackageSpecification osgiImports[] = bd.getImportPackages(); - for (int i = 0; i < osgiImports.length; i++) { - // TODO we need to sort out how we want to handle wild-carded dynamic imports - for now we ignore them - ImportPackageSpecification importSpec = osgiImports[i]; - String importPackageName = importSpec.getName(); - if (importPackageName.indexOf('*') != -1) - continue; - - VersionRange versionRange = fromOSGiVersionRange(importSpec.getVersionRange()); - - //TODO this needs to be refined to take into account all the attribute handled by imports - reqsDeps.add(MetadataFactory.createRequirement(CAPABILITY_NS_JAVA_PACKAGE, importPackageName, versionRange, null, isOptional(importSpec), false)); - } - iu.setRequirements((IRequirement[]) reqsDeps.toArray(new IRequirement[reqsDeps.size()])); - - // Create set of provided capabilities - ArrayList providedCapabilities = new ArrayList(); - providedCapabilities.add(createSelfCapability(bd.getSymbolicName(), fromOSGiVersion(bd.getVersion()))); - providedCapabilities.add(MetadataFactory.createProvidedCapability(CAPABILITY_NS_OSGI_BUNDLE, bd.getSymbolicName(), fromOSGiVersion(bd.getVersion()))); - - // Process the export package - ExportPackageDescription exports[] = bd.getExportPackages(); - for (int i = 0; i < exports.length; i++) { - //TODO make sure that we support all the refinement on the exports - providedCapabilities.add(MetadataFactory.createProvidedCapability(CAPABILITY_NS_JAVA_PACKAGE, exports[i].getName(), fromOSGiVersion(exports[i].getVersion()))); - } - // Here we add a bundle capability to identify bundles - if (isBinaryBundle) - providedCapabilities.add(BUNDLE_CAPABILITY); - else - providedCapabilities.add(SOURCE_BUNDLE_CAPABILITY); - - if (isFragment) - providedCapabilities.add(MetadataFactory.createProvidedCapability(CAPABILITY_NS_OSGI_FRAGMENT, bd.getHost().getName(), fromOSGiVersion(bd.getVersion()))); - - if (manifestLocalizations != null) { - for (Iterator iter = manifestLocalizations.keySet().iterator(); iter.hasNext();) { - Locale locale = (Locale) iter.next(); - Properties translatedStrings = (Properties) manifestLocalizations.get(locale); - Enumeration propertyKeys = translatedStrings.propertyNames(); - while (propertyKeys.hasMoreElements()) { - String nextKey = (String) propertyKeys.nextElement(); - iu.setProperty(locale.toString() + '.' + nextKey, translatedStrings.getProperty(nextKey)); - } - providedCapabilities.add(makeTranslationCapability(bd.getSymbolicName(), locale)); - } - } - - iu.setCapabilities((IProvidedCapability[]) providedCapabilities.toArray(new IProvidedCapability[providedCapabilities.size()])); - - iu.setArtifacts(new IArtifactKey[] {key}); - - iu.setTouchpointType(TOUCHPOINT_OSGI); - - // Set certain properties from the manifest header attributes as IU properties. - // The values of these attributes may be localized (strings starting with '%') - // with the translated values appearing in the localization IU fragments - // associated with the bundle IU. - if (manifest != null) { - int i = 0; - while (i < BUNDLE_IU_PROPERTY_MAP.length) { - if (manifest.containsKey(BUNDLE_IU_PROPERTY_MAP[i])) { - String value = (String) manifest.get(BUNDLE_IU_PROPERTY_MAP[i]); - if (value != null && value.length() > 0) { - iu.setProperty(BUNDLE_IU_PROPERTY_MAP[i + 1], value); - } - } - i += 2; - } - } - - // Define the immutable metadata for this IU. In this case immutable means - // that this is something that will not impact the configuration. - Map touchpointData = new HashMap(); - if (isFolderPlugin) - touchpointData.put("zipped", "true"); //$NON-NLS-1$ //$NON-NLS-2$ - touchpointData.put("manifest", toManifestString(manifest)); //$NON-NLS-1$ - - if (useNestedAdvice) - mergeInstructionsAdvice(touchpointData, getBundleAdvice(bd.getLocation(), BUNDLE_ADVICE_FILE)); - - iu.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - - return MetadataFactory.createInstallableUnit(iu); - } - - /** - * @deprecated moved to AdviceFileAdvice - */ - public static void mergeInstructionsAdvice(Map touchpointData, Map bundleAdvice) { - if (touchpointData == null || bundleAdvice == null) - return; - - for (Iterator iterator = bundleAdvice.keySet().iterator(); iterator.hasNext();) { - String key = (String) iterator.next(); - if (key.startsWith(ADVICE_INSTRUCTIONS_PREFIX)) { - String phase = key.substring(ADVICE_INSTRUCTIONS_PREFIX.length()); - String instructions = touchpointData.containsKey(phase) ? (String) touchpointData.get(phase) : ""; //$NON-NLS-1$ - if (instructions.length() > 0) - instructions += ";"; //$NON-NLS-1$ - instructions += ((String) bundleAdvice.get(key)).trim(); - touchpointData.put(phase, instructions); - } - } - } - - /** - * @deprecated moved to BundlesAction - */ - public static void createHostLocalizationFragment(IInstallableUnit bundleIU, BundleDescription bd, String hostId, String[] hostBundleManifestValues, Set localizationIUs) { - Map hostLocalizations = getHostLocalizations(new File(bd.getLocation()), hostBundleManifestValues); - if (hostLocalizations != null) { - IInstallableUnitFragment localizationFragment = createLocalizationFragmentOfHost(bd, hostId, hostBundleManifestValues, hostLocalizations); - localizationIUs.add(localizationFragment); - } - } - - /* - * @param hostId - * @param bd - * @param locale - * @param localizedStrings - * @return installableUnitFragment - */ - /** - * @deprecated moved to BundlesAction - */ - private static IInstallableUnitFragment createLocalizationFragmentOfHost(BundleDescription bd, String hostId, String[] hostManifestValues, Map hostLocalizations) { - InstallableUnitFragmentDescription fragment = new MetadataFactory.InstallableUnitFragmentDescription(); - String fragmentId = makeHostLocalizationFragmentId(bd.getSymbolicName()); - fragment.setId(fragmentId); - fragment.setVersion(fromOSGiVersion(bd.getVersion())); // TODO: is this a meaningful version? - - HostSpecification hostSpec = bd.getHost(); - IRequirement[] hostReqs = new IRequirement[] {MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, hostSpec.getName(), fromOSGiVersionRange(hostSpec.getVersionRange()), null, false, false, false)}; - fragment.setHost(hostReqs); - - fragment.setSingleton(true); - fragment.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); - - // Create a provided capability for each locale and add the translated properties. - ArrayList providedCapabilities = new ArrayList(hostLocalizations.keySet().size()); - for (Iterator iter = hostLocalizations.keySet().iterator(); iter.hasNext();) { - Locale locale = (Locale) iter.next(); - Properties translatedStrings = (Properties) hostLocalizations.get(locale); - - Enumeration propertyKeys = translatedStrings.propertyNames(); - while (propertyKeys.hasMoreElements()) { - String nextKey = (String) propertyKeys.nextElement(); - fragment.setProperty(locale.toString() + '.' + nextKey, translatedStrings.getProperty(nextKey)); - } - providedCapabilities.add(makeTranslationCapability(hostId, locale)); - } - fragment.setCapabilities((IProvidedCapability[]) providedCapabilities.toArray(new IProvidedCapability[providedCapabilities.size()])); - - return MetadataFactory.createInstallableUnitFragment(fragment); - } - - /** - * @param id - * @return the id for the iu fragment containing the localized properties - * for the bundle with the given id - */ - // private static String makeBundleLocalizationFragmentId(String id) { - // return id + ".translated_properties"; //$NON-NLS-1$ - // } - /** - * @param id - * @return the id for the iu fragment containing localized properties - * for the fragment with the given id. - */ - /** - * @deprecated moved to BundlesAction - */ - private static String makeHostLocalizationFragmentId(String id) { - return id + ".translated_host_properties"; //$NON-NLS-1$ - } - - private static IProvidedCapability makeTranslationCapability(String hostId, Locale locale) { - return MetadataFactory.createProvidedCapability(NAMESPACE_IU_LOCALIZATION, locale.toString(), Version.createOSGi(1, 0, 0)); - } - - /** - * Creates an IU corresponding to an update site category - * @param category The category descriptor - * @param featureIUs The IUs of the features that belong to the category - * @param parentCategory The parent category, or <code>null</code> - * @return an IU representing the category - * @deprecated moved to SiteXMLAction - */ - public static IInstallableUnit createCategoryIU(SiteCategory category, Set featureIUs, IInstallableUnit parentCategory) { - InstallableUnitDescription cat = new MetadataFactory.InstallableUnitDescription(); - cat.setSingleton(true); - String categoryId = category.getName(); - cat.setId(categoryId); - cat.setVersion(Version.emptyVersion); - cat.setProperty(IInstallableUnit.PROP_NAME, category.getLabel()); - cat.setProperty(IInstallableUnit.PROP_DESCRIPTION, category.getDescription()); - - ArrayList reqsConfigurationUnits = new ArrayList(featureIUs.size()); - for (Iterator iterator = featureIUs.iterator(); iterator.hasNext();) { - IInstallableUnit iu = (IInstallableUnit) iterator.next(); - VersionRange range = new VersionRange(iu.getVersion(), true, iu.getVersion(), true); - reqsConfigurationUnits.add(MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, iu.getId(), range, iu.getFilter() == null ? null : iu.getFilter(), false, false)); - } - //note that update sites don't currently support nested categories, but it may be useful to add in the future - if (parentCategory != null) { - reqsConfigurationUnits.add(MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, parentCategory.getId(), VersionRange.emptyRange, parentCategory.getFilter() == null ? null : parentCategory.getFilter(), false, false)); - } - cat.setRequirements((IRequirement[]) reqsConfigurationUnits.toArray(new IRequirement[reqsConfigurationUnits.size()])); - - // Create set of provided capabilities - ArrayList providedCapabilities = new ArrayList(); - providedCapabilities.add(createSelfCapability(categoryId, Version.emptyVersion)); - - Map localizations = category.getLocalizations(); - if (localizations != null) { - for (Iterator iter = localizations.keySet().iterator(); iter.hasNext();) { - Locale locale = (Locale) iter.next(); - Properties translatedStrings = (Properties) localizations.get(locale); - Enumeration propertyKeys = translatedStrings.propertyNames(); - while (propertyKeys.hasMoreElements()) { - String nextKey = (String) propertyKeys.nextElement(); - cat.setProperty(locale.toString() + '.' + nextKey, translatedStrings.getProperty(nextKey)); - } - providedCapabilities.add(makeTranslationCapability(categoryId, locale)); - } - } - - cat.setCapabilities((IProvidedCapability[]) providedCapabilities.toArray(new IProvidedCapability[providedCapabilities.size()])); - - cat.setArtifacts(new IArtifactKey[0]); - cat.setProperty(InstallableUnitDescription.PROP_TYPE_CATEGORY, "true"); //$NON-NLS-1$ - return MetadataFactory.createInstallableUnit(cat); - } - - /** - * @deprecated moved to BundlesAction - */ - private static String createConfigScript(GeneratorBundleInfo configInfo, boolean isBundleFragment) { - if (configInfo == null) - return ""; //$NON-NLS-1$ - - String configScript = "";//$NON-NLS-1$ - if (!isBundleFragment && configInfo.getStartLevel() != BundleInfo.NO_LEVEL) { - configScript += "setStartLevel(startLevel:" + configInfo.getStartLevel() + ");"; //$NON-NLS-1$ //$NON-NLS-2$ - } - if (!isBundleFragment && configInfo.isMarkedAsStarted()) { - configScript += "markStarted(started: true);"; //$NON-NLS-1$ - } - - if (configInfo.getSpecialConfigCommands() != null) { - configScript += configInfo.getSpecialConfigCommands(); - } - - return configScript; - } - - /** - * @deprecated moved to BundlesAction - */ - private static String createDefaultBundleConfigScript(GeneratorBundleInfo configInfo) { - return createConfigScript(configInfo, false); - } - - /** - * @deprecated moved to BundlesAction - */ - public static IInstallableUnit createDefaultBundleConfigurationUnit(GeneratorBundleInfo configInfo, GeneratorBundleInfo unconfigInfo, String configurationFlavor) { - InstallableUnitFragmentDescription cu = new InstallableUnitFragmentDescription(); - String configUnitId = createDefaultConfigUnitId(OSGI_BUNDLE_CLASSIFIER, configurationFlavor); - cu.setId(configUnitId); - Version configUnitVersion = Version.createOSGi(1, 0, 0); - cu.setVersion(configUnitVersion); - - // Add capabilities for fragment, self, and describing the flavor supported - cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); - cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, configUnitVersion), MetadataFactory.createProvidedCapability(NAMESPACE_FLAVOR, configurationFlavor, Version.createOSGi(1, 0, 0))}); - - // Create a required capability on bundles - IRequirement[] reqs = new IRequirement[] {MetadataFactory.createRequirement(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_BUNDLE, VersionRange.emptyRange, null, false, true, false)}; - cu.setHost(reqs); - Map touchpointData = new HashMap(); - - touchpointData.put("install", "installBundle(bundle:${artifact})"); //$NON-NLS-1$ //$NON-NLS-2$ - touchpointData.put("uninstall", "uninstallBundle(bundle:${artifact})"); //$NON-NLS-1$ //$NON-NLS-2$ - touchpointData.put("configure", createDefaultBundleConfigScript(configInfo)); //$NON-NLS-1$ - touchpointData.put("unconfigure", createDefaultBundleUnconfigScript(unconfigInfo)); //$NON-NLS-1$ - - cu.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - return MetadataFactory.createInstallableUnit(cu); - } - - /** - * @deprecated moved to BundlesAction - */ - private static String createDefaultBundleUnconfigScript(GeneratorBundleInfo unconfigInfo) { - return createUnconfigScript(unconfigInfo, false); - } - - public static String createDefaultConfigUnitId(String classifier, String configurationFlavor) { - return configurationFlavor + "." + classifier + ".default"; //$NON-NLS-1$ //$NON-NLS-2$ - } - - public static IInstallableUnit createDefaultFeatureConfigurationUnit(String configurationFlavor) { - InstallableUnitFragmentDescription cu = new InstallableUnitFragmentDescription(); - String configUnitId = createDefaultConfigUnitId(ECLIPSE_FEATURE_CLASSIFIER, configurationFlavor); - cu.setId(configUnitId); - Version configUnitVersion = Version.createOSGi(1, 0, 0); - cu.setVersion(configUnitVersion); - - // Add capabilities for fragment, self, and describing the flavor supported - cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); - cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, configUnitVersion), MetadataFactory.createProvidedCapability(NAMESPACE_FLAVOR, configurationFlavor, Version.createOSGi(1, 0, 0))}); - - // Create a required capability on features - IRequirement[] reqs = new IRequirement[] {MetadataFactory.createRequirement(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_FEATURE, VersionRange.emptyRange, null, true, true, false)}; - cu.setHost(reqs); - - cu.setFilter(INSTALL_FEATURES_FILTER); - Map touchpointData = new HashMap(); - touchpointData.put("install", "installFeature(feature:${artifact},featureId:default,featureVersion:default)"); //$NON-NLS-1$//$NON-NLS-2$ - touchpointData.put("uninstall", "uninstallFeature(feature:${artifact},featureId:default,featureVersion:default)"); //$NON-NLS-1$//$NON-NLS-2$ - cu.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - - return MetadataFactory.createInstallableUnit(cu); - } - - public static IInstallableUnit createDefaultConfigurationUnitForSourceBundles(String configurationFlavor) { - InstallableUnitFragmentDescription cu = new InstallableUnitFragmentDescription(); - String configUnitId = createDefaultConfigUnitId("source", configurationFlavor); //$NON-NLS-1$ - cu.setId(configUnitId); - Version configUnitVersion = Version.createOSGi(1, 0, 0); - cu.setVersion(configUnitVersion); - - // Add capabilities for fragment, self, and describing the flavor supported - cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); - cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, configUnitVersion), MetadataFactory.createProvidedCapability(NAMESPACE_FLAVOR, configurationFlavor, Version.createOSGi(1, 0, 0))}); - - // Create a required capability on source providers - IRequirement[] reqs = new IRequirement[] {MetadataFactory.createRequirement(NAMESPACE_ECLIPSE_TYPE, TYPE_ECLIPSE_SOURCE, VersionRange.emptyRange, null, true, true, false)}; - cu.setHost(reqs); - Map touchpointData = new HashMap(); - - touchpointData.put("install", "addSourceBundle(bundle:${artifact})"); //$NON-NLS-1$ //$NON-NLS-2$ - touchpointData.put("uninstall", "removeSourceBundle(bundle:${artifact})"); //$NON-NLS-1$ //$NON-NLS-2$ - cu.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - return MetadataFactory.createInstallableUnit(cu); - } - - /** - * @deprecated moved to FeaturesAction - */ - public static IArtifactKey createFeatureArtifactKey(String fsn, String version) { - return new ArtifactKey(ECLIPSE_FEATURE_CLASSIFIER, fsn, Version.create(version)); - } - - /** - * @deprecated moved to FeaturesAction - */ - public static IInstallableUnit createFeatureJarIU(Feature feature, boolean isExploded) { - return createFeatureJarIU(feature, isExploded, null); - } - - /** - * @deprecated moved to FeaturesAction - */ - public static IInstallableUnit createFeatureJarIU(Feature feature, boolean isExploded, Properties extraProperties) { - InstallableUnitDescription iu = new MetadataFactory.InstallableUnitDescription(); - String id = getTransformedId(feature.getId(), /*isPlugin*/false, /*isGroup*/false); - iu.setId(id); - Version version = fromOSGiVersion(new org.osgi.framework.Version(feature.getVersion())); - iu.setVersion(version); - iu.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor(id, computeUpdateRange(new org.osgi.framework.Version(feature.getVersion())), IUpdateDescriptor.NORMAL, null)); - iu.setProperty(IInstallableUnit.PROP_NAME, feature.getLabel()); - if (feature.getDescription() != null) - iu.setProperty(IInstallableUnit.PROP_DESCRIPTION, feature.getDescription()); - if (feature.getDescriptionURL() != null) - iu.setProperty(IInstallableUnit.PROP_DESCRIPTION_URL, feature.getDescriptionURL()); - if (feature.getProviderName() != null) - iu.setProperty(IInstallableUnit.PROP_PROVIDER, feature.getProviderName()); - if (feature.getLicense() != null) - iu.setLicenses(new ILicense[] {MetadataFactory.createLicense(toURIOrNull(feature.getLicenseURL()), feature.getLicense())}); - if (feature.getCopyright() != null) - iu.setCopyright(MetadataFactory.createCopyright(toURIOrNull(feature.getCopyrightURL()), feature.getCopyright())); - if (feature.getApplication() != null) - iu.setProperty(UPDATE_FEATURE_APPLICATION_PROP, feature.getApplication()); - if (feature.getPlugin() != null) - iu.setProperty(UPDATE_FEATURE_PLUGIN_PROP, feature.getPlugin()); - if (feature.isExclusive()) - iu.setProperty(UPDATE_FEATURE_EXCLUSIVE_PROP, Boolean.TRUE.toString()); - if (feature.isPrimary()) - iu.setProperty(UPDATE_FEATURE_PRIMARY_PROP, Boolean.TRUE.toString()); - - // The required capabilities are not specified at this level because we don't want the feature jar to be attractive to install. - - iu.setTouchpointType(TOUCHPOINT_OSGI); - iu.setFilter(INSTALL_FEATURES_FILTER); - iu.setSingleton(true); - - if (feature.getInstallHandler() != null && feature.getInstallHandler().trim().length() > 0) { - String installHandlerProperty = "handler=" + feature.getInstallHandler(); //$NON-NLS-1$ - - if (feature.getInstallHandlerLibrary() != null) - installHandlerProperty += ", library=" + feature.getInstallHandlerLibrary(); //$NON-NLS-1$ - - if (feature.getInstallHandlerURL() != null) - installHandlerProperty += ", url=" + feature.getInstallHandlerURL(); //$NON-NLS-1$ - - iu.setProperty(ECLIPSE_INSTALL_HANDLER_PROP, installHandlerProperty); - } - - // Create set of provided capabilities - ArrayList providedCapabilities = new ArrayList(); - providedCapabilities.add(createSelfCapability(id, version)); - providedCapabilities.add(FEATURE_CAPABILITY); - providedCapabilities.add(MetadataFactory.createProvidedCapability(CAPABILITY_NS_UPDATE_FEATURE, feature.getId(), version)); - - iu.setArtifacts(new IArtifactKey[] {createFeatureArtifactKey(feature.getId(), version.toString())}); - - if (isExploded) { - // Define the immutable metadata for this IU. In this case immutable means - // that this is something that will not impact the configuration. - Map touchpointData = new HashMap(); - touchpointData.put("zipped", "true"); //$NON-NLS-1$ //$NON-NLS-2$ - iu.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - } - - Map localizations = feature.getLocalizations(); - if (localizations != null) { - for (Iterator iter = localizations.keySet().iterator(); iter.hasNext();) { - Locale locale = (Locale) iter.next(); - Properties translatedStrings = (Properties) localizations.get(locale); - Enumeration propertyKeys = translatedStrings.propertyNames(); - while (propertyKeys.hasMoreElements()) { - String nextKey = (String) propertyKeys.nextElement(); - iu.setProperty(locale.toString() + '.' + nextKey, translatedStrings.getProperty(nextKey)); - } - providedCapabilities.add(makeTranslationCapability(id, locale)); - } - } - - iu.setCapabilities((IProvidedCapability[]) providedCapabilities.toArray(new IProvidedCapability[providedCapabilities.size()])); - - if (extraProperties != null) { - Enumeration e = extraProperties.propertyNames(); - while (e.hasMoreElements()) { - String name = (String) e.nextElement(); - iu.setProperty(name, extraProperties.getProperty(name)); - } - } - - return MetadataFactory.createInstallableUnit(iu); - } - - /** - * @deprecated moved to FeaturesAction - */ - public static IInstallableUnit createGroupIU(Feature feature, IInstallableUnit featureIU) { - return createGroupIU(feature, featureIU, null, true); - } - - public static IInstallableUnit createGroupIU(Feature feature, IInstallableUnit featureIU, Properties extraProperties, boolean transformIds) { - if (isPatch(feature)) - return createPatchIU(feature, featureIU, extraProperties); - InstallableUnitDescription iu = new MetadataFactory.InstallableUnitDescription(); - String id = feature.getId(); - if (transformIds) - id = getTransformedId(id, /*isPlugin*/false, /*isGroup*/true); - iu.setId(id); - Version version = fromOSGiVersion(new org.osgi.framework.Version(feature.getVersion())); - iu.setVersion(version); - iu.setProperty(IInstallableUnit.PROP_NAME, feature.getLabel()); - if (feature.getDescription() != null) - iu.setProperty(IInstallableUnit.PROP_DESCRIPTION, feature.getDescription()); - if (feature.getDescriptionURL() != null) - iu.setProperty(IInstallableUnit.PROP_DESCRIPTION_URL, feature.getDescriptionURL()); - if (feature.getProviderName() != null) - iu.setProperty(IInstallableUnit.PROP_PROVIDER, feature.getProviderName()); - if (feature.getLicense() != null) - iu.setLicenses(new ILicense[] {MetadataFactory.createLicense(toURIOrNull(feature.getLicenseURL()), feature.getLicense())}); - if (feature.getCopyright() != null) - iu.setCopyright(MetadataFactory.createCopyright(toURIOrNull(feature.getCopyrightURL()), feature.getCopyright())); - iu.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor(id, computeUpdateRange(new org.osgi.framework.Version(feature.getVersion())), IUpdateDescriptor.NORMAL, null)); - - FeatureEntry entries[] = feature.getEntries(); - IRequirement[] required = new IRequirement[entries.length + (featureIU == null ? 0 : 1)]; - for (int i = 0; i < entries.length; i++) { - VersionRange range = getVersionRange(entries[i]); - String requiredId = entries[i].getId(); - if (transformIds) - requiredId = getTransformedId(entries[i].getId(), entries[i].isPlugin(), /*isGroup*/true); - required[i] = MetadataFactory.createRequirement(IU_NAMESPACE, requiredId, range, getFilter(entries[i]), entries[i].isOptional(), false); - } - // the feature IU could be null if we are just generating a feature structure rather than - // actual features. - if (featureIU != null) - required[entries.length] = MetadataFactory.createRequirement(IU_NAMESPACE, featureIU.getId(), new VersionRange(featureIU.getVersion(), true, featureIU.getVersion(), true), INSTALL_FEATURES_FILTER, false, false); - iu.setRequirements(required); - iu.setTouchpointType(ITouchpointType.NONE); - iu.setProperty(InstallableUnitDescription.PROP_TYPE_GROUP, Boolean.TRUE.toString()); - // TODO: shouldn't the filter for the group be constructed from os, ws, arch, nl - // of the feature? - // iu.setFilter(filter); - - // Create set of provided capabilities - ArrayList providedCapabilities = new ArrayList(); - providedCapabilities.add(createSelfCapability(id, version)); - - Map localizations = feature.getLocalizations(); - if (localizations != null) { - for (Iterator iter = localizations.keySet().iterator(); iter.hasNext();) { - Locale locale = (Locale) iter.next(); - Properties translatedStrings = (Properties) localizations.get(locale); - Enumeration propertyKeys = translatedStrings.propertyNames(); - while (propertyKeys.hasMoreElements()) { - String nextKey = (String) propertyKeys.nextElement(); - iu.setProperty(locale.toString() + '.' + nextKey, translatedStrings.getProperty(nextKey)); - } - providedCapabilities.add(makeTranslationCapability(id, locale)); - } - } - - iu.setCapabilities((IProvidedCapability[]) providedCapabilities.toArray(new IProvidedCapability[providedCapabilities.size()])); - - if (extraProperties != null) { - Enumeration e = extraProperties.propertyNames(); - while (e.hasMoreElements()) { - String name = (String) e.nextElement(); - iu.setProperty(name, extraProperties.getProperty(name)); - } - } - - return MetadataFactory.createInstallableUnit(iu); - } - - public static IInstallableUnit createPatchIU(Feature feature, IInstallableUnit featureIU, Properties extraProperties) { - InstallableUnitPatchDescription iu = new MetadataFactory.InstallableUnitPatchDescription(); - String id = getTransformedId(feature.getId(), /*isPlugin*/false, /*isGroup*/true); - iu.setId(id); - Version version = fromOSGiVersion(new org.osgi.framework.Version(feature.getVersion())); - iu.setVersion(version); - iu.setProperty(IInstallableUnit.PROP_NAME, feature.getLabel()); - if (feature.getDescription() != null) - iu.setProperty(IInstallableUnit.PROP_DESCRIPTION, feature.getDescription()); - if (feature.getDescriptionURL() != null) - iu.setProperty(IInstallableUnit.PROP_DESCRIPTION_URL, feature.getDescriptionURL()); - if (feature.getProviderName() != null) - iu.setProperty(IInstallableUnit.PROP_PROVIDER, feature.getProviderName()); - if (feature.getLicense() != null) - iu.setLicenses(new ILicense[] {MetadataFactory.createLicense(toURIOrNull(feature.getLicenseURL()), feature.getLicense())}); - if (feature.getCopyright() != null) - iu.setCopyright(MetadataFactory.createCopyright(toURIOrNull(feature.getCopyrightURL()), feature.getCopyright())); - iu.setUpdateDescriptor(MetadataFactory.createUpdateDescriptor(id, computeUpdateRange(new org.osgi.framework.Version(feature.getVersion())), IUpdateDescriptor.NORMAL, null)); - - FeatureEntry entries[] = feature.getEntries(); - ArrayList applicabilityScope = new ArrayList(); - ArrayList patchRequirements = new ArrayList(); - ArrayList requirementChanges = new ArrayList(); - for (int i = 0; i < entries.length; i++) { - VersionRange range = getVersionRange(entries[i]); - IRequirement req = MetadataFactory.createRequirement(IU_NAMESPACE, getTransformedId(entries[i].getId(), entries[i].isPlugin(), /*isGroup*/true), range, getFilter(entries[i]), entries[i].isOptional(), false); - if (entries[i].isRequires()) { - applicabilityScope.add(req); - if (applicabilityScope.size() == 1) { - iu.setLifeCycle(MetadataFactory.createRequirement(IU_NAMESPACE, getTransformedId(entries[i].getId(), entries[i].isPlugin(), /*isGroup*/true), range, null, false, false, false)); - } - continue; - } - if (entries[i].isPlugin()) { - IRequirement from = MetadataFactory.createRequirement(IU_NAMESPACE, getTransformedId(entries[i].getId(), entries[i].isPlugin(), /*isGroup*/true), VersionRange.emptyRange, getFilter(entries[i]), entries[i].isOptional(), false); - requirementChanges.add(MetadataFactory.createRequirementChange(from, req)); - continue; - } - patchRequirements.add(req); - } - //Always add a requirement on the IU containing the feature jar - patchRequirements.add(MetadataFactory.createRequirement(IU_NAMESPACE, featureIU.getId(), new VersionRange(featureIU.getVersion(), true, featureIU.getVersion(), true), INSTALL_FEATURES_FILTER, false, false)); - iu.setRequirements((IRequirement[]) patchRequirements.toArray(new IRequirement[patchRequirements.size()])); - iu.setApplicabilityScope(new IRequirement[][] {(IRequirement[]) applicabilityScope.toArray(new IRequirement[applicabilityScope.size()])}); - iu.setRequirementChanges((IRequirementChange[]) requirementChanges.toArray(new IRequirementChange[requirementChanges.size()])); - - //Generate lifecycle - // IRequirement lifeCycle = null; - // if (applicabilityScope.size() > 0) { - // IRequirement req = (IRequirement) applicabilityScope.get(0); - // } - - iu.setTouchpointType(ITouchpointType.NONE); - iu.setProperty(InstallableUnitDescription.PROP_TYPE_GROUP, Boolean.TRUE.toString()); - iu.setProperty(InstallableUnitDescription.PROP_TYPE_PATCH, Boolean.TRUE.toString()); - // TODO: shouldn't the filter for the group be constructed from os, ws, arch, nl - // of the feature? - // iu.setFilter(filter); - - // Create set of provided capabilities - ArrayList providedCapabilities = new ArrayList(); - providedCapabilities.add(createSelfCapability(id, version)); - - Map localizations = feature.getLocalizations(); - if (localizations != null) { - for (Iterator iter = localizations.keySet().iterator(); iter.hasNext();) { - Locale locale = (Locale) iter.next(); - Properties translatedStrings = (Properties) localizations.get(locale); - Enumeration propertyKeys = translatedStrings.propertyNames(); - while (propertyKeys.hasMoreElements()) { - String nextKey = (String) propertyKeys.nextElement(); - iu.setProperty(locale.toString() + '.' + nextKey, translatedStrings.getProperty(nextKey)); - } - providedCapabilities.add(makeTranslationCapability(id, locale)); - } - } - - iu.setCapabilities((IProvidedCapability[]) providedCapabilities.toArray(new IProvidedCapability[providedCapabilities.size()])); - - if (extraProperties != null) { - Enumeration e = extraProperties.propertyNames(); - while (e.hasMoreElements()) { - String name = (String) e.nextElement(); - iu.setProperty(name, extraProperties.getProperty(name)); - } - } - - return MetadataFactory.createInstallableUnitPatch(iu); - } - - private static boolean isPatch(Feature feature) { - FeatureEntry[] entries = feature.getEntries(); - for (int i = 0; i < entries.length; i++) { - if (entries[i].isPatch()) - return true; - } - return false; - } - - /** - * Creates IUs and artifact descriptors for the JRE. The resulting IUs are added - * to the given set, and the resulting artifact descriptor, if any, is returned. - * If the jreLocation is <code>null</code>, default information is generated. - */ - /** - * @deprecated moved to JREAction - */ - public static IArtifactDescriptor createJREData(File jreLocation, Set resultantIUs) { - InstallableUnitDescription iu = new MetadataFactory.InstallableUnitDescription(); - iu.setSingleton(false); - String id = "a.jre"; //$NON-NLS-1$ - Version version = DEFAULT_JRE_VERSION; - iu.setId(id); - iu.setVersion(version); - iu.setTouchpointType(TOUCHPOINT_NATIVE); - - InstallableUnitFragmentDescription cu = new InstallableUnitFragmentDescription(); - String configId = "config." + id;//$NON-NLS-1$ - cu.setId(configId); - cu.setVersion(version); - cu.setHost(new IRequirement[] {MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, id, new VersionRange(version, true, Version.MAX_VERSION, true), null, false, false)}); - cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); - cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configId, version)}); - cu.setTouchpointType(TOUCHPOINT_NATIVE); - Map touchpointData = new HashMap(); - - if (jreLocation == null || !jreLocation.exists()) { - //set some reasonable defaults - iu.setVersion(version); - iu.setCapabilities(generateJRECapability(id, version, null)); - resultantIUs.add(MetadataFactory.createInstallableUnit(iu)); - - touchpointData.put("install", ""); //$NON-NLS-1$ //$NON-NLS-2$ - cu.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - resultantIUs.add(MetadataFactory.createInstallableUnit(cu)); - return null; - } - generateJREIUData(iu, id, version, jreLocation); - - //Generate artifact for JRE - IArtifactKey key = new ArtifactKey(BINARY_ARTIFACT_CLASSIFIER, id, version); - iu.setArtifacts(new IArtifactKey[] {key}); - resultantIUs.add(MetadataFactory.createInstallableUnit(iu)); - - //Create config info for the CU - String configurationData = "unzip(source:@artifact, target:${installFolder});"; //$NON-NLS-1$ - touchpointData.put("install", configurationData); //$NON-NLS-1$ - String unConfigurationData = "cleanupzip(source:@artifact, target:${installFolder});"; //$NON-NLS-1$ - touchpointData.put("uninstall", unConfigurationData); //$NON-NLS-1$ - cu.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - resultantIUs.add(MetadataFactory.createInstallableUnit(cu)); - - //Create the artifact descriptor - return createArtifactDescriptor(key, jreLocation, false, true); - } - - public static ArtifactKey createLauncherArtifactKey(String id, Version version) { - return new ArtifactKey(BINARY_ARTIFACT_CLASSIFIER, id, version); - } - - /** - * Creates IUs and artifacts for the Launcher executable. The resulting IUs are added - * to the given set, and the resulting artifact descriptor is returned. - * @deprecated use the EquinoxExecutablesAction instead - */ - public static IArtifactDescriptor createLauncherIU(File launcher, String configurationFlavor, Set resultantIUs) { - if (launcher == null || !launcher.exists()) - return null; - - //Create the IU - InstallableUnitDescription iu = new MetadataFactory.InstallableUnitDescription(); - iu.setSingleton(true); - String launcherId = LAUNCHER_ID_PREFIX + '_' + launcher.getName(); - iu.setId(launcherId); - iu.setVersion(LAUNCHER_VERSION); - - IArtifactKey key = createLauncherArtifactKey(launcherId, LAUNCHER_VERSION); - iu.setArtifacts(new IArtifactKey[] {key}); - iu.setCapabilities(new IProvidedCapability[] {createSelfCapability(launcherId, LAUNCHER_VERSION)}); - iu.setTouchpointType(TOUCHPOINT_NATIVE); - resultantIUs.add(MetadataFactory.createInstallableUnit(iu)); - - //Create the CU - InstallableUnitFragmentDescription cu = new InstallableUnitFragmentDescription(); - String configUnitId = configurationFlavor + launcherId; - cu.setId(configUnitId); - cu.setVersion(LAUNCHER_VERSION); - cu.setHost(new IRequirement[] {MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, launcherId, new VersionRange(LAUNCHER_VERSION, true, Version.MAX_VERSION, true), null, false, false)}); - cu.setProperty(InstallableUnitDescription.PROP_TYPE_FRAGMENT, Boolean.TRUE.toString()); - cu.setCapabilities(new IProvidedCapability[] {createSelfCapability(configUnitId, LAUNCHER_VERSION)}); - cu.setTouchpointType(TOUCHPOINT_NATIVE); - Map touchpointData = new HashMap(); - String configurationData = "unzip(source:@artifact, target:${installFolder});"; //$NON-NLS-1$ - EnvironmentInfo info = (EnvironmentInfo) ServiceHelper.getService(Activator.getContext(), EnvironmentInfo.class.getName()); - if (!info.getOS().equals(org.eclipse.osgi.service.environment.Constants.OS_WIN32)) { - if (info.getOS().equals(org.eclipse.osgi.service.environment.Constants.OS_MACOSX)) { - configurationData += " chmod(targetDir:${installFolder}/Eclipse.app/Contents/MacOS, targetFile:eclipse, permissions:755);"; //$NON-NLS-1$ - generateLauncherSetter("Eclipse", launcherId, LAUNCHER_VERSION, "macosx", null, null, resultantIUs); //$NON-NLS-1$//$NON-NLS-2$ - } else - configurationData += " chmod(targetDir:${installFolder}, targetFile:" + launcher.getName() + ", permissions:755);"; //$NON-NLS-1$ //$NON-NLS-2$ - } else { - generateLauncherSetter("eclipse", launcherId, LAUNCHER_VERSION, "win32", null, null, resultantIUs); //$NON-NLS-1$ //$NON-NLS-2$ - } - touchpointData.put("install", configurationData); //$NON-NLS-1$ - String unConfigurationData = "cleanupzip(source:@artifact, target:${installFolder});"; //$NON-NLS-1$ - touchpointData.put("uninstall", unConfigurationData); //$NON-NLS-1$ - cu.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - resultantIUs.add(MetadataFactory.createInstallableUnitFragment(cu)); - - //Create the artifact descriptor - return createArtifactDescriptor(key, launcher, false, true); - } - - /** - * @deprecated moved to EquinoxExecutablesAction - */ - public static IInstallableUnit generateLauncherSetter(String launcherName, String iuId, Version version, String os, String ws, String arch, Set result) { - InstallableUnitDescription iud = new MetadataFactory.InstallableUnitDescription(); - iud.setId(iuId + '.' + launcherName); - iud.setVersion(version); - iud.setTouchpointType(MetadataGeneratorHelper.TOUCHPOINT_OSGI); - iud.setCapabilities(new IProvidedCapability[] {createSelfCapability(iuId + '.' + launcherName, version)}); - - if (os != null || ws != null || arch != null) { - String filterOs = os != null ? "(osgi.os=" + os + ")" : ""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - String filterWs = ws != null ? "(osgi.ws=" + ws + ")" : ""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - String filterArch = arch != null ? "(osgi.arch=" + arch + ")" : ""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - iud.setFilter("(& " + filterOs + filterWs + filterArch + ")"); //$NON-NLS-1$ //$NON-NLS-2$ - } - Map touchpointData = new HashMap(); - touchpointData.put("configure", "setLauncherName(name:" + launcherName + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - touchpointData.put("unconfigure", "setLauncherName()"); //$NON-NLS-1$ //$NON-NLS-2$ - iud.addTouchpointData(MetadataFactory.createTouchpointData(touchpointData)); - - IInstallableUnit iu = MetadataFactory.createInstallableUnit(iud); - result.add(iu); - return iu; - } - - public static IProvidedCapability createSelfCapability(String installableUnitId, Version installableUnitVersion) { - return MetadataFactory.createProvidedCapability(IU_NAMESPACE, installableUnitId, installableUnitVersion); - } - - /** - * @deprecated moved to BundlesAction - */ - private static String createUnconfigScript(GeneratorBundleInfo unconfigInfo, boolean isBundleFragment) { - if (unconfigInfo == null) - return ""; //$NON-NLS-1$ - String unconfigScript = "";//$NON-NLS-1$ - if (!isBundleFragment && unconfigInfo.getStartLevel() != BundleInfo.NO_LEVEL) { - unconfigScript += "setStartLevel(startLevel:" + BundleInfo.NO_LEVEL + ");"; //$NON-NLS-1$ //$NON-NLS-2$ - } - if (!isBundleFragment && unconfigInfo.isMarkedAsStarted()) { - unconfigScript += "markStarted(started: false);"; //$NON-NLS-1$ - } - - if (unconfigInfo.getSpecialUnconfigCommands() != null) { - unconfigScript += unconfigInfo.getSpecialUnconfigCommands(); - } - return unconfigScript; - - } - - /** - * @deprecated moved to JREAction - */ - private static IProvidedCapability[] generateJRECapability(String installableUnitId, Version installableUnitVersion, InputStream profileStream) { - if (profileStream == null) { - //use the 1.6 profile stored in the generator bundle - try { - profileStream = Activator.getContext().getBundle().getEntry("JavaSE-1.6.profile").openStream(); //$NON-NLS-1$ - } catch (IOException e) { - throw new RuntimeException(e); - } - } - Properties p = new Properties(); - try { - p.load(profileStream); - ManifestElement[] jrePackages = ManifestElement.parseHeader("org.osgi.framework.system.packages", (String) p.get("org.osgi.framework.system.packages")); //$NON-NLS-1$ //$NON-NLS-2$ - IProvidedCapability[] exportedPackageAsCapabilities = new IProvidedCapability[jrePackages.length + 1]; - exportedPackageAsCapabilities[0] = createSelfCapability(installableUnitId, installableUnitVersion); - for (int i = 1; i <= jrePackages.length; i++) { - exportedPackageAsCapabilities[i] = MetadataFactory.createProvidedCapability(CAPABILITY_NS_JAVA_PACKAGE, jrePackages[i - 1].getValue(), null); - } - return exportedPackageAsCapabilities; - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (BundleException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } finally { - if (profileStream != null) { - try { - profileStream.close(); - } catch (IOException e) { - //ignore secondary failure - } - } - } - return new IProvidedCapability[0]; - } - - /** - * @deprecated moved to JREAction - */ - private static void generateJREIUData(InstallableUnitDescription iu, String installableUnitId, Version installableUnitVersion, File jreLocation) { - //Look for a JRE profile file to set version and capabilities - File[] profiles = jreLocation.listFiles(new FileFilter() { - public boolean accept(File pathname) { - return pathname.getAbsolutePath().endsWith(".profile"); //$NON-NLS-1$ - } - }); - if (profiles.length != 1) { - iu.setVersion(DEFAULT_JRE_VERSION); - iu.setCapabilities(generateJRECapability(installableUnitId, installableUnitVersion, null)); - return; - } - String profileName = profiles[0].getAbsolutePath().substring(profiles[0].getAbsolutePath().lastIndexOf('/')); - Version version = DEFAULT_JRE_VERSION; - //TODO Find a better way to determine JRE version - if (profileName.indexOf("1.6") > 0) { //$NON-NLS-1$ - version = Version.create("1.6"); //$NON-NLS-1$ - } else if (profileName.indexOf("1.5") > 0) { //$NON-NLS-1$ - version = Version.create("1.5"); //$NON-NLS-1$ - } else if (profileName.indexOf("1.4") > 0) { //$NON-NLS-1$ - version = Version.create("1.4"); //$NON-NLS-1$ - } - iu.setVersion(version); - try { - iu.setCapabilities(generateJRECapability(installableUnitId, installableUnitVersion, new FileInputStream(profiles[0]))); - } catch (FileNotFoundException e) { - //Shouldn't happen, but ignore and fall through to use default - } - } - - /** - * @deprecated moved to FeaturesAction - */ - public static IMatchExpression getFilter(FeatureEntry entry) { - StringBuffer result = new StringBuffer(); - result.append("(&"); //$NON-NLS-1$ - if (entry.getFilter() != null) - result.append(entry.getFilter()); - if (entry.getOS() != null) - result.append("(osgi.os=" + entry.getOS() + ')');//$NON-NLS-1$ - if (entry.getWS() != null) - result.append("(osgi.ws=" + entry.getWS() + ')');//$NON-NLS-1$ - if (entry.getArch() != null) - result.append("(osgi.arch=" + entry.getArch() + ')');//$NON-NLS-1$ - if (entry.getNL() != null) - result.append("(osgi.nl=" + entry.getNL() + ')');//$NON-NLS-1$ - if (result.length() == 2) - return null; - result.append(')'); - return InstallableUnit.parseFilter(result.toString()); - } - - /** - * @deprecated moved to FeaturesAction - */ - public static String getTransformedId(String original, boolean isPlugin, boolean isGroup) { - return (isPlugin ? original : original + (isGroup ? ".feature.group" : ".feature.jar")); //$NON-NLS-1$//$NON-NLS-2$ - } - - /** - * @deprecated moved to FeaturesAction - */ - public static VersionRange getVersionRange(FeatureEntry entry) { - String versionSpec = entry.getVersion(); - if (versionSpec == null) - return VersionRange.emptyRange; - Version version = Version.create(versionSpec); - if (version.equals(Version.emptyVersion)) - return VersionRange.emptyRange; - if (!entry.isRequires()) - return new VersionRange(version, true, version, true); - String match = entry.getMatch(); - - org.osgi.framework.Version osgiVersion = toOSGiVersion(version); - if (match == null || match.equals("compatible")) { //$NON-NLS-1$ - Version upper = Version.createOSGi(osgiVersion.getMajor() + 1, 0, 0); - return new VersionRange(version, true, upper, false); - } - if (match.equals("perfect")) //$NON-NLS-1$ - return new VersionRange(version, true, version, true); - if (match.equals("equivalent")) { //$NON-NLS-1$ - Version upper = Version.createOSGi(osgiVersion.getMajor(), osgiVersion.getMinor() + 1, 0); - return new VersionRange(version, true, upper, false); - } - if (match.equals("greaterOrEqual")) //$NON-NLS-1$ - return new VersionRange(version, true, new VersionRange(null).getMaximum(), true); - return null; - } - - /** - * @deprecated moved to AdviceFileAdvice - */ - public static Map getBundleAdvice(String bundleLocation, String suffixLocation) { - if (bundleLocation == null) - return Collections.EMPTY_MAP; - - File bundle = new File(bundleLocation); - if (!bundle.exists()) - return Collections.EMPTY_MAP; - - ZipFile jar = null; - InputStream stream = null; - if (bundle.isDirectory()) { - File adviceFile = new File(bundle, suffixLocation); - if (adviceFile.exists()) { - try { - stream = new BufferedInputStream(new FileInputStream(adviceFile)); - } catch (IOException e) { - return Collections.EMPTY_MAP; - } - } - } else if (bundle.isFile()) { - try { - jar = new ZipFile(bundle); - ZipEntry entry = jar.getEntry(suffixLocation); - if (entry != null) - stream = new BufferedInputStream(jar.getInputStream(entry)); - } catch (IOException e) { - if (jar != null) - try { - jar.close(); - } catch (IOException e1) { - //boo - } - return Collections.EMPTY_MAP; - } - } - - Properties advice = null; - if (stream != null) { - try { - advice = new Properties(); - advice.load(stream); - } catch (IOException e) { - return Collections.EMPTY_MAP; - } finally { - try { - stream.close(); - } catch (IOException e) { - //boo - } - } - } - - if (jar != null) { - try { - jar.close(); - } catch (IOException e) { - // boo - } - } - - return advice != null ? advice : Collections.EMPTY_MAP; - } - - /** - * @deprecated moved to BundlesAction - */ - private static boolean isOptional(ImportPackageSpecification importedPackage) { - if (importedPackage.getDirective(Constants.RESOLUTION_DIRECTIVE).equals(ImportPackageSpecification.RESOLUTION_DYNAMIC) || importedPackage.getDirective(Constants.RESOLUTION_DIRECTIVE).equals(ImportPackageSpecification.RESOLUTION_OPTIONAL)) - return true; - return false; - } - - /** - * @deprecated moved to BundlesAction - */ - private static String toManifestString(Map p) { - if (p == null) - return null; - Collection properties = p.entrySet(); - StringBuffer result = new StringBuffer(); - for (Iterator iterator = properties.iterator(); iterator.hasNext();) { - Map.Entry aProperty = (Map.Entry) iterator.next(); - if (aProperty.getKey().equals(BundleDescriptionFactory.BUNDLE_FILE_KEY)) - continue; - result.append(aProperty.getKey()).append(": ").append(aProperty.getValue()).append('\n'); //$NON-NLS-1$ - } - return result.toString(); - } - - /** - * Returns a URI corresponding to the given URL in string form, or null - * if a well formed URI could not be created. - */ - private static URI toURIOrNull(String url) { - if (url == null) - return null; - try { - return URIUtil.fromString(url); - } catch (URISyntaxException e) { - return null; - } - } - - // Return a map from locale to property set for the manifest localizations - // from the given bundle directory and given bundle localization path/name - // manifest property value. - /** - * @deprecated moved to BundlesAction - */ - private static Map getManifestLocalizations(Map manifest, File bundleLocation) { - Map localizations; - Locale defaultLocale = null; // = Locale.ENGLISH; // TODO: get this from GeneratorInfo - String[] bundleManifestValues = getManifestCachedValues(manifest); - String bundleLocalization = bundleManifestValues[BUNDLE_LOCALIZATION_INDEX]; - - if ("jar".equalsIgnoreCase(new Path(bundleLocation.getName()).getFileExtension()) && //$NON-NLS-1$ - bundleLocation.isFile()) { - localizations = LocalizationHelper.getJarPropertyLocalizations(bundleLocation, bundleLocalization, defaultLocale, bundleManifestValues); - //localizations = getJarManifestLocalization(bundleLocation, bundleLocalization, defaultLocale, bundleManifestValues); - } else { - localizations = LocalizationHelper.getDirPropertyLocalizations(bundleLocation, bundleLocalization, defaultLocale, bundleManifestValues); - // localizations = getDirManifestLocalization(bundleLocation, bundleLocalization, defaultLocale, bundleManifestValues); - } - - return localizations; - } - - /** - * @deprecated moved to BundlesAction - */ - public static String[] getManifestCachedValues(Map manifest) { - String[] cachedValues = new String[BUNDLE_LOCALIZED_PROPERTIES.length + 1]; - for (int j = 0; j < MetadataGeneratorHelper.BUNDLE_LOCALIZED_PROPERTIES.length; j++) { - String value = (String) manifest.get(BUNDLE_LOCALIZED_PROPERTIES[j]); - if (value != null && value.length() > 1 && value.charAt(0) == '%') { - cachedValues[j] = value.substring(1); - } - } - String localizationFile = (String) manifest.get(org.osgi.framework.Constants.BUNDLE_LOCALIZATION); - cachedValues[BUNDLE_LOCALIZATION_INDEX] = (localizationFile != null ? localizationFile : DEFAULT_BUNDLE_LOCALIZATION); - return cachedValues; - } - - // Return a map from locale to property set for the manifest localizations - // from the given bundle directory and given bundle localization path/name - // manifest property value. - /** - * @deprecated moved to BundlesAction - */ - public static Map getHostLocalizations(File bundleLocation, String[] hostBundleManifestValues) { - Map localizations; - Locale defaultLocale = null; // = Locale.ENGLISH; // TODO: get this from GeneratorInfo - String hostBundleLocalization = hostBundleManifestValues[BUNDLE_LOCALIZATION_INDEX]; - - if ("jar".equalsIgnoreCase(new Path(bundleLocation.getName()).getFileExtension()) && //$NON-NLS-1$ - bundleLocation.isFile()) { - localizations = LocalizationHelper.getJarPropertyLocalizations(bundleLocation, hostBundleLocalization, defaultLocale, hostBundleManifestValues); - //localizations = getJarManifestLocalization(bundleLocation, hostBundleLocalization, defaultLocale, hostBundleManifestValues); - } else { - localizations = LocalizationHelper.getDirPropertyLocalizations(bundleLocation, hostBundleLocalization, defaultLocale, hostBundleManifestValues); - // localizations = getDirManifestLocalization(bundleLocation, hostBundleLocalization, defaultLocale, hostBundleManifestValues); - } - - return localizations; - } - - /** - * Convert <code>version</code> into its OSGi equivalent if possible. - * - * @param version The version to convert. Can be <code>null</code> - * @return The converted version or <code>null</code> if the argument was <code>null</code> - * @throws UnsupportedOperationException if the version could not be converted into an OSGi version - */ - public static org.osgi.framework.Version toOSGiVersion(Version version) { - if (version == null) - return null; - if (version == Version.emptyVersion) - return org.osgi.framework.Version.emptyVersion; - if (version == Version.MAX_VERSION) - return new org.osgi.framework.Version(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); - - BasicVersion bv = (BasicVersion) version; - return new org.osgi.framework.Version(bv.getMajor(), bv.getMinor(), bv.getMicro(), bv.getQualifier()); - } - - /** - * Create an omni version from an OSGi <code>version</code>. - * @param version The OSGi version. Can be <code>null</code>. - * @return The created omni version - */ - public static Version fromOSGiVersion(org.osgi.framework.Version version) { - if (version == null) - return null; - if (version.getMajor() == Integer.MAX_VALUE && version.getMicro() == Integer.MAX_VALUE && version.getMicro() == Integer.MAX_VALUE) - return Version.MAX_VERSION; - return Version.createOSGi(version.getMajor(), version.getMinor(), version.getMicro(), version.getQualifier()); - } - - public static org.eclipse.osgi.service.resolver.VersionRange toOSGiVersionRange(VersionRange range) { - if (range.equals(VersionRange.emptyRange)) - return org.eclipse.osgi.service.resolver.VersionRange.emptyRange; - return new org.eclipse.osgi.service.resolver.VersionRange(toOSGiVersion(range.getMinimum()), range.getIncludeMinimum(), toOSGiVersion(range.getMaximum()), range.getIncludeMinimum()); - } - - public static VersionRange fromOSGiVersionRange(org.eclipse.osgi.service.resolver.VersionRange range) { - if (range.equals(org.eclipse.osgi.service.resolver.VersionRange.emptyRange)) - return VersionRange.emptyRange; - return new VersionRange(fromOSGiVersion(range.getMinimum()), range.getIncludeMinimum(), fromOSGiVersion(range.getMaximum()), range.getIncludeMaximum()); - } -}; diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/URLEntry.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/URLEntry.java deleted file mode 100644 index 8e928f65c..000000000 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/provisional/p2/metadata/generator/URLEntry.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.equinox.internal.provisional.p2.metadata.generator; - -public class URLEntry { - private String annotation; - private String url; - - public URLEntry() { - } - - public URLEntry(String url, String annotation) { - this.url = url; - this.annotation = annotation; - } - - public void setAnnotation(String annotation) { - this.annotation = annotation; - } - - public String getAnnotation() { - return annotation; - } - - public void setURL(String url) { - this.url = url; - } - - public String getURL() { - return url; - } -} |