org.jvnet.hk2.config.ConfigModel Maven / Gradle / Ivy
Show all versions of payara-micro Show documentation
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2007-2017 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://oss.oracle.com/licenses/CDDL+GPL-1.1
* or LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.jvnet.hk2.config;
import org.glassfish.hk2.api.ActiveDescriptor;
import org.glassfish.hk2.api.HK2Loader;
import org.glassfish.hk2.api.MultiException;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.utilities.HK2LoaderImpl;
import org.glassfish.hk2.utilities.ServiceLocatorUtilities;
import org.jvnet.tiger_types.Types;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* Describes the configuration model for a particular class (called "target type" in this class.)
*
* TODO: we need to remember if element values are single-valued or multi-valued.
*
* @author Kohsuke Kawaguchi
*/
public final class ConfigModel {
/**
* Reference to the {@link ConfigInjector} used to inject values to
* objects of this model.
*/
public final ActiveDescriptor extends ConfigInjector> injector;
/**
* Legal attribute names.
*/
final Map attributes = new HashMap();
/**
* Legal child element names and how they should be handled
*/
final Map elements = new HashMap();
final Map duckMethods = new HashMap();
/**
* Cache to map methods to properties
*/
final Map methodCache = new HashMap();
/**
* Contracts under which the inhabitant should be registered.
*/
final List contracts;
/**
* Type names for which this type creates a symbol space.
*/
final Set symbolSpaces;
/**
* The element name of this model itself, if this element can appear globally.
* Otherwise null.
*
* Note that in many circumstances the tag name is determined by the parent element,
* even if a {@link ConfigModel} has a tag name.
*/
final String tagName;
/**
* getter for tagName
* @return the element name of this model itself, if this element can appear globally
* Otherwise null
*/
public String getTagName() {
return tagName;
}
/**
* Deferred reference to the class loader that loaded the injector.
* This classloader can also load the configurable object.
*/
public final HK2Loader classLoaderHolder;
/**
* Fully-qualified name of the target type that this injector works on.
*/
public final String targetTypeName;
private Class targetTypeClass;
/**
* Fully-qualified name under which this type is indexed.
* This is the class name where the key property is defined.
*
*
* Null if this type is not keyed.
*/
public final String keyedAs;
/**
* If this model has any property that works as a key.
*
* @see ConfigMetadata#KEY
*/
public final String key;
private final ServiceLocator locator;
/**
* Returns the set of possible attributes names on this configuration model.
*
* @return the set of all possible attributes names on this model
*/
public Set getAttributeNames() {
return Collections.unmodifiableSet( attributes.keySet() );
}
/**
* Return the proxy type for this model
* @param the proxy type
* @return the class object for this proxy type
*/
public Class getProxyType() {
if (targetTypeClass == null) {
targetTypeClass = (Class) classLoaderHolder.loadClass(targetTypeName);
}
return targetTypeClass;
}
/**
* Returns the list of all the leaf attribute names on this model
*
* @return the list of all leaf attribute names.
*/
public Set getLeafElementNames() {
final Set results = new HashSet();
for (Map.Entry prop : elements.entrySet()) {
if (prop.getValue().isLeaf()) {
results.add(prop.getKey());
}
}
return Collections.unmodifiableSet(results);
}
/**
* Returns the list of all posible elements names on this model
*
* @return the list of all posible elements names.
*/
public Set getElementNames() {
return Collections.unmodifiableSet(elements.keySet());
}
/**
* Returns the Property model for an element associated with this model
* or null of the element name is not known,
* @param elementName element name identifying the property
* @return the Property instance describing the element
*/
public Property getElement(String elementName) {
return elements.get(elementName);
}
public Property getElementFromXMlName( final String xmlName ) {
final ConfigModel.Property cmp = findIgnoreCase(xmlName);
if (cmp == null) {
throw new IllegalArgumentException( "Illegal name: " + xmlName );
}
return cmp;
}
/**
* Performs injection to the given object.
*/
/*package*/ void inject(Dom dom, Object target) {
try {
ServiceLocatorUtilities.getService(locator, injector).inject(dom,target);
} catch (ConfigurationException e) {
e.setLocation(dom.getLocation());
throw e;
}
}
public Map> getMetadata() {
return injector.getMetadata();
}
/**
* Obtains the duck method implementation from a method on the {@link ConfigBeanProxy}-derived interface.
*/
public Method getDuckMethod(Method method) throws ClassNotFoundException, NoSuchMethodException {
synchronized (duckMethods) {
Method duckMethod = duckMethods.get(method);
if(duckMethod!=null) return duckMethod;
final Class> clz = method.getDeclaringClass();
ClassLoader cl = System.getSecurityManager()==null?clz.getClassLoader():
AccessController.doPrivileged(new PrivilegedAction() {
@Override
public ClassLoader run() {
return clz.getClassLoader();
}
});
Class> duck = cl.loadClass(clz.getName() + "$Duck");
Class>[] types = method.getParameterTypes();
Class[] paramTypes = new Class[types.length+1];
System.arraycopy(types,0,paramTypes,1,types.length);
paramTypes[0] = clz;
duckMethod = duck.getMethod(method.getName(), paramTypes);
duckMethods.put(method,duckMethod);
return duckMethod;
}
}
/**
* Obtain XML names (like "abc-def") from strings like "getAbcDef" and "hasAbcDef".
*
* The conversion rule uses the model to find a good match.
*/
public ConfigModel.Property toProperty(Method method) {
Property prop = methodCache.get(method);
if (prop != null) {
return prop;
}
String name = method.getName();
// check annotations first
Element e = method.getAnnotation(Element.class);
if(e!=null) {
String en = e.value();
if(en.length()>0) {
prop = elements.get(en);
methodCache.put(method, prop);
return prop;
}
}
Attribute a = method.getAnnotation(Attribute.class);
if(a!=null) {
String an = a.value();
if(an.length()>0) {
prop = attributes.get(an);
methodCache.put(method, prop);
return prop;
}
}
// TODO: check annotations on the getter/setter
// first, trim off the prefix
for (String p : Dom.PROPERTY_PREFIX) {
if(name.startsWith(p)) {
name = name.substring(p.length());
break;
}
}
name = camelCaseToXML(name);
// at this point name should match XML names in the model, modulo case.
prop = findIgnoreCase(name);
methodCache.put(method, prop);
return prop;
}
public static String trimPrefix(String name) {
// first, trim off the prefix
for (String p : Dom.PROPERTY_PREFIX) {
if(name.startsWith(p)) {
name = name.substring(p.length());
break;
}
}
// lowecase first letter.
return name.toLowerCase(Locale.ENGLISH).charAt(0) + name.substring(1);
}
public static String camelCaseToXML(String camelCase) {
// tokenize by finding 'x|X' and 'X|Xx' then insert '-'.
StringBuilder buf = new StringBuilder(camelCase.length()+5);
for(String t : Dom.TOKENIZER.split(camelCase)) {
if(buf.length()>0) buf.append('-');
buf.append(t.toLowerCase(Locale.ENGLISH));
}
return buf.toString();
}
public abstract static class Property {
public final List annotations = new ArrayList();
/**
* @see #xmlName()
*/
public final String xmlName;
protected Property(String xmlName) {
this.xmlName = xmlName;
}
/**
* XML name of the property, like "abc-def".
*/
public final String xmlName() {
return xmlName;
}
public abstract boolean isLeaf();
/**
* Is multiple values allowed?
*/
public abstract boolean isCollection();
/**
* Gets the value from {@link Dom} in the specified type.
*
* @param dom
* The DOM instance to get the value from.
* @param returnType
* The expected type of the returned object.
* Valid types are (1) primitive and 'leaf' Java types, such as {@link String},
* (2) {@link ConfigBeanProxy}, (3) {@link Dom}, and (4) collections of any of above.
*/
public abstract Object get(Dom dom, Type returnType);
/**
* Sets the value to {@link Dom}.
*
* @param arg
* The new value. See the return type of the get method for the discussion of
* possible types.
*/
public abstract void set(Dom dom, Object arg);
public List getAnnotations() {
return annotations;
}
}
public static abstract class Node extends Property {
final ConfigModel model;
public Node(ConfigModel model, String xmlName) {
super(xmlName);
this.model = model;
}
public boolean isLeaf() {
return false;
}
/**
* Returns the config model for this Node
*
* @return
*/
public ConfigModel getModel() {
return model;
}
/**
* Coerce the given type to {@link Dom}.
* Only handles those types that are valid to the {@link #set(Dom, Object)} method.
*/
protected final Dom toDom(Object arg) {
if(arg==null)
return null;
if(arg instanceof Dom)
return (Dom)arg;
if(arg instanceof ConfigBeanProxy)
return Dom.unwrap((ConfigBeanProxy)arg);
throw new IllegalArgumentException("Unexpected type "+arg.getClass()+" for "+xmlName);
}
}
static final class CollectionNode extends Node {
CollectionNode(ConfigModel model, String xmlName) {
super(model, xmlName);
}
public boolean isCollection() {
return true;
}
public Object get(final Dom dom, Type returnType) {
// TODO: perhaps support more collection types?
if(!(returnType instanceof ParameterizedType))
throw new IllegalArgumentException("List needs to be parameterized");
final Class itemType = Types.erasure(Types.getTypeArgument(returnType,0));
final List v = ("*".equals(xmlName)?dom.domNodeByTypeElements(itemType):dom.nodeElements(xmlName));
if(itemType==Dom.class)
// TODO: this returns a view, not a live list
return v;
if(ConfigBeanProxy.class.isAssignableFrom(itemType)) {
// return a live list
return new AbstractList