org.glassfish.config.support.GenericCrudCommand Maven / Gradle / Ivy
The newest version!
/*
* Copyright (c) 2023 Contributors to the Eclipse Foundation
* Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.config.support;
import com.sun.enterprise.config.util.ConfigApiLoggerInfo;
import com.sun.enterprise.util.LocalStringManagerImpl;
import jakarta.inject.Inject;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.glassfish.api.Param;
import org.glassfish.api.admin.AdminCommandContext;
import org.glassfish.api.admin.AdminCommandSecurity;
import org.glassfish.api.admin.CommandModelProvider;
import org.glassfish.api.logging.LogHelper;
import org.glassfish.common.util.admin.ParamTokenizer;
import org.glassfish.hk2.api.ActiveDescriptor;
import org.glassfish.hk2.api.HK2Loader;
import org.glassfish.hk2.api.MultiException;
import org.glassfish.hk2.api.PostConstruct;
import org.glassfish.hk2.api.Self;
import org.glassfish.hk2.api.ServiceLocator;
import org.jvnet.hk2.config.Attribute;
import org.jvnet.hk2.config.ConfigBeanProxy;
import org.jvnet.hk2.config.ConfigModel;
import org.jvnet.hk2.config.DomDocument;
import org.jvnet.hk2.config.GenerateServiceFromMethod;
import org.jvnet.hk2.config.InjectionManager;
import org.jvnet.hk2.config.InjectionResolver;
import org.jvnet.hk2.config.TransactionFailure;
import org.jvnet.hk2.config.tiger.Types;
/**
* services pertinent to generic CRUD command implementations
*
* @author Jerome Dochez
*
*/
public abstract class GenericCrudCommand implements CommandModelProvider, PostConstruct, AdminCommandSecurity.Preauthorization {
protected static final Logger logger = ConfigApiLoggerInfo.getLogger();
protected static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(GenericCrudCommand.class);
private InjectionResolver injector;
@Inject
@Self
private ActiveDescriptor> myself;
protected String commandName;
protected Class parentType;
protected Class targetType;
protected Method targetMethod;
// default level of noise, useful for just swithching these classes in debugging.
protected final Level level = Level.FINE;
@Inject
ServiceLocator habitat;
InjectionManager manager;
CrudResolver resolver;
InjectionResolver paramResolver;
Class extends CrudResolver> resolverType;
void prepareInjection(final AdminCommandContext ctx) {
// inject resolver with command parameters...
manager = new InjectionManager();
resolver = habitat.getService(resolverType);
paramResolver = getInjectionResolver();
manager.inject(resolver, paramResolver);
}
@Override
public boolean preAuthorization(AdminCommandContext adminCommandContext) {
prepareInjection(adminCommandContext);
return true;
}
private static String getOne(String key, Map> metadata) {
if (key == null || metadata == null) {
return null;
}
List findInMe = metadata.get(key);
if (findInMe == null) {
return null;
}
return findInMe.get(0);
}
@Override
public void postConstruct() {
commandName = myself.getName();
String parentTypeName = getOne(GenerateServiceFromMethod.PARENT_CONFIGURED, myself.getMetadata());
if (logger.isLoggable(level)) {
logger.log(level, "Generic method parent targeted type is " + parentTypeName);
}
try {
parentType = loadClass(parentTypeName);
} catch (ClassNotFoundException e) {
String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.configbean_not_found",
"The Config Bean {0} cannot be loaded by the generic command implementation : {1}", parentTypeName, e.getMessage());
LogHelper.log(logger, Level.SEVERE, ConfigApiLoggerInfo.CFG_BEAN_CL_FAILED, e, parentTypeName);
throw new RuntimeException(msg, e);
}
// find now the accessor method.
String methodName = getOne(GenerateServiceFromMethod.METHOD_NAME, myself.getMetadata());
targetMethod = null;
methodlookup: for (Method m : parentType.getMethods()) {
if (m.getName().equals(methodName)) {
// Make sure that this method is annotated with an annotation
// that is annotated with InhabitantAnnotation (such as @Create).
// This makes sure that we have found the method we are looking for
// in case there is a like-named method that is not annotated.
for (Annotation a : m.getAnnotations()) {
if (a.annotationType().getAnnotation(GenerateServiceFromMethod.class) != null) {
targetMethod = m;
break methodlookup;
}
}
}
}
if (targetMethod == null) {
String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.configbean_not_found",
"The Config Bean {0} cannot be loaded by the generic command implementation : {1}", parentTypeName, methodName);
logger.log(Level.SEVERE, ConfigApiLoggerInfo.CFG_BEAN_CL_FAILED, parentTypeName);
throw new RuntimeException(msg);
}
String targetTypeName = getOne(GenerateServiceFromMethod.METHOD_ACTUAL, myself.getMetadata());
try {
targetType = loadClass(targetTypeName);
} catch (ClassNotFoundException e) {
String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.configbean_not_found",
"The Config Bean {0} cannot be loaded by the generic command implementation : {1}", targetTypeName, e.getMessage());
LogHelper.log(logger, Level.SEVERE, ConfigApiLoggerInfo.CFG_BEAN_CL_FAILED, e, targetTypeName);
throw new RuntimeException(msg, e);
}
}
protected T getAnnotation(Method target, Class type) {
T annotation = targetMethod.getAnnotation(type);
if (annotation == null) {
String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.annotation_not_found",
"Cannot find annotation {0} with value {1} on method {2}", type.getName(), commandName, targetMethod.toString());
throw new RuntimeException(msg);
}
return annotation;
}
/**
* we need to have access to the injector instance that has all the parameters context
*
* @param injector the original command injector
*/
// todo : would be lovely to replace this with some smart injection...
public void setInjectionResolver(InjectionResolver injector) {
this.injector = injector;
}
public InjectionResolver getInjectionResolver() {
final InjectionResolver delegate = injector;
return new InjectionResolver(Param.class) {
@Override
public V getValue(Object component, AnnotatedElement annotated, Type genericType, Class type) throws MultiException {
if (type.isAssignableFrom(List.class)) {
final List values;
try {
if (annotated instanceof Method) {
values = (List) ((Method) annotated).invoke(component);
} else if (annotated instanceof Field) {
values = (List) ((Field) annotated).get(component);
} else {
String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.invalid_type",
"Invalid annotated type {0} passed to InjectionResolver:getValue()", annotated.getClass().toString());
logger.log(Level.SEVERE, ConfigApiLoggerInfo.INVALID_ANNO_TYPE, annotated.getClass().toString());
throw new MultiException(new IllegalArgumentException(msg));
}
} catch (IllegalAccessException e) {
String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.invocation_failure",
"Failure {0} while getting List> values from component", e.getMessage());
logger.log(Level.SEVERE, ConfigApiLoggerInfo.INVOKE_FAILURE);
throw new MultiException(new IllegalStateException(msg, e));
} catch (InvocationTargetException e) {
String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.invocation_failure",
"Failure {0} while getting List> values from component", e.getMessage());
logger.log(Level.SEVERE, ConfigApiLoggerInfo.INVOKE_FAILURE);
throw new MultiException(new IllegalStateException(msg, e));
}
Object value = delegate.getValue(component, annotated, genericType, type);
if (value == null) {
if (logger.isLoggable(level)) {
logger.log(level, "Value of " + annotated.toString() + " is null");
}
return null;
}
Type genericReturnType = null;
if (annotated instanceof Method) {
genericReturnType = ((Method) annotated).getGenericReturnType();
} else if (annotated instanceof Field) {
genericReturnType = ((Field) annotated).getGenericType();
}
if (genericReturnType == null) {
throw new MultiException(
new IllegalArgumentException("Cannot determine parametized type from " + annotated.toString()));
}
final Class extends ConfigBeanProxy> itemType = Types.erasure(Types.getTypeArgument(genericReturnType, 0));
if (logger.isLoggable(level)) {
logger.log(level, "Found that List> really is a List<" + itemType.toString() + ">");
}
if (itemType == null) {
String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.nongeneric_type",
"The List type returned by {0} must be a generic type", annotated.toString());
logger.log(Level.SEVERE, ConfigApiLoggerInfo.LIST_NOT_GENERIC_TYPE, annotated.toString());
throw new MultiException(new IllegalArgumentException(msg));
}
if (!ConfigBeanProxy.class.isAssignableFrom(itemType)) {
String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.wrong_type",
"The generic type {0} is not supported, only List extends ConfigBeanProxy> is", annotated.toString());
logger.log(Level.SEVERE, ConfigApiLoggerInfo.GENERIC_TYPE_NOT_SUPPORTED, annotated.toString());
throw new MultiException(new IllegalArgumentException(msg));
}
Properties props = convertStringToProperties(value.toString(), ':');
if (logger.isLoggable(level)) {
for (Map.Entry