Search in sources :

Example 1 with InjectionTarget

use of org.jvnet.hk2.config.InjectionTarget in project Payara by payara.

the class WebServiceReferenceManagerImpl method resolveWSReference.

public Object resolveWSReference(ServiceReferenceDescriptor desc, Context context) throws NamingException {
    // Taken from NamingManagerImpl.getClientServiceObject
    Class serviceInterfaceClass = null;
    Object returnObj = null;
    WsUtil wsUtil = new WsUtil();
    // Implementation for new lookup element in WebserviceRef
    InitialContext iContext = new InitialContext();
    if (desc.hasLookupName()) {
        return iContext.lookup(desc.getLookupName());
    }
    try {
        WSContainerResolver.set(desc);
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        serviceInterfaceClass = cl.loadClass(desc.getServiceInterface());
        resolvePortComponentLinks(desc);
        javax.xml.rpc.Service serviceDelegate = null;
        javax.xml.ws.Service jaxwsDelegate = null;
        Object injValue = null;
        if (desc.hasGeneratedServiceInterface() || desc.hasWsdlFile()) {
            String serviceImplName = desc.getServiceImplClassName();
            if (serviceImplName != null) {
                Class serviceImplClass = cl.loadClass(serviceImplName);
                serviceDelegate = (javax.xml.rpc.Service) serviceImplClass.newInstance();
            } else {
                // as the interface through DD
                if (javax.xml.ws.Service.class.isAssignableFrom(serviceInterfaceClass) && !javax.xml.ws.Service.class.equals(serviceInterfaceClass)) {
                    // OK - the interface class is indeed the generated service class; get an instance
                    injValue = initiateInstance(serviceInterfaceClass, desc);
                } else {
                    // interface, therefore I take the first one.
                    if (desc.isInjectable()) {
                        InjectionTarget target = desc.getInjectionTargets().iterator().next();
                        Class serviceType = null;
                        if (target.isFieldInjectable()) {
                            java.lang.reflect.Field f = target.getField();
                            if (f == null) {
                                String fName = target.getFieldName();
                                Class targetClass = cl.loadClass(target.getClassName());
                                try {
                                    f = targetClass.getDeclaredField(fName);
                                }// ignoring exception
                                 catch (java.lang.NoSuchFieldException nsfe) {
                                }
                            }
                            if (f != null) {
                                serviceType = f.getType();
                            }
                        }
                        if (target.isMethodInjectable()) {
                            Method m = target.getMethod();
                            if (m == null) {
                                String mName = target.getMethodName();
                                Class targetClass = cl.loadClass(target.getClassName());
                                try {
                                    m = targetClass.getDeclaredMethod(mName);
                                }// ignoring exception
                                 catch (java.lang.NoSuchMethodException nsfe) {
                                }
                            }
                            if (m != null && m.getParameterTypes().length == 1) {
                                serviceType = m.getParameterTypes()[0];
                            }
                        }
                        if (serviceType != null) {
                            Class loadedSvcClass = cl.loadClass(serviceType.getCanonicalName());
                            injValue = initiateInstance(loadedSvcClass, desc);
                        }
                    }
                }
                // Unable to get hold of generated service class -> try the Service.create avenue to get a Service
                if (injValue == null) {
                    // Here create the service with WSDL (overridden wsdl if wsdl-override is present)
                    // so that JAXWS runtime uses this wsdl @ runtime
                    javax.xml.ws.Service svc = javax.xml.ws.Service.create((new WsUtil()).privilegedGetServiceRefWsdl(desc), desc.getServiceName());
                    jaxwsDelegate = new JAXWSServiceDelegate(desc, svc, cl);
                }
            }
            if (desc.hasHandlers()) {
                // We need the service's ports to configure the
                // handler chain (since service-ref handler chain can
                // optionally specify handler-port association)
                // so create a configured service and call getPorts
                javax.xml.rpc.Service configuredService = wsUtil.createConfiguredService(desc);
                Iterator ports = configuredService.getPorts();
                wsUtil.configureHandlerChain(desc, serviceDelegate, ports, cl);
            }
            // check if this is a post 1.1 web service
            if (javax.xml.ws.Service.class.isAssignableFrom(serviceInterfaceClass)) {
                // This is a JAXWS based webservice client;
                // process handlers and mtom setting
                // moved test for handlers into wsUtil, in case
                // we have to add system handler
                javax.xml.ws.Service service = (injValue != null ? (javax.xml.ws.Service) injValue : jaxwsDelegate);
                if (service != null) {
                    // Now configure client side handlers
                    wsUtil.configureJAXWSClientHandlers(service, desc);
                }
                // the requested resource is not the service but one of its port.
                if (injValue != null && desc.getInjectionTargetType() != null) {
                    Class requestedPortType = service.getClass().getClassLoader().loadClass(desc.getInjectionTargetType());
                    ArrayList<WebServiceFeature> wsFeatures = getWebServiceFeatures(desc);
                    if (wsFeatures.size() > 0) {
                        injValue = service.getPort(requestedPortType, wsFeatures.toArray(new WebServiceFeature[wsFeatures.size()]));
                    } else {
                        injValue = service.getPort(requestedPortType);
                    }
                }
            }
        } else {
            // Generic service interface / no WSDL
            QName serviceName = desc.getServiceName();
            if (serviceName == null) {
                // ServiceFactory API requires a service-name.
                // However, 109 does not allow getServiceName() to be
                // called, so it's ok to use a dummy value.
                serviceName = new QName("urn:noservice", "servicename");
            }
            ServiceFactory serviceFac = ServiceFactory.newInstance();
            serviceDelegate = serviceFac.createService(serviceName);
        }
        // Create a proxy for the service object.
        // Get a proxy only in jaxrpc case because in jaxws the service class is not
        // an interface any more
        InvocationHandler handler = null;
        if (serviceDelegate != null) {
            handler = new ServiceInvocationHandler(desc, serviceDelegate, cl);
            returnObj = Proxy.newProxyInstance(cl, new Class[] { serviceInterfaceClass }, handler);
        } else if (jaxwsDelegate != null) {
            returnObj = jaxwsDelegate;
        } else if (injValue != null) {
            returnObj = injValue;
        }
    } catch (PrivilegedActionException pae) {
        logger.log(Level.WARNING, LogUtils.EXCEPTION_THROWN, pae);
        NamingException ne = new NamingException();
        ne.initCause(pae.getCause());
        throw ne;
    } catch (Exception e) {
        logger.log(Level.WARNING, LogUtils.EXCEPTION_THROWN, e);
        NamingException ne = new NamingException();
        ne.initCause(e);
        throw ne;
    } finally {
        WSContainerResolver.unset();
    }
    return returnObj;
}
Also used : ServiceFactory(javax.xml.rpc.ServiceFactory) java.lang.reflect(java.lang.reflect) Iterator(java.util.Iterator) NamingException(javax.naming.NamingException) PrivilegedActionException(java.security.PrivilegedActionException) QName(javax.xml.namespace.QName) Service(org.jvnet.hk2.annotations.Service) InitialContext(javax.naming.InitialContext) NamingException(javax.naming.NamingException) PrivilegedActionException(java.security.PrivilegedActionException) WebServiceException(javax.xml.ws.WebServiceException) WebServiceFeature(javax.xml.ws.WebServiceFeature)

Example 2 with InjectionTarget

use of org.jvnet.hk2.config.InjectionTarget in project Payara by payara.

the class CommandRunnerImpl method injectParameters.

public static boolean injectParameters(final CommandModel model, final Object injectionTarget, final InjectionResolver<Param> injector, final ActionReport report) {
    if (injectionTarget instanceof GenericCrudCommand) {
        GenericCrudCommand c = GenericCrudCommand.class.cast(injectionTarget);
        c.setInjectionResolver(injector);
    }
    // inject
    try {
        injectionMgr.inject(injectionTarget, injector);
    } catch (UnsatisfiedDependencyException e) {
        Param param = e.getAnnotation(Param.class);
        CommandModel.ParamModel paramModel = null;
        for (CommandModel.ParamModel pModel : model.getParameters()) {
            if (pModel.getParam().equals(param)) {
                paramModel = pModel;
                break;
            }
        }
        String errorMsg;
        final String usage = getUsageText(model);
        if (paramModel != null) {
            String paramName = paramModel.getName();
            String paramDesc = paramModel.getLocalizedDescription();
            if (param.primary()) {
                errorMsg = adminStrings.getLocalString("commandrunner.operand.required", "Operand required.");
            } else if (param.password()) {
                errorMsg = adminStrings.getLocalString("adapter.param.missing.passwordfile", "{0} command requires the passwordfile " + "parameter containing {1} entry.", model.getCommandName(), paramName);
            } else if (paramDesc != null) {
                errorMsg = adminStrings.getLocalString("admin.param.missing", "{0} command requires the {1} parameter ({2})", model.getCommandName(), paramName, paramDesc);
            } else {
                errorMsg = adminStrings.getLocalString("admin.param.missing.nodesc", "{0} command requires the {1} parameter", model.getCommandName(), paramName);
            }
        } else {
            errorMsg = adminStrings.getLocalString("admin.param.missing.nofound", "Cannot find {1} in {0} command model, file a bug", model.getCommandName(), e.getUnsatisfiedName());
        }
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage(errorMsg);
        report.setFailureCause(e);
        ActionReport.MessagePart childPart = report.getTopMessagePart().addChild();
        childPart.setMessage(usage);
        return false;
    } catch (MultiException e) {
        // If the cause is UnacceptableValueException -- we want the message
        // from it.  It is wrapped with a less useful Exception.
        Exception exception = null;
        for (Throwable th : e.getErrors()) {
            Throwable cause = th;
            while (cause != null) {
                if ((cause instanceof UnacceptableValueException) || (cause instanceof IllegalArgumentException)) {
                    exception = (Exception) th;
                    break;
                }
                cause = cause.getCause();
            }
        }
        if (exception == null) {
            // Not an UnacceptableValueException or IllegalArgumentException
            exception = e;
        }
        logger.log(Level.SEVERE, KernelLoggerInfo.invocationException, exception);
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage(exception.getMessage());
        report.setFailureCause(exception);
        ActionReport.MessagePart childPart = report.getTopMessagePart().addChild();
        childPart.setMessage(getUsageText(model));
        return false;
    }
    checkAgainstBeanConstraints(injectionTarget, model.getCommandName());
    return true;
}
Also used : GenericCrudCommand(org.glassfish.config.support.GenericCrudCommand) UnsatisfiedDependencyException(org.jvnet.hk2.config.UnsatisfiedDependencyException) Param(org.glassfish.api.Param) UnacceptableValueException(org.glassfish.common.util.admin.UnacceptableValueException) MultiException(org.glassfish.hk2.api.MultiException) MultiException(org.glassfish.hk2.api.MultiException) UnacceptableValueException(org.glassfish.common.util.admin.UnacceptableValueException) IOException(java.io.IOException) UnsatisfiedDependencyException(org.jvnet.hk2.config.UnsatisfiedDependencyException)

Example 3 with InjectionTarget

use of org.jvnet.hk2.config.InjectionTarget in project Payara by payara.

the class WebServiceRefHandler method processAWsRef.

protected HandlerProcessingResult processAWsRef(AnnotationInfo annInfo, WebServiceRef annotation) throws AnnotationProcessorException {
    AnnotatedElementHandler annCtx = annInfo.getProcessingContext().getHandler();
    AnnotatedElement annElem = annInfo.getAnnotatedElement();
    Class annotatedType = null;
    Class declaringClass = null;
    InjectionTarget target = null;
    String defaultServiceRefName = null;
    if (annInfo.getElementType().equals(ElementType.FIELD)) {
        // this is a field injection
        Field annotatedField = (Field) annElem;
        // check this is a valid field
        if (annCtx instanceof AppClientContext) {
            if (!Modifier.isStatic(annotatedField.getModifiers())) {
                throw new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.injectionfieldnotstatic", "Injection fields for application clients must be declared STATIC"), annInfo);
            }
        }
        annotatedType = annotatedField.getType();
        declaringClass = annotatedField.getDeclaringClass();
        defaultServiceRefName = declaringClass.getName() + "/" + annotatedField.getName();
        target = new InjectionTarget();
        target.setFieldName(annotatedField.getName());
        target.setClassName(annotatedField.getDeclaringClass().getName());
    } else if (annInfo.getElementType().equals(ElementType.METHOD)) {
        // this is a method injection
        Method annotatedMethod = (Method) annElem;
        validateInjectionMethod(annotatedMethod, annInfo);
        if (annCtx instanceof AppClientContext) {
            if (!Modifier.isStatic(annotatedMethod.getModifiers())) {
                throw new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.injectionmethodnotstatic", "Injection methods for application clients must be declared STATIC"), annInfo);
            }
        }
        annotatedType = annotatedMethod.getParameterTypes()[0];
        declaringClass = annotatedMethod.getDeclaringClass();
        // Derive javabean property name.
        String propertyName = getInjectionMethodPropertyName(annotatedMethod, annInfo);
        // prefixing with fully qualified type name
        defaultServiceRefName = declaringClass.getName() + "/" + propertyName;
        target = new InjectionTarget();
        target.setMethodName(annotatedMethod.getName());
        target.setClassName(annotatedMethod.getDeclaringClass().getName());
    } else if (annInfo.getElementType().equals(ElementType.TYPE)) {
        // name must be specified.
        if (!ok(annotation.name())) {
            throw new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.nonametypelevel", "TYPE-Level annotation  must specify name member."), annInfo);
        }
        // this is a dependency declaration, we need the service interface
        // to be specified
        annotatedType = annotation.type();
        if (annotatedType == null || annotatedType == Object.class) {
            throw new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.typenotfound", "TYPE-level annotation symbol must specify type member."), annInfo);
        }
        declaringClass = (Class) annElem;
    } else {
        throw new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.invalidtype", "annotation not allowed on this element."), annInfo);
    }
    MTOM mtom = null;
    Addressing addressing = null;
    RespectBinding respectBinding = null;
    // Other annotations like SchemaValidation etc to be passed on to
    // ServiceReferenceDescriptor
    Map<Class<? extends Annotation>, Annotation> otherAnnotations = new HashMap<Class<? extends Annotation>, Annotation>();
    for (Annotation a : annElem.getAnnotations()) {
        if (!(a.annotationType().isAnnotationPresent(WebServiceFeatureAnnotation.class)))
            continue;
        if (a instanceof MTOM) {
            mtom = (MTOM) a;
        } else if (a instanceof Addressing) {
            addressing = (Addressing) a;
        } else if (a instanceof RespectBinding) {
            respectBinding = (RespectBinding) a;
        } else {
            if (!otherAnnotations.containsKey(a.getClass())) {
                otherAnnotations.put(a.getClass(), a);
            }
        }
    }
    String serviceRefName = !ok(annotation.name()) ? defaultServiceRefName : annotation.name();
    ServiceReferenceContainer[] containers = null;
    if (annCtx instanceof ServiceReferenceContainerContext) {
        containers = ((ServiceReferenceContainerContext) annCtx).getServiceRefContainers();
    }
    if (containers == null || containers.length == 0) {
        annInfo.getProcessingContext().getErrorHandler().fine(new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.invalidannotationforthisclass", "Illegal annotation symbol for this class will be ignored"), annInfo));
        return HandlerProcessingResultImpl.getDefaultResult(getAnnotationType(), ResultType.PROCESSED);
    }
    // now process the annotation for all the containers.
    for (ServiceReferenceContainer container : containers) {
        ServiceReferenceDescriptor aRef = null;
        try {
            aRef = container.getServiceReferenceByName(serviceRefName);
        }// ignore
         catch (Throwable t) {
        }
        if (aRef == null) {
            // time to create it...
            aRef = new ServiceReferenceDescriptor();
            aRef.setName(serviceRefName);
            container.addServiceReferenceDescriptor(aRef);
        }
        // merge other annotations
        Map<Class<? extends Annotation>, Annotation> oa = aRef.getOtherAnnotations();
        if (oa == null)
            aRef.setOtherAnnotations(otherAnnotations);
        else {
            for (Map.Entry<Class<? extends Annotation>, Annotation> entry : otherAnnotations.entrySet()) {
                if (!oa.containsKey(entry.getKey()))
                    oa.put(entry.getKey(), entry.getValue());
            }
        }
        // merge wsdlLocation
        if (!ok(aRef.getWsdlFileUri()) && ok(annotation.wsdlLocation()))
            aRef.setWsdlFileUri(annotation.wsdlLocation());
        if (!aRef.hasMtomEnabled() && mtom != null) {
            aRef.setMtomEnabled(mtom.enabled());
            aRef.setMtomThreshold(mtom.threshold());
        }
        // check Addressing annotation
        if (aRef.getAddressing() == null && addressing != null) {
            aRef.setAddressing(new com.sun.enterprise.deployment.Addressing(addressing.enabled(), addressing.required(), addressing.responses().toString()));
        }
        // check RespectBinding annotation
        if (aRef.getRespectBinding() == null && respectBinding != null) {
            aRef.setRespectBinding(new com.sun.enterprise.deployment.RespectBinding(respectBinding.enabled()));
        }
        // Store mapped name that is specified
        if (!ok(aRef.getMappedName()) && ok(annotation.mappedName()))
            aRef.setMappedName(annotation.mappedName());
        // Store lookup name that is specified
        if (!aRef.hasLookupName() && ok(getLookupValue(annotation, annInfo)))
            aRef.setLookupName(getLookupValue(annotation, annInfo));
        aRef.setInjectResourceType("javax.jws.WebServiceRef");
        if (target != null)
            aRef.addInjectionTarget(target);
        // Read the WebServiceClient annotation for the service name space
        // uri and wsdl (if required)
        WebServiceClient wsclientAnn;
        // of these default values.
        if (!Object.class.equals(annotation.value()) && (!javax.xml.ws.Service.class.equals(annotation.value()))) {
            // port.
            if (aRef.getServiceInterface() == null) {
                aRef.setServiceInterface(annotation.value().getName());
            }
            if (aRef.getPortInfoBySEI(annotatedType.getName()) == null) {
                ServiceRefPortInfo portInfo = new ServiceRefPortInfo();
                portInfo.setServiceEndpointInterface(annotatedType.getName());
                aRef.addPortInfo(portInfo);
            }
            // set the port type requested for injection
            if (aRef.getInjectionTargetType() == null) {
                aRef.setInjectionTargetType(annotatedType.getName());
            }
            wsclientAnn = (WebServiceClient) annotation.value().getAnnotation(WebServiceClient.class);
        } else {
            // no value provided in the annotation
            wsclientAnn = (WebServiceClient) annotatedType.getAnnotation(WebServiceClient.class);
        }
        if (wsclientAnn == null) {
            throw new AnnotationProcessorException(localStrings.getLocalString("enterprise.deployment.annotation.handlers.classnotannotated", "Class must be annotated with a {1} annotation\n symbol : {1}\n location: {0}", new Object[] { annotatedType.toString(), WebServiceClient.class.toString() }));
        }
        // annotation, get it from WebServiceClient annotation
        if (aRef.getWsdlFileUri() == null) {
            aRef.setWsdlFileUri(wsclientAnn.wsdlLocation());
        }
        // Set service name space URI and service local part
        if (aRef.getServiceName() == null) {
            aRef.setServiceNamespaceUri(wsclientAnn.targetNamespace());
            aRef.setServiceLocalPart(wsclientAnn.name());
        }
        if (aRef.getServiceInterface() == null) {
            aRef.setServiceInterface(annotatedType.getName());
        }
    }
    // have @HandlerChain but the SEI has one specified through JAXWS customization
    if (annElem.getAnnotation(javax.jws.HandlerChain.class) == null) {
        return (new HandlerChainHandler()).processHandlerChainAnnotation(annInfo, annCtx, annotatedType, declaringClass, false);
    }
    return HandlerProcessingResultImpl.getDefaultResult(getAnnotationType(), ResultType.PROCESSED);
}
Also used : HashMap(java.util.HashMap) AnnotatedElement(java.lang.reflect.AnnotatedElement) ServiceReferenceContainer(com.sun.enterprise.deployment.types.ServiceReferenceContainer) Addressing(javax.xml.ws.soap.Addressing) AppClientContext(com.sun.enterprise.deployment.annotation.context.AppClientContext) Field(java.lang.reflect.Field) ServiceReferenceContainerContext(com.sun.enterprise.deployment.annotation.context.ServiceReferenceContainerContext) com.sun.enterprise.deployment(com.sun.enterprise.deployment) MTOM(javax.xml.ws.soap.MTOM) Service(org.jvnet.hk2.annotations.Service) RespectBinding(javax.xml.ws.RespectBinding) Method(java.lang.reflect.Method) WebServiceFeatureAnnotation(javax.xml.ws.spi.WebServiceFeatureAnnotation) Annotation(java.lang.annotation.Annotation) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with InjectionTarget

use of org.jvnet.hk2.config.InjectionTarget in project Payara by payara.

the class CommandRunnerImpl method doCommand.

/**
 * Called from ExecutionContext.execute.
 */
private void doCommand(ExecutionContext inv, AdminCommand command, final Subject subject, final Job job) {
    boolean fromCheckpoint = job != null && (job.getState() == AdminCommandState.State.REVERTING || job.getState() == AdminCommandState.State.FAILED_RETRYABLE);
    CommandModel model;
    try {
        CommandModelProvider c = CommandModelProvider.class.cast(command);
        model = c.getModel();
    } catch (ClassCastException e) {
        model = new CommandModelImpl(command.getClass());
    }
    UploadedFilesManager ufm = null;
    ActionReport report = inv.report();
    if (!fromCheckpoint) {
        report.setActionDescription(model.getCommandName() + " command");
        report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
    }
    ParameterMap parameters;
    final AdminCommandContext context = new AdminCommandContextImpl(logger, report, inv.inboundPayload(), inv.outboundPayload(), job.getEventBroker(), job.getId());
    context.setSubject(subject);
    List<RuntimeType> runtimeTypes = new ArrayList<>();
    FailurePolicy fp = null;
    Set<CommandTarget> targetTypesAllowed = new HashSet<>();
    ActionReport.ExitCode preSupplementalReturn = ActionReport.ExitCode.SUCCESS;
    ActionReport.ExitCode postSupplementalReturn = ActionReport.ExitCode.SUCCESS;
    CommandRunnerProgressHelper progressHelper = new CommandRunnerProgressHelper(command, model.getCommandName(), job, inv.progressStatusChild);
    // If this glassfish installation does not have stand alone instances / clusters at all, then
    // lets not even look Supplemental command and such. A small optimization
    boolean doReplication = false;
    if ((domain.getServers().getServer().size() > 1) || (!domain.getClusters().getCluster().isEmpty())) {
        doReplication = true;
    } else {
        logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.devmode", "The GlassFish environment does not have any clusters or instances present; Replication is turned off"));
    }
    try {
        // Get list of supplemental commands
        Collection<SupplementalCommand> supplementalCommands = supplementalExecutor.listSupplementalCommands(model.getCommandName());
        try {
            /*
                 * Extract any uploaded files and build a map from parameter names
                 * to the corresponding extracted, uploaded file.
                 */
            ufm = new UploadedFilesManager(inv.report, logger, inv.inboundPayload());
            if (inv.typedParams() != null) {
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.delegatedcommand", "This command is a delegated command. Dynamic reconfiguration will be bypassed"));
                InjectionResolver<Param> injectionTarget = new DelegatedInjectionResolver(model, inv.typedParams(), ufm.optionNameToFileMap());
                if (injectParameters(model, command, injectionTarget, report)) {
                    inv.setReport(doCommand(model, command, context, progressHelper));
                }
                return;
            }
            parameters = inv.parameters();
            if (parameters == null) {
                // no parameters, pass an empty collection
                parameters = new ParameterMap();
            }
            if (isSet(parameters, "help") || isSet(parameters, "Xhelp")) {
                BufferedReader in = getManPage(model.getCommandName(), model);
                String manPage = encodeManPage(in);
                if (manPage != null && isSet(parameters, "help")) {
                    inv.report().getTopMessagePart().addProperty("MANPAGE", manPage);
                } else {
                    report.getTopMessagePart().addProperty(AdminCommandResponse.GENERATED_HELP, "true");
                    getHelp(command, report);
                }
                return;
            }
            try {
                if (!fromCheckpoint && !skipValidation(command)) {
                    validateParameters(model, parameters);
                }
            } catch (MultiException e) {
                // If the cause is UnacceptableValueException -- we want the message
                // from it.  It is wrapped with a less useful Exception.
                Exception exception = e;
                for (Throwable cause : e.getErrors()) {
                    if (cause != null && (cause instanceof UnacceptableValueException)) {
                        // throw away the wrapper.
                        exception = (Exception) cause;
                        break;
                    }
                }
                logger.log(Level.SEVERE, KernelLoggerInfo.invocationException, exception);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                report.setMessage(exception.getMessage());
                report.setFailureCause(exception);
                ActionReport.MessagePart childPart = report.getTopMessagePart().addChild();
                childPart.setMessage(getUsageText(model));
                return;
            }
            // initialize the injector and inject
            MapInjectionResolver injectionMgr = new MapInjectionResolver(model, parameters, ufm.optionNameToFileMap());
            injectionMgr.setContext(context);
            if (!injectParameters(model, command, injectionMgr, report)) {
                return;
            }
            CommandSupport.init(habitat, command, context, job);
            /*
                 * Now that parameters have been injected into the command object,
                 * decide if the current Subject should be permitted to execute
                 * the command.  We need to wait until after injection is done
                 * because the class might implement its own authorization check
                 * and that logic might need the injected values.
                 */
            final Map<String, Object> env = buildEnvMap(parameters);
            try {
                if (!commandSecurityChecker.authorize(context.getSubject(), env, command, context)) {
                    /*
                         * If the command class tried to prepare itself but
                         * could not then the return is false and the command has
                         * set the action report accordingly.  Don't process
                         * the command further and leave the action report alone.
                         */
                    return;
                }
            } catch (SecurityException ex) {
                report.setFailureCause(ex);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                report.setMessage(adminStrings.getLocalString("commandrunner.noauth", "User is not authorized for this command"));
                return;
            } catch (Exception ex) {
                report.setFailureCause(ex);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                report.setMessage(adminStrings.getLocalString("commandrunner.errAuth", "Error during authorization"));
                return;
            }
            logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.injectiondone", "Parameter mapping, validation, injection completed successfully; Starting paramater injection"));
            // Read cluster annotation attributes
            org.glassfish.api.admin.ExecuteOn clAnnotation = model.getClusteringAttributes();
            if (clAnnotation == null) {
                runtimeTypes.add(RuntimeType.DAS);
                runtimeTypes.add(RuntimeType.INSTANCE);
                fp = FailurePolicy.Error;
            } else {
                if (clAnnotation.value().length == 0) {
                    runtimeTypes.add(RuntimeType.DAS);
                    runtimeTypes.add(RuntimeType.INSTANCE);
                } else {
                    runtimeTypes.addAll(Arrays.asList(clAnnotation.value()));
                }
                if (clAnnotation.ifFailure() == null) {
                    fp = FailurePolicy.Error;
                } else {
                    fp = clAnnotation.ifFailure();
                }
            }
            TargetType tgtTypeAnnotation = command.getClass().getAnnotation(TargetType.class);
            // @TargetType since we do not want to replicate the command
            if (runtimeTypes.contains(RuntimeType.SINGLE_INSTANCE)) {
                if (tgtTypeAnnotation != null) {
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.targettype.unallowed", "Target type is not allowed on single instance command {0}  ,", model.getCommandName()));
                    return;
                }
                // Do not replicate the command when there is
                // @ExecuteOn(RuntimeType.SINGLE_INSTANCE)
                doReplication = false;
            }
            String targetName = parameters.getOne("target");
            if (targetName == null || model.getModelFor("target").getParam().obsolete()) {
                if (command instanceof DeploymentTargetResolver) {
                    targetName = ((DeploymentTargetResolver) command).getTarget(parameters);
                } else {
                    targetName = "server";
                }
            }
            logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.target", "@ExecuteOn parsing and default settings done; Current target is {0}", targetName));
            if (serverEnv.isDas()) {
                if (tgtTypeAnnotation != null) {
                    targetTypesAllowed.addAll(Arrays.asList(tgtTypeAnnotation.value()));
                }
                // If not @TargetType, default it
                if (targetTypesAllowed.isEmpty()) {
                    targetTypesAllowed.add(CommandTarget.DAS);
                    targetTypesAllowed.add(CommandTarget.STANDALONE_INSTANCE);
                    targetTypesAllowed.add(CommandTarget.CLUSTER);
                    targetTypesAllowed.add(CommandTarget.CONFIG);
                    targetTypesAllowed.add(CommandTarget.DEPLOYMENT_GROUP);
                }
                // ONLY if the target is "server"
                if (CommandTarget.DAS.isValid(habitat, targetName) && !runtimeTypes.contains(RuntimeType.DAS)) {
                    runtimeTypes.add(RuntimeType.DAS);
                }
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.runtimeTypes", "RuntimeTypes are: {0}", runtimeTypes.toString()));
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration,diagnostics.targetTypes", "TargetTypes are: {0}", targetTypesAllowed.toString()));
                // Is there a server or a cluster or a config with given name ?
                if ((!CommandTarget.DOMAIN.isValid(habitat, targetName)) && (domain.getServerNamed(targetName) == null) && (domain.getClusterNamed(targetName) == null) && (domain.getConfigNamed(targetName) == null) && (domain.getDeploymentGroupNamed(targetName) == null)) {
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.invalidtarget", "Unable to find a valid target with name {0}", targetName));
                    return;
                }
                // Does this command allow this target type
                boolean isTargetValidType = false;
                Iterator<CommandTarget> it = targetTypesAllowed.iterator();
                while (it.hasNext()) {
                    if (it.next().isValid(habitat, targetName)) {
                        isTargetValidType = true;
                        break;
                    }
                }
                if (!isTargetValidType) {
                    StringBuilder validTypes = new StringBuilder();
                    it = targetTypesAllowed.iterator();
                    while (it.hasNext()) {
                        validTypes.append(it.next().getDescription()).append(", ");
                    }
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.invalidtargettype", "Target {0} is not a supported type. Command {1} supports these types of targets only : {2}", targetName, model.getCommandName(), validTypes.toString()));
                    return;
                }
                // instance, return error
                if ((CommandTarget.CLUSTERED_INSTANCE.isValid(habitat, targetName)) && (!targetTypesAllowed.contains(CommandTarget.CLUSTERED_INSTANCE))) {
                    Cluster c = domain.getClusterForInstance(targetName);
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.instanceopnotallowed", "The {0} command is not allowed on instance {1} because it is part of cluster {2}", model.getCommandName(), targetName, c.getName()));
                    return;
                }
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.replicationvalidationdone", "All @ExecuteOn attribute and type validation completed successfully. Starting replication stages"));
            }
            /**
             * We're finally ready to actually execute the command instance.
             * Acquire the appropriate lock.
             */
            Lock lock = null;
            boolean lockTimedOut = false;
            try {
                // XXX: The owner of the lock should not be hardcoded.  The
                // value is not used yet.
                lock = adminLock.getLock(command, "asadmin");
                // Set there progress statuses
                if (!fromCheckpoint) {
                    for (SupplementalCommand supplementalCommand : supplementalCommands) {
                        progressHelper.addProgressStatusToSupplementalCommand(supplementalCommand);
                    }
                }
                // If command is undoable, then invoke prepare method
                if (command instanceof UndoableCommand) {
                    UndoableCommand uCmd = (UndoableCommand) command;
                    logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.prepareunodable", "Command execution stage 1 : Calling prepare for undoable command {0}", inv.name()));
                    if (!uCmd.prepare(context, parameters).equals(ActionReport.ExitCode.SUCCESS)) {
                        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                        report.setMessage(adminStrings.getLocalString("commandrunner.executor.errorinprepare", "The command {0} cannot be completed because the preparation for the command failed " + "indicating potential issues : {1}", model.getCommandName(), report.getMessage()));
                        return;
                    }
                }
                ClusterOperationUtil.clearInstanceList();
                // Run Supplemental commands that have to run before this command on this instance type
                if (!fromCheckpoint) {
                    logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.presupplemental", "Command execution stage 2 : Call pre supplemental commands for {0}", inv.name()));
                    preSupplementalReturn = supplementalExecutor.execute(supplementalCommands, Supplemental.Timing.Before, context, parameters, ufm.optionNameToFileMap());
                    if (preSupplementalReturn.equals(ActionReport.ExitCode.FAILURE)) {
                        report.setActionExitCode(preSupplementalReturn);
                        if (!StringUtils.ok(report.getTopMessagePart().getMessage())) {
                            report.setMessage(adminStrings.getLocalString("commandrunner.executor.supplementalcmdfailed", "A supplemental command failed; cannot proceed further"));
                        }
                        return;
                    }
                }
                // Run main command if it is applicable for this instance type
                if ((runtimeTypes.contains(RuntimeType.ALL)) || (serverEnv.isDas() && (CommandTarget.DOMAIN.isValid(habitat, targetName) || runtimeTypes.contains(RuntimeType.DAS))) || runtimeTypes.contains(RuntimeType.SINGLE_INSTANCE) || (serverEnv.isInstance() && runtimeTypes.contains(RuntimeType.INSTANCE))) {
                    logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.maincommand", "Command execution stage 3 : Calling main command implementation for {0}", inv.name()));
                    report = doCommand(model, command, context, progressHelper);
                    inv.setReport(report);
                }
                if (!FailurePolicy.applyFailurePolicy(fp, report.getActionExitCode()).equals(ActionReport.ExitCode.FAILURE)) {
                    // Run Supplemental commands that have to be run after this command on this instance type
                    logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.postsupplemental", "Command execution stage 4 : Call post supplemental commands for {0}", inv.name()));
                    postSupplementalReturn = supplementalExecutor.execute(supplementalCommands, Supplemental.Timing.After, context, parameters, ufm.optionNameToFileMap());
                    if (postSupplementalReturn.equals(ActionReport.ExitCode.FAILURE)) {
                        report.setActionExitCode(postSupplementalReturn);
                        report.setMessage(adminStrings.getLocalString("commandrunner.executor.supplementalcmdfailed", "A supplemental command failed; cannot proceed further"));
                        return;
                    }
                }
            } catch (AdminCommandLockTimeoutException ex) {
                lockTimedOut = true;
                String lockTime = formatSuspendDate(ex.getTimeOfAcquisition());
                String logMsg = "Command: " + model.getCommandName() + " failed to acquire a command lock.  REASON: time out " + "(current lock acquired on " + lockTime + ")";
                String msg = adminStrings.getLocalString("lock.timeout", "Command timed out.  Unable to acquire a lock to access " + "the domain.  Another command acquired exclusive access " + "to the domain on {0}.  Retry the command at a later " + "time.", lockTime);
                report.setMessage(msg);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            } catch (AdminCommandLockException ex) {
                lockTimedOut = true;
                String lockTime = formatSuspendDate(ex.getTimeOfAcquisition());
                String lockMsg = ex.getMessage();
                String logMsg;
                logMsg = "Command: " + model.getCommandName() + " was blocked.  The domain was suspended by a " + "user on:" + lockTime;
                if (lockMsg != null && !lockMsg.isEmpty()) {
                    logMsg += " Reason: " + lockMsg;
                }
                String msg = adminStrings.getLocalString("lock.notacquired", "The command was blocked.  The domain was suspended by " + "a user on {0}.", lockTime);
                if (lockMsg != null && !lockMsg.isEmpty()) {
                    msg += " " + adminStrings.getLocalString("lock.reason", "Reason:") + " " + lockMsg;
                }
                report.setMessage(msg);
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            } finally {
                // command is done, release the lock
                if (lock != null && lockTimedOut == false) {
                    lock.unlock();
                }
            }
        } catch (Exception ex) {
            logger.log(Level.SEVERE, KernelLoggerInfo.invocationException, ex);
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setMessage(ex.getMessage());
            report.setFailureCause(ex);
            ActionReport.MessagePart childPart = report.getTopMessagePart().addChild();
            childPart.setMessage(getUsageText(model));
            return;
        }
        if (processEnv.getProcessType().isEmbedded()) {
            return;
        }
        if (preSupplementalReturn == ActionReport.ExitCode.WARNING || postSupplementalReturn == ActionReport.ExitCode.WARNING) {
            report.setActionExitCode(ActionReport.ExitCode.WARNING);
        }
        if (doReplication && (!FailurePolicy.applyFailurePolicy(fp, report.getActionExitCode()).equals(ActionReport.ExitCode.FAILURE)) && (serverEnv.isDas()) && (runtimeTypes.contains(RuntimeType.INSTANCE) || runtimeTypes.contains(RuntimeType.ALL))) {
            logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.startreplication", "Command execution stages completed on DAS; Starting replication on remote instances"));
            ClusterExecutor executor = null;
            // This try-catch block is a fix for 13838
            try {
                if (model.getClusteringAttributes() != null && model.getClusteringAttributes().executor() != null) {
                    executor = habitat.getService(model.getClusteringAttributes().executor());
                } else {
                    executor = habitat.getService(ClusterExecutor.class, "GlassFishClusterExecutor");
                }
            } catch (UnsatisfiedDependencyException usdepex) {
                logger.log(Level.WARNING, KernelLoggerInfo.cantGetClusterExecutor, usdepex);
            }
            if (executor != null) {
                report.setActionExitCode(executor.execute(model.getCommandName(), command, context, parameters));
                if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
                    report.setMessage(adminStrings.getLocalString("commandrunner.executor.errorwhilereplication", "An error occurred during replication"));
                } else {
                    if (!FailurePolicy.applyFailurePolicy(fp, report.getActionExitCode()).equals(ActionReport.ExitCode.FAILURE)) {
                        logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.afterreplsupplemental", "Command execution stage 5 : Call post-replication supplemental commands for {0}", inv.name()));
                        ActionReport.ExitCode afterReplicationSupplementalReturn = supplementalExecutor.execute(supplementalCommands, Supplemental.Timing.AfterReplication, context, parameters, ufm.optionNameToFileMap());
                        if (afterReplicationSupplementalReturn.equals(ActionReport.ExitCode.FAILURE)) {
                            report.setActionExitCode(afterReplicationSupplementalReturn);
                            report.setMessage(adminStrings.getLocalString("commandrunner.executor.supplementalcmdfailed", "A supplemental command failed; cannot proceed further"));
                            return;
                        }
                    }
                }
            }
        }
        if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
            // If command is undoable, then invoke undo method method
            if (command instanceof UndoableCommand) {
                UndoableCommand uCmd = (UndoableCommand) command;
                logger.fine(adminStrings.getLocalString("dynamicreconfiguration.diagnostics.undo", "Command execution failed; calling undo() for command {0}", inv.name()));
                uCmd.undo(context, parameters, ClusterOperationUtil.getCompletedInstances());
            }
        } else {
            // TODO : Is there a better way of doing this ? Got to look into it
            if ("_register-instance".equals(model.getCommandName())) {
                state.addServerToStateService(parameters.getOne("DEFAULT"));
            }
            if ("_unregister-instance".equals(model.getCommandName())) {
                state.removeInstanceFromStateService(parameters.getOne("DEFAULT"));
            }
        }
    } finally {
        if (ufm != null) {
            ufm.close();
        }
    }
}
Also used : DeploymentTargetResolver(org.glassfish.internal.deployment.DeploymentTargetResolver) ActionReport(org.glassfish.api.ActionReport) UnsatisfiedDependencyException(org.jvnet.hk2.config.UnsatisfiedDependencyException) UnacceptableValueException(org.glassfish.common.util.admin.UnacceptableValueException) CommandModelImpl(org.glassfish.common.util.admin.CommandModelImpl) SupplementalCommand(org.glassfish.api.admin.SupplementalCommandExecutor.SupplementalCommand) UndoableCommand(org.glassfish.internal.api.UndoableCommand) MultiException(org.glassfish.hk2.api.MultiException) org.glassfish.api.admin(org.glassfish.api.admin) TargetType(org.glassfish.config.support.TargetType) CachedCommandModel(com.sun.enterprise.admin.util.CachedCommandModel) MapInjectionResolver(org.glassfish.common.util.admin.MapInjectionResolver) CommandTarget(org.glassfish.config.support.CommandTarget) Cluster(com.sun.enterprise.config.serverbeans.Cluster) MultiException(org.glassfish.hk2.api.MultiException) UnacceptableValueException(org.glassfish.common.util.admin.UnacceptableValueException) IOException(java.io.IOException) UnsatisfiedDependencyException(org.jvnet.hk2.config.UnsatisfiedDependencyException) Lock(java.util.concurrent.locks.Lock) Param(org.glassfish.api.Param) BufferedReader(java.io.BufferedReader)

Aggregations

IOException (java.io.IOException)2 Param (org.glassfish.api.Param)2 UnacceptableValueException (org.glassfish.common.util.admin.UnacceptableValueException)2 MultiException (org.glassfish.hk2.api.MultiException)2 Service (org.jvnet.hk2.annotations.Service)2 UnsatisfiedDependencyException (org.jvnet.hk2.config.UnsatisfiedDependencyException)2 CachedCommandModel (com.sun.enterprise.admin.util.CachedCommandModel)1 Cluster (com.sun.enterprise.config.serverbeans.Cluster)1 com.sun.enterprise.deployment (com.sun.enterprise.deployment)1 AppClientContext (com.sun.enterprise.deployment.annotation.context.AppClientContext)1 ServiceReferenceContainerContext (com.sun.enterprise.deployment.annotation.context.ServiceReferenceContainerContext)1 ServiceReferenceContainer (com.sun.enterprise.deployment.types.ServiceReferenceContainer)1 BufferedReader (java.io.BufferedReader)1 Annotation (java.lang.annotation.Annotation)1 java.lang.reflect (java.lang.reflect)1 AnnotatedElement (java.lang.reflect.AnnotatedElement)1 Field (java.lang.reflect.Field)1 Method (java.lang.reflect.Method)1 PrivilegedActionException (java.security.PrivilegedActionException)1 HashMap (java.util.HashMap)1