Debian Codegraph @

bundles/org.eclipse.equinox.p2.updatesite/src/org/eclipse/equinox/internal/p2/updatesite/SiteXMLAction.java

raw
1 /*******************************************************************************
2 * Copyright (c) 2008, 2020 Code 9 and others.
3 *
4 * This
5 * program and the accompanying materials are made available under the terms of
6 * the Eclipse Public License 2.0 which accompanies this distribution, and is
7 * available at
8 * https://www.eclipse.org/legal/epl-2.0/
9 *
10 * SPDX-License-Identifier: EPL-2.0
11 *
12 * Contributors:
13 * Code 9 - initial API and implementation
14 * IBM - ongoing development
15 * Sonatype, Inc. - transport split
16 * Red Hat Inc. - 383795 (bundle element)
17 ******************************************************************************/
18 package org.eclipse.equinox.internal.p2.updatesite;
19
20 import java.io.File;
21 import java.net.URI;
22 import java.net.URISyntaxException;
23 import java.util.*;
24 import java.util.Map.Entry;
25 import org.eclipse.core.runtime.*;
26 import org.eclipse.equinox.internal.p2.core.helpers.LogHelper;
27 import org.eclipse.equinox.internal.p2.repository.Transport;
28 import org.eclipse.equinox.p2.core.ProvisionException;
29 import org.eclipse.equinox.p2.metadata.*;
30 import org.eclipse.equinox.p2.metadata.MetadataFactory.InstallableUnitDescription;
31 import org.eclipse.equinox.p2.metadata.expression.ExpressionUtil;
32 import org.eclipse.equinox.p2.metadata.expression.IExpression;
33 import org.eclipse.equinox.p2.publisher.*;
34 import org.eclipse.equinox.p2.publisher.eclipse.*;
35 import org.eclipse.equinox.p2.query.*;
36 import org.eclipse.equinox.p2.repository.IRepository;
37 import org.eclipse.equinox.p2.repository.IRepositoryReference;
38 import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor;
39 import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository;
40 import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor;
41 import org.eclipse.equinox.p2.repository.spi.RepositoryReference;
42 import org.eclipse.equinox.spi.p2.publisher.LocalizationHelper;
43 import org.eclipse.equinox.spi.p2.publisher.PublisherHelper;
44
45 /**
46 * Action which processes a site.xml and generates categories. The
47 * categorization process relies on IUs for the various features to have already
48 * been generated.
49 */
50 public class SiteXMLAction extends AbstractPublisherAction {
51 static final private String QUALIFIER = "qualifier"; //$NON-NLS-1$
52 static final private String P_STATS_URI = "p2.statsURI"; //$NON-NLS-1$
53 static final private String P_STATS_MARKER = "download.stats"; //$NON-NLS-1$
54 private static final VersionSuffixGenerator versionSuffixGenerator = new VersionSuffixGenerator();
55 protected UpdateSite updateSite;
56 private SiteCategory defaultCategory;
57 private HashSet<SiteCategory> defaultCategorySet;
58 protected URI location;
59 private String categoryQualifier = null;
60 private Version categoryVersion = null;
61
62 /**
63 * Creates a SiteXMLAction from a Location (URI) with an optional qualifier to
64 * use for category names
65 *
66 * @param location The location of the update site
67 * @param categoryQualifier The qualifier to prepend to categories. This
68 * qualifier is used to ensure that the category IDs
69 * are unique between update sites. If <b>null</b> a
70 * default qualifier will be generated
71 */
72 public SiteXMLAction(URI location, String categoryQualifier) {
73 this.location = location;
74 this.categoryQualifier = categoryQualifier;
75 }
76
77 /**
78 * Creates a SiteXMLAction from an Update site with an optional qualifier to use
79 * for category names
80 *
81 * @param updateSite The update site
82 * @param categoryQualifier The qualifier to prepend to categories. This
83 * qualifier is used to ensure that the category IDs
84 * are unique between update sites. If <b>null</b> a
85 * default qualifier will be generated
86 */
87 public SiteXMLAction(UpdateSite updateSite, String categoryQualifier) {
88 this.updateSite = updateSite;
89 this.categoryQualifier = categoryQualifier;
90 }
91
92 public void setCategoryVersion(String version) {
93 categoryVersion = Version.parseVersion(version);
94 }
95
96 private void initialize() {
97 if (defaultCategory != null)
98 return;
99 defaultCategory = new SiteCategory();
100 defaultCategory.setDescription("Default category for otherwise uncategorized features"); //$NON-NLS-1$
101 defaultCategory.setLabel("Uncategorized"); //$NON-NLS-1$
102 defaultCategory.setName("Default"); //$NON-NLS-1$
103 defaultCategorySet = new HashSet<>(1);
104 defaultCategorySet.add(defaultCategory);
105 }
106
107 @Override
108 public IStatus perform(IPublisherInfo publisherInfo, IPublisherResult results, IProgressMonitor monitor) {
109 if (updateSite == null) {
110 try {
111 updateSite = UpdateSite.load(location,
112 publisherInfo.getMetadataRepository().getProvisioningAgent().getService(Transport.class),
113 monitor);
114 } catch (ProvisionException e) {
115 return new Status(IStatus.ERROR, Activator.ID, Messages.Error_generating_siteXML, e);
116 } catch (OperationCanceledException e) {
117 return Status.CANCEL_STATUS;
118 }
119 }
120 initialize();
121 initializeRepoFromSite(publisherInfo);
122 IStatus markingStats = markStatsArtifacts(publisherInfo, results, monitor);
123 if (markingStats.isOK()) {
124 return generateCategories(publisherInfo, results, monitor);
125 }
126 return markingStats;
127 }
128
129 private IStatus markStatsArtifacts(IPublisherInfo publisherInfo, IPublisherResult results,
130 IProgressMonitor monitor) {
131 IArtifactRepository artifactRepo = publisherInfo.getArtifactRepository();
132 SiteModel site = updateSite.getSite();
133 // process all features listed and mark artifacts
134 SiteFeature[] features = site.getStatsFeatures();
135 if (features != null && artifactRepo != null) {
136 for (SiteFeature feature : features) {
137 if (monitor.isCanceled())
138 return Status.CANCEL_STATUS;
139 Collection<IInstallableUnit> ius = getFeatureIU(feature, publisherInfo, results);
140 if (ius != null) {
141 for (IInstallableUnit iu : ius) {
142 IArtifactKey key = FeaturesAction.createFeatureArtifactKey(feature.getFeatureIdentifier(),
143 iu.getVersion().toString());
144 IArtifactDescriptor[] descriptors = artifactRepo.getArtifactDescriptors(key);
145 if (descriptors.length > 0 && descriptors[0] instanceof ArtifactDescriptor) {
146 HashMap<String, String> map = new HashMap<>();
147 map.put(P_STATS_MARKER, feature.getFeatureIdentifier());
148 ((ArtifactDescriptor) descriptors[0]).addProperties(map);
149 }
150 }
151 }
152 }
153 }
154 // process all bundles listed and mark artifacts
155 SiteBundle[] bundles = site.getStatsBundles();
156 if (bundles != null && artifactRepo != null) {
157 for (SiteBundle bundle : bundles) {
158 if (monitor.isCanceled())
159 return Status.CANCEL_STATUS;
160 Collection<IInstallableUnit> ius = getBundleIU(bundle, publisherInfo, results);
161 if (ius != null) {
162 for (IInstallableUnit iu : ius) {
163 IArtifactKey key = BundlesAction.createBundleArtifactKey(iu.getId(),
164 iu.getVersion().toString());
165 IArtifactDescriptor[] descriptors = artifactRepo.getArtifactDescriptors(key);
166 if (descriptors.length > 0 && descriptors[0] instanceof ArtifactDescriptor) {
167 HashMap<String, String> map = new HashMap<>();
168 map.put(P_STATS_MARKER, iu.getId());
169 ((ArtifactDescriptor) descriptors[0]).addProperties(map);
170 }
171 }
172 }
173 }
174 }
175 // If there was no artifact repository available and stats were to be tracked,
176 // issue
177 // a warning.
178 boolean markingBundles = bundles != null && bundles.length > 0;
179 boolean markingFeatures = features != null && features.length > 0;
180 if (artifactRepo == null && (markingBundles || markingFeatures))
181 return new Status(IStatus.WARNING, Activator.ID,
182 "Artifact repository was not specified so stats properties could not be published."); //$NON-NLS-1$
183 return Status.OK_STATUS;
184
185 }
186
187 private IStatus generateCategories(IPublisherInfo publisherInfo, IPublisherResult results,
188 IProgressMonitor monitor) {
189 Map<SiteCategory, Set<IInstallableUnit>> categoriesToIUs = new HashMap<>();
190 Map<SiteFeature, Set<SiteCategory>> featuresToCategories = getFeatureToCategoryMappings(publisherInfo);
191 for (SiteFeature feature : featuresToCategories.keySet()) {
192 if (monitor.isCanceled())
193 return Status.CANCEL_STATUS;
194 Collection<IInstallableUnit> ius = getFeatureIU(feature, publisherInfo, results);
195 if (ius == null)
196 continue;
197 Set<SiteCategory> categories = featuresToCategories.get(feature);
198 // if there are no categories for this feature then add it to the default
199 // category.
200 if (categories == null || categories.isEmpty())
201 categories = defaultCategorySet;
202 for (SiteCategory category : categories) {
203 Set<IInstallableUnit> iusInCategory = categoriesToIUs.get(category);
204 if (iusInCategory == null) {
205 iusInCategory = new HashSet<>();
206 categoriesToIUs.put(category, iusInCategory);
207 }
208 iusInCategory.addAll(ius);
209 }
210 }
211 // Bundles -- bug 378338
212 Map<SiteBundle, Set<SiteCategory>> bundlesToCategories = getBundleToCategoryMappings(publisherInfo);
213 for (SiteBundle bundle : bundlesToCategories.keySet()) {
214 if (monitor.isCanceled())
215 return Status.CANCEL_STATUS;
216 Collection<IInstallableUnit> ius = getBundleIU(bundle, publisherInfo, results);
217 if (ius == null)
218 continue;
219 Set<SiteCategory> categories = bundlesToCategories.get(bundle);
220 // if there are no categories for this feature then add it to the default
221 // category.
222 if (categories == null || categories.isEmpty())
223 categories = defaultCategorySet;
224 for (SiteCategory category : categories) {
225 Set<IInstallableUnit> iusInCategory = categoriesToIUs.get(category);
226 if (iusInCategory == null) {
227 iusInCategory = new HashSet<>();
228 categoriesToIUs.put(category, iusInCategory);
229 }
230 iusInCategory.addAll(ius);
231 }
232 }
233
234 addSiteIUsToCategories(categoriesToIUs, publisherInfo, results);
235 generateCategoryIUs(categoriesToIUs, results);
236 return Status.OK_STATUS;
237 }
238
239 private void addSiteIUsToCategories(Map<SiteCategory, Set<IInstallableUnit>> categoriesToIUs,
240 IPublisherInfo publisherInfo, IPublisherResult results) {
241 Map<SiteIU, Set<SiteCategory>> iusToCategories = getIUToCategoryMappings(publisherInfo);
242 SiteModel site = updateSite.getSite();
243 if (site == null)
244 return;
245 SiteIU[] siteIUs = site.getIUs();
246 for (SiteIU siteIU : siteIUs) {
247 Collection<IInstallableUnit> ius = getIUs(siteIU, publisherInfo, results);
248 if (ius == null)
249 continue;
250 Set<SiteCategory> categories = iusToCategories.get(siteIU);
251 // if there are no categories for this feature then add it to the default
252 // category.
253 if (categories == null || categories.isEmpty())
254 categories = defaultCategorySet;
255 for (SiteCategory category : categories) {
256 Set<IInstallableUnit> iusInCategory = categoriesToIUs.get(category);
257 if (iusInCategory == null) {
258 iusInCategory = new HashSet<>();
259 categoriesToIUs.put(category, iusInCategory);
260 }
261 iusInCategory.addAll(ius);
262 }
263 }
264 }
265
266 private Map<SiteIU, Set<SiteCategory>> getIUToCategoryMappings(IPublisherInfo publisherInfo) {
267 HashMap<SiteIU, Set<SiteCategory>> mappings = new HashMap<>();
268 if (updateSite == null)
269 return mappings;
270 SiteModel site = updateSite.getSite();
271 if (site == null)
272 return mappings;
273
274 SiteIU[] ius = site.getIUs();
275 for (SiteIU iu : ius) {
276 // add a mapping for each category this feature belongs to
277 String[] categoryNames = iu.getCategoryNames();
278 Set<SiteCategory> categories = new HashSet<>();
279 mappings.put(iu, categories);
280 for (String categoryName : categoryNames) {
281 SiteCategory category = site.getCategory(categoryName);
282 if (category != null)
283 categories.add(category);
284 }
285 }
286 return mappings;
287
288 }
289
290 private Collection<IInstallableUnit> getIUs(SiteIU siteIU, IPublisherInfo publisherInfo, IPublisherResult results) {
291 String id = siteIU.getID();
292 String range = siteIU.getRange();
293 String type = siteIU.getQueryType();
294 String expression = siteIU.getQueryExpression();
295 Object[] params = siteIU.getQueryParams();
296 if (id == null && (type == null || expression == null))
297 return Collections.emptyList();
298 IQuery<IInstallableUnit> query = null;
299 if (id != null) {
300 VersionRange vRange = VersionRange.create(range);
301 query = QueryUtil.createIUQuery(id, vRange);
302 } else if (type.equals("context")) { //$NON-NLS-1$
303 query = QueryUtil.createQuery(expression, params);
304 } else if (type.equals("match")) //$NON-NLS-1$
305 query = QueryUtil.createMatchQuery(expression, params);
306 if (query == null)
307 return Collections.emptyList();
308 IQueryResult<IInstallableUnit> queryResult = results.query(query, null);
309 if (queryResult.isEmpty())
310 queryResult = publisherInfo.getMetadataRepository().query(query, null);
311 if (queryResult.isEmpty() && publisherInfo.getContextMetadataRepository() != null)
312 queryResult = publisherInfo.getContextMetadataRepository().query(query, null);
313
314 return queryResult.toUnmodifiableSet();
315 }
316
317 private static final IExpression qualifierMatchExpr = ExpressionUtil.parse("id == $0 && version ~= $1"); //$NON-NLS-1$
318
319 private Collection<IInstallableUnit> getFeatureIU(SiteFeature feature, IPublisherInfo publisherInfo,
320 IPublisherResult results) {
321 String id = feature.getFeatureIdentifier() + ".feature.group"; //$NON-NLS-1$
322 String versionString = feature.getFeatureVersion();
323 Version version = versionString != null && versionString.length() > 0 ? Version.create(versionString)
324 : Version.emptyVersion;
325 IQuery<IInstallableUnit> query = null;
326 if (version.equals(Version.emptyVersion)) {
327 query = QueryUtil.createIUQuery(id);
328 } else {
329 String qualifier;
330 try {
331 qualifier = PublisherHelper.toOSGiVersion(version).getQualifier();
332 } catch (UnsupportedOperationException e) {
333 qualifier = null;
334 }
335 if (qualifier != null && qualifier.endsWith(QUALIFIER)) {
336 VersionRange range = createVersionRange(version.toString());
337 IQuery<IInstallableUnit> qualifierQuery = QueryUtil.createMatchQuery(qualifierMatchExpr, id, range);
338 query = qualifierQuery;
339 } else {
340 query = QueryUtil.createLimitQuery(QueryUtil.createIUQuery(id, version), 1);
341 }
342 }
343
344 IQueryResult<IInstallableUnit> queryResult = results.query(query, null);
345 if (queryResult.isEmpty())
346 queryResult = publisherInfo.getMetadataRepository().query(query, null);
347 if (queryResult.isEmpty() && publisherInfo.getContextMetadataRepository() != null)
348 queryResult = publisherInfo.getContextMetadataRepository().query(query, null);
349
350 if (!queryResult.isEmpty())
351 return queryResult.toUnmodifiableSet();
352 return null;
353 }
354
355 private Collection<IInstallableUnit> getBundleIU(SiteBundle bundle, IPublisherInfo publisherInfo,
356 IPublisherResult results) {
357 String id = bundle.getBundleIdentifier();
358 String versionString = bundle.getBundleVersion();
359 Version version = versionString != null && versionString.length() > 0 ? Version.create(versionString)
360 : Version.emptyVersion;
361 IQuery<IInstallableUnit> query = null;
362 if (version.equals(Version.emptyVersion)) {
363 query = QueryUtil.createIUQuery(id);
364 } else {
365 String qualifier;
366 try {
367 qualifier = PublisherHelper.toOSGiVersion(version).getQualifier();
368 } catch (UnsupportedOperationException e) {
369 qualifier = null;
370 }
371 if (qualifier != null && qualifier.endsWith(QUALIFIER)) {
372 VersionRange range = createVersionRange(version.toString());
373 IQuery<IInstallableUnit> qualifierQuery = QueryUtil.createMatchQuery(qualifierMatchExpr, id, range);
374 query = qualifierQuery;
375 } else {
376 query = QueryUtil.createLimitQuery(QueryUtil.createIUQuery(id, version), 1);
377 }
378 }
379
380 IQueryResult<IInstallableUnit> queryResult = results.query(query, null);
381 if (queryResult.isEmpty())
382 queryResult = publisherInfo.getMetadataRepository().query(query, null);
383 if (queryResult.isEmpty() && publisherInfo.getContextMetadataRepository() != null)
384 queryResult = publisherInfo.getContextMetadataRepository().query(query, null);
385
386 if (!queryResult.isEmpty())
387 return queryResult.toUnmodifiableSet();
388 return null;
389 }
390
391 protected VersionRange createVersionRange(String versionId) {
392 VersionRange range = null;
393 if (versionId == null || "0.0.0".equals(versionId)) //$NON-NLS-1$
394 range = VersionRange.emptyRange;
395 else {
396 int qualifierIdx = versionId.indexOf(QUALIFIER);
397 if (qualifierIdx != -1) {
398 String newVersion = versionId.substring(0, qualifierIdx);
399 if (newVersion.endsWith(".")) //$NON-NLS-1$
400 newVersion = newVersion.substring(0, newVersion.length() - 1);
401
402 Version lower = Version.parseVersion(newVersion);
403 Version upper = null;
404 String newQualifier = VersionSuffixGenerator
405 .incrementQualifier(PublisherHelper.toOSGiVersion(lower).getQualifier());
406 org.osgi.framework.Version osgiVersion = PublisherHelper.toOSGiVersion(lower);
407 if (newQualifier == null)
408 upper = Version.createOSGi(osgiVersion.getMajor(), osgiVersion.getMinor(),
409 osgiVersion.getMicro() + 1);
410 else
411 upper = Version.createOSGi(osgiVersion.getMajor(), osgiVersion.getMinor(), osgiVersion.getMicro(),
412 newQualifier);
413 range = new VersionRange(lower, true, upper, false);
414 } else {
415 range = new VersionRange(Version.parseVersion(versionId), true, Version.parseVersion(versionId), true);
416 }
417 }
418 return range;
419 }
420
421 /**
422 * Computes the mapping of features to categories as defined in the site.xml, if
423 * available. Returns an empty map if there is not site.xml, or no categories.
424 *
425 * @return A map of SiteFeature -> Set<SiteCategory>.
426 */
427 protected Map<SiteFeature, Set<SiteCategory>> getFeatureToCategoryMappings(IPublisherInfo publisherInfo) {
428 HashMap<SiteFeature, Set<SiteCategory>> mappings = new HashMap<>();
429 if (updateSite == null)
430 return mappings;
431 SiteModel site = updateSite.getSite();
432 if (site == null)
433 return mappings;
434
435 SiteFeature[] features = site.getFeatures();
436 for (SiteFeature feature : features) {
437 // add a mapping for each category this feature belongs to
438 String[] categoryNames = feature.getCategoryNames();
439 Set<SiteCategory> categories = mappings.get(feature);
440 if (categories == null) {
441 categories = new HashSet<>();
442 mappings.put(feature, categories);
443 }
444 for (String categoryName : categoryNames) {
445 SiteCategory category = site.getCategory(categoryName);
446 if (category != null)
447 categories.add(category);
448 }
449 }
450 return mappings;
451 }
452
453 /**
454 * Computes the mapping of bundles to categories as defined in the site.xml, if
455 * available. Returns an empty map if there is not site.xml, or no categories.
456 *
457 * @return A map of SiteBundle -> Set<SiteCategory>.
458 */
459 protected Map<SiteBundle, Set<SiteCategory>> getBundleToCategoryMappings(IPublisherInfo publisherInfo) {
460 HashMap<SiteBundle, Set<SiteCategory>> mappings = new HashMap<>();
461 if (updateSite == null)
462 return mappings;
463 SiteModel site = updateSite.getSite();
464 if (site == null)
465 return mappings;
466
467 SiteBundle[] bundles = site.getBundles();
468 for (SiteBundle bundle : bundles) {
469 // add a mapping for each category this feature belongs to
470 String[] categoryNames = bundle.getCategoryNames();
471 Set<SiteCategory> categories = new HashSet<>();
472 mappings.put(bundle, categories);
473 for (String categoryName : categoryNames) {
474 SiteCategory category = site.getCategory(categoryName);
475 if (category != null)
476 categories.add(category);
477 }
478 }
479 return mappings;
480 }
481
482 /**
483 * Initializes new p2 repository attributes such as mirror info, associate
484 * sites, localization...
485 *
486 * @param publisherInfo configuration for output repository
487 */
488 private void initializeRepoFromSite(IPublisherInfo publisherInfo) {
489 SiteModel site = updateSite.getSite();
490 // copy mirror information from update site to p2 repositories
491 String mirrors = site.getMirrorsURI();
492 if (mirrors != null) {
493 // remove site.xml file reference
494 int index = mirrors.indexOf("site.xml"); //$NON-NLS-1$
495 if (index != -1)
496 mirrors = mirrors.substring(0, index) + mirrors.substring(index + "site.xml".length()); //$NON-NLS-1$
497 publisherInfo.getMetadataRepository().setProperty(IRepository.PROP_MIRRORS_URL, mirrors);
498 // there does not really need to be an artifact repo but if there is, setup its
499 // mirrors.
500 if (publisherInfo.getArtifactRepository() != null)
501 publisherInfo.getArtifactRepository().setProperty(IRepository.PROP_MIRRORS_URL, mirrors);
502 }
503
504 // publish associate sites as repository references
505 URLEntry[] associatedSites = site.getAssociatedSites();
506 if (associatedSites != null) {
507 ArrayList<IRepositoryReference> refs = new ArrayList<>(associatedSites.length * 2);
508 for (URLEntry associatedSite : associatedSites) {
509 String siteLocation = associatedSite.getURL();
510 try {
511 URI associateLocation = new URI(siteLocation);
512 String label = associatedSite.getAnnotation();
513 refs.add(new RepositoryReference(associateLocation, label, IRepository.TYPE_METADATA,
514 IRepository.ENABLED));
515 refs.add(new RepositoryReference(associateLocation, label, IRepository.TYPE_ARTIFACT,
516 IRepository.ENABLED));
517 } catch (URISyntaxException e) {
518 String message = "Invalid site reference: " + siteLocation; //$NON-NLS-1$
519 LogHelper.log(new Status(IStatus.ERROR, Activator.ID, message));
520 }
521 }
522 publisherInfo.getMetadataRepository().addReferences(refs);
523 }
524
525 // publish repository references from category file
526 IRepositoryReference[] refs = site.getRepositoryReferences();
527 if (refs != null) {
528 ArrayList<IRepositoryReference> toAdd = new ArrayList<>(Arrays.asList(refs));
529 publisherInfo.getMetadataRepository().addReferences(toAdd);
530 }
531
532 // publish download stats URL from category file
533 String statsURI = site.getStatsURI();
534 if (statsURI != null && statsURI.length() > 0) {
535 if (publisherInfo.getArtifactRepository() != null)
536 publisherInfo.getArtifactRepository().setProperty(P_STATS_URI, statsURI);
537 }
538
539 File siteFile = URIUtil.toFile(updateSite.getLocation());
540 if (siteFile != null && siteFile.exists()) {
541 File siteParent = siteFile.getParentFile();
542 List<String> messageKeys = site.getMessageKeys();
543 if (siteParent.isDirectory()) {
544 String[] keyStrings = messageKeys.toArray(new String[messageKeys.size()]);
545 site.setLocalizations(
546 LocalizationHelper.getDirPropertyLocalizations(siteParent, "site", null, keyStrings)); //$NON-NLS-1$
547 } else if (siteFile.getName().endsWith(".jar")) { //$NON-NLS-1$
548 String[] keyStrings = messageKeys.toArray(new String[messageKeys.size()]);
549 site.setLocalizations(
550 LocalizationHelper.getJarPropertyLocalizations(siteParent, "site", null, keyStrings)); //$NON-NLS-1$
551 }
552 }
553 }
554
555 /**
556 * Generates IUs corresponding to update site categories.
557 *
558 * @param categoriesToIUs Map of SiteCategory ->Set (Feature IUs in that
559 * category).
560 * @param result The generator result being built
561 */
562 protected void generateCategoryIUs(Map<SiteCategory, Set<IInstallableUnit>> categoriesToIUs,
563 IPublisherResult result) {
564 Map<String, SiteCategory> nameToCategory = new HashMap<>();
565 for (SiteCategory category : this.updateSite.getSite().getCategories()) {
566 nameToCategory.put(category.getName(), category);
567 }
568 final Map<SiteCategory, Set<SiteCategory>> categoryToNestedCategories = new HashMap<>();
569 for (SiteCategory category : this.updateSite.getSite().getCategories()) {
570 for (String parentCategoryName : category.getCategoryNames()) {
571 SiteCategory parentCategory = nameToCategory.get(parentCategoryName);
572 if (categoryToNestedCategories.get(parentCategory) == null) {
573 categoryToNestedCategories.put(parentCategory, new HashSet<>());
574 }
575 categoryToNestedCategories.get(parentCategory).add(category);
576 }
577 }
578
579 List<SiteCategory> categories = new ArrayList<>(Arrays.asList(this.updateSite.getSite().getCategories()));
580 categories.add(this.defaultCategory);
581 // sort category so they are processed in reverse order of dependency
582 // (Nested categories go first)
583 Comparator<SiteCategory> isNestedCategoryComparator = new Comparator<>() {
584 @Override
585 public int compare(SiteCategory category1, SiteCategory category2) {
586 Set<SiteCategory> childrenOfCategory1 = categoryToNestedCategories.get(category1);
587 Set<SiteCategory> childrenOfCategory2 = categoryToNestedCategories.get(category2);
588 if (childrenOfCategory1 != null && childrenOfCategory1.contains(category2)) {
589 // category2 nested in category1 => category2 < category1
590 return +1;
591 }
592 if (childrenOfCategory2 != null && childrenOfCategory2.contains(category1)) {
593 // category1 nested in category2 => category1 < category2
594 return -1;
595 }
596 // Then recurse in childrenCategories for transitivity
597 if (childrenOfCategory1 != null) {
598 for (SiteCategory childOfCategory1 : childrenOfCategory1) {
599 int res = this.compare(childOfCategory1, category2);
600 if (res != 0) {
601 return res;
602 }
603 }
604 }
605 if (childrenOfCategory2 != null) {
606 for (SiteCategory childOfCategory2 : childrenOfCategory2) {
607 int res = this.compare(category1, childOfCategory2);
608 if (res != 0) {
609 return res;
610 }
611 }
612 }
613 return 0;
614 }
615 };
616 categories.sort(isNestedCategoryComparator);
617
618 // Then create categories in the right order
619 Map<String, IInstallableUnit> nameToCategoryIU = new HashMap<>();
620 for (SiteCategory category : categories) {
621 Set<IInstallableUnit> units = categoriesToIUs.get(category);
622 if (units == null) {
623 units = new HashSet<>();
624 }
625 Set<SiteCategory> nestedCategories = categoryToNestedCategories.get(category);
626 if (nestedCategories != null) {
627 for (SiteCategory nestedCategory : nestedCategories) {
628 IInstallableUnit nestedCategoryIU = nameToCategoryIU.get(nestedCategory.getName());
629 if (nestedCategoryIU != null) {
630 units.add(nestedCategoryIU);
631 }
632 }
633 }
634 if (!units.isEmpty()) {
635 IInstallableUnit categoryIU = createCategoryIU(category, units);
636 result.addIU(categoryIU, IPublisherResult.NON_ROOT);
637 nameToCategoryIU.put(category.getName(), categoryIU);
638 }
639 }
640 }
641
642 /**
643 * Creates an IU corresponding to an update site category
644 *
645 * @param category The category descriptor
646 * @param childrenIUs The IUs of the children that belong to the category
647 * (can be bundle, feature or nested categories)
648 * @param nestedCategory A nested category (optional)
649 * @return an IU representing the category
650 * @deprecated use
651 * {@link IInstallableUnit}{@link #createCategoryIU(SiteCategory, Set)}
652 * instead
653 */
654 @Deprecated
655 public IInstallableUnit createCategoryIU(SiteCategory category, Set<IInstallableUnit> childrenIUs,
656 IInstallableUnit nestedCategory) {
657 Set<IInstallableUnit> allIUs = new HashSet<>();
658 if (childrenIUs != null) {
659 allIUs.addAll(childrenIUs);
660 }
661 if (nestedCategory != null) {
662 allIUs.add(nestedCategory);
663 }
664 return createCategoryIU(category, allIUs);
665 }
666
667 /**
668 * Creates an IU corresponding to an update site category
669 *
670 * @param category The category descriptor
671 * @param childrenIUs The IUs of the children that belong to the category (can
672 * be bundle, feature or nested categories)
673 * @return an IU representing the category
674 */
675 public IInstallableUnit createCategoryIU(SiteCategory category, Set<IInstallableUnit> childrenIUs) {
676 InstallableUnitDescription cat = new MetadataFactory.InstallableUnitDescription();
677 cat.setSingleton(true);
678 String categoryId = buildCategoryId(category.getName());
679 cat.setId(categoryId);
680 if (categoryVersion == null)
681 cat.setVersion(Version.createOSGi(1, 0, 0,
682 versionSuffixGenerator.generateSuffix(childrenIUs, Collections.emptyList())));
683 else {
684 if (categoryVersion.isOSGiCompatible()) {
685 org.osgi.framework.Version osgiVersion = PublisherHelper.toOSGiVersion(categoryVersion);
686 String qualifier = osgiVersion.getQualifier();
687 if (qualifier.endsWith(QUALIFIER)) {
688 String suffix = versionSuffixGenerator.generateSuffix(childrenIUs, Collections.emptyList());
689 qualifier = qualifier.substring(0, qualifier.length() - 9) + suffix;
690 categoryVersion = Version.createOSGi(osgiVersion.getMajor(), osgiVersion.getMinor(),
691 osgiVersion.getMicro(), qualifier);
692 }
693 }
694 cat.setVersion(categoryVersion);
695 }
696
697 String label = category.getLabel();
698 cat.setProperty(IInstallableUnit.PROP_NAME, label != null ? label : category.getName());
699 cat.setProperty(IInstallableUnit.PROP_DESCRIPTION, category.getDescription());
700
701 ArrayList<IRequirement> reqsConfigurationUnits = new ArrayList<>(childrenIUs.size());
702 for (IInstallableUnit iu : childrenIUs) {
703 VersionRange range = new VersionRange(iu.getVersion(), true, iu.getVersion(), true);
704 reqsConfigurationUnits.add(MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, iu.getId(),
705 range, iu.getFilter(), false, false));
706 }
707 cat.setRequirements(reqsConfigurationUnits.toArray(new IRequirement[reqsConfigurationUnits.size()]));
708
709 // Create set of provided capabilities
710 ArrayList<IProvidedCapability> providedCapabilities = new ArrayList<>();
711 providedCapabilities.add(PublisherHelper.createSelfCapability(categoryId, cat.getVersion()));
712
713 Map<Locale, Map<String, String>> localizations = category.getLocalizations();
714 if (localizations != null) {
715 for (Entry<Locale, Map<String, String>> locEntry : localizations.entrySet()) {
716 Locale locale = locEntry.getKey();
717 Map<String, String> translatedStrings = locEntry.getValue();
718 for (Entry<String, String> e : translatedStrings.entrySet()) {
719 cat.setProperty(locale.toString() + '.' + e.getKey(), e.getValue());
720 }
721 providedCapabilities.add(PublisherHelper.makeTranslationCapability(categoryId, locale));
722 }
723 }
724
725 cat.setCapabilities(providedCapabilities.toArray(new IProvidedCapability[providedCapabilities.size()]));
726
727 cat.setArtifacts(new IArtifactKey[0]);
728 cat.setProperty(InstallableUnitDescription.PROP_TYPE_CATEGORY, "true"); //$NON-NLS-1$
729 return MetadataFactory.createInstallableUnit(cat);
730 }
731
732 /**
733 * Creates a qualified category id. This action's qualifier is used if one
734 * exists or an existing update site's location is used.
735 */
736 private String buildCategoryId(String categoryName) {
737 if (categoryQualifier != null) {
738 if (categoryQualifier.length() > 0)
739 return categoryQualifier + "." + categoryName; //$NON-NLS-1$
740 return categoryName;
741 }
742 if (updateSite != null)
743 return URIUtil.toUnencodedString(updateSite.getLocation()) + "." + categoryName; //$NON-NLS-1$
744 return categoryName;
745 }
746
747 protected Transport getTransport(IPublisherInfo info) {
748 @SuppressWarnings("rawtypes")
749 IRepository repo = info.getMetadataRepository();
750 if (repo == null)
751 repo = info.getArtifactRepository();
752 if (repo == null)
753 throw new IllegalStateException("The transport service can not be found."); //$NON-NLS-1$
754 return repo.getProvisioningAgent().getService(Transport.class);
755 }
756 }