Search in sources :

Example 21 with Param

use of org.glassfish.api.Param in project Payara by payara.

the class CommandSupport method getParamValue.

/**
 * Get parameter value for a command.
 *
 * @param command
 * @param name parameter name
 * @param paramType expected return type
 *
 * @return parameter value or null in case of any problem.
 */
public static <T> T getParamValue(AdminCommand command, String name, Class<T> paramType) {
    AdminCommand unwrappedCommand = getUnwrappedCommand(command);
    Class<?> commandClass = unwrappedCommand.getClass();
    for (final Field field : commandClass.getDeclaredFields()) {
        Param param = field.getAnnotation(Param.class);
        if (param != null && name.equals(CommandModel.getParamName(param, field))) {
            if (!paramType.isAssignableFrom(field.getType())) {
                // return null
                break;
            }
            try {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {

                    @Override
                    public Object run() {
                        field.setAccessible(true);
                        return null;
                    }
                });
                Object value = field.get(unwrappedCommand);
                return paramType.cast(value);
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Unexpected error", e);
            }
        }
    }
    return null;
}
Also used : Field(java.lang.reflect.Field) Param(org.glassfish.api.Param)

Example 22 with Param

use of org.glassfish.api.Param in project Payara by payara.

the class ClientGenerator method generateParameterName.

protected String generateParameterName(ParamModel model) {
    Param param = model.getParam();
    final String paramName = (!param.alias().isEmpty()) ? param.alias() : model.getName();
    return paramName;
}
Also used : Param(org.glassfish.api.Param)

Example 23 with Param

use of org.glassfish.api.Param in project Payara by payara.

the class JavaClientClassWriter method generateMethodBody.

@Override
public String generateMethodBody(CommandModel cm, String httpMethod, String resourcePath, boolean includeOptional, boolean needsMultiPart) {
    StringBuilder sb = new StringBuilder();
    Collection<ParamModel> params = cm.getParameters();
    if ((params != null) && (!params.isEmpty())) {
        for (ParamModel model : params) {
            Param param = model.getParam();
            boolean include = true;
            if (param.optional() && !includeOptional) {
                continue;
            }
            String key = (!param.alias().isEmpty()) ? param.alias() : model.getName();
            String paramName = Util.eleminateHypen(model.getName());
            String put = "        payload.put(\"" + key + "\", _" + paramName + ");\n";
            sb.append(put);
        }
    }
    return TMPL_METHOD_BODY.replace("PUTS", sb.toString()).replace("HTTPMETHOD", httpMethod.toUpperCase(Locale.US)).replace("RESOURCEPATH", resourcePath).replace("NEEDSMULTIPART", Boolean.toString(needsMultiPart));
}
Also used : Param(org.glassfish.api.Param) ParamModel(org.glassfish.api.admin.CommandModel.ParamModel)

Example 24 with Param

use of org.glassfish.api.Param in project Payara by payara.

the class GenericCrudCommand method getInjectionResolver.

public InjectionResolver<Param> getInjectionResolver() {
    final InjectionResolver<Param> delegate = injector;
    return new InjectionResolver<Param>(Param.class) {

        @Override
        public <V> V getValue(Object component, AnnotatedElement annotated, Type genericType, Class<V> type) throws MultiException {
            if (type.isAssignableFrom(List.class)) {
                final List<ConfigBeanProxy> values;
                try {
                    if (annotated instanceof Method) {
                        values = (List<ConfigBeanProxy>) ((Method) annotated).invoke(component);
                    } else if (annotated instanceof Field) {
                        values = (List<ConfigBeanProxy>) ((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<Object, Object> entry : props.entrySet()) {
                        logger.log(level, "Subtype " + itemType + " key:" + entry.getKey() + " value:" + entry.getValue());
                    }
                }
                final BeanInfo beanInfo;
                try {
                    beanInfo = Introspector.getBeanInfo(itemType);
                } catch (IntrospectionException e) {
                    String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.introspection_failure", "Failure {0} while instrospecting {1} to find all getters and setters", e.getMessage(), itemType.getName());
                    LogHelper.log(logger, Level.SEVERE, ConfigApiLoggerInfo.INTROSPECTION_FAILED, e, itemType.getName());
                    throw new MultiException(new IllegalStateException(msg, e));
                }
                for (final Map.Entry<Object, Object> entry : props.entrySet()) {
                    ConfigBeanProxy child = (ConfigBeanProxy) component;
                    try {
                        ConfigBeanProxy cc = child.createChild(itemType);
                        new InjectionManager().inject(cc, itemType, new InjectionResolver<Attribute>(Attribute.class) {

                            @Override
                            public boolean isOptional(AnnotatedElement annotated, Attribute annotation) {
                                return true;
                            }

                            @Override
                            public Method getSetterMethod(Method annotated, Attribute annotation) {
                                // variant.
                                for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
                                    if (pd.getReadMethod().equals(annotated)) {
                                        return pd.getWriteMethod();
                                    }
                                }
                                return annotated;
                            }

                            @Override
                            public <V> V getValue(Object component, AnnotatedElement annotated, Type genericType, Class<V> type) throws MultiException {
                                String name = annotated.getAnnotation(Attribute.class).value();
                                if ((name == null || name.length() == 0) && annotated instanceof Method) {
                                    // maybe there is a better way to do this...
                                    name = ((Method) annotated).getName().substring(3);
                                    if (name.equalsIgnoreCase("name") || name.equalsIgnoreCase("key")) {
                                        return type.cast(entry.getKey());
                                    }
                                    if (name.equalsIgnoreCase("value")) {
                                        return type.cast(entry.getValue());
                                    }
                                }
                                return null;
                            }
                        });
                        values.add(cc);
                    } catch (TransactionFailure transactionFailure) {
                        String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.transactionException", "Transaction exception {0} while injecting {1}", transactionFailure.getMessage(), itemType);
                        LogHelper.log(logger, Level.SEVERE, ConfigApiLoggerInfo.TX_FAILED, transactionFailure, itemType);
                        throw new MultiException(new IllegalStateException(msg, transactionFailure));
                    }
                }
                return null;
            }
            return delegate.getValue(component, annotated, genericType, type);
        }

        @Override
        public boolean isOptional(AnnotatedElement annotated, Param annotation) {
            return annotation.optional();
        }
    };
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Attribute(org.jvnet.hk2.config.Attribute) BeanInfo(java.beans.BeanInfo) AnnotatedElement(java.lang.reflect.AnnotatedElement) IntrospectionException(java.beans.IntrospectionException) Properties(java.util.Properties) Field(java.lang.reflect.Field) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) List(java.util.List) PropertyDescriptor(java.beans.PropertyDescriptor) GenerateServiceFromMethod(org.jvnet.hk2.config.GenerateServiceFromMethod) Method(java.lang.reflect.Method) InjectionResolver(org.jvnet.hk2.config.InjectionResolver) InvocationTargetException(java.lang.reflect.InvocationTargetException) Type(java.lang.reflect.Type) Param(org.glassfish.api.Param) MultiException(org.glassfish.hk2.api.MultiException) Map(java.util.Map) InjectionManager(org.jvnet.hk2.config.InjectionManager)

Aggregations

Param (org.glassfish.api.Param)24 CommandModel (org.glassfish.api.admin.CommandModel)5 MultiException (org.glassfish.hk2.api.MultiException)4 Field (java.lang.reflect.Field)3 Method (java.lang.reflect.Method)3 Properties (java.util.Properties)3 UnacceptableValueException (org.glassfish.common.util.admin.UnacceptableValueException)3 Attribute (org.jvnet.hk2.config.Attribute)3 UnsatisfiedDependencyException (org.jvnet.hk2.config.UnsatisfiedDependencyException)3 File (java.io.File)2 AnnotatedElement (java.lang.reflect.AnnotatedElement)2 ParameterMetaData (org.glassfish.admin.rest.provider.ParameterMetaData)2 ActionReport (org.glassfish.api.ActionReport)2 CachedCommandModel (com.sun.enterprise.admin.util.CachedCommandModel)1 ParamModelData (com.sun.enterprise.admin.util.CommandModelData.ParamModelData)1 Cluster (com.sun.enterprise.config.serverbeans.Cluster)1 BeanInfo (java.beans.BeanInfo)1 IntrospectionException (java.beans.IntrospectionException)1 PropertyDescriptor (java.beans.PropertyDescriptor)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1