Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 2008, 2010 Code 9 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: Code 9 - initial API and implementation IBM - ongoing development Sonatype, Inc. - transport split /
 
 package org.eclipse.equinox.internal.p2.updatesite;
 
 import java.io.File;
 import java.net.URI;
 import java.util.*;
 import  org.eclipse.equinox.p2.publisher.eclipse.URLEntry;
Action which processes a site.xml and generates categories. The categorization process relies on IUs for the various features to have already been generated.
 
 public class SiteXMLAction extends AbstractPublisherAction {
 	static final private String QUALIFIER = "qualifier"//$NON-NLS-1$
 	protected UpdateSite updateSite;
 	protected URI location;
 	private String categoryQualifier = null;
 	private Version categoryVersion = null;

Creates a SiteXMLAction from a Location (URI) with an optional qualifier to use for category names

Parameters:
location The location of the update site
categoryQualifier The qualifier to prepend to categories. This qualifier is used to ensure that the category IDs are unique between update sites. If null a default qualifier will be generated
 
 	public SiteXMLAction(URI locationString categoryQualifier) {
 		this. = location;
 		this. = categoryQualifier;
 	}

Creates a SiteXMLAction from an Update site with an optional qualifier to use for category names

Parameters:
updateSite The update site
categoryQualifier The qualifier to prepend to categories. This qualifier is used to ensure that the category IDs are unique between update sites. If null a default qualifier will be generated
 
 	public SiteXMLAction(UpdateSite updateSiteString categoryQualifier) {
 		this. = updateSite;
 		this. = categoryQualifier;
 	}
 
 	public void setCategoryVersion(String version) {
 		 = Version.parseVersion(version);
 	}
 
 	private void initialize() {
 		if ( != null)
 			return;
 		.setDescription("Default category for otherwise uncategorized features"); //$NON-NLS-1$
 		.setLabel("Uncategorized"); //$NON-NLS-1$
 		.setName("Default"); //$NON-NLS-1$
 	}
 
 	public IStatus perform(IPublisherInfo publisherInfoIPublisherResult resultsIProgressMonitor monitor) {
 		if ( == null) {
 			try {
 			} catch (ProvisionException e) {
 			} catch (OperationCanceledException e) {
 			}
 		}
		return generateCategories(publisherInforesultsmonitor);
	}
	private IStatus generateCategories(IPublisherInfo publisherInfoIPublisherResult resultsIProgressMonitor monitor) {
		Map<SiteFeatureSet<SiteCategory>> featuresToCategories = getFeatureToCategoryMappings(publisherInfo);
		for (SiteFeature feature : featuresToCategories.keySet()) {
			if (monitor.isCanceled())
			Collection<IInstallableUnitius = getFeatureIU(featurepublisherInforesults);
			if (ius == null)
				continue;
			Set<SiteCategorycategories = featuresToCategories.get(feature);
			// if there are no categories for this feature then add it to the default category.
			if (categories == null || categories.isEmpty())
				categories = ;
			for (SiteCategory category : categories) {
				Set<IInstallableUnitfeatureIUs = categoriesToIUs.get(category);
				if (featureIUs == null) {
					featureIUs = new HashSet<IInstallableUnit>();
					categoriesToIUs.put(categoryfeatureIUs);
				}
				featureIUs.addAll(ius);
			}
		}
		addSiteIUsToCategories(categoriesToIUspublisherInforesults);
		generateCategoryIUs(categoriesToIUsresults);
	}
	private void addSiteIUsToCategories(Map<SiteCategorySet<IInstallableUnit>> categoriesToIUsIPublisherInfo publisherInfoIPublisherResult results) {
		if ( == null)
			return;
		if (site == null)
			return;
		SiteIU[] siteIUs = site.getIUs();
		for (SiteIU siteIU : siteIUs) {
			String[] categoryNames = siteIU.getCategoryNames();
			if (categoryNames.length == 0)
				continue;
			Collection<IInstallableUnitius = getIUs(siteIUpublisherInforesults);
			if (ius.size() == 0)
				continue;
			for (String categoryName : categoryNames) {
				SiteCategory category = site.getCategory(categoryName);
				if (category == null)
					continue;
				Set<IInstallableUnitcategoryIUs = categoriesToIUs.get(category);
				if (categoryIUs == null) {
					categoryIUs = new HashSet<IInstallableUnit>();
					categoriesToIUs.put(categorycategoryIUs);
				}
				categoryIUs.addAll(ius);
			}
		}
	}
	private Collection<IInstallableUnitgetIUs(SiteIU siteIUIPublisherInfo publisherInfoIPublisherResult results) {
		String id = siteIU.getID();
		String range = siteIU.getRange();
		String type = siteIU.getQueryType();
		String expression = siteIU.getQueryExpression();
		Object[] params = siteIU.getQueryParams();
		if (id == null && (type == null || expression == null))
			return CollectionUtils.emptyList();
		IQuery<IInstallableUnitquery = null;
		if (id != null) {
			VersionRange vRange = new VersionRange(range);
			query = QueryUtil.createIUQuery(idvRange);
else if (type.equals("context")) { //$NON-NLS-1$
			query = QueryUtil.createQuery(expressionparams);
else if (type.equals("match")) //$NON-NLS-1$
			query = QueryUtil.createMatchQuery(expressionparams);
		if (query == null)
			return CollectionUtils.emptyList();
		IQueryResult<IInstallableUnitqueryResult = results.query(querynull);
		if (queryResult.isEmpty())
			queryResult = publisherInfo.getMetadataRepository().query(querynull);
		if (queryResult.isEmpty() && publisherInfo.getContextMetadataRepository() != null)
			queryResult = publisherInfo.getContextMetadataRepository().query(querynull);
		return queryResult.toUnmodifiableSet();
	}
	private static final IExpression qualifierMatchExpr = ExpressionUtil.parse("id == $0 && version ~= $1"); //$NON-NLS-1$
	private Collection<IInstallableUnitgetFeatureIU(SiteFeature featureIPublisherInfo publisherInfoIPublisherResult results) {
		String id = feature.getFeatureIdentifier() + ".feature.group"//$NON-NLS-1$
		String versionString = feature.getFeatureVersion();
		Version version = versionString != null && versionString.length() > 0 ? Version.create(versionString) : .;
		IQuery<IInstallableUnitquery = null;
		if (version.equals(.)) {
			query = QueryUtil.createIUQuery(id);
else {
			String qualifier;
			try {
				qualifier = PublisherHelper.toOSGiVersion(version).getQualifier();
				qualifier = null;
			}
			if (qualifier != null && qualifier.endsWith()) {
				IQuery<IInstallableUnitqualifierQuery = QueryUtil.createMatchQuery(idrange);
				query = qualifierQuery;
else {
				query = QueryUtil.createLimitQuery(QueryUtil.createIUQuery(idversion), 1);
			}
		}
		IQueryResult<IInstallableUnitqueryResult = results.query(querynull);
		if (queryResult.isEmpty())
			queryResult = publisherInfo.getMetadataRepository().query(querynull);
		if (queryResult.isEmpty() && publisherInfo.getContextMetadataRepository() != null)
			queryResult = publisherInfo.getContextMetadataRepository().query(querynull);
		if (!queryResult.isEmpty())
			return queryResult.toUnmodifiableSet();
		return null;
	}
	protected VersionRange createVersionRange(String versionId) {
		VersionRange range = null;
		if (versionId == null || "0.0.0".equals(versionId)) //$NON-NLS-1$
		else {
			int qualifierIdx = versionId.indexOf();
			if (qualifierIdx != -1) {
				String newVersion = versionId.substring(0, qualifierIdx);
				if (newVersion.endsWith(".")) //$NON-NLS-1$
					newVersion = newVersion.substring(0, newVersion.length() - 1);
				Version lower = Version.parseVersion(newVersion);
				Version upper = null;
				String newQualifier = VersionSuffixGenerator.incrementQualifier(PublisherHelper.toOSGiVersion(lower).getQualifier());
				org.osgi.framework.Version osgiVersion = PublisherHelper.toOSGiVersion(lower);
				if (newQualifier == null)
					upper = Version.createOSGi(osgiVersion.getMajor(), osgiVersion.getMinor(), osgiVersion.getMicro() + 1);
				else
					upper = Version.createOSGi(osgiVersion.getMajor(), osgiVersion.getMinor(), osgiVersion.getMicro(), newQualifier);
				range = new VersionRange(lowertrueupperfalse);
else {
				range = new VersionRange(Version.parseVersion(versionId), true, Version.parseVersion(versionId), true);
			}
		}
		return range;
	}

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.

Returns:
A map of SiteFeature -> Set<SiteCategory>.
		if ( == null)
			return mappings;
		if (site == null)
			return mappings;
		//copy mirror information from update site to p2 repositories
		String mirrors = site.getMirrorsURI();
		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$
			// there does not really need to be an artifact repo but if there is, setup its mirrors.
			if (publisherInfo.getArtifactRepository() != null)
		}
		//publish associate sites as repository references
		URLEntry[] associatedSites = site.getAssociatedSites();
		if (associatedSites != null) {
			ArrayList<IRepositoryReferencerefs = new ArrayList<IRepositoryReference>(associatedSites.length * 2);
			for (int i = 0; i < associatedSites.length; i++) {
				URLEntry associatedSite = associatedSites[i];
				String siteLocation = associatedSite.getURL();
				try {
					URI associateLocation = new URI(siteLocation);
					String label = associatedSite.getAnnotation();
					refs.add(new RepositoryReference(associateLocationlabel..));
					refs.add(new RepositoryReference(associateLocationlabel..));
catch (URISyntaxException e) {
					String message = "Invalid site reference: " + siteLocation//$NON-NLS-1$
					LogHelper.log(new Status(..message));
				}
			}
			publisherInfo.getMetadataRepository().addReferences(refs);
		}
		File siteFile = URIUtil.toFile(.getLocation());
		if (siteFile != null && siteFile.exists()) {
			File siteParent = siteFile.getParentFile();
			List<StringmessageKeys = site.getMessageKeys();
			if (siteParent.isDirectory()) {
				String[] keyStrings = messageKeys.toArray(new String[messageKeys.size()]);
				site.setLocalizations(LocalizationHelper.getDirPropertyLocalizations(siteParent"site"nullkeyStrings)); //$NON-NLS-1$
else if (siteFile.getName().endsWith(".jar")) { //$NON-NLS-1$
				String[] keyStrings = messageKeys.toArray(new String[messageKeys.size()]);
				site.setLocalizations(LocalizationHelper.getJarPropertyLocalizations(siteParent"site"nullkeyStrings)); //$NON-NLS-1$
			}
		}
		SiteFeature[] features = site.getFeatures();
		for (int i = 0; i < features.lengthi++) {
			//add a mapping for each category this feature belongs to
			String[] categoryNames = features[i].getCategoryNames();
			Set<SiteCategorycategories = new HashSet<SiteCategory>();
			mappings.put(features[i], categories);
			for (int j = 0; j < categoryNames.lengthj++) {
				SiteCategory category = site.getCategory(categoryNames[j]);
				if (category != null)
					categories.add(category);
			}
		}
		return mappings;
	}

Generates IUs corresponding to update site categories.

Parameters:
categoriesToFeatures Map of SiteCategory ->Set (Feature IUs in that category).
result The generator result being built
	protected void generateCategoryIUs(Map<SiteCategorySet<IInstallableUnit>> categoriesToFeaturesIPublisherResult result) {
		for (SiteCategory category : categoriesToFeatures.keySet()) {
			result.addIU(createCategoryIU(categorycategoriesToFeatures.get(category), null), .);
		}
	}

Creates an IU corresponding to an update site category

Parameters:
category The category descriptor
featureIUs The IUs of the features that belong to the category
parentCategory The parent category, or null
Returns:
an IU representing the category
	public IInstallableUnit createCategoryIU(SiteCategory categorySet<IInstallableUnitfeatureIUsIInstallableUnit parentCategory) {
		cat.setSingleton(true);
		String categoryId = buildCategoryId(category.getName());
		cat.setId(categoryId);
		if ( == null)
			cat.setVersion(Version.createOSGi(1, 0, 0, .generateSuffix(featureIUs, CollectionUtils.<IVersionedIdemptyList())));
		else {
				org.osgi.framework.Version osgiVersion = PublisherHelper.toOSGiVersion();
				String qualifier = osgiVersion.getQualifier();
				if (qualifier.endsWith()) {
					String suffix = .generateSuffix(featureIUs, CollectionUtils.<IVersionedIdemptyList());
					qualifier = qualifier.substring(0, qualifier.length() - 9) + suffix;
					 = Version.createOSGi(osgiVersion.getMajor(), osgiVersion.getMinor(), osgiVersion.getMicro(), qualifier);
				}
			}
		}
		String label = category.getLabel();
		cat.setProperty(.label != null ? label : category.getName());
		ArrayList<IRequirementreqsConfigurationUnits = new ArrayList<IRequirement>(featureIUs.size());
		for (IInstallableUnit iu : featureIUs) {
			VersionRange range = new VersionRange(iu.getVersion(), trueiu.getVersion(), true);
			reqsConfigurationUnits.add(MetadataFactory.createRequirement(.iu.getId(), rangeiu.getFilter(), falsefalse));
		}
		//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(.parentCategory.getId(), .parentCategory.getFilter(), falsefalse));
		}
		cat.setRequirements(reqsConfigurationUnits.toArray(new IRequirement[reqsConfigurationUnits.size()]));
		// Create set of provided capabilities
		ArrayList<IProvidedCapabilityprovidedCapabilities = new ArrayList<IProvidedCapability>();
		providedCapabilities.add(PublisherHelper.createSelfCapability(categoryIdcat.getVersion()));
		Map<LocaleMap<StringString>> localizations = category.getLocalizations();
		if (localizations != null) {
			for (Entry<LocaleMap<StringString>> locEntry : localizations.entrySet()) {
				Locale locale = locEntry.getKey();
				Map<StringStringtranslatedStrings = locEntry.getValue();
				for (Entry<StringStringe : translatedStrings.entrySet()) {
					cat.setProperty(locale.toString() + '.' + e.getKey(), e.getValue());
				}
				providedCapabilities.add(PublisherHelper.makeTranslationCapability(categoryIdlocale));
			}
		}
		cat.setCapabilities(providedCapabilities.toArray(new IProvidedCapability[providedCapabilities.size()]));
		return MetadataFactory.createInstallableUnit(cat);
	}

Creates a qualified category id. This action's qualifier is used if one exists or an existing update site's location is used.
	private String buildCategoryId(String categoryName) {
		if ( != null) {
				return  + "." + categoryName//$NON-NLS-1$
			return categoryName;
		}
		if ( != null)
			return URIUtil.toUnencodedString(.getLocation()) + "." + categoryName//$NON-NLS-1$
		return categoryName;
	}
		@SuppressWarnings("rawtypes")
		if (repo == null)
			repo = info.getArtifactRepository();
		if (repo == null)
			throw new IllegalStateException("The transport service can not be found."); //$NON-NLS-1$
	}
New to GrepCode? Check out our FAQ X