org.glassfish.config.support.GenericCrudCommand Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of payara-micro Show documentation
Show all versions of payara-micro Show documentation
Micro Distribution of the Payara Project
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2010-2013 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://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/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 packager/legal/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.
*/
// Portions Copyright [2018-2021] Payara Foundation and/or affiliates
package org.glassfish.config.support;
import com.sun.enterprise.config.util.ConfigApiLoggerInfo;
import com.sun.enterprise.util.LocalStringManagerImpl;
import org.glassfish.api.Param;
import org.glassfish.api.admin.AdminCommandContext;
import org.glassfish.api.admin.CommandModelProvider;
import org.glassfish.common.util.admin.ParamTokenizer;
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.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.tiger_types.Types;
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 jakarta.inject.Inject;
import org.glassfish.api.admin.AdminCommandSecurity;
import org.glassfish.api.logging.LogHelper;
/**
* services pertinent to generic CRUD command implementations
*
* @author Jerome Dochez
*
*/
public abstract class GenericCrudCommand implements CommandModelProvider, PostConstruct, AdminCommandSecurity.Preauthorization {
private InjectionResolver injector;
@Inject @Self
private ActiveDescriptor> myself;
protected static final Logger LOGGER = ConfigApiLoggerInfo.getLogger();
protected static final LocalStringManagerImpl LOCAL_STRINGS = new LocalStringManagerImpl(GenericCrudCommand.class);
protected String commandName;
protected Class parentType=null;
protected Class targetType=null;
protected Method targetMethod;
// default level of noise, useful for just swithching these classes in debugging.
protected static 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());
LOGGER.log(level, "Generic method parent targeted type is {0}", parentTypeName);
try {
parentType = loadClass(parentTypeName);
} catch(ClassNotFoundException e) {
String msg = LOCAL_STRINGS.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;
targetMethod = getMethodFromAnnotation(methodName);
if (targetMethod==null) {
String msg = LOCAL_STRINGS.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 = LOCAL_STRINGS.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 = LOCAL_STRINGS.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 = LOCAL_STRINGS.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 | InvocationTargetException e) {
String msg = LOCAL_STRINGS.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) {
LOGGER.log(level, "Value of {0} is null", annotated);
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));
}
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<{0}>", itemType);
}
if (itemType==null) {
String msg = LOCAL_STRINGS.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 = LOCAL_STRINGS.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