Search in sources :

Example 16 with Service

use of org.apache.tapestry5.annotations.Service 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 17 with Service

use of org.apache.tapestry5.annotations.Service in project Payara by payara.

the class ApplicationLifecycle method loadDeployers.

private List<Deployer> loadDeployers(Map<Deployer, EngineInfo> containerInfosByDeployers, DeploymentContext context) throws IOException {
    final ActionReport report = context.getActionReport();
    final Map<Class, ApplicationMetaDataProvider> typeByProvider = getTypeByProvider();
    final Map<Class, Deployer> typeByDeployer = getTypeByDeployer(containerInfosByDeployers);
    final StructuredDeploymentTracing tracing = StructuredDeploymentTracing.load(context);
    for (Deployer deployer : containerInfosByDeployers.keySet()) {
        if (deployer.getMetaData() != null) {
            for (Class dependency : deployer.getMetaData().requires()) {
                if (!typeByDeployer.containsKey(dependency) && !typeByProvider.containsKey(dependency)) {
                    Service s = deployer.getClass().getAnnotation(Service.class);
                    String serviceName;
                    if (s != null && s.name() != null && s.name().length() > 0) {
                        serviceName = s.name();
                    } else {
                        serviceName = deployer.getClass().getSimpleName();
                    }
                    report.failure(logger, serviceName + " deployer requires " + dependency + " but no other deployer provides it", null);
                    return null;
                }
            }
        }
    }
    List<Deployer> orderedDeployers = new ArrayList<>();
    for (Map.Entry<Deployer, EngineInfo> entry : containerInfosByDeployers.entrySet()) {
        Deployer deployer = entry.getKey();
        if (logger.isLoggable(Level.FINE)) {
            logger.log(FINE, "Keyed Deployer {0}", deployer.getClass());
        }
        DeploymentSpan span = tracing.startSpan(TraceContext.Level.CONTAINER, entry.getValue().getSniffer().getModuleType(), DeploymentTracing.AppStage.PREPARE);
        loadDeployer(orderedDeployers, deployer, typeByDeployer, typeByProvider, context);
        span.close();
    }
    return orderedDeployers;
}
Also used : HotDeployService(fish.payara.nucleus.hotdeploy.HotDeployService) Service(org.jvnet.hk2.annotations.Service) PayaraExecutorService(fish.payara.nucleus.executorservice.PayaraExecutorService) ExecutorService(java.util.concurrent.ExecutorService) ActionReport(org.glassfish.api.ActionReport) EngineInfo(org.glassfish.internal.data.EngineInfo) StructuredDeploymentTracing(org.glassfish.internal.deployment.analysis.StructuredDeploymentTracing) DeploymentSpan(org.glassfish.internal.deployment.analysis.DeploymentSpan) Collectors.toMap(java.util.stream.Collectors.toMap) ParameterMap(org.glassfish.api.admin.ParameterMap) ApplicationMetaDataProvider(org.glassfish.api.deployment.ApplicationMetaDataProvider) Deployer(org.glassfish.api.deployment.Deployer)

Example 18 with Service

use of org.apache.tapestry5.annotations.Service in project Payara by payara.

the class ConfigModule method bindInjector.

private void bindInjector(DynamicConfiguration configurator, String elementName, Class contract, final Class clz) {
    DescriptorBuilder db = BuilderHelper.link(clz).to(ConfigInjector.class).to(InjectionTarget.class).to(contract).in(Singleton.class.getName()).qualifiedBy(clz.getAnnotation(InjectionTarget.class)).named(elementName).andLoadWith(new MyHk2Loader(clz.getClassLoader()));
    String metaData = ((Service) clz.getAnnotation(Service.class)).metadata();
    Map<String, List<String>> metaMap = new HashMap<String, List<String>>();
    for (StringTokenizer st = new StringTokenizer(metaData, ","); st.hasMoreTokens(); ) {
        String tok = st.nextToken();
        int index = tok.indexOf('=');
        if (index > 0) {
            String key = tok.substring(0, index);
            String value = tok.substring(index + 1);
            List<String> lst = metaMap.get(key);
            if (lst == null) {
                lst = new LinkedList<String>();
                metaMap.put(key, lst);
            }
            lst.add(value);
        // System.out.println("**     Added Metadata: " + tok.substring(0, index) + "  : " + tok.substring(index+1));
        }
    // db.andLoadWith(new MyHk2Loader(clz.getClassLoader()));
    }
    for (String key : metaMap.keySet()) {
        db.has(key, metaMap.get(key));
    }
    ActiveDescriptor desc = configurator.bind(db.build());
    configurator.bind(new AliasDescriptor(serviceLocator, desc, InjectionTarget.class.getName(), contract.getName()));
    System.out.println("**Successfully bound an alias descriptor for: " + elementName);
}
Also used : ActiveDescriptor(org.glassfish.hk2.api.ActiveDescriptor) Service(org.jvnet.hk2.annotations.Service) DescriptorBuilder(org.glassfish.hk2.utilities.DescriptorBuilder) AliasDescriptor(org.glassfish.hk2.utilities.AliasDescriptor) InjectionTarget(org.jvnet.hk2.config.InjectionTarget)

Example 19 with Service

use of org.apache.tapestry5.annotations.Service in project glassfish-hk2 by eclipse-ee4j.

the class BuilderHelper method createConstantDescriptor.

/**
 * This creates a descriptor that will always return the given object.
 * The advertised contracts is given in the incoming parameter and the
 * name on the descriptor also comes from the incoming parameter.
 *
 * @param constant The non-null constant that should always be returned from
 * the create method of this ActiveDescriptor.
 * @param name The possibly null name that should be associated with this constant descriptor
 * @param contracts The possibly empty set of contracts that should be associated with this
 * descriptor
 * @return The descriptor returned can be used in calls to
 * DynamicConfiguration.addActiveDescriptor
 * @throws IllegalArgumentException if constant is null
 */
public static <T> AbstractActiveDescriptor<T> createConstantDescriptor(T constant, String name, Type... contracts) {
    if (constant == null)
        throw new IllegalArgumentException();
    Annotation scope = ReflectionHelper.getScopeAnnotationFromObject(constant);
    Class<? extends Annotation> scopeClass = (scope == null) ? PerLookup.class : scope.annotationType();
    Set<Annotation> qualifiers = ReflectionHelper.getQualifiersFromObject(constant);
    Map<String, List<String>> metadata = new HashMap<String, List<String>>();
    if (scope != null) {
        getMetadataValues(scope, metadata);
    }
    for (Annotation qualifier : qualifiers) {
        getMetadataValues(qualifier, metadata);
    }
    Set<Type> contractsAsSet;
    if (contracts.length <= 0) {
        contractsAsSet = ReflectionHelper.getAdvertisedTypesFromObject(constant, Contract.class);
    } else {
        contractsAsSet = new LinkedHashSet<Type>();
        for (Type cType : contracts) {
            contractsAsSet.add(cType);
        }
    }
    Boolean proxy = null;
    UseProxy up = constant.getClass().getAnnotation(UseProxy.class);
    if (up != null) {
        proxy = up.value();
    }
    Boolean proxyForSameScope = null;
    ProxyForSameScope pfss = constant.getClass().getAnnotation(ProxyForSameScope.class);
    if (pfss != null) {
        proxyForSameScope = pfss.value();
    }
    DescriptorVisibility visibility = DescriptorVisibility.NORMAL;
    Visibility vi = constant.getClass().getAnnotation(Visibility.class);
    if (vi != null) {
        visibility = vi.value();
    }
    String classAnalysisName = null;
    Service service = constant.getClass().getAnnotation(Service.class);
    if (service != null) {
        classAnalysisName = service.analyzer();
    }
    int rank = getRank(constant.getClass());
    return new ConstantActiveDescriptor<T>(constant, contractsAsSet, scopeClass, name, qualifiers, visibility, proxy, proxyForSameScope, classAnalysisName, metadata, rank);
}
Also used : UseProxy(org.glassfish.hk2.api.UseProxy) HashMap(java.util.HashMap) Service(org.jvnet.hk2.annotations.Service) Annotation(java.lang.annotation.Annotation) ConstantActiveDescriptor(org.glassfish.hk2.internal.ConstantActiveDescriptor) DescriptorVisibility(org.glassfish.hk2.api.DescriptorVisibility) DescriptorType(org.glassfish.hk2.api.DescriptorType) Type(java.lang.reflect.Type) ProxyForSameScope(org.glassfish.hk2.api.ProxyForSameScope) List(java.util.List) Visibility(org.glassfish.hk2.api.Visibility) DescriptorVisibility(org.glassfish.hk2.api.DescriptorVisibility) Contract(org.jvnet.hk2.annotations.Contract)

Example 20 with Service

use of org.apache.tapestry5.annotations.Service in project glassfish-hk2 by eclipse-ee4j.

the class Utilities method createAutoDescriptor.

/**
 * Creates a reified automatically generated descriptor
 *
 * @param clazz The class to create the desciptor for
 * @param locator The service locator for whom we are creating this
 * @return A reified active descriptor
 *
 * @throws MultiException if there was an error in the class
 * @throws IllegalArgumentException If the class is null
 * @throws IllegalStateException If the name could not be determined from the Named annotation
 */
public static <T> AutoActiveDescriptor<T> createAutoDescriptor(Class<T> clazz, ServiceLocatorImpl locator) throws MultiException, IllegalArgumentException, IllegalStateException {
    if (clazz == null)
        throw new IllegalArgumentException();
    Collector collector = new Collector();
    ClazzCreator<T> creator;
    Set<Annotation> qualifiers;
    Set<Type> contracts;
    Class<? extends Annotation> scope;
    String name;
    Boolean proxy = null;
    Boolean proxyForSameScope = null;
    String analyzerName;
    String serviceMetadata = null;
    // Qualifiers naming dance
    String serviceName = null;
    Service serviceAnno = clazz.getAnnotation(Service.class);
    if (serviceAnno != null) {
        if (!"".equals(serviceAnno.name())) {
            serviceName = serviceAnno.name();
        }
        if (!"".equals(serviceAnno.metadata())) {
            serviceMetadata = serviceAnno.metadata();
        }
    }
    qualifiers = ReflectionHelper.getQualifierAnnotations(clazz);
    name = ReflectionHelper.getNameFromAllQualifiers(qualifiers, clazz);
    if (serviceName != null && name != null) {
        // They must match
        if (!serviceName.equals(name)) {
            throw new IllegalArgumentException("The class " + clazz.getName() + " has an @Service name of " + serviceName + " and has an @Named value of " + name + " which names do not match");
        }
    } else if (name == null && serviceName != null) {
        name = serviceName;
    }
    // Fixes the @Named qualifier if it has no value
    qualifiers = getAllQualifiers(clazz, name, collector);
    contracts = getAutoAdvertisedTypes(clazz);
    ScopeInfo scopeInfo = getScopeInfo(clazz, null, collector);
    scope = scopeInfo.getAnnoType();
    analyzerName = locator.getPerLocatorUtilities().getAutoAnalyzerName(clazz);
    creator = new ClazzCreator<T>(locator, clazz);
    Map<String, List<String>> metadata = new HashMap<String, List<String>>();
    if (serviceMetadata != null) {
        try {
            ReflectionHelper.readMetadataMap(serviceMetadata, metadata);
        } catch (IOException ioe) {
            // If we can not read it, someone else may have
            // a different metadata parser
            metadata.clear();
            ReflectionHelper.parseServiceMetadataString(serviceMetadata, metadata);
        }
    }
    collector.throwIfErrors();
    if (scopeInfo.getScope() != null) {
        BuilderHelper.getMetadataValues(scopeInfo.getScope(), metadata);
    }
    for (Annotation qualifier : qualifiers) {
        BuilderHelper.getMetadataValues(qualifier, metadata);
    }
    UseProxy useProxy = clazz.getAnnotation(UseProxy.class);
    if (useProxy != null) {
        proxy = useProxy.value();
    }
    ProxyForSameScope pfss = clazz.getAnnotation(ProxyForSameScope.class);
    if (pfss != null) {
        proxyForSameScope = pfss.value();
    }
    DescriptorVisibility visibility = DescriptorVisibility.NORMAL;
    Visibility vi = clazz.getAnnotation(Visibility.class);
    if (vi != null) {
        visibility = vi.value();
    }
    int rank = BuilderHelper.getRank(clazz);
    AutoActiveDescriptor<T> retVal = new AutoActiveDescriptor<T>(clazz, creator, contracts, scope, name, qualifiers, visibility, rank, proxy, proxyForSameScope, analyzerName, metadata, DescriptorType.CLASS, clazz);
    retVal.setScopeAsAnnotation(scopeInfo.getScope());
    creator.initialize(retVal, analyzerName, collector);
    collector.throwIfErrors();
    return retVal;
}
Also used : UseProxy(org.glassfish.hk2.api.UseProxy) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Service(org.jvnet.hk2.annotations.Service) DynamicConfigurationService(org.glassfish.hk2.api.DynamicConfigurationService) ErrorService(org.glassfish.hk2.api.ErrorService) ValidationService(org.glassfish.hk2.api.ValidationService) InterceptionService(org.glassfish.hk2.api.InterceptionService) ScopeInfo(org.glassfish.hk2.utilities.reflection.ScopeInfo) IOException(java.io.IOException) Annotation(java.lang.annotation.Annotation) DescriptorVisibility(org.glassfish.hk2.api.DescriptorVisibility) DescriptorType(org.glassfish.hk2.api.DescriptorType) Type(java.lang.reflect.Type) WildcardType(java.lang.reflect.WildcardType) ErrorType(org.glassfish.hk2.api.ErrorType) ParameterizedType(java.lang.reflect.ParameterizedType) ProxyForSameScope(org.glassfish.hk2.api.ProxyForSameScope) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) Visibility(org.glassfish.hk2.api.Visibility) DescriptorVisibility(org.glassfish.hk2.api.DescriptorVisibility)

Aggregations

Service (org.jvnet.hk2.annotations.Service)11 Test (org.testng.annotations.Test)7 List (java.util.List)4 Config (com.sun.enterprise.config.serverbeans.Config)2 PropertyVetoException (java.beans.PropertyVetoException)2 IOException (java.io.IOException)2 Annotation (java.lang.annotation.Annotation)2 Type (java.lang.reflect.Type)2 HashMap (java.util.HashMap)2 Level (java.util.logging.Level)2 Logger (java.util.logging.Logger)2 Inject (javax.inject.Inject)2 AnnotationProvider (org.apache.tapestry5.commons.AnnotationProvider)2 Contribute (org.apache.tapestry5.ioc.annotations.Contribute)2 TapestryIOCModule (org.apache.tapestry5.ioc.modules.TapestryIOCModule)2 AdminCommand (org.glassfish.api.admin.AdminCommand)2 RestEndpoint (org.glassfish.api.admin.RestEndpoint)2 RestEndpoints (org.glassfish.api.admin.RestEndpoints)2 ServerEnvironment (org.glassfish.api.admin.ServerEnvironment)2 DescriptorType (org.glassfish.hk2.api.DescriptorType)2