How to use dependency injection in an Enterprise application? From EAR module to WAR?
vinnywm Dec 6, 2012 9:49 AMI created a preset default Maven Enterprise Application in Netbeans and I'm trying inject in a class of the module war (web context) a DAO of EJB module (EJB context) and I can not.
A similar question is in https://community.jboss.org/message/725092#725092 and I already do all e already I've read about classloaders as mandated but could not yet.
I already have beans.xml in the WEB-INF directory of the web module and too in META-INF of ejb module.
Regra Class (ejb module):
@Stateless @LocalBean public class RegraDAO extends GenericDAO<Regra> implements VerificadorDeEntidades { @PersistenceContext(unitName = PersistenceUnitsUtil.UNIT_INTOUCH) private EntityManager em; QRegra REGRA = QRegra.regra; public RegraDAO() { super(Regra.class); } /** * Retorna o Set com o nome das de todas as permissões do conjunto de regras * repassado. * * @param roleNames Conjunto com nomes de regras. * @return Set com o nome das permissões. * @throws RegraException Em caso de erro lança essa exceção. */ // @Override public Set<String> getPermissoesDasRegras(Set<String> roleNames) throws RegraException { if (roleNames == null) { throw new RegraException("O valor rolesNames recebeu nulo," + " um conjunto de nomes de regras deve obrigatóriamente ser atribuído."); } Set<String> permissoesToString = null; List<Permissao> permissoesList = null; JPQLQuery query = new JPAQuery(getEntityManager()); //Pega o Set de permissões que pertence a regra e depois disto, //intera o Set de permissões pegando o nome das permissões. for (String regra : roleNames) { Object regras = query.from(REGRA).where(REGRA.nomeDaRegra.eq(regra)).list(REGRA.permissoes); if (regras != null && (regras instanceof List)) { permissoesList = (List<Permissao>) regras; permissoesToString = new HashSet<String>(); for (Permissao permissao : permissoesList) { permissoesToString.add(permissao.getNomeDaPermissao()); } } else { throw new RegraException("As permissões não foram encontradas para esta regra."); } } return permissoesToString; } /** * Verifica duplicidade de valores nos campos NOME. * * @param valor Valor a ser verificado * @return True se existe duplicidade, false para caso negativo. */ @Override public boolean verficaValorJaExistenteParaCamposRestritos(String valor) { boolean isExistente = false; try { JPQLQuery query = new JPAQuery(getEntityManager()); isExistente = query.from(REGRA).where(REGRA.nomeDaRegra.eq(valor)).exists(); } catch (Exception e) { Logger.getLogger(REGRA.getClass().getName()).log(Level.SEVERE, null, e); } return isExistente; } @Override protected EntityManager getEntityManager() { return em; } }
DatabaseRealm Class (web module):
public class DataBaseRealm extends AuthorizingRealm { @Inject private PessoaDAO pessoaDAO; //Continues NULL. @Inject private RegraDAO regraDAO; //Continues NULL. @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { //O CÓDIGO DESTE MÉTODO ESTÁ BEM DIDÁTICO //Se os principals (diretrizes identificadoras) forem null, isto //significa que os usernames são inválidos. if (principals == null) { throw new AuthorizationException("O argumento PrincipalCollection do método não podem ser null"); } String username = (String) getAvailablePrincipal(principals); Set<String> roleNames = null; Set<String> permissoesDasRegras = null; Set<String> permissoesAvulsasDePessoa = null; Set<String> todasAsPermissoes = null; try { //Adiquire regras e permissões do banco de dados. //Regras. roleNames = pessoaDAO.getRegrasDePessoaPeloLogin(username); //Permissões das regras. permissoesDasRegras = regraDAO.getPermissoesDasRegras(roleNames); //Permissões avulsas permissoesAvulsasDePessoa = pessoaDAO.getPermissoesDePessoaPeloLogin(username); //Junta todas as permissões. todasAsPermissoes = new HashSet<>(); todasAsPermissoes.addAll(permissoesDasRegras); todasAsPermissoes.addAll(permissoesAvulsasDePessoa); } catch (PessoaException | RegraException ex) { Logger.getLogger(DataBaseRealm.class.getName()).log(Level.SEVERE, null, ex); } SimpleAuthorizationInfo info = ((roleNames == null) || (roleNames.isEmpty())) ? new SimpleAuthorizationInfo() : new SimpleAuthorizationInfo(roleNames); info.setStringPermissions(todasAsPermissoes); return info; } /** * Retorna um * <code>AuthenticationInfo</code> para a classe * <code>AuthorizingRealm</code> poder completar o processo de autenticação. * ( * <code>Subject</code>) com suas * <code>Principals</code> e credenciais. * * @param token Um token contendo o nome de usuário e a senha para * avaliação. * @return Retorna um AuthenticationInfo. Este objeto representa um sujeito * do Realm em questão. * @throws AuthenticationException Retorna essa exceção caso entre em * condição de erro. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; String userName = usernamePasswordToken.getUsername(); //Nome de usuário inválido if (userName == null) { throw new AccountException("Nomes de usuário nulos não são permitidos neste reino."); } SaltedAuthenticationInfo info = null; try { //Tenta pegar a senha do login repassado String senha = pessoaDAO.getSenhaPeloLogin(userName); String salDaSenha = pessoaDAO.getSalDeSenhaPeloLogin(userName); ByteSource salt = new SimpleByteSource(Base64.decode(salDaSenha)); info = new SimpleAuthenticationInfo(userName, senha, salt, getName()); } catch (PessoaException ex) { Logger.getLogger(DataBaseRealm.class.getName()).log(Level.SEVERE, null, ex.getMessage()); } return info; } }
Here are the pom.xml of the modules:
MyProject.ear:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>SagaEnterpise</artifactId> <groupId>br.com.webbiz.saga</groupId> <version>1.0-SNAPSHOT</version> </parent> <groupId>br.com.webbiz.saga</groupId> <artifactId>SagaEnterpise-ear</artifactId> <version>1.0-SNAPSHOT</version> <packaging>ear</packaging> <name>SagaEnterpise-ear</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <netbeans.hint.deploy.server>gfv3ee6</netbeans.hint.deploy.server> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-ear-plugin</artifactId> <version>2.6</version> <configuration> <version>6</version> <defaultLibBundleDir>lib</defaultLibBundleDir> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>br.com.webbiz.saga</groupId> <artifactId>SagaEnterpise-ejb</artifactId> <version>1.0-SNAPSHOT</version> <type>ejb</type> </dependency> <dependency> <groupId>br.com.webbiz.saga</groupId> <artifactId>SagaEnterpise-web</artifactId> <version>1.0-SNAPSHOT</version> <type>war</type> </dependency> </dependencies> </project>
MyProject-ejb:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>SagaEnterpise</artifactId> <groupId>br.com.webbiz.saga</groupId> <version>1.0-SNAPSHOT</version> </parent> <groupId>br.com.webbiz.saga</groupId> <artifactId>SagaEnterpise-ejb</artifactId> <version>1.0-SNAPSHOT</version> <packaging>ejb</packaging> <name>SagaEnterpise-ejb</name> <properties> <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <netbeans.hint.deploy.server>gfv3ee6</netbeans.hint.deploy.server> <!-- VERSOES DE PROJETOS --> <querydsl.version>2.8.0</querydsl.version> <shiro.version>1.2.1</shiro.version> <mysql.version>5.1.21</mysql.version> <primefaces.version>3.4.2</primefaces.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.jboss.arquillian</groupId> <artifactId>arquillian-bom</artifactId> <version>1.0.2.Final</version> <scope>import</scope> <type>pom</type> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>eclipselink</artifactId> <version>2.3.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>javax.persistence</artifactId> <version>2.0.3</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId> <version>2.3.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.mysema.querydsl</groupId> <artifactId>querydsl-jpa</artifactId> <version>${querydsl.version}</version> <type>jar</type> </dependency> <dependency> <groupId>com.mysema.querydsl</groupId> <artifactId>querydsl-apt</artifactId> <version>${querydsl.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>org.primefaces</groupId> <artifactId>primefaces</artifactId> <version>${primefaces.version}</version> <type>jar</type> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> <type>jar</type> </dependency> <!-- JAVA EE API --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>6.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.arquillian.junit</groupId> <artifactId>arquillian-junit-container</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.2</version> </dependency> </dependencies> <profiles> <profile> <id>arquillian-glassfish-embedded</id> <activation> <activeByDefault>true</activeByDefault> </activation> <dependencies> <dependency> <groupId>org.jboss.arquillian.container</groupId> <artifactId>arquillian-glassfish-embedded-3.1</artifactId> <version>1.0.0.CR3</version> <scope>test</scope> </dependency> <dependency> <groupId>org.glassfish.main.extras</groupId> <artifactId>glassfish-embedded-all</artifactId> <version>3.1.2.2</version> <scope>provided</scope> </dependency> </dependencies> </profile> </profiles> <build> <resources> <resource> <targetPath>META-INF</targetPath> <directory>src</directory> <includes> <!--<include>**/*.xml</include>--> <include>jax-ws-catalog.xml</include> <!--<include>META-INF/persistence.xml</include>--> <include>wsdl/**</include> </includes> </resource> <resource> <targetPath>META-INF</targetPath> <directory>src/main/resources/META-INF</directory> <includes> <include>persistence.xml</include> <include>beans.xml</include> </includes> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> <compilerArguments> <endorseddirs>${endorsed.dir}</endorseddirs> </compilerArguments> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-ejb-plugin</artifactId> <version>2.3</version> <configuration> <ejbVersion>3.1</ejbVersion> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1.1</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.1</version> <executions> <execution> <phase>validate</phase> <goals> <goal>copy</goal> </goals> <configuration> <outputDirectory>${endorsed.dir}</outputDirectory> <silent>true</silent> <artifactItems> <artifactItem> <groupId>javax</groupId> <artifactId>javaee-endorsed-api</artifactId> <version>6.0</version> <type>jar</type> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> <plugin> <groupId>com.mysema.maven</groupId> <artifactId>apt-maven-plugin</artifactId> <version>1.0.6</version> <executions> <execution> <goals> <goal>process</goal> </goals> <configuration> <outputDirectory>target/generated-sources/java</outputDirectory> <processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.4</version> <configuration> <systemPropertyVariables> <java.util.logging.config.file>${basedir}/src/test/resources/logging.properties</java.util.logging.config.file> </systemPropertyVariables> </configuration> </plugin> <plugin> <groupId>org.jvnet.jax-ws-commons</groupId> <artifactId>jaxws-maven-plugin</artifactId> <version>2.2</version> <executions> <execution> <goals> <goal>wsimport</goal> </goals> <configuration> <wsdlFiles> <wsdlFile>GrepCep.xml.wsdl</wsdlFile> </wsdlFiles> <wsdlLocation>file:/home/vinicius/.netbeans/7.2/config/WebServices/GrepCep-xml/catalog/GrepCep.xml.wsdl</wsdlLocation> <staleFile>${project.build.directory}/jaxws/stale/GrepCep.xml.stale</staleFile> </configuration> <id>wsimport-generate-GrepCep.xml</id> <phase>generate-sources</phase> </execution> <execution> <goals> <goal>wsimport</goal> </goals> <configuration> <wsdlFiles> <wsdlFile>GrepCep.xml.wsdl</wsdlFile> </wsdlFiles> <wsdlLocation>file:/home/vinicius/.netbeans/7.2/config/WebServices/GrepCep-xml/catalog/GrepCep.xml.wsdl</wsdlLocation> <staleFile>${project.build.directory}/jaxws/stale/GrepCep.xml_1.stale</staleFile> </configuration> <id>wsimport-generate-GrepCep.xml_1</id> <phase>generate-sources</phase> </execution> </executions> <dependencies> <dependency> <groupId>javax.xml</groupId> <artifactId>webservices-api</artifactId> <version>1.4</version> </dependency> </dependencies> <configuration> <sourceDestDir>${project.build.directory}/generated-sources/jaxws-wsimport</sourceDestDir> <xnocompile>true</xnocompile> <verbose>true</verbose> <extension>true</extension> <catalog>${basedir}/src/jax-ws-catalog.xml</catalog> <target>2.0</target> </configuration> </plugin> </plugins> </build> <repositories> <repository> <id>JBoss</id> <name>JBoss Repository</name> <url>https://repository.jboss.org/nexus/content/groups/public/</url> </repository> <repository> <url>http://download.eclipse.org/rt/eclipselink/maven.repo/</url> <id>eclipselink</id> <layout>default</layout> <name>Repository for library EclipseLink (JPA 2.0)</name> </repository> <repository> <id>prime-repo</id> <name>PrimeFaces Maven Repository</name> <url>http://repository.primefaces.org</url> <layout>default</layout> </repository> </repositories> </project>
MyProject-war:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <artifactId>SagaEnterpise</artifactId> <groupId>br.com.webbiz.saga</groupId> <version>1.0-SNAPSHOT</version> </parent> <groupId>br.com.webbiz.saga</groupId> <artifactId>SagaEnterpise-web</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>SagaEnterpise-web</name> <properties> <shiro.version>1.2.1</shiro.version> <log4j.version>1.2.17</log4j.version> <primefaces.version>3.4.1</primefaces.version> <primefaces-extensions.version>0.6.1</primefaces-extensions.version> <slf4j-simple.version>1.7.2</slf4j-simple.version> <junit.version>4.10</junit.version> <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <netbeans.hint.deploy.server>gfv3ee6</netbeans.hint.deploy.server> </properties> <dependencies> <dependency> <groupId>br.com.webbiz.saga</groupId> <artifactId>SagaEnterpise-ejb</artifactId> <version>1.0-SNAPSHOT</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>6.0</version> <type>jar</type> <scope>provided</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>6.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.primefaces</groupId> <artifactId>primefaces</artifactId> <version>3.3</version> <type>jar</type> </dependency> <dependency> <groupId>org.primefaces.extensions</groupId> <artifactId>primefaces-extensions</artifactId> <version>${primefaces-extensions.version}</version> </dependency> <dependency> <groupId>org.primefaces.themes</groupId> <artifactId>humanity</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> <type>jar</type> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>${slf4j-simple.version}</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> <compilerArguments> <endorseddirs>${endorsed.dir}</endorseddirs> </compilerArguments> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1.1</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.1</version> <executions> <execution> <phase>validate</phase> <goals> <goal>copy</goal> </goals> <configuration> <outputDirectory>${endorsed.dir}</outputDirectory> <silent>true</silent> <artifactItems> <artifactItem> <groupId>javax</groupId> <artifactId>javaee-endorsed-api</artifactId> <version>6.0</version> <type>jar</type> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> </plugins> </build> <repositories> <repository> <url>http://repository.primefaces.org/</url> <id>primefaces</id> <layout>default</layout> <name>Repository for library PrimeFaces 3.2</name> </repository> </repositories> </project>
Guys, here is missing some setting? I'm using Glassfish 3.1.2 (I can attach the application case would anyone want to help me in a more direct way).
Excuse me for any grammatical error committed, I'm Brazilian.
Thanks for all.
The Maven Project was attached.
-
SagaEnterpise.rar.zip 635.5 KB