Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 5b443c686decca44a12052078d3dbdb24a5ff8a6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
/*******************************************************************************
 * Copyright (c) 2008, 2018 Code 9 and others.
 *
 * This
 * program and the accompanying materials are made available under the terms of
 * the Eclipse Public License 2.0 which accompanies this distribution, and is
 * available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *   Code 9 - initial API and implementation
 *   IBM - ongoing development
 *   Sonatype, Inc. - transport split
 *   Red Hat Inc. - 383795 (bundle element)
 ******************************************************************************/
package org.eclipse.equinox.internal.p2.updatesite;

import java.io.File;
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.internal.p2.core.helpers.LogHelper;
import org.eclipse.equinox.internal.p2.repository.Transport;
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.expression.ExpressionUtil;
import org.eclipse.equinox.p2.metadata.expression.IExpression;
import org.eclipse.equinox.p2.publisher.*;
import org.eclipse.equinox.p2.publisher.eclipse.*;
import org.eclipse.equinox.p2.query.*;
import org.eclipse.equinox.p2.repository.IRepository;
import org.eclipse.equinox.p2.repository.IRepositoryReference;
import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor;
import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository;
import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor;
import org.eclipse.equinox.p2.repository.spi.RepositoryReference;
import org.eclipse.equinox.spi.p2.publisher.LocalizationHelper;
import org.eclipse.equinox.spi.p2.publisher.PublisherHelper;

/**
 * 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$
	static final private String P_STATS_URI = "p2.statsURI"; //$NON-NLS-1$
	static final private String P_STATS_MARKER = "download.stats"; //$NON-NLS-1$
	private static final VersionSuffixGenerator versionSuffixGenerator = new VersionSuffixGenerator();
	protected UpdateSite updateSite;
	private SiteCategory defaultCategory;
	private HashSet<SiteCategory> defaultCategorySet;
	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
	 * 
	 * @param location          The location of the update site
	 * @param categoryQualifier The qualifier to prepend to categories. This
	 *                          qualifier is used to ensure that the category IDs
	 *                          are unique between update sites. If <b>null</b> a
	 *                          default qualifier will be generated
	 */
	public SiteXMLAction(URI location, String categoryQualifier) {
		this.location = location;
		this.categoryQualifier = categoryQualifier;
	}

	/**
	 * Creates a SiteXMLAction from an Update site with an optional qualifier to use
	 * for category names
	 * 
	 * @param updateSite        The update site
	 * @param categoryQualifier The qualifier to prepend to categories. This
	 *                          qualifier is used to ensure that the category IDs
	 *                          are unique between update sites. If <b>null</b> a
	 *                          default qualifier will be generated
	 */
	public SiteXMLAction(UpdateSite updateSite, String categoryQualifier) {
		this.updateSite = updateSite;
		this.categoryQualifier = categoryQualifier;
	}

	public void setCategoryVersion(String version) {
		categoryVersion = Version.parseVersion(version);
	}

	private void initialize() {
		if (defaultCategory != null)
			return;
		defaultCategory = new SiteCategory();
		defaultCategory.setDescription("Default category for otherwise uncategorized features"); //$NON-NLS-1$
		defaultCategory.setLabel("Uncategorized"); //$NON-NLS-1$
		defaultCategory.setName("Default"); //$NON-NLS-1$
		defaultCategorySet = new HashSet<>(1);
		defaultCategorySet.add(defaultCategory);
	}

	@Override
	public IStatus perform(IPublisherInfo publisherInfo, IPublisherResult results, IProgressMonitor monitor) {
		if (updateSite == null) {
			try {
				updateSite = UpdateSite.load(location,
						publisherInfo.getMetadataRepository().getProvisioningAgent().getService(Transport.class),
						monitor);
			} catch (ProvisionException e) {
				return new Status(IStatus.ERROR, Activator.ID, Messages.Error_generating_siteXML, e);
			} catch (OperationCanceledException e) {
				return Status.CANCEL_STATUS;
			}
		}
		initialize();
		initializeRepoFromSite(publisherInfo);
		IStatus markingStats = markStatsArtifacts(publisherInfo, results, monitor);
		if (markingStats.isOK()) {
			return generateCategories(publisherInfo, results, monitor);
		}
		return markingStats;
	}

	private IStatus markStatsArtifacts(IPublisherInfo publisherInfo, IPublisherResult results,
			IProgressMonitor monitor) {
		IArtifactRepository artifactRepo = publisherInfo.getArtifactRepository();
		SiteModel site = updateSite.getSite();
		// process all features listed and mark artifacts
		SiteFeature[] features = site.getStatsFeatures();
		if (features != null && artifactRepo != null) {
			for (SiteFeature feature : features) {
				if (monitor.isCanceled())
					return Status.CANCEL_STATUS;
				Collection<IInstallableUnit> ius = getFeatureIU(feature, publisherInfo, results);
				if (ius != null) {
					for (IInstallableUnit iu : ius) {
						IArtifactKey key = FeaturesAction.createFeatureArtifactKey(feature.getFeatureIdentifier(),
								iu.getVersion().toString());
						IArtifactDescriptor[] descriptors = artifactRepo.getArtifactDescriptors(key);
						if (descriptors.length > 0 && descriptors[0] instanceof ArtifactDescriptor) {
							HashMap<String, String> map = new HashMap<>();
							map.put(P_STATS_MARKER, feature.getFeatureIdentifier());
							((ArtifactDescriptor) descriptors[0]).addProperties(map);
						}
					}
				}
			}
		}
		// process all bundles listed and mark artifacts
		SiteBundle[] bundles = site.getStatsBundles();
		if (bundles != null && artifactRepo != null) {
			for (SiteBundle bundle : bundles) {
				if (monitor.isCanceled())
					return Status.CANCEL_STATUS;
				Collection<IInstallableUnit> ius = getBundleIU(bundle, publisherInfo, results);
				if (ius != null) {
					for (IInstallableUnit iu : ius) {
						IArtifactKey key = BundlesAction.createBundleArtifactKey(iu.getId(),
								iu.getVersion().toString());
						IArtifactDescriptor[] descriptors = artifactRepo.getArtifactDescriptors(key);
						if (descriptors.length > 0 && descriptors[0] instanceof ArtifactDescriptor) {
							HashMap<String, String> map = new HashMap<>();
							map.put(P_STATS_MARKER, iu.getId());
							((ArtifactDescriptor) descriptors[0]).addProperties(map);
						}
					}
				}
			}
		}
		// If there was no artifact repository available and stats were to be tracked,
		// issue
		// a warning.
		boolean markingBundles = bundles != null && bundles.length > 0;
		boolean markingFeatures = features != null && features.length > 0;
		if (artifactRepo == null && (markingBundles || markingFeatures))
			return new Status(IStatus.WARNING, Activator.ID,
					"Artifact repository was not specified so stats properties could not be published."); //$NON-NLS-1$
		return Status.OK_STATUS;

	}

	private IStatus generateCategories(IPublisherInfo publisherInfo, IPublisherResult results,
			IProgressMonitor monitor) {
		Map<SiteCategory, Set<IInstallableUnit>> categoriesToIUs = new HashMap<>();
		Map<SiteFeature, Set<SiteCategory>> featuresToCategories = getFeatureToCategoryMappings(publisherInfo);
		for (SiteFeature feature : featuresToCategories.keySet()) {
			if (monitor.isCanceled())
				return Status.CANCEL_STATUS;
			Collection<IInstallableUnit> ius = getFeatureIU(feature, publisherInfo, results);
			if (ius == null)
				continue;
			Set<SiteCategory> categories = featuresToCategories.get(feature);
			// if there are no categories for this feature then add it to the default
			// category.
			if (categories == null || categories.isEmpty())
				categories = defaultCategorySet;
			for (SiteCategory category : categories) {
				Set<IInstallableUnit> iusInCategory = categoriesToIUs.get(category);
				if (iusInCategory == null) {
					iusInCategory = new HashSet<>();
					categoriesToIUs.put(category, iusInCategory);
				}
				iusInCategory.addAll(ius);
			}
		}
		// Bundles -- bug 378338
		Map<SiteBundle, Set<SiteCategory>> bundlesToCategories = getBundleToCategoryMappings(publisherInfo);
		for (SiteBundle bundle : bundlesToCategories.keySet()) {
			if (monitor.isCanceled())
				return Status.CANCEL_STATUS;
			Collection<IInstallableUnit> ius = getBundleIU(bundle, publisherInfo, results);
			if (ius == null)
				continue;
			Set<SiteCategory> categories = bundlesToCategories.get(bundle);
			// if there are no categories for this feature then add it to the default
			// category.
			if (categories == null || categories.isEmpty())
				categories = defaultCategorySet;
			for (SiteCategory category : categories) {
				Set<IInstallableUnit> iusInCategory = categoriesToIUs.get(category);
				if (iusInCategory == null) {
					iusInCategory = new HashSet<>();
					categoriesToIUs.put(category, iusInCategory);
				}
				iusInCategory.addAll(ius);
			}
		}

		addSiteIUsToCategories(categoriesToIUs, publisherInfo, results);
		generateCategoryIUs(categoriesToIUs, results);
		return Status.OK_STATUS;
	}

	private void addSiteIUsToCategories(Map<SiteCategory, Set<IInstallableUnit>> categoriesToIUs,
			IPublisherInfo publisherInfo, IPublisherResult results) {
		Map<SiteIU, Set<SiteCategory>> iusToCategories = getIUToCategoryMappings(publisherInfo);
		SiteModel site = updateSite.getSite();
		if (site == null)
			return;
		SiteIU[] siteIUs = site.getIUs();
		for (SiteIU siteIU : siteIUs) {
			Collection<IInstallableUnit> ius = getIUs(siteIU, publisherInfo, results);
			if (ius == null)
				continue;
			Set<SiteCategory> categories = iusToCategories.get(siteIU);
			// if there are no categories for this feature then add it to the default
			// category.
			if (categories == null || categories.isEmpty())
				categories = defaultCategorySet;
			for (SiteCategory category : categories) {
				Set<IInstallableUnit> iusInCategory = categoriesToIUs.get(category);
				if (iusInCategory == null) {
					iusInCategory = new HashSet<>();
					categoriesToIUs.put(category, iusInCategory);
				}
				iusInCategory.addAll(ius);
			}
		}
	}

	private Map<SiteIU, Set<SiteCategory>> getIUToCategoryMappings(IPublisherInfo publisherInfo) {
		HashMap<SiteIU, Set<SiteCategory>> mappings = new HashMap<>();
		if (updateSite == null)
			return mappings;
		SiteModel site = updateSite.getSite();
		if (site == null)
			return mappings;

		SiteIU[] ius = site.getIUs();
		for (SiteIU iu : ius) {
			// add a mapping for each category this feature belongs to
			String[] categoryNames = iu.getCategoryNames();
			Set<SiteCategory> categories = new HashSet<>();
			mappings.put(iu, categories);
			for (String categoryName : categoryNames) {
				SiteCategory category = site.getCategory(categoryName);
				if (category != null)
					categories.add(category);
			}
		}
		return mappings;

	}

	private Collection<IInstallableUnit> getIUs(SiteIU siteIU, IPublisherInfo publisherInfo, IPublisherResult 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 Collections.emptyList();
		IQuery<IInstallableUnit> query = null;
		if (id != null) {
			VersionRange vRange = VersionRange.create(range);
			query = QueryUtil.createIUQuery(id, vRange);
		} else if (type.equals("context")) { //$NON-NLS-1$
			query = QueryUtil.createQuery(expression, params);
		} else if (type.equals("match")) //$NON-NLS-1$
			query = QueryUtil.createMatchQuery(expression, params);
		if (query == null)
			return Collections.emptyList();
		IQueryResult<IInstallableUnit> queryResult = results.query(query, null);
		if (queryResult.isEmpty())
			queryResult = publisherInfo.getMetadataRepository().query(query, null);
		if (queryResult.isEmpty() && publisherInfo.getContextMetadataRepository() != null)
			queryResult = publisherInfo.getContextMetadataRepository().query(query, null);

		return queryResult.toUnmodifiableSet();
	}

	private static final IExpression qualifierMatchExpr = ExpressionUtil.parse("id == $0 && version ~= $1"); //$NON-NLS-1$

	private Collection<IInstallableUnit> getFeatureIU(SiteFeature feature, IPublisherInfo publisherInfo,
			IPublisherResult results) {
		String id = feature.getFeatureIdentifier() + ".feature.group"; //$NON-NLS-1$
		String versionString = feature.getFeatureVersion();
		Version version = versionString != null && versionString.length() > 0 ? Version.create(versionString)
				: Version.emptyVersion;
		IQuery<IInstallableUnit> query = null;
		if (version.equals(Version.emptyVersion)) {
			query = QueryUtil.createIUQuery(id);
		} else {
			String qualifier;
			try {
				qualifier = PublisherHelper.toOSGiVersion(version).getQualifier();
			} catch (UnsupportedOperationException e) {
				qualifier = null;
			}
			if (qualifier != null && qualifier.endsWith(QUALIFIER)) {
				VersionRange range = createVersionRange(version.toString());
				IQuery<IInstallableUnit> qualifierQuery = QueryUtil.createMatchQuery(qualifierMatchExpr, id, range);
				query = qualifierQuery;
			} else {
				query = QueryUtil.createLimitQuery(QueryUtil.createIUQuery(id, version), 1);
			}
		}

		IQueryResult<IInstallableUnit> queryResult = results.query(query, null);
		if (queryResult.isEmpty())
			queryResult = publisherInfo.getMetadataRepository().query(query, null);
		if (queryResult.isEmpty() && publisherInfo.getContextMetadataRepository() != null)
			queryResult = publisherInfo.getContextMetadataRepository().query(query, null);

		if (!queryResult.isEmpty())
			return queryResult.toUnmodifiableSet();
		return null;
	}

	private Collection<IInstallableUnit> getBundleIU(SiteBundle bundle, IPublisherInfo publisherInfo,
			IPublisherResult results) {
		String id = bundle.getBundleIdentifier();
		String versionString = bundle.getBundleVersion();
		Version version = versionString != null && versionString.length() > 0 ? Version.create(versionString)
				: Version.emptyVersion;
		IQuery<IInstallableUnit> query = null;
		if (version.equals(Version.emptyVersion)) {
			query = QueryUtil.createIUQuery(id);
		} else {
			String qualifier;
			try {
				qualifier = PublisherHelper.toOSGiVersion(version).getQualifier();
			} catch (UnsupportedOperationException e) {
				qualifier = null;
			}
			if (qualifier != null && qualifier.endsWith(QUALIFIER)) {
				VersionRange range = createVersionRange(version.toString());
				IQuery<IInstallableUnit> qualifierQuery = QueryUtil.createMatchQuery(qualifierMatchExpr, id, range);
				query = qualifierQuery;
			} else {
				query = QueryUtil.createLimitQuery(QueryUtil.createIUQuery(id, version), 1);
			}
		}

		IQueryResult<IInstallableUnit> queryResult = results.query(query, null);
		if (queryResult.isEmpty())
			queryResult = publisherInfo.getMetadataRepository().query(query, null);
		if (queryResult.isEmpty() && publisherInfo.getContextMetadataRepository() != null)
			queryResult = publisherInfo.getContextMetadataRepository().query(query, null);

		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$
			range = VersionRange.emptyRange;
		else {
			int qualifierIdx = versionId.indexOf(QUALIFIER);
			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(lower, true, upper, false);
			} 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.
	 * 
	 * @return A map of SiteFeature -> Set<SiteCategory>.
	 */
	protected Map<SiteFeature, Set<SiteCategory>> getFeatureToCategoryMappings(IPublisherInfo publisherInfo) {
		HashMap<SiteFeature, Set<SiteCategory>> mappings = new HashMap<>();
		if (updateSite == null)
			return mappings;
		SiteModel site = updateSite.getSite();
		if (site == null)
			return mappings;

		SiteFeature[] features = site.getFeatures();
		for (SiteFeature feature : features) {
			// add a mapping for each category this feature belongs to
			String[] categoryNames = feature.getCategoryNames();
			Set<SiteCategory> categories = mappings.get(feature);
			if (categories == null) {
				categories = new HashSet<>();
				mappings.put(feature, categories);
			}
			for (String categoryName : categoryNames) {
				SiteCategory category = site.getCategory(categoryName);
				if (category != null)
					categories.add(category);
			}
		}
		return mappings;
	}

	/**
	 * Computes the mapping of bundles 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 SiteBundle -> Set<SiteCategory>.
	 */
	protected Map<SiteBundle, Set<SiteCategory>> getBundleToCategoryMappings(IPublisherInfo publisherInfo) {
		HashMap<SiteBundle, Set<SiteCategory>> mappings = new HashMap<>();
		if (updateSite == null)
			return mappings;
		SiteModel site = updateSite.getSite();
		if (site == null)
			return mappings;

		SiteBundle[] bundles = site.getBundles();
		for (SiteBundle bundle : bundles) {
			// add a mapping for each category this feature belongs to
			String[] categoryNames = bundle.getCategoryNames();
			Set<SiteCategory> categories = new HashSet<>();
			mappings.put(bundle, categories);
			for (String categoryName : categoryNames) {
				SiteCategory category = site.getCategory(categoryName);
				if (category != null)
					categories.add(category);
			}
		}
		return mappings;
	}

	/**
	 * Initializes new p2 repository attributes such as mirror info, associate
	 * sites, localization...
	 * 
	 * @param publisherInfo configuration for output repository
	 */
	private void initializeRepoFromSite(IPublisherInfo publisherInfo) {
		SiteModel site = updateSite.getSite();
		// 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$
			publisherInfo.getMetadataRepository().setProperty(IRepository.PROP_MIRRORS_URL, mirrors);
			// there does not really need to be an artifact repo but if there is, setup its
			// mirrors.
			if (publisherInfo.getArtifactRepository() != null)
				publisherInfo.getArtifactRepository().setProperty(IRepository.PROP_MIRRORS_URL, mirrors);
		}

		// publish associate sites as repository references
		URLEntry[] associatedSites = site.getAssociatedSites();
		if (associatedSites != null) {
			ArrayList<IRepositoryReference> refs = new ArrayList<>(associatedSites.length * 2);
			for (URLEntry associatedSite : associatedSites) {
				String siteLocation = associatedSite.getURL();
				try {
					URI associateLocation = new URI(siteLocation);
					String label = associatedSite.getAnnotation();
					refs.add(new RepositoryReference(associateLocation, label, IRepository.TYPE_METADATA,
						IRepository.ENABLED));
					refs.add(new RepositoryReference(associateLocation, label, IRepository.TYPE_ARTIFACT,
						IRepository.ENABLED));
				} catch (URISyntaxException e) {
					String message = "Invalid site reference: " + siteLocation; //$NON-NLS-1$
					LogHelper.log(new Status(IStatus.ERROR, Activator.ID, message));
				}
			}
			publisherInfo.getMetadataRepository().addReferences(refs);
		}

		// publish repository references from category file
		IRepositoryReference[] refs = site.getRepositoryReferences();
		if (refs != null) {
			ArrayList<IRepositoryReference> toAdd = new ArrayList<>(Arrays.asList(refs));
			publisherInfo.getMetadataRepository().addReferences(toAdd);
		}

		// publish download stats URL from category file
		String statsURI = site.getStatsURI();
		if (statsURI != null && statsURI.length() > 0) {
			if (publisherInfo.getArtifactRepository() != null)
				publisherInfo.getArtifactRepository().setProperty(P_STATS_URI, statsURI);
		}

		File siteFile = URIUtil.toFile(updateSite.getLocation());
		if (siteFile != null && siteFile.exists()) {
			File siteParent = siteFile.getParentFile();
			List<String> messageKeys = site.getMessageKeys();
			if (siteParent.isDirectory()) {
				String[] keyStrings = 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 = messageKeys.toArray(new String[messageKeys.size()]);
				site.setLocalizations(
						LocalizationHelper.getJarPropertyLocalizations(siteParent, "site", null, keyStrings)); //$NON-NLS-1$
			}
		}
	}

	/**
	 * Generates IUs corresponding to update site categories.
	 * 
	 * @param categoriesToIUs Map of SiteCategory ->Set (Feature IUs in that
	 *                        category).
	 * @param result          The generator result being built
	 */
	protected void generateCategoryIUs(Map<SiteCategory, Set<IInstallableUnit>> categoriesToIUs,
			IPublisherResult result) {
		Map<String, SiteCategory> nameToCategory = new HashMap<>();
		for (SiteCategory category : this.updateSite.getSite().getCategories()) {
			nameToCategory.put(category.getName(), category);
		}
		final Map<SiteCategory, Set<SiteCategory>> categoryToNestedCategories = new HashMap<>();
		for (SiteCategory category : this.updateSite.getSite().getCategories()) {
			for (String parentCategoryName : category.getCategoryNames()) {
				SiteCategory parentCategory = nameToCategory.get(parentCategoryName);
				if (categoryToNestedCategories.get(parentCategory) == null) {
					categoryToNestedCategories.put(parentCategory, new HashSet<>());
				}
				categoryToNestedCategories.get(parentCategory).add(category);
			}
		}

		List<SiteCategory> categories = new ArrayList<>(Arrays.asList(this.updateSite.getSite().getCategories()));
		categories.add(this.defaultCategory);
		// sort category so they are processed in reverse order of dependency
		// (Nested categories go first)
		Comparator<SiteCategory> isNestedCategoryComparator = new Comparator<SiteCategory>() {
			@Override
			public int compare(SiteCategory category1, SiteCategory category2) {
				Set<SiteCategory> childrenOfCategory1 = categoryToNestedCategories.get(category1);
				Set<SiteCategory> childrenOfCategory2 = categoryToNestedCategories.get(category2);
				if (childrenOfCategory1 != null && childrenOfCategory1.contains(category2)) {
					// category2 nested in category1 => category2 < category1
					return +1;
				}
				if (childrenOfCategory2 != null && childrenOfCategory2.contains(category1)) {
					// category1 nested in category2 => category1 < category2
					return -1;
				}
				// Then recurse in childrenCategories for transitivity
				if (childrenOfCategory1 != null) {
					for (SiteCategory childOfCategory1 : childrenOfCategory1) {
						int res = this.compare(childOfCategory1, category2);
						if (res != 0) {
							return res;
						}
					}
				}
				if (childrenOfCategory2 != null) {
					for (SiteCategory childOfCategory2 : childrenOfCategory2) {
						int res = this.compare(category1, childOfCategory2);
						if (res != 0) {
							return res;
						}
					}
				}
				return 0;
			}
		};
		Collections.sort(categories, isNestedCategoryComparator);

		// Then create categories in the right order
		Map<String, IInstallableUnit> nameToCategoryIU = new HashMap<>();
		for (SiteCategory category : categories) {
			Set<IInstallableUnit> units = categoriesToIUs.get(category);
			if (units == null) {
				units = new HashSet<>();
			}
			Set<SiteCategory> nestedCategories = categoryToNestedCategories.get(category);
			if (nestedCategories != null) {
				for (SiteCategory nestedCategory : nestedCategories) {
					IInstallableUnit nestedCategoryIU = nameToCategoryIU.get(nestedCategory.getName());
					if (nestedCategoryIU != null) {
						units.add(nestedCategoryIU);
					}
				}
			}
			if (!units.isEmpty()) {
				IInstallableUnit categoryIU = createCategoryIU(category, units);
				result.addIU(categoryIU, IPublisherResult.NON_ROOT);
				nameToCategoryIU.put(category.getName(), categoryIU);
			}
		}
	}

	/**
	 * Creates an IU corresponding to an update site category
	 * 
	 * @param category       The category descriptor
	 * @param childrenIUs    The IUs of the children that belong to the category
	 *                       (can be bundle, feature or nested categories)
	 * @param nestedCategory A nested category (optional)
	 * @return an IU representing the category
	 * @deprecated use
	 *             {@link IInstallableUnit}{@link #createCategoryIU(SiteCategory, Set)}
	 *             instead
	 */
	@Deprecated
	public IInstallableUnit createCategoryIU(SiteCategory category, Set<IInstallableUnit> childrenIUs,
			IInstallableUnit nestedCategory) {
		Set<IInstallableUnit> allIUs = new HashSet<>();
		if (childrenIUs != null) {
			allIUs.addAll(childrenIUs);
		}
		if (nestedCategory != null) {
			allIUs.add(nestedCategory);
		}
		return createCategoryIU(category, allIUs);
	}

	/**
	 * Creates an IU corresponding to an update site category
	 * 
	 * @param category    The category descriptor
	 * @param childrenIUs The IUs of the children that belong to the category (can
	 *                    be bundle, feature or nested categories)
	 * @return an IU representing the category
	 */
	public IInstallableUnit createCategoryIU(SiteCategory category, Set<IInstallableUnit> childrenIUs) {
		InstallableUnitDescription cat = new MetadataFactory.InstallableUnitDescription();
		cat.setSingleton(true);
		String categoryId = buildCategoryId(category.getName());
		cat.setId(categoryId);
		if (categoryVersion == null)
			cat.setVersion(Version.createOSGi(1, 0, 0,
					versionSuffixGenerator.generateSuffix(childrenIUs, Collections.emptyList())));
		else {
			if (categoryVersion.isOSGiCompatible()) {
				org.osgi.framework.Version osgiVersion = PublisherHelper.toOSGiVersion(categoryVersion);
				String qualifier = osgiVersion.getQualifier();
				if (qualifier.endsWith(QUALIFIER)) {
					String suffix = versionSuffixGenerator.generateSuffix(childrenIUs, Collections.emptyList());
					qualifier = qualifier.substring(0, qualifier.length() - 9) + suffix;
					categoryVersion = Version.createOSGi(osgiVersion.getMajor(), osgiVersion.getMinor(),
							osgiVersion.getMicro(), qualifier);
				}
			}
			cat.setVersion(categoryVersion);
		}

		String label = category.getLabel();
		cat.setProperty(IInstallableUnit.PROP_NAME, label != null ? label : category.getName());
		cat.setProperty(IInstallableUnit.PROP_DESCRIPTION, category.getDescription());

		ArrayList<IRequirement> reqsConfigurationUnits = new ArrayList<>(childrenIUs.size());
		for (IInstallableUnit iu : childrenIUs) {
			VersionRange range = new VersionRange(iu.getVersion(), true, iu.getVersion(), true);
			reqsConfigurationUnits.add(MetadataFactory.createRequirement(IInstallableUnit.NAMESPACE_IU_ID, iu.getId(),
					range, iu.getFilter(), false, false));
		}
		cat.setRequirements(reqsConfigurationUnits.toArray(new IRequirement[reqsConfigurationUnits.size()]));

		// Create set of provided capabilities
		ArrayList<IProvidedCapability> providedCapabilities = new ArrayList<>();
		providedCapabilities.add(PublisherHelper.createSelfCapability(categoryId, cat.getVersion()));

		Map<Locale, Map<String, String>> localizations = category.getLocalizations();
		if (localizations != null) {
			for (Entry<Locale, Map<String, String>> locEntry : localizations.entrySet()) {
				Locale locale = locEntry.getKey();
				Map<String, String> translatedStrings = locEntry.getValue();
				for (Entry<String, String> e : translatedStrings.entrySet()) {
					cat.setProperty(locale.toString() + '.' + e.getKey(), e.getValue());
				}
				providedCapabilities.add(PublisherHelper.makeTranslationCapability(categoryId, locale));
			}
		}

		cat.setCapabilities(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);
	}

	/**
	 * 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 (categoryQualifier != null) {
			if (categoryQualifier.length() > 0)
				return categoryQualifier + "." + categoryName; //$NON-NLS-1$
			return categoryName;
		}
		if (updateSite != null)
			return URIUtil.toUnencodedString(updateSite.getLocation()) + "." + categoryName; //$NON-NLS-1$
		return categoryName;
	}

	protected Transport getTransport(IPublisherInfo info) {
		@SuppressWarnings("rawtypes")
		IRepository repo = info.getMetadataRepository();
		if (repo == null)
			repo = info.getArtifactRepository();
		if (repo == null)
			throw new IllegalStateException("The transport service can not be found."); //$NON-NLS-1$
		return repo.getProvisioningAgent().getService(Transport.class);
	}
}

Back to the top