1 11 package org.eclipse.ui.internal.components.framework; 12 13 14 import org.eclipse.core.runtime.IAdaptable; 15 import org.eclipse.osgi.util.NLS; 16 import org.eclipse.ui.internal.WorkbenchPlugin; 17 import org.eclipse.ui.internal.components.Assert; 18 import org.eclipse.ui.internal.components.ComponentMessages; 19 import org.eclipse.ui.internal.components.util.ServiceMap; 20 21 32 public final class Components { 33 34 private Components() { 35 } 36 37 40 public static final IServiceProvider EMPTY_PROVIDER = new ServiceMap(); 41 42 60 public static Object getAdapter(Object sourceObject, Class adapter) { 61 if (adapter.isInstance(sourceObject)) { 62 return sourceObject; 63 } 64 65 if (sourceObject instanceof IAdaptable) { 66 IAdaptable adaptable = (IAdaptable)sourceObject; 67 68 Object result = adaptable.getAdapter(adapter); 69 if (result != null) { 70 Assert.isTrue(adapter.isInstance(result)); 72 return result; 73 } 74 } 75 76 if (sourceObject instanceof IServiceProvider) { 77 try { 78 return ((IServiceProvider)sourceObject).getService(adapter); 79 } catch (ComponentException e) { 80 WorkbenchPlugin.log(e); 81 } 82 } 83 84 return null; 85 } 86 87 96 public static Object queryInterface(IAdaptable toQuery, Class interf) throws ComponentException { 97 Object result = toQuery.getAdapter(interf); 98 99 if (result == null) { 100 throw new ComponentException(NLS.bind(ComponentMessages.Components_missing_required, 101 interf.toString()), null); 102 } 103 104 if (!interf.isInstance(result)) { 105 throw new ComponentException(interf, 106 NLS.bind(ComponentMessages.Components_wrong_type,interf.getName(), result.getClass().getName()), 107 null); 108 } 109 110 return result; 111 } 112 113 132 public static Object queryInterface(IServiceProvider toQuery, Object key) throws ComponentException { 133 Object result = toQuery.getService(key); 134 135 if (key == IServiceProvider.class) { 136 return toQuery; 137 } 138 139 if (result == null) { 140 throw new ComponentException(key, NLS.bind(ComponentMessages.Components_missing_required, 141 key.toString()), null); 142 } 143 144 if (key instanceof Class ) { 145 Class c = (Class )key; 146 if (!c.isInstance(result)) { 147 throw new ComponentException(key, 148 NLS.bind(ComponentMessages.Components_wrong_type, 149 c.getName(), result.getClass().getName()), 150 null); 151 } 152 } 153 154 return result; 155 } 156 157 190 public static Object [] queryInterfaces(IServiceProvider toQuery, Object [] requiredKeys) throws ComponentException { 191 Object [] result = new Object [requiredKeys.length]; 192 193 for (int i = 0; i < result.length; i++) { 194 result[i] = queryInterface(toQuery, requiredKeys[i]); 195 } 196 197 return result; 198 } 199 200 } 201 | Popular Tags |