1 /*******************************************************************************
2  * Copyright (c) 2004, 2019 IBM Corporation and others.
3  *
4  * This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License 2.0
6  * which accompanies this distribution, and is available at
7  * https://www.eclipse.org/legal/epl-2.0/
8  *
9  * SPDX-License-Identifier: EPL-2.0
10  *
11  * Contributors:
12  *     IBM Corporation - initial API and implementation
13  *******************************************************************************/
14 package org.eclipse.ui.tests.dynamicplugins;
15 
16 import static java.util.Arrays.asList;
17 
18 import java.util.List;
19 
20 import org.osgi.framework.Bundle;
21 import org.osgi.framework.BundleContext;
22 import org.osgi.framework.BundleException;
23 import org.osgi.framework.Constants;
24 import org.osgi.framework.FrameworkEvent;
25 import org.osgi.framework.FrameworkListener;
26 import org.osgi.framework.wiring.FrameworkWiring;
27 
28 public class TestInstallUtil {
29 	static BundleContext context;
30 
setContext(BundleContext newContext)31 	public static void setContext(BundleContext newContext) {
32 		context = newContext;
33 	}
34 
installBundle(String pluginLocation)35 	public static Bundle installBundle(String pluginLocation)
36 			throws BundleException, IllegalStateException {
37 		Bundle target = context.installBundle(pluginLocation);
38 		int state = target.getState();
39 		if (state != Bundle.INSTALLED) {
40 			throw new IllegalStateException("Bundle " + target
41 					+ " is in a wrong state: " + state);
42 		}
43 		refreshPackages(asList(target));
44 		return target;
45 	}
46 
uninstallBundle(Bundle target)47 	public static void uninstallBundle(Bundle target) throws BundleException {
48 		target.uninstall();
49 		refreshPackages(null);
50 	}
51 
refreshPackages(List<Bundle> bundles)52 	public static void refreshPackages(List<Bundle> bundles) {
53 		FrameworkWiring wiring = context.getBundle(Constants.SYSTEM_BUNDLE_LOCATION).adapt(FrameworkWiring.class);
54 
55 		final boolean[] flag = new boolean[] { false };
56 		FrameworkListener listener = event -> {
57 			if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) {
58 				synchronized (flag) {
59 					flag[0] = true;
60 					flag.notifyAll();
61 				}
62 			}
63 		};
64 
65 		wiring.refreshBundles(bundles, listener);
66 
67 		synchronized (flag) {
68 			while (!flag[0]) {
69 				try {
70 					flag.wait();
71 				} catch (InterruptedException e) {
72 				}
73 			}
74 		}
75 	}
76 }
77