View Javadoc

1   /*
2    * ModeShape (http://www.modeshape.org)
3    * See the COPYRIGHT.txt file distributed with this work for information
4    * regarding copyright ownership.  Some portions may be licensed
5    * to Red Hat, Inc. under one or more contributor license agreements.
6    * See the AUTHORS.txt file in the distribution for a full listing of 
7    * individual contributors. 
8    *
9    * ModeShape is free software. Unless otherwise indicated, all code in ModeShape
10   * is licensed to you under the terms of the GNU Lesser General Public License as
11   * published by the Free Software Foundation; either version 2.1 of
12   * the License, or (at your option) any later version.
13   *
14   * ModeShape is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17   * Lesser General Public License for more details.
18   *
19   * You should have received a copy of the GNU Lesser General Public
20   * License along with this software; if not, write to the Free
21   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
22   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
23   */
24  
25  package org.modeshape.rhq.plugin.util;
26  
27  import java.io.File;
28  import java.net.MalformedURLException;
29  import java.net.URL;
30  import java.util.Collection;
31  import java.util.LinkedHashMap;
32  import java.util.Map;
33  import java.util.Set;
34  
35  import javax.naming.InitialContext;
36  import javax.naming.NamingException;
37  
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  import org.jboss.deployers.spi.management.KnownDeploymentTypes;
41  import org.jboss.deployers.spi.management.ManagementView;
42  import org.jboss.deployers.spi.management.deploy.DeploymentManager;
43  import org.jboss.managed.api.ComponentType;
44  import org.jboss.managed.api.ManagedCommon;
45  import org.jboss.managed.api.ManagedComponent;
46  import org.jboss.managed.api.ManagedDeployment;
47  import org.jboss.managed.api.ManagedProperty;
48  import org.jboss.metatype.api.types.MapCompositeMetaType;
49  import org.jboss.metatype.api.types.MetaType;
50  import org.jboss.metatype.api.types.SimpleMetaType;
51  import org.jboss.metatype.api.values.EnumValue;
52  import org.jboss.metatype.api.values.MetaValue;
53  import org.jboss.metatype.api.values.SimpleValue;
54  import org.jboss.profileservice.spi.ProfileService;
55  import org.rhq.core.domain.configuration.Configuration;
56  import org.rhq.core.domain.configuration.Property;
57  import org.rhq.core.domain.configuration.PropertyMap;
58  import org.rhq.core.domain.configuration.PropertySimple;
59  import org.rhq.core.domain.configuration.definition.ConfigurationDefinition;
60  import org.rhq.core.domain.configuration.definition.PropertyDefinition;
61  import org.rhq.core.domain.configuration.definition.PropertyDefinitionList;
62  import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
63  import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple;
64  import org.rhq.core.domain.configuration.definition.PropertySimpleType;
65  import org.rhq.core.domain.resource.ResourceType;
66  
67  public class ProfileServiceUtil {
68  
69  	protected final static Log LOG = LogFactory
70  			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
71  	private static ComponentType DQPTYPE = new ComponentType("teiid", "dqp");
72  	private static String DQPNAME = "org.teiid.jboss.deployers.RuntimeEngineDeployer";
73  
74  	protected static final String PLUGIN = "ProfileService";
75  
76  	/**
77  	 * @param managementView
78  	 * @param name
79  	 * @param componentType
80  	 * @return boolean
81  	 */
82  	public static boolean isManagedComponent(ManagementView managementView,
83  			String name, ComponentType componentType) {
84  		boolean isDeployed = false;
85  		if (name != null) {
86  			try {
87  				ManagedComponent component = getManagedComponent(componentType,
88  						name);
89  				if (component != null)
90  					isDeployed = true;
91  			} catch (Exception e) {
92  				// Setting it to true to be safe than sorry, since there might
93  				// be a component
94  				// already deployed in the AS.
95  				isDeployed = true;
96  			}
97  		}
98  		return isDeployed;
99  	}
100 
101 	/**
102 	 * Get the passed in {@link ManagedComponent}
103 	 * 
104 	 * @param componentType
105 	 * @param componentName
106 	 * 
107 	 * @return {@link ManagedComponent}
108 	 * @throws NamingException
109 	 * @throws Exception
110 	 */
111 	public static ManagedComponent getManagedComponent(
112 			ComponentType componentType, String componentName)
113 			throws NamingException, Exception {
114 		ProfileService ps = getProfileService();
115 		ManagementView mv = getManagementView(ps, true);
116 
117 		ManagedComponent mc = mv.getComponent(componentName, componentType);
118 
119 		return mc;
120 	}
121 
122 	/**
123 	 * Get the {@link ManagedComponent} for the {@link ComponentType} and sub
124 	 * type.
125 	 * 
126 	 * @param componentType
127 	 * 
128 	 * @return Set of {@link ManagedComponent}s
129 	 * @throws NamingException
130 	 *             , Exception
131 	 * @throws Exception
132 	 */
133 	public static Set<ManagedComponent> getManagedComponents(
134 			ComponentType componentType) throws NamingException, Exception {
135 		ProfileService ps = getProfileService();
136 		ManagementView mv = getManagementView(ps, true);
137 
138 		Set<ManagedComponent> mcSet = mv.getComponentsForType(componentType);
139 
140 		return mcSet;
141 	}
142 
143 	/**
144 	 * @param ps
145 	 * @param load
146 	 * @return {@link ManagementView}
147 	 */
148 	public static ManagementView getManagementView(ProfileService ps,
149 			boolean load) {
150 		ManagementView mv = ps.getViewManager();
151 		if (load) {
152 			mv.load();
153 		}
154 		return mv;
155 	}
156 
157 	/**
158 	 * Get the {@link DeploymentManager} from the ProfileService
159 	 * 
160 	 * @return DeploymentManager
161 	 * @throws NamingException
162 	 * @throws Exception
163 	 */
164 	public static DeploymentManager getDeploymentManager()
165 			throws NamingException, Exception {
166 		ProfileService ps = getProfileService();
167 		DeploymentManager deploymentManager = ps.getDeploymentManager();
168 
169 		return deploymentManager;
170 	}
171 
172 	/**
173 	 * @return {@link ProfileService}
174 	 * @throws NamingException
175 	 *             , Exception
176 	 */
177 	public static ProfileService getProfileService() throws NamingException {
178 		InitialContext ic = new InitialContext();
179 		ProfileService ps = (ProfileService) ic
180 				.lookup(PluginConstants.PROFILE_SERVICE);
181 		return ps;
182 	}
183 
184 	/**
185 	 * @return {@link File}
186 	 * @throws NamingException
187 	 * @throws Exception
188 	 */
189 	public static File getDeployDirectory() throws NamingException, Exception {
190 		ProfileService ps = getProfileService();
191 		ManagementView mv = getManagementView(ps, false);
192 		Set<ManagedDeployment> warDeployments;
193 		try {
194 			warDeployments = mv
195 					.getDeploymentsForType(KnownDeploymentTypes.JavaEEWebApplication
196 							.getType());
197 		} catch (Exception e) {
198 			throw new IllegalStateException(e);
199 		}
200 		ManagedDeployment standaloneWarDeployment = null;
201 		for (ManagedDeployment warDeployment : warDeployments) {
202 			if (warDeployment.getParent() == null) {
203 				standaloneWarDeployment = warDeployment;
204 				break;
205 			}
206 		}
207 		if (standaloneWarDeployment == null)
208 			// This could happen if no standalone WARs, including the admin
209 			// console WAR, have been fully deployed yet.
210 			return null;
211 		URL warUrl;
212 		try {
213 			warUrl = new URL(standaloneWarDeployment.getName());
214 		} catch (MalformedURLException e) {
215 			throw new IllegalStateException(e);
216 		}
217 		File warFile = new File(warUrl.getPath());
218 		File deployDir = warFile.getParentFile();
219 		return deployDir;
220 	}
221 
222 	public static ManagedComponent getModeShapeManagementView()
223 			throws NamingException, Exception {
224 
225 		return getManagedComponent(DQPTYPE, DQPNAME);
226 	}
227 
228 	public static String stringValue(MetaValue v1) throws Exception {
229 		if (v1 != null) {
230 			MetaType type = v1.getMetaType();
231 			if (type instanceof SimpleMetaType) {
232 				SimpleValue simple = (SimpleValue) v1;
233 				return simple.getValue().toString();
234 			}
235 			throw new Exception("Failed to convert value to string value");
236 		}
237 		return null;
238 	}
239 
240 	public static Boolean booleanValue(MetaValue v1) throws Exception {
241 		if (v1 != null) {
242 			MetaType type = v1.getMetaType();
243 			if (type instanceof SimpleMetaType) {
244 				SimpleValue simple = (SimpleValue) v1;
245 				return Boolean.valueOf(simple.getValue().toString());
246 			}
247 			throw new Exception("Failed to convert value to boolean value");
248 		}
249 		return null;
250 	}
251 
252 	public static <T> T getSimpleValue(ManagedComponent mc, String prop,
253 			Class<T> expectedType) {
254 		ManagedProperty mp = mc.getProperty(prop);
255 		if (mp != null) {
256 			MetaType metaType = mp.getMetaType();
257 			if (metaType.isSimple()) {
258 				SimpleValue simpleValue = (SimpleValue) mp.getValue();
259 				return expectedType.cast((simpleValue != null) ? simpleValue
260 						.getValue() : null);
261 			} else if (metaType.isEnum()) {
262 				EnumValue enumValue = (EnumValue) mp.getValue();
263 				return expectedType.cast((enumValue != null) ? enumValue
264 						.getValue() : null);
265 			}
266 			throw new IllegalStateException(prop + " is not a simple type");
267 		}
268 		return null;
269 	}
270 
271 	public static <T> T getSimpleValue(ManagedCommon mc, String prop,
272 			Class<T> expectedType) {
273 		ManagedProperty mp = mc.getProperty(prop);
274 		if (mp != null) {
275 			MetaType metaType = mp.getMetaType();
276 			if (metaType.isSimple()) {
277 				SimpleValue simpleValue = (SimpleValue) mp.getValue();
278 				return expectedType.cast((simpleValue != null) ? simpleValue
279 						.getValue() : null);
280 			} else if (metaType.isEnum()) {
281 				EnumValue enumValue = (EnumValue) mp.getValue();
282 				return expectedType.cast((enumValue != null) ? enumValue
283 						.getValue() : null);
284 			}
285 			throw new IllegalArgumentException(prop + " is not a simple type"); //$NON-NLS-1$
286 		}
287 		return null;
288 	}
289 
290 	public static Map<String, PropertySimple> getCustomProperties(
291 			Configuration pluginConfig) {
292 		Map<String, PropertySimple> customProperties = new LinkedHashMap<String, PropertySimple>();
293 		if (pluginConfig == null)
294 			return customProperties;
295 		PropertyMap customPropsMap = pluginConfig.getMap("custom-properties");
296 		if (customPropsMap != null) {
297 			Collection<Property> customProps = customPropsMap.getMap().values();
298 			for (Property customProp : customProps) {
299 				if (!(customProp instanceof PropertySimple)) {
300 					LOG
301 							.error("Custom property definitions in plugin configuration must be simple properties - property "
302 									+ customProp + " is not - ignoring...");
303 					continue;
304 				}
305 				customProperties.put(customProp.getName(),
306 						(PropertySimple) customProp);
307 			}
308 		}
309 		return customProperties;
310 	}
311 
312 	public static Configuration convertManagedObjectToConfiguration(
313 			Map<String, ManagedProperty> managedProperties,
314 			Map<String, PropertySimple> customProps, ResourceType resourceType) {
315 		// Configuration config = new Configuration();
316 		// ConfigurationDefinition configDef = resourceType
317 		// .getResourceConfigurationDefinition();
318 		// Map<String, PropertyDefinition> propDefs = configDef
319 		// .getPropertyDefinitions();
320 		// Set<String> propNames = managedProperties.keySet();
321 		// for (String propName : propNames) {
322 		// PropertyDefinition propertyDefinition = propDefs.get(propName);
323 		// ManagedProperty managedProperty = managedProperties.get(propName);
324 		// if (propertyDefinition == null) {
325 		// if (!managedProperty.hasViewUse(ViewUse.STATISTIC))
326 		// LOG
327 		// .debug(resourceType
328 		// + " does not define a property corresponding to ManagedProperty '"
329 		// + propName + "'.");
330 		// continue;
331 		// }
332 		// if (managedProperty == null) {
333 		// // This should never happen, but don't let it blow us up.
334 		// LOG.error("ManagedProperty '" + propName
335 		// + "' has a null value in the ManagedProperties Map.");
336 		// continue;
337 		// }
338 		// MetaValue metaValue = managedProperty.getValue();
339 		// if (managedProperty.isRemoved() || metaValue == null) {
340 		// // Don't even add a Property to the Configuration if the
341 		// // ManagedProperty is flagged as removed or has a
342 		// // null value.
343 		// continue;
344 		// }
345 		// PropertySimple customProp = customProps.get(propName);
346 		// PropertyAdapter<Property, PropertyDefinition> propertyAdapter =
347 		// PropertyAdapterFactory
348 		// .getCustomPropertyAdapter(customProp);
349 		// if (propertyAdapter == null)
350 		// propertyAdapter = PropertyAdapterFactory
351 		// .getPropertyAdapter(metaValue);
352 		// if (propertyAdapter == null) {
353 		// LOG
354 		// .error("Unable to find a PropertyAdapter for ManagedProperty '"
355 		// + propName
356 		// + "' with MetaType ["
357 		// + metaValue.getMetaType()
358 		// + "] for ResourceType '"
359 		// + resourceType.getName() + "'.");
360 		// continue;
361 		// }
362 		// Property property = propertyAdapter.convertToProperty(metaValue,
363 		// propertyDefinition);
364 		// config.put(property);
365 		// }
366 		return null;
367 	}
368 
369 	public static void convertConfigurationToManagedProperties(
370 			Map<String, ManagedProperty> managedProperties,
371 			Configuration configuration, ResourceType resourceType) {
372 		ConfigurationDefinition configDefinition = resourceType
373 				.getResourceConfigurationDefinition();
374 		for (ManagedProperty managedProperty : managedProperties.values()) {
375 			String propertyName = managedProperty.getName();
376 			PropertyDefinition propertyDefinition = configDefinition
377 					.get(propertyName);
378 			if (propertyDefinition == null) {
379 				// The managed property is not defined in the configuration
380 				continue;
381 			}
382 			populateManagedPropertyFromProperty(managedProperty,
383 					propertyDefinition, configuration);
384 		}
385 		return;
386 	}
387 
388 	public static void populateManagedPropertyFromProperty(
389 			ManagedProperty managedProperty,
390 			PropertyDefinition propertyDefinition, Configuration configuration) {
391 		// If the ManagedProperty defines a default value, assume it's more
392 		// definitive than any default value that may
393 		// have been defined in the plugin descriptor, and update the
394 		// PropertyDefinition to use that as its default
395 		// value.
396 		// MetaValue defaultValue = managedProperty.getDefaultValue();
397 		// if (defaultValue != null)
398 		// updateDefaultValueOnPropertyDefinition(propertyDefinition,
399 		// defaultValue);
400 		// MetaValue metaValue = managedProperty.getValue();
401 		// PropertyAdapter propertyAdapter = null;
402 		// if (metaValue != null) {
403 		// LOG.trace("Populating existing MetaValue of type "
404 		// + metaValue.getMetaType() + " from Teiid property "
405 		// + propertyDefinition.getName() + " with definition " +
406 		// propertyDefinition
407 		// + "...");
408 		// propertyAdapter = PropertyAdapterFactory
409 		// .getPropertyAdapter(metaValue);
410 		//			
411 		// propertyAdapter.populateMetaValueFromProperty(configuration.getSimple(propertyDefinition.getName()),
412 		// metaValue,
413 		// propertyDefinition);
414 		// managedProperty.setValue(metaValue);
415 		// } else {
416 		// MetaType metaType = managedProperty.getMetaType();
417 		// if (propertyAdapter == null)
418 		// propertyAdapter = PropertyAdapterFactory
419 		// .getPropertyAdapter(metaType);
420 		// LOG.trace("Converting property " + propertyDefinition.getName() +
421 		// " with definition "
422 		// + propertyDefinition + " to MetaValue of type " + metaType
423 		// + "...");
424 		// metaValue =
425 		// propertyAdapter.convertToMetaValue(configuration.getSimple(propertyDefinition.getName()),
426 		// propertyDefinition, metaType);
427 		// managedProperty.setValue(metaValue);
428 		// }
429 
430 	}
431 
432 	public static MetaType convertPropertyDefinitionToMetaType(
433 			PropertyDefinition propDef) {
434 		MetaType memberMetaType;
435 		if (propDef instanceof PropertyDefinitionSimple) {
436 			PropertySimpleType propSimpleType = ((PropertyDefinitionSimple) propDef)
437 					.getType();
438 			memberMetaType = convertPropertySimpleTypeToSimpleMetaType(propSimpleType);
439 		} else if (propDef instanceof PropertyDefinitionList) {
440 			// TODO (very low priority, since lists of lists are not going to be
441 			// at all common)
442 			memberMetaType = null;
443 		} else if (propDef instanceof PropertyDefinitionMap) {
444 			Map<String, PropertyDefinition> memberPropDefs = ((PropertyDefinitionMap) propDef)
445 					.getPropertyDefinitions();
446 			if (memberPropDefs.isEmpty())
447 				throw new IllegalStateException(
448 						"PropertyDefinitionMap doesn't contain any member PropertyDefinitions."); //$NON-NLS-1$
449 			// NOTE: We assume member prop defs are all of the same type, since
450 			// for MapCompositeMetaTypes, they have to be.
451 			PropertyDefinition mapMemberPropDef = memberPropDefs.values()
452 					.iterator().next();
453 			MetaType mapMemberMetaType = convertPropertyDefinitionToMetaType(mapMemberPropDef);
454 			memberMetaType = new MapCompositeMetaType(mapMemberMetaType);
455 		} else {
456 			throw new IllegalStateException(
457 					"List member PropertyDefinition has unknown type: " //$NON-NLS-1$
458 							+ propDef.getClass().getName());
459 		}
460 		return memberMetaType;
461 	}
462 
463 	private static MetaType convertPropertySimpleTypeToSimpleMetaType(
464 			PropertySimpleType memberSimpleType) {
465 		MetaType memberMetaType;
466 		Class memberClass;
467 		switch (memberSimpleType) {
468 		case BOOLEAN:
469 			memberClass = Boolean.class;
470 			break;
471 		case INTEGER:
472 			memberClass = Integer.class;
473 			break;
474 		case LONG:
475 			memberClass = Long.class;
476 			break;
477 		case FLOAT:
478 			memberClass = Float.class;
479 			break;
480 		case DOUBLE:
481 			memberClass = Double.class;
482 			break;
483 		default:
484 			memberClass = String.class;
485 			break;
486 		}
487 		memberMetaType = SimpleMetaType.resolve(memberClass.getName());
488 		return memberMetaType;
489 	}
490 
491 }