Quantcast
Channel: DevOps tips & tricks
Viewing all articles
Browse latest Browse all 181

Load application configuration using CDI on Weblogic 12c

$
0
0
Testing this solution on Weblogic 12c
http://weblogs.java.net/blog/jjviana/archive/2010/05/18/applicaction-configuration-java-ee-6-using-cdi-simple-example

Deployed EJB module requires beans.xml file on META-INF
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>


Annotation Config
package dave;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.inject.Qualifier;

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface Config {
 
}

Configuration factory
package dave;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;

public class ConfigurationFactory {

    private volatile static Properties configProperties;
    public static final String propertiesFilePath = "/application.properties";

    public synchronized static Properties getProperties() {

        if (configProperties == null) {
            configProperties = new Properties();
            try {
                InputStream is = ConfigurationFactory.class.getResourceAsStream(propertiesFilePath);
                System.out.println("Found resource file" + (is != null));
                configProperties.load(is);
            } catch (IOException ex) {
                Logger.getLogger(ConfigurationFactory.class.getName()).log(
                        Level.SEVERE, null, ex);
                throw new RuntimeException(ex);
            }

        }

        return configProperties;
    }

    public @Produces
    @Config
    String getConfiguration(InjectionPoint p) {

        String configKey = p.getMember().getDeclaringClass().getName() + "."
                + p.getMember().getName();
        Properties config = getProperties();
        if (config.getProperty(configKey) == null) {
            configKey = p.getMember().getDeclaringClass().getSimpleName() + "."
                    + p.getMember().getName();
            if (config.getProperty(configKey) == null)
                configKey = p.getMember().getName();
        }
        System.err.println("Config key= " + configKey + " value = "
                + config.getProperty(configKey));

        return config.getProperty(configKey);
    }

    public @Produces
    @Config
    Double getConfigurationDouble(InjectionPoint p) {

        String val = getConfiguration(p);
        return Double.parseDouble(val);

    }

}


Test Facade
package dave;

import javax.ejb.EJB;
import javax.ejb.Stateless;

/**
 * Session Bean implementation class TestFacade
 */
@Stateless(mappedName = "TestFacade")
public class TestFacade implements TestFacadeRemote {

    @EJB
    TestStateless stateless;

    public String getServerAddress() {
        return stateless.getServerAddress();
    }

}

Facade Remote interface
package dave;

import javax.ejb.Remote;

@Remote
public interface TestFacadeRemote {

public String getServerAddress();

}


EJB client calling facade
Client requires  /opt/weblogic/wlserver_12.1/server/lib/wlthint3client.jar on CLASSPATH
package dave;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class TestEJBClient {

    /**
     * @param args
     */
    public static void main(String[] args) {
       
        try {
            Properties props = new Properties();
            props.put(Context.PROVIDER_URL, "t3://localhost:7001");
            props.put(Context.INITIAL_CONTEXT_FACTORY,
                    "weblogic.jndi.WLInitialContextFactory");
            Context ctx = new InitialContext(props);
            TestFacadeRemote facade = (TestFacadeRemote) ctx.lookup("TestFacade#dave.TestFacadeRemote");
           
            System.out.println(facade.getServerAddress());
           
        } catch (NamingException e) {
            e.printStackTrace();
        }

    }

}



Loading configuration value in application class
package dave;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.inject.Inject;

/**
 * Session Bean implementation class TestStateless
 */
@Stateless(mappedName = "TestStateless")
@LocalBean
public class TestStateless {

    @Inject @Config
    private String serverAddress;
   
    public String getServerAddress() {
        return serverAddress;
    }
   

}


Output in Weblogic server log
Found resource filetrue
Config key= serverAddress value = dave

Test with plain Java class
package dave;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;


@ApplicationScoped
public class TestBean {
   
    @Inject @Config
    private String serverAddress;
   
    public String getServerAddress() {
        return serverAddress;
    }

}

Added call to plain class
package dave;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;

/**
 * Session Bean implementation class TestFacade
 */
@Stateless(mappedName = "TestFacade")
public class TestFacade implements TestFacadeRemote {

    @EJB
    TestStateless stateless;
   
    @Inject
    TestBean testBean;

    public String getServerAddress() {
       
        System.out.println("get value from testbean " + testBean.getServerAddress());
       
        System.out.println("get value from testbean " + testBean.getServerAddress());
       
        System.out.println("get value from stateless " + stateless.getServerAddress());
       
        System.out.println("get value from stateless " + stateless.getServerAddress());
       
        return stateless.getServerAddress();
    }

}


Output in Weblogic log
Found resource filetrue
Config key= serverAddress value = dave
get value from testbean dave
get value from testbean dave
Config key= serverAddress value = dave
get value from stateless dave
get value from stateless dave



Exception when config file is not found
Exception in thread "main" javax.ejb.EJBTransactionRolledbackException: EJB Exception: 
    at weblogic.ejb.container.internal.BaseLocalObject.handleSystemException(BaseLocalObject.java:453)
    at weblogic.ejb.container.internal.BaseLocalObject.getBeanInstance(BaseLocalObject.java:166)
    at weblogic.ejb.container.internal.BaseLocalObject.preInvoke(BaseLocalObject.java:103)
    at weblogic.ejb.container.internal.BaseLocalObject.__WL_preInvoke(BaseLocalObject.java:67)
    at weblogic.ejb.container.internal.SessionLocalMethodInvoker.invoke(SessionLocalMethodInvoker.java:20)
    at dave.TestStateless_954dmo_NoIntfViewImpl.getServerAddress(Unknown Source)
    at dave.TestFacade.getServerAddress(TestFacade.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.bea.core.repackaged.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
    at com.oracle.pitchfork.intercept.MethodInvocationInvocationContext.proceed(MethodInvocationInvocationContext.java:103)
    at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.oracle.pitchfork.intercept.JeeInterceptorInterceptor.invoke(JeeInterceptorInterceptor.java:108)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
    at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at com.bea.core.repackaged.springframework.aop.framework.JdkDynamicAopProxy.invoke(Unknown Source)
    at $Proxy111.getServerAddress(Unknown Source)
    at dave.TestFacade_23kp48_TestFacadeRemoteImpl.__WL_invoke(Unknown Source)
    at weblogic.ejb.container.internal.SessionRemoteMethodInvoker.invoke(SessionRemoteMethodInvoker.java:32)
    at dave.TestFacade_23kp48_TestFacadeRemoteImpl.getServerAddress(Unknown Source)
    at dave.TestFacade_23kp48_TestFacadeRemoteImpl_WLSkel.invoke(Unknown Source)
    at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:695)
    at weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:230)
    at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:520)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
    at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:516)
    at weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
Caused by: java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:418)
    at java.util.Properties.load0(Properties.java:337)
    at java.util.Properties.load(Properties.java:325)
    at dave.ConfigurationFactory.getProperties(ConfigurationFactory.java:22)
    at dave.ConfigurationFactory.getConfiguration(ConfigurationFactory.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:264)
    at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:52)
    at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:137)
    at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:260)
    at org.jboss.weld.introspector.jlr.WeldMethodImpl.invokeOnInstance(WeldMethodImpl.java:170)
    at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstance(MethodInjectionPoint.java:137)
    at org.jboss.weld.bean.ProducerMethod$1.produce(ProducerMethod.java:132)
    at org.jboss.weld.bean.AbstractProducerBean.create(AbstractProducerBean.java:299)
    at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:61)
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:630)
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:691)
    at org.jboss.weld.injection.FieldInjectionPoint.inject(FieldInjectionPoint.java:118)
    at org.jboss.weld.util.Beans.injectBoundFields(Beans.java:691)
    at org.jboss.weld.util.Beans.injectFieldsAndInitializers(Beans.java:700)
    at org.jboss.weld.bean.SessionBean$1$1.proceed(SessionBean.java:175)
    at com.oracle.injection.provider.weld.WeldInjectionServicesAdapter.aroundInject(WeldInjectionServicesAdapter.java:88)
    at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:45)
    at org.jboss.weld.bean.SessionBean$1.inject(SessionBean.java:172)
    at com.oracle.injection.provider.weld.WeldEjbBeanManager$ExtendedInjectionTarget.inject(WeldEjbBeanManager.java:119)
    at com.oracle.injection.provider.weld.WeldEjbBeanManager.newBeanInstance(WeldEjbBeanManager.java:82)
    at weblogic.ejb.container.injection.InjectionBasedEjbComponentCreator.getBean(InjectionBasedEjbComponentCreator.java:75)
    at weblogic.ejb.container.manager.BaseEJBManager.createNewBeanInstance(BaseEJBManager.java:209)
    at weblogic.ejb.container.manager.BaseEJBManager.allocateBean(BaseEJBManager.java:235)
    at weblogic.ejb.container.manager.StatelessManager.createBean(StatelessManager.java:293)
    at weblogic.ejb.container.pool.StatelessSessionPool.createBean(StatelessSessionPool.java:185)
    at weblogic.ejb.container.pool.StatelessSessionPool.getBean(StatelessSessionPool.java:114)
    at weblogic.ejb.container.manager.StatelessManager.preInvoke(StatelessManager.java:174)
    at weblogic.ejb.container.internal.BaseLocalObject.getBeanInstance(BaseLocalObject.java:146)
    ... 38 more

Viewing all articles
Browse latest Browse all 181

Trending Articles