Commit 0de6a9d87e12029af1d7c9a883e36f46f2f461f9
Exists in
master
Merge branch '2.4.0' of git@github.com:demoiselle/framework.git into 2.4.0
Showing
37 changed files
with
1673 additions
and
877 deletions
Show diff stats
documentation/reference/pt-BR/gerenciamento.xml
1 | <?xml version='1.0' encoding="utf-8"?> | 1 | <?xml version='1.0' encoding="utf-8"?> |
2 | <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" | 2 | <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" |
3 | "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" []> | 3 | "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" []> |
4 | -<chapter id="mensagem"> | 4 | +<chapter id="gerenciamento"> |
5 | 5 | ||
6 | <title>Monitoração e Gerenciamento de Recursos</title> | 6 | <title>Monitoração e Gerenciamento de Recursos</title> |
7 | 7 | ||
@@ -32,31 +32,179 @@ | @@ -32,31 +32,179 @@ | ||
32 | anotada com o estereótipo <code>@ManagementController</code>.</para> | 32 | anotada com o estereótipo <code>@ManagementController</code>.</para> |
33 | 33 | ||
34 | <programlisting role="JAVA"><![CDATA[ | 34 | <programlisting role="JAVA"><![CDATA[ |
35 | - @ManagementController | ||
36 | - public class GerenciadorUsuarios]]></programlisting> | 35 | +@ManagementController |
36 | +public class GerenciadorUsuarios]]></programlisting> | ||
37 | 37 | ||
38 | <para>Essa anotação é suficiente para o mecanismo de gerenciamento descobrir sua classe e disponibiliza-la para ser monitorada e gerenciada.</para> | 38 | <para>Essa anotação é suficiente para o mecanismo de gerenciamento descobrir sua classe e disponibiliza-la para ser monitorada e gerenciada.</para> |
39 | 39 | ||
40 | <para>Contudo, a simples anotação acima não informa ao mecanismo quais aspectos da classe serão expostos. Por padrão, um <emphasis>Management Controller</emphasis> | 40 | <para>Contudo, a simples anotação acima não informa ao mecanismo quais aspectos da classe serão expostos. Por padrão, um <emphasis>Management Controller</emphasis> |
41 | - não expõe nenhum aspecto seu. Para selecionais quais aspectos serão expostos usamos as anotações <code>@ManagedProperty</code> e <code>@ManagedOperation</code>.</para> | ||
42 | - | ||
43 | - <table> | ||
44 | - <tbody> | ||
45 | - <row> | ||
46 | - <entry> | ||
47 | - <emphasis role="BOLD">@ManagedProperty</emphasis> | ||
48 | - </entry> | ||
49 | - </row> | ||
50 | - | ||
51 | - <row> | ||
52 | - <entry> | ||
53 | - <para>Marca um atributo na classe como uma propriedade gerenciada, significando que clientes externos podem ler e/ou escrever valores nesses atributos.</para> | ||
54 | - <para>Um</para> | ||
55 | - </entry> | ||
56 | - </row> | ||
57 | - </tbody> | ||
58 | - </table> | 41 | + não expõe nenhum aspecto seu. Para selecionar quais aspectos serão expostos usamos as anotações |
42 | + <emphasis>@ManagedProperty</emphasis> e <emphasis>@ManagedOperation</emphasis>. Além disso outras anotações podem ser usadas para personalizar o funcionamento | ||
43 | + de classes anotadas com <code>@ManagementController</code>.</para> | ||
59 | 44 | ||
45 | + <informaltable> | ||
46 | + <tgroup cols="3"> | ||
47 | + <thead> | ||
48 | + <row> | ||
49 | + <entry>Anotação</entry> | ||
50 | + <entry>Descrição</entry> | ||
51 | + <entry>Atributos</entry> | ||
52 | + </row> | ||
53 | + </thead> | ||
54 | + | ||
55 | + <tbody> | ||
56 | + <row> | ||
57 | + <entry> | ||
58 | + <emphasis role="BOLD">@ManagedProperty</emphasis> | ||
59 | + </entry> | ||
60 | + | ||
61 | + <entry> | ||
62 | + <para>Marca um atributo na classe como uma propriedade gerenciada, significando que clientes externos podem ler e/ou escrever valores nesses atributos.</para> | ||
63 | + <para>Um atributo marcado pode estar disponível para leitura e/ou escrita. Por padrão, o que determina a visibilidade de um atributo | ||
64 | + marcado é a presença dos métodos <emphasis>getAtributo</emphasis> e <emphasis>setAtributo</emphasis>, respectivamente disponibilizando o atributo | ||
65 | + para leitura e escrita.</para> | ||
66 | + <para>Para sobrescrever esse comportamento existe na anotação <emphasis role="BOLD">@ManagedProperty</emphasis> o atributo <emphasis>accessLevel</emphasis>. | ||
67 | + Com ele é possível criar um atributo apenas para leitura, mas que contenha um método <emphasis>set</emphasis>. O contrário também é possível.</para> | ||
68 | + </entry> | ||
69 | + | ||
70 | + <entry> | ||
71 | + <itemizedlist> | ||
72 | + <listitem><emphasis role="BOLD">description</emphasis>: Um texto descritivo documentando o propósito da propriedade.</listitem> | ||
73 | + <listitem><emphasis role="BOLD">accessLevel</emphasis>: Sobrescreve o nível padrão de acesso de uma propriedade. Os valores possíveis são | ||
74 | + READ_ONLY, WRITE_ONLY e DEFAULT, que significa que a presença de métodos <emphasis>get</emphasis> e <emphasis>set</emphasis> vai determinar o nível de acesso.</listitem> | ||
75 | + </itemizedlist> | ||
76 | + </entry> | ||
77 | + </row> | ||
78 | + | ||
79 | + <row> | ||
80 | + <entry> | ||
81 | + <emphasis role="BOLD">@ManagedOperation</emphasis> | ||
82 | + </entry> | ||
83 | + | ||
84 | + <entry> | ||
85 | + <para>Marca um método da classe gerenciada como uma operação, o que significa que clientes externos podem invocar esse método remotamente.</para> | ||
86 | + <para>Operações gerenciadas normalmente são criadas para executar intervenções em um sistema já em execução. Por exemplo, é possível criar uma | ||
87 | + operação que, ao ser invocada, destrua todas as seções abertas no servidor e não utilizadas nos últimos 30 minutos.</para> | ||
88 | + </entry> | ||
89 | + | ||
90 | + <entry> | ||
91 | + <itemizedlist> | ||
92 | + <listitem><emphasis role="BOLD">description</emphasis>: Um texto descritivo documentando o propósito da operação.</listitem> | ||
93 | + <listitem><emphasis role="BOLD">type</emphasis>: Documenta o propósito da operação. <emphasis>ACTION</emphasis> informa que a operação modificará | ||
94 | + o sistema de alguma forma. <emphasis>INFO</emphasis> diz que a operação coletará e retornará informações sobre o sistema. <emphasis>ACTION_INFO</emphasis> | ||
95 | + informa que a operação modificará o sistema de alguma forma e retornará informações sobre o resultado. <emphasis>UNKNOWN</emphasis> é o padrão | ||
96 | + e significa que o resultado da execução da operação é desconhecido.</listitem> | ||
97 | + </itemizedlist> | ||
98 | + </entry> | ||
99 | + </row> | ||
100 | + | ||
101 | + <row> | ||
102 | + <entry> | ||
103 | + <emphasis role="BOLD">@OperationParameter</emphasis> | ||
104 | + </entry> | ||
105 | + | ||
106 | + <entry> | ||
107 | + <para>Esta anotação opcional pode ser usada para cada parâmetro de um método anotado com <emphasis role="BOLD">@ManagedOperation</emphasis>.</para> | ||
108 | + | ||
109 | + <para>Ele permite detalhar melhor parâmetros em uma operação gerenciada. O efeito desta anotação é dependente da | ||
110 | + tecnologia utilizada para comunicação entre cliente e servidor. Na maioria das tecnologias, essa anotação meramente permite ao cliente | ||
111 | + exibir informações sobre cada parâmetro: nome, tipo e descrição.</para> | ||
112 | + </entry> | ||
113 | + | ||
114 | + <entry> | ||
115 | + <itemizedlist> | ||
116 | + <listitem><emphasis role="BOLD">name</emphasis>: O nome do parâmetro quando exibido para clientes.</listitem> | ||
117 | + <listitem><emphasis role="BOLD">description</emphasis>: Um texto descritivo documentando o propósito do parâmetro.</listitem> | ||
118 | + </itemizedlist> | ||
119 | + </entry> | ||
120 | + </row> | ||
121 | + </tbody> | ||
122 | + </tgroup> | ||
123 | + </informaltable> | ||
124 | + | ||
125 | + </section> | ||
126 | + | ||
127 | + | ||
128 | + | ||
129 | + <section> | ||
130 | + <title>Expondo aspectos de sua aplicação para monitoração</title> | ||
131 | + | ||
132 | + <para>Uma vez que uma classe esteja anotada com <emphasis>@ManagementController</emphasis> e seus atributos e operações estejam expostos, a classe está pronta para | ||
133 | + ser monitorada.</para> | ||
134 | + | ||
135 | + <para>Suponha que a aplicação deseje expor o número de usuários que efetuaram login. A operação de <emphasis>login</emphasis> será processada em | ||
136 | + uma classe de negócio <emphasis>ControleAcesso</emphasis>. Vamos supor também que existe uma classe chamada <emphasis>MonitorLogin</emphasis> responsável | ||
137 | + por expor o número de usuários que efetuaram login no sistema.</para> | ||
138 | + | ||
139 | + <programlisting role="JAVA"><![CDATA[ | ||
140 | +@BusinessController | ||
141 | +public class ControleAcesso{ | ||
142 | + | ||
143 | + @Inject | ||
144 | + private MonitorLogin monitorLogin; | ||
145 | + | ||
146 | + public boolean efetuarLogin(String usuario , String senha){ | ||
147 | + // codigo de login | ||
148 | + monitorLogin.setContadorLogin( monitorLogin.getContadorLogin() + 1 ); | ||
149 | + } | ||
150 | +}]]></programlisting> | ||
151 | + | ||
152 | + <para>Como é possível ver, classes anotadas com <emphasis>@ManagementController</emphasis> podem ser injetadas em qualquer ponto do código. Valores definidos | ||
153 | + para seus atributos retêm seu estado, então um cliente que acesse remotamente o sistema e monitore o valor do atributo <emphasis>contadorLogin</emphasis> verá | ||
154 | + a quantidade de logins efetuados no momento da consulta.</para> | ||
60 | </section> | 155 | </section> |
156 | + | ||
157 | + <section> | ||
158 | + <title>Conectando um cliente de monitoração</title> | ||
159 | + | ||
160 | + <para>O <emphasis>demoiselle-core</emphasis> contém as funcionalidades necessárias para marcar aspectos monitoráveis de sua aplicação, | ||
161 | + mas não conta com nenhum mecanismo para estabelecer uma conexão com um cliente de monitoração. Para isso utiliza-se extensões do framework.</para> | ||
162 | + | ||
163 | + <para>A extensão padrão do framework <emphasis>Demoiselle</emphasis> responsável pela tecnologia de monitoração é a <emphasis>demoiselle-jmx</emphasis>. | ||
164 | + Essa extensão utiliza a especificação JMX (JSR 3) e permite registrar as classes marcadas para monitoração como <emphasis>MBeans</emphasis>. | ||
165 | + Uma vez que as classes sejam registradas como <emphasis>MBeans</emphasis>, seus atributos e operações expostos para monitoração podem ser | ||
166 | + acessados via JMX por um cliente adequado, como o <emphasis>JConsole</emphasis> que acompanha por padrão o JDK da Oracle.</para> | ||
167 | + | ||
168 | + <tip> | ||
169 | + <para>Para acrescentar a extensão <emphasis>demoiselle-jmx</emphasis> em um projeto Maven, adicione a dependência abaixo no arquivo <emphasis>pom.xml</emphasis>.</para> | ||
170 | + | ||
171 | + <programlisting role="XML"><![CDATA[ | ||
172 | +<dependency> | ||
173 | + <groupId>br.gov.frameworkdemoiselle</groupId> | ||
174 | + <artifactId>demoiselle-jmx</artifactId> | ||
175 | + <scope>compile</scope> | ||
176 | +</dependency>]]></programlisting> | ||
177 | + </tip> | ||
178 | + | ||
179 | + <tip> | ||
180 | + <para>A API de monitoração é compatível com o uso de múltiplas extensões simultãneas. Adicione em seu projeto a dependência às extensões desejadas e configure-as | ||
181 | + individualmente, as classes monitoradas serão então expostas para todas as extensões escolhidas.</para> | ||
182 | + </tip> | ||
183 | + | ||
184 | + <para>A figura <xref linkend="exemplo_jconsole"/> mostra como uma classe monitorada na aplicação <emphasis>Bookmark</emphasis> é exibida no <emphasis>JConsole</emphasis>.</para> | ||
185 | + | ||
186 | + <programlisting role="JAVA"><![CDATA[ | ||
187 | +@ManagementController | ||
188 | +public class BookmarkMonitor { | ||
189 | + | ||
190 | + @Inject | ||
191 | + private BookmarkDAO bookmarkDAO; | ||
192 | + | ||
193 | + @ManagedOperation(type=OperationType.INFO , description="Informa quantos bookmarks estao salvos no sistema") | ||
194 | + public int countSavedBookmarks(){ | ||
195 | + return bookmarkDAO.findAll().size(); | ||
196 | + } | ||
197 | +}]]></programlisting> | ||
198 | + | ||
199 | + <figure id="exemplo_jconsole"><title>JConsole acessando a aplicação <emphasis>Bookmark</emphasis></title> | ||
200 | + <mediaobject> | ||
201 | + <imageobject> | ||
202 | + <imagedata fileref="images/jmx-jconsole-example.png" width="90%" /> | ||
203 | + </imageobject> | ||
204 | + <textobject><phrase>JConsole acessando a aplicação <emphasis>Bookmark</emphasis></phrase></textobject> | ||
205 | + </mediaobject> | ||
206 | + </figure> | ||
207 | + </section> | ||
208 | + | ||
61 | 209 | ||
62 | </chapter> | 210 | </chapter> |
63 | \ No newline at end of file | 211 | \ No newline at end of file |
290 KB
documentation/reference/pt-BR/master.xml
@@ -39,7 +39,9 @@ | @@ -39,7 +39,9 @@ | ||
39 | <xi:include href="templates.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> | 39 | <xi:include href="templates.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> |
40 | <xi:include href="security.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> | 40 | <xi:include href="security.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> |
41 | <xi:include href="paginacao.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> | 41 | <xi:include href="paginacao.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> |
42 | - <xi:include href="properties.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> | 42 | + <xi:include href="gerenciamento.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> |
43 | + <!-- | ||
44 | + <xi:include href="properties.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> --> | ||
43 | 45 | ||
44 | <!-- parte 1 --> | 46 | <!-- parte 1 --> |
45 | <!-- TODO: dividir melhor os capítulos em seções --> | 47 | <!-- TODO: dividir melhor os capítulos em seções --> |
@@ -74,5 +76,6 @@ | @@ -74,5 +76,6 @@ | ||
74 | 76 | ||
75 | <!-- apêndices --> | 77 | <!-- apêndices --> |
76 | <xi:include href="instalacao.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> | 78 | <xi:include href="instalacao.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> |
79 | + <xi:include href="properties.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> | ||
77 | 80 | ||
78 | </book> | 81 | </book> |
documentation/reference/pt-BR/persistencia.xml
@@ -4,72 +4,250 @@ | @@ -4,72 +4,250 @@ | ||
4 | <chapter id="persistencia"> | 4 | <chapter id="persistencia"> |
5 | 5 | ||
6 | <title>Persistência</title> | 6 | <title>Persistência</title> |
7 | + | ||
8 | + <para> | ||
9 | + Persistência é um dos aspectos mais importantes de sistemas corporativos - grande parte desses sistemas devem | ||
10 | + em algum ponto persistir informações em um sistema gerenciador de banco de dados. A tecnologia Java conta | ||
11 | + hoje com algumas formas de facilitar o acesso a SGBD's - algumas são especificações Java como o JDBC | ||
12 | + e o JPA, outras são tecnologias desenvolvidas por terceiros como o Hibernate. | ||
13 | + </para> | ||
14 | + | ||
15 | + <para> | ||
16 | + O Framework Demoiselle facilita o acesso e a configuração a algumas dessas tecnologias fornecendo produtores | ||
17 | + padrão para seus pontos de entrada e centralizando a configuração. Tudo que o desenvolvedor deve fazer | ||
18 | + é apenas injetar o recurso adequado em seu código e o Framework Demoiselle se encarregará de | ||
19 | + produzi-lo e configurá-lo. | ||
20 | + </para> | ||
7 | 21 | ||
8 | <section> | 22 | <section> |
23 | + | ||
9 | <title>JDBC</title> | 24 | <title>JDBC</title> |
25 | + | ||
26 | + <para> | ||
27 | + O Framework Demoiselle fornece um produtor padrão para conexões JDBC puras. Esse produtor possui suporte | ||
28 | + ao acesso direto utilizando uma URL e ao acesso via <code>DataSource</code>, acessando a conexão através | ||
29 | + de um nome <code>JNDI</code> configurado em um servidor de aplicação. | ||
30 | + </para> | ||
31 | + | ||
10 | <para> | 32 | <para> |
11 | - A persistência de dados usando JDBC, está disponível na extensão <literal>demoiselle-jdbc</literal>, | ||
12 | - que provê uma fábrica de <literal>Connection</literal>. Para utilizá-la basta incluir a dependência para extensão JDBC | ||
13 | - no arquivo pom.xml. | 33 | + A persistência de dados usando JDBC está disponível na extensão <literal>demoiselle-jdbc</literal>. Para ter acesso |
34 | + a essa extensão em um projeto Maven declare sua dependência no arquivo <literal>pom.xml</literal> de seu projeto. | ||
14 | </para> | 35 | </para> |
15 | - <programlisting role="XML"><![CDATA[<dependency> | 36 | + |
37 | + <tip> | ||
38 | + <para> | ||
39 | + Para acrescentar a dependência à extensão <literal>demoiselle-jdbc</literal>, adicione esse código | ||
40 | + em seu arquivo <literal>pom.xml</literal>, na seção <literal>dependencies</literal>. | ||
41 | + </para> | ||
42 | + | ||
43 | + <programlisting role="XML"><![CDATA[<dependency> | ||
16 | <groupId>br.gov.frameworkdemoiselle</groupId> | 44 | <groupId>br.gov.frameworkdemoiselle</groupId> |
17 | <artifactId>demoiselle-jdbc</artifactId> | 45 | <artifactId>demoiselle-jdbc</artifactId> |
18 | <scope>compile</scope> | 46 | <scope>compile</scope> |
19 | -</dependency>]]> | ||
20 | - </programlisting> | 47 | +</dependency>]]></programlisting> |
48 | + </tip> | ||
49 | + | ||
50 | + <section> | ||
51 | + <title>Configuração</title> | ||
21 | 52 | ||
22 | - <para> | ||
23 | - Para obter uma instância de uma conexão, basta injetá-la na classe: | ||
24 | - </para> | ||
25 | - <programlisting role="JAVA"><![CDATA[@Inject | ||
26 | -private Connection conn;]]></programlisting> | ||
27 | - <para> | ||
28 | - A conexão será criada pela fábrica do Demoiselle de acordo com as configurações no arquivo de propriedade (<emphasis>demoiselle.properties</emphasis>). | ||
29 | - </para> | ||
30 | - <para> | ||
31 | - Você pode configurar as propriedades da conexão: | ||
32 | - </para> | ||
33 | - <programlisting>frameworkdemoiselle.persistence.driver.class=MeuDriver | ||
34 | -frameworkdemoiselle.persistence.url=MinhaUrl | ||
35 | -frameworkdemoiselle.persistence.username=MeuUsername | ||
36 | -frameworkdemoiselle.persistence.password=MeuPassword</programlisting> | ||
37 | - <para> | ||
38 | - ou indicar o JNDI do datasource: | ||
39 | - </para> | ||
40 | - <programlisting>frameworkdemoiselle.persistence.jndi.name=MeuJndiName</programlisting> | 53 | + <para> |
54 | + A conexão será criada pela fábrica do Demoiselle de acordo com as configurações no arquivo de propriedade (<emphasis>demoiselle.properties</emphasis>). | ||
55 | + Para configurar uma conexão diretamente através de uma URL utilize as propriedades abaixo: | ||
56 | + </para> | ||
57 | + | ||
58 | + <informaltable width="100%"> | ||
59 | + <tgroup cols="2"> | ||
60 | + <colspec align="left"/> | ||
61 | + <colspec align="left"/> | ||
62 | + | ||
63 | + <thead> | ||
64 | + <row valign="top"> | ||
65 | + <entry><emphasis role="bold">Propriedade</emphasis></entry> | ||
66 | + <entry><emphasis role="bold">Descrição</emphasis></entry> | ||
67 | + </row> | ||
68 | + </thead> | ||
69 | + | ||
70 | + <tbody> | ||
71 | + <row valign="top"> | ||
72 | + <entry>frameworkdemoiselle.​persistence.​driver.​class</entry> | ||
73 | + <entry> | ||
74 | + <para> | ||
75 | + Implementação da interface <code>java.sql.Driver</code> que dá acesso | ||
76 | + ao SGBD utilizado pela aplicação. | ||
77 | + </para> | ||
78 | + </entry> | ||
79 | + </row> | ||
80 | + | ||
81 | + <row valign="top"> | ||
82 | + <entry>frameworkdemoiselle.​persistence.​url</entry> | ||
83 | + <entry> | ||
84 | + <para> | ||
85 | + URL de conexão no formato <code>jdbc:vendor:database-properties</code>. | ||
86 | + </para> | ||
87 | + </entry> | ||
88 | + </row> | ||
89 | + | ||
90 | + <row valign="top"> | ||
91 | + <entry>frameworkdemoiselle.​persistence.​username</entry> | ||
92 | + <entry> | ||
93 | + <para> | ||
94 | + Login de acesso ao SGBD. | ||
95 | + </para> | ||
96 | + </entry> | ||
97 | + </row> | ||
98 | + | ||
99 | + <row valign="top"> | ||
100 | + <entry>frameworkdemoiselle.​persistence.​password</entry> | ||
101 | + <entry> | ||
102 | + <para> | ||
103 | + Senha de acesso ao SGBD. | ||
104 | + </para> | ||
105 | + </entry> | ||
106 | + </row> | ||
107 | + </tbody> | ||
108 | + </tgroup> | ||
109 | + </informaltable> | ||
110 | + | ||
111 | + <para> | ||
112 | + Também é possível configurar o acesso indicando um nome <code>JNDI</code> que esteja | ||
113 | + configurado no servidor de aplicação. | ||
114 | + </para> | ||
115 | + | ||
116 | + <informaltable width="100%"> | ||
117 | + <tgroup cols="2"> | ||
118 | + <colspec align="left"/> | ||
119 | + <colspec align="left"/> | ||
120 | + | ||
121 | + <thead> | ||
122 | + <row valign="top"> | ||
123 | + <entry><emphasis role="bold">Propriedade</emphasis></entry> | ||
124 | + <entry><emphasis role="bold">Descrição</emphasis></entry> | ||
125 | + </row> | ||
126 | + </thead> | ||
127 | + | ||
128 | + <tbody> | ||
129 | + <row valign="top"> | ||
130 | + <entry>frameworkdemoiselle.​persistence.​jndi.​name</entry> | ||
131 | + <entry> | ||
132 | + <para> | ||
133 | + Nome <code>JNDI</code> criado no servidor de aplicação para dar acesso | ||
134 | + à conexão ao banco de dados. | ||
135 | + </para> | ||
136 | + </entry> | ||
137 | + </row> | ||
138 | + </tbody> | ||
139 | + </tgroup> | ||
140 | + </informaltable> | ||
141 | + | ||
142 | + <para> | ||
143 | + É possível configurar mais de uma conexão JDBC. Para isso acrescente nas propriedades nomes | ||
144 | + separados para cada conexão como no exemplo abaixo: | ||
145 | + </para> | ||
146 | + | ||
147 | + <example> | ||
148 | + <title>Criando múltiplas conexões</title> | ||
149 | + | ||
150 | + <programlisting>frameworkdemoiselle.​persistence.​<emphasis role="bold">conn1</emphasis>.​driver.​class=MinhaClasse | ||
151 | +frameworkdemoiselle.​persistence.​<emphasis role="bold">conn1</emphasis>.​url=MinhaURL | ||
152 | +frameworkdemoiselle.​persistence.​<emphasis role="bold">conn1</emphasis>.​username=MeuLogin | ||
153 | +frameworkdemoiselle.​persistence.​<emphasis role="bold">conn1</emphasis>.​password=MinhaSenha | ||
41 | 154 | ||
42 | - <para> | ||
43 | - Caso você necessite usar conexões com datasources diferentes, você pode usar a anotoção | ||
44 | - <literal>@Name</literal> passando como valor o nome da conexão definida no arquivo | ||
45 | - <literal>demoiselle.properties</literal> | ||
46 | - </para> | ||
47 | - | ||
48 | - <para> | ||
49 | - No <literal>demoiselle.properties</literal> basta adicionar um nome qualquer para identificar a conexão: | ||
50 | - </para> | ||
51 | - <programlisting>frameworkdemoiselle.persistence.conn1.jndi.name=MeuJndiName1 | ||
52 | -frameworkdemoiselle.persistence.conn2.jndi.name=MeuJndiName2</programlisting> | ||
53 | - | ||
54 | - <para> | ||
55 | - Injetar o <literal>Connection</literal> usando <literal>@Name</literal> com o nome da conexão escolhida: | ||
56 | - </para> | ||
57 | - | ||
58 | - <programlisting role="JAVA"><![CDATA[@Inject | ||
59 | -@Name("conn1") | ||
60 | -private Connection conn1; | 155 | +frameworkdemoiselle.​persistence.​<emphasis role="bold">conn2</emphasis>.​driver.​class=MinhaClasse |
156 | +frameworkdemoiselle.​persistence.​<emphasis role="bold">conn2</emphasis>.​url=MinhaURL | ||
157 | +frameworkdemoiselle.​persistence.​<emphasis role="bold">conn2</emphasis>.​username=MeuLogin | ||
158 | +frameworkdemoiselle.​persistence.​<emphasis role="bold">conn2</emphasis>.​password=MinhaSenha</programlisting> | ||
159 | + | ||
160 | + <programlisting>frameworkdemoiselle.​persistence.​<emphasis role="bold">conn1</emphasis>.​jndi.​name=MeuJndiName1 | ||
161 | +frameworkdemoiselle.​persistence.​<emphasis role="bold">conn2</emphasis>.​jndi.​name=MeuJndiName2</programlisting> | ||
162 | + </example> | ||
163 | + | ||
164 | + <para> | ||
165 | + Caso várias conexões sejam configuradas, é possível determinal a conexão padrão - aquela | ||
166 | + que será utilizada quando o desenvolvedor não especificar qual deseja utilizar. | ||
167 | + </para> | ||
168 | + | ||
169 | + <informaltable width="100%"> | ||
170 | + <tgroup cols="2"> | ||
171 | + <colspec align="left"/> | ||
172 | + <colspec align="left"/> | ||
173 | + | ||
174 | + <thead> | ||
175 | + <row valign="top"> | ||
176 | + <entry><emphasis role="bold">Propriedade</emphasis></entry> | ||
177 | + <entry><emphasis role="bold">Descrição</emphasis></entry> | ||
178 | + </row> | ||
179 | + </thead> | ||
180 | + | ||
181 | + <tbody> | ||
182 | + <row valign="top"> | ||
183 | + <entry>frameworkdemoiselle.​persistence.​default.​datasource.​name</entry> | ||
184 | + <entry> | ||
185 | + <para> | ||
186 | + Caso múltiplas conexões sejam criadas, define a conexão padrão | ||
187 | + quando uma <code>Connection</code> é injetada no código sem utilizar | ||
188 | + a anotação <code>@Name</code>. | ||
189 | + </para> | ||
190 | + </entry> | ||
191 | + </row> | ||
192 | + </tbody> | ||
193 | + </tgroup> | ||
194 | + </informaltable> | ||
195 | + </section> | ||
196 | + | ||
197 | + <section> | ||
198 | + <title>Utilização</title> | ||
199 | + | ||
200 | + <para> | ||
201 | + Para utilizar uma conexão JDBC em seu código, basta injetá-la. O Demoiselle se encarregará de produzir | ||
202 | + o tipo adequado de conexão. | ||
203 | + </para> | ||
204 | + | ||
205 | + <programlisting role="JAVA"><![CDATA[public class ClasseDAO { | ||
206 | + | ||
207 | + @Inject | ||
208 | + private Connection conn1; | ||
209 | + | ||
210 | + public void metodoPersistir(){ | ||
211 | + conn1.prepareStatement("INSERT INTO TAB_1 VALUES (1,'JDBC')").execute(); | ||
212 | + } | ||
213 | + | ||
214 | +}]]></programlisting> | ||
61 | 215 | ||
62 | -@Inject | ||
63 | -@Name("conn2") | ||
64 | -private Connection conn2; | ||
65 | -]]></programlisting> | 216 | + <para> |
217 | + Caso multiplas conexões tenham sido definidas, é possível utilizar a anotação <code>@Name</code> para injetar | ||
218 | + uma conexão específica. | ||
219 | + </para> | ||
220 | + | ||
221 | + <programlisting role="JAVA"><![CDATA[public class ClasseDAO { | ||
222 | + | ||
223 | + @Inject | ||
224 | + @Name("conn1") | ||
225 | + private Connection conn1; | ||
226 | + | ||
227 | + @Inject | ||
228 | + @Name("conn2") | ||
229 | + private Connection conn2; | ||
230 | + | ||
231 | + public void metodoPersistirEmConn1(){ | ||
232 | + conn1.prepareStatement("INSERT INTO TAB_1 VALUES (1,'JDBC')").execute(); | ||
233 | + } | ||
234 | + | ||
235 | + public void metodoPersistirEmConn2(){ | ||
236 | + conn2.prepareStatement("INSERT INTO TAB_2 VALUES (1,'JDBC')").execute(); | ||
237 | + } | ||
238 | + | ||
239 | +}]]></programlisting> | ||
66 | 240 | ||
241 | + <caution> | ||
242 | + <para> | ||
243 | + Caso a propriedade <code>frameworkdemoiselle.persistence.default.datasource.name</code> seja utilizada para | ||
244 | + especificar uma conexão padrão, a anotação <code>@Name</code> só é necessária para utilizar conexões diferentes | ||
245 | + da padrão. Caso essa propriedade não seja utilizada e existam múltiplas conexões configuradas, torna-se obrigatório | ||
246 | + o uso da anotação <code>@Name</code> em todos os pontos de injeção. | ||
247 | + </para> | ||
248 | + </caution> | ||
67 | 249 | ||
68 | - <para> | ||
69 | - Caso possua mais de uma configuração de datasource você pode definir uma configuração padrão | ||
70 | - para sua aplicação. | ||
71 | - </para> | ||
72 | - <programlisting>frameworkdemoiselle.persistence.default.unit.name=conn1</programlisting> | 250 | + </section> |
73 | 251 | ||
74 | </section> | 252 | </section> |
75 | 253 |
documentation/reference/pt-BR/properties.xml
1 | <?xml version='1.0' encoding="utf-8"?> | 1 | <?xml version='1.0' encoding="utf-8"?> |
2 | <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" | 2 | <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" |
3 | "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [ ]> | 3 | "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [ ]> |
4 | -<chapter id="properties"> | 4 | +<appendix id="propriedades"> |
5 | 5 | ||
6 | <title>Atributos do demoiselle.properties</title> | 6 | <title>Atributos do demoiselle.properties</title> |
7 | 7 | ||
@@ -14,12 +14,12 @@ | @@ -14,12 +14,12 @@ | ||
14 | </para> | 14 | </para> |
15 | 15 | ||
16 | <para> | 16 | <para> |
17 | - <table> | 17 | + <table width="100%"> |
18 | <title>Configurações do Core</title> | 18 | <title>Configurações do Core</title> |
19 | <tgroup cols="3"> | 19 | <tgroup cols="3"> |
20 | - <colspec align="left"/> | ||
21 | - <colspec align="left"/> | ||
22 | - <colspec align="right"/> | 20 | + <colspec align="left" colwidth="0.4*"/> |
21 | + <colspec align="left" colwidth="0.4*"/> | ||
22 | + <colspec align="right" colwidth="0.2*"/> | ||
23 | 23 | ||
24 | <thead> | 24 | <thead> |
25 | <row valign="top"> | 25 | <row valign="top"> |
@@ -30,7 +30,7 @@ | @@ -30,7 +30,7 @@ | ||
30 | </thead> | 30 | </thead> |
31 | <tbody> | 31 | <tbody> |
32 | <row valign="top"> | 32 | <row valign="top"> |
33 | - <entry>frameworkdemoiselle.security.enabled</entry> | 33 | + <entry>frameworkdemoiselle.​security.​enabled</entry> |
34 | <entry> | 34 | <entry> |
35 | <para> | 35 | <para> |
36 | Habilita o mecanismo de segurança. | 36 | Habilita o mecanismo de segurança. |
@@ -39,7 +39,7 @@ | @@ -39,7 +39,7 @@ | ||
39 | <entry>true</entry> | 39 | <entry>true</entry> |
40 | </row> | 40 | </row> |
41 | <row valign="top"> | 41 | <row valign="top"> |
42 | - <entry>frameworkdemoiselle.security.authenticator.class</entry> | 42 | + <entry>frameworkdemoiselle.​security.​authenticator.​class</entry> |
43 | <entry> | 43 | <entry> |
44 | <para> | 44 | <para> |
45 | Define a classe que implementa a estratégia de autenticação. | 45 | Define a classe que implementa a estratégia de autenticação. |
@@ -48,7 +48,7 @@ | @@ -48,7 +48,7 @@ | ||
48 | <entry></entry> | 48 | <entry></entry> |
49 | </row> | 49 | </row> |
50 | <row valign="top"> | 50 | <row valign="top"> |
51 | - <entry>frameworkdemoiselle.security.authorizer.class</entry> | 51 | + <entry>frameworkdemoiselle.​security.​authorizer.​class</entry> |
52 | <entry> | 52 | <entry> |
53 | <para> | 53 | <para> |
54 | Define a classe que implementa a estratégia de autorização. | 54 | Define a classe que implementa a estratégia de autorização. |
@@ -57,7 +57,7 @@ | @@ -57,7 +57,7 @@ | ||
57 | <entry></entry> | 57 | <entry></entry> |
58 | </row> | 58 | </row> |
59 | <row valign="top"> | 59 | <row valign="top"> |
60 | - <entry>frameworkdemoiselle.transaction.class</entry> | 60 | + <entry>frameworkdemoiselle.​transaction.​class</entry> |
61 | <entry> | 61 | <entry> |
62 | <para> | 62 | <para> |
63 | Define a classe que implementa a estratégia de controle transacional. | 63 | Define a classe que implementa a estratégia de controle transacional. |
@@ -66,7 +66,7 @@ | @@ -66,7 +66,7 @@ | ||
66 | <entry></entry> | 66 | <entry></entry> |
67 | </row> | 67 | </row> |
68 | <row valign="top"> | 68 | <row valign="top"> |
69 | - <entry>frameworkdemoiselle.pagination.page.size</entry> | 69 | + <entry>frameworkdemoiselle.​pagination.​page.​size</entry> |
70 | <entry> | 70 | <entry> |
71 | <para> | 71 | <para> |
72 | Define o tamanho da página padrão do mecanismo de paginação. | 72 | Define o tamanho da página padrão do mecanismo de paginação. |
@@ -77,13 +77,13 @@ | @@ -77,13 +77,13 @@ | ||
77 | </tbody> | 77 | </tbody> |
78 | </tgroup> | 78 | </tgroup> |
79 | </table> | 79 | </table> |
80 | - <table> | 80 | + <table width="100%"> |
81 | <title>Configurações da extensão JSF</title> | 81 | <title>Configurações da extensão JSF</title> |
82 | <tgroup cols="3"> | 82 | <tgroup cols="3"> |
83 | - <colspec align="left"/> | ||
84 | - <colspec align="left"/> | ||
85 | - <colspec align="right"/> | ||
86 | - | 83 | + <colspec align="left" colwidth="0.4*"/> |
84 | + <colspec align="left" colwidth="0.4*"/> | ||
85 | + <colspec align="right" colwidth="0.2*"/> | ||
86 | + | ||
87 | <thead> | 87 | <thead> |
88 | <row valign="top"> | 88 | <row valign="top"> |
89 | <entry><emphasis role="bold">Propriedade</emphasis></entry> | 89 | <entry><emphasis role="bold">Propriedade</emphasis></entry> |
@@ -93,7 +93,7 @@ | @@ -93,7 +93,7 @@ | ||
93 | </thead> | 93 | </thead> |
94 | <tbody> | 94 | <tbody> |
95 | <row valign="top"> | 95 | <row valign="top"> |
96 | - <entry>frameworkdemoiselle.security.login.page</entry> | 96 | + <entry>frameworkdemoiselle.​security.​login.​page</entry> |
97 | <entry> | 97 | <entry> |
98 | <para> | 98 | <para> |
99 | Define a página de login da aplicação. | 99 | Define a página de login da aplicação. |
@@ -102,7 +102,7 @@ | @@ -102,7 +102,7 @@ | ||
102 | <entry>"/login"</entry> | 102 | <entry>"/login"</entry> |
103 | </row> | 103 | </row> |
104 | <row valign="top"> | 104 | <row valign="top"> |
105 | - <entry>frameworkdemoiselle.security.redirect.after.login</entry> | 105 | + <entry>frameworkdemoiselle.​security.​redirect.​after.​login</entry> |
106 | <entry> | 106 | <entry> |
107 | <para> | 107 | <para> |
108 | Define a tela para qual o usuário será redirecionado após o processo de <emphasis>login</emphasis> bem sucedido. | 108 | Define a tela para qual o usuário será redirecionado após o processo de <emphasis>login</emphasis> bem sucedido. |
@@ -111,7 +111,7 @@ | @@ -111,7 +111,7 @@ | ||
111 | <entry>"/index"</entry> | 111 | <entry>"/index"</entry> |
112 | </row> | 112 | </row> |
113 | <row valign="top"> | 113 | <row valign="top"> |
114 | - <entry>frameworkdemoiselle.security.redirect.after.logout</entry> | 114 | + <entry>frameworkdemoiselle.​security.​redirect.​after.​logout</entry> |
115 | <entry> | 115 | <entry> |
116 | <para> | 116 | <para> |
117 | Define a tela para qual o usuário será redirecionado após o processo de <emphasis>logout</emphasis> bem sucedido. | 117 | Define a tela para qual o usuário será redirecionado após o processo de <emphasis>logout</emphasis> bem sucedido. |
@@ -120,7 +120,7 @@ | @@ -120,7 +120,7 @@ | ||
120 | <entry>"/login"</entry> | 120 | <entry>"/login"</entry> |
121 | </row> | 121 | </row> |
122 | <row valign="top"> | 122 | <row valign="top"> |
123 | - <entry>frameworkdemoiselle.security.redirect.enabled</entry> | 123 | + <entry>frameworkdemoiselle.​security.​redirect.​enabled</entry> |
124 | <entry> | 124 | <entry> |
125 | <para> | 125 | <para> |
126 | Habilita os redirecionamentos relacionados aos processos de login e logout. | 126 | Habilita os redirecionamentos relacionados aos processos de login e logout. |
@@ -129,7 +129,7 @@ | @@ -129,7 +129,7 @@ | ||
129 | <entry>true</entry> | 129 | <entry>true</entry> |
130 | </row> | 130 | </row> |
131 | <row valign="top"> | 131 | <row valign="top"> |
132 | - <entry>frameworkdemoiselle.handle.application.exception</entry> | 132 | + <entry>frameworkdemoiselle.​handle.​application.​exception</entry> |
133 | <entry> | 133 | <entry> |
134 | <para> | 134 | <para> |
135 | Habilita o tratamento automático das exceções da aplicação anotadas com @ApplicationException. | 135 | Habilita o tratamento automático das exceções da aplicação anotadas com @ApplicationException. |
@@ -138,7 +138,7 @@ | @@ -138,7 +138,7 @@ | ||
138 | <entry>true</entry> | 138 | <entry>true</entry> |
139 | </row> | 139 | </row> |
140 | <row valign="top"> | 140 | <row valign="top"> |
141 | - <entry>frameworkdemoiselle.handle.application.exception.page</entry> | 141 | + <entry>frameworkdemoiselle.​handle.​application.​exception.​page</entry> |
142 | <entry> | 142 | <entry> |
143 | <para> | 143 | <para> |
144 | Define o redirecionamento das exceções da aplicação anotadas com @ApplicationException ocorridas | 144 | Define o redirecionamento das exceções da aplicação anotadas com @ApplicationException ocorridas |
@@ -148,7 +148,7 @@ | @@ -148,7 +148,7 @@ | ||
148 | <entry>"/application_error"</entry> | 148 | <entry>"/application_error"</entry> |
149 | </row> | 149 | </row> |
150 | <row valign="top"> | 150 | <row valign="top"> |
151 | - <entry>frameworkdemoiselle.pagination.max.page.links</entry> | 151 | + <entry>frameworkdemoiselle.​pagination.​max.​page.​links</entry> |
152 | <entry> | 152 | <entry> |
153 | <para> | 153 | <para> |
154 | Configura a quantidade de links que será exibido em uma página. | 154 | Configura a quantidade de links que será exibido em uma página. |
@@ -159,12 +159,12 @@ | @@ -159,12 +159,12 @@ | ||
159 | </tbody> | 159 | </tbody> |
160 | </tgroup> | 160 | </tgroup> |
161 | </table> | 161 | </table> |
162 | - <table> | 162 | + <table width="100%"> |
163 | <title>Configurações da extensão JDBC</title> | 163 | <title>Configurações da extensão JDBC</title> |
164 | <tgroup cols="3"> | 164 | <tgroup cols="3"> |
165 | - <colspec align="left"/> | ||
166 | - <colspec align="left"/> | ||
167 | - <colspec align="right"/> | 165 | + <colspec align="left" colwidth="0.4*"/> |
166 | + <colspec align="left" colwidth="0.4*"/> | ||
167 | + <colspec align="right" colwidth="0.2*"/> | ||
168 | 168 | ||
169 | <thead> | 169 | <thead> |
170 | <row valign="top"> | 170 | <row valign="top"> |
@@ -175,7 +175,7 @@ | @@ -175,7 +175,7 @@ | ||
175 | </thead> | 175 | </thead> |
176 | <tbody> | 176 | <tbody> |
177 | <row valign="top"> | 177 | <row valign="top"> |
178 | - <entry>frameworkdemoiselle.persistence.jndi.name</entry> | 178 | + <entry>frameworkdemoiselle.​persistence.​jndi.​name</entry> |
179 | <entry> | 179 | <entry> |
180 | <para> | 180 | <para> |
181 | Define o nome JNDI onde o DataSource está disponível. | 181 | Define o nome JNDI onde o DataSource está disponível. |
@@ -184,7 +184,7 @@ | @@ -184,7 +184,7 @@ | ||
184 | <entry></entry> | 184 | <entry></entry> |
185 | </row> | 185 | </row> |
186 | <row valign="top"> | 186 | <row valign="top"> |
187 | - <entry>frameworkdemoiselle.persistence.driver.class</entry> | 187 | + <entry>frameworkdemoiselle.​persistence.​driver.​class</entry> |
188 | <entry> | 188 | <entry> |
189 | <para> | 189 | <para> |
190 | Define a classe que implementa o Driver de conexão com a base de dados. | 190 | Define a classe que implementa o Driver de conexão com a base de dados. |
@@ -193,7 +193,7 @@ | @@ -193,7 +193,7 @@ | ||
193 | <entry></entry> | 193 | <entry></entry> |
194 | </row> | 194 | </row> |
195 | <row valign="top"> | 195 | <row valign="top"> |
196 | - <entry>frameworkdemoiselle.persistence.url</entry> | 196 | + <entry>frameworkdemoiselle.​persistence.​url</entry> |
197 | <entry> | 197 | <entry> |
198 | <para> | 198 | <para> |
199 | Define a URL de conexão com a base de dados. | 199 | Define a URL de conexão com a base de dados. |
@@ -202,7 +202,7 @@ | @@ -202,7 +202,7 @@ | ||
202 | <entry></entry> | 202 | <entry></entry> |
203 | </row> | 203 | </row> |
204 | <row valign="top"> | 204 | <row valign="top"> |
205 | - <entry>frameworkdemoiselle.persistence.username</entry> | 205 | + <entry>frameworkdemoiselle.​persistence.​username</entry> |
206 | <entry> | 206 | <entry> |
207 | <para> | 207 | <para> |
208 | Define o username para estabelecer a conexão com a base de dados. | 208 | Define o username para estabelecer a conexão com a base de dados. |
@@ -211,7 +211,7 @@ | @@ -211,7 +211,7 @@ | ||
211 | <entry></entry> | 211 | <entry></entry> |
212 | </row> | 212 | </row> |
213 | <row valign="top"> | 213 | <row valign="top"> |
214 | - <entry>frameworkdemoiselle.persistence.password</entry> | 214 | + <entry>frameworkdemoiselle.​persistence.​password</entry> |
215 | <entry> | 215 | <entry> |
216 | <para> | 216 | <para> |
217 | Define o password para estabelecer a conexão com a base de dados. | 217 | Define o password para estabelecer a conexão com a base de dados. |
@@ -220,7 +220,7 @@ | @@ -220,7 +220,7 @@ | ||
220 | <entry></entry> | 220 | <entry></entry> |
221 | </row> | 221 | </row> |
222 | <row valign="top"> | 222 | <row valign="top"> |
223 | - <entry>frameworkdemoiselle.persistence.default.datasource.name</entry> | 223 | + <entry>frameworkdemoiselle.​persistence.​default.​datasource.​name</entry> |
224 | <entry> | 224 | <entry> |
225 | <para> | 225 | <para> |
226 | Define a configuração de banco de dados padrão para aplicações que possuem mais | 226 | Define a configuração de banco de dados padrão para aplicações que possuem mais |
@@ -232,12 +232,12 @@ | @@ -232,12 +232,12 @@ | ||
232 | </tbody> | 232 | </tbody> |
233 | </tgroup> | 233 | </tgroup> |
234 | </table> | 234 | </table> |
235 | - <table> | 235 | + <table width="100%"> |
236 | <title>Configurações da extensão JPA</title> | 236 | <title>Configurações da extensão JPA</title> |
237 | <tgroup cols="3"> | 237 | <tgroup cols="3"> |
238 | - <colspec align="left"/> | ||
239 | - <colspec align="left"/> | ||
240 | - <colspec align="right"/> | 238 | + <colspec align="left" colwidth="0.4*"/> |
239 | + <colspec align="left" colwidth="0.4*"/> | ||
240 | + <colspec align="right" colwidth="0.2*"/> | ||
241 | 241 | ||
242 | <thead> | 242 | <thead> |
243 | <row valign="top"> | 243 | <row valign="top"> |
@@ -248,7 +248,7 @@ | @@ -248,7 +248,7 @@ | ||
248 | </thead> | 248 | </thead> |
249 | <tbody> | 249 | <tbody> |
250 | <row valign="top"> | 250 | <row valign="top"> |
251 | - <entry>frameworkdemoiselle.persistence.default.unit.name</entry> | 251 | + <entry>frameworkdemoiselle.​persistence.​default.​unit.​name</entry> |
252 | <entry> | 252 | <entry> |
253 | <para> | 253 | <para> |
254 | Define a unidade de persistência padrão para aplicações que possuem mais | 254 | Define a unidade de persistência padrão para aplicações que possuem mais |
@@ -260,12 +260,12 @@ | @@ -260,12 +260,12 @@ | ||
260 | </tbody> | 260 | </tbody> |
261 | </tgroup> | 261 | </tgroup> |
262 | </table> | 262 | </table> |
263 | - <table> | 263 | + <table width="100%"> |
264 | <title>Configurações da extensão JMX</title> | 264 | <title>Configurações da extensão JMX</title> |
265 | <tgroup cols="3"> | 265 | <tgroup cols="3"> |
266 | - <colspec align="left"/> | ||
267 | - <colspec align="left"/> | ||
268 | - <colspec align="right"/> | 266 | + <colspec align="left" colwidth="0.4*"/> |
267 | + <colspec align="left" colwidth="0.4*"/> | ||
268 | + <colspec align="right" colwidth="0.2*"/> | ||
269 | 269 | ||
270 | <thead> | 270 | <thead> |
271 | <row valign="top"> | 271 | <row valign="top"> |
@@ -276,30 +276,30 @@ | @@ -276,30 +276,30 @@ | ||
276 | </thead> | 276 | </thead> |
277 | <tbody> | 277 | <tbody> |
278 | <row valign="top"> | 278 | <row valign="top"> |
279 | - <entry>frameworkdemoiselle.management.jmx.mbean.domain</entry> | 279 | + <entry role="">frameworkdemoiselle.​management.​jmx.​mbean.​domain</entry> |
280 | <entry> | 280 | <entry> |
281 | <para>Define o domínio padrão onde classes anotadas com <emphasis>@ManagementController</emphasis> serão registradas no MBeanServer.</para> | 281 | <para>Define o domínio padrão onde classes anotadas com <emphasis>@ManagementController</emphasis> serão registradas no MBeanServer.</para> |
282 | <para>Na especificação JMX, um MBean é registrado no MBeanServer com um nome no formato <emphasis>domain:name=MBeanName</emphasis> | 282 | <para>Na especificação JMX, um MBean é registrado no MBeanServer com um nome no formato <emphasis>domain:name=MBeanName</emphasis> |
283 | - (ex: <emphasis>br.gov.frameworkdemoiselle.jmx:name=NotificationBroadcaster</emphasis>). Esse parâmetro controla a porção <emphasis>domain</emphasis> | 283 | + (ex: <emphasis>br.​gov.​frameworkdemoiselle.​jmx.​name=NotificationBroadcaster</emphasis>). Esse parâmetro controla a porção <emphasis>domain</emphasis> |
284 | desse formato.</para> | 284 | desse formato.</para> |
285 | </entry> | 285 | </entry> |
286 | - <entry>O pacote da classe anotada com <emphasis>@ManagementController</emphasis></entry> | 286 | + <entry>O pacote da classe anotada com <emphasis>@Management​Controller</emphasis></entry> |
287 | </row> | 287 | </row> |
288 | <row valign="top"> | 288 | <row valign="top"> |
289 | - <entry>frameworkdemoiselle.management.jmx.notification.domain</entry> | ||
290 | - <entry> | ||
291 | - <para>O mesmo que <emphasis>frameworkdemoiselle.management.jmx.mbean.domain</emphasis>, mas apenas para o domínio do | ||
292 | - MBean <emphasis role="bold">br.gov.frameworkdemoiselle.jmx.internal.NotificationBroadcaster</emphasis>. Esse MBean é automaticamente | ||
293 | - registrado para receber notificações enviadas usando a classe <emphasis role="bold">br.gov.frameworkdemoiselle.management.NotificationManager</emphasis></para> | 289 | + <entry colsep="1">frameworkdemoiselle.​management.​jmx.​notification.​domain</entry> |
290 | + <entry colsep="1"> | ||
291 | + <para>O mesmo que <emphasis>frameworkdemoiselle.​management.​jmx.​mbean.​domain</emphasis>, mas apenas para o domínio do | ||
292 | + MBean <emphasis role="bold">br.​gov.​frameworkdemoiselle.​jmx.​internal.​NotificationBroadcaster</emphasis>. Esse MBean é automaticamente | ||
293 | + registrado para receber notificações enviadas usando a classe <emphasis role="bold">br.​gov.​frameworkdemoiselle.​management.​NotificationManager</emphasis></para> | ||
294 | </entry> | 294 | </entry> |
295 | - <entry>br.gov.frameworkdemoiselle.jmx</entry> | 295 | + <entry>br.​gov.​frameworkdemoiselle.​jmx</entry> |
296 | </row> | 296 | </row> |
297 | <row valign="top"> | 297 | <row valign="top"> |
298 | - <entry>frameworkdemoiselle.management.jmx.notification.name</entry> | 298 | + <entry>frameworkdemoiselle.​management.​jmx.​notification.​name</entry> |
299 | <entry> | 299 | <entry> |
300 | - <para>O nome usado para registrar a classe <emphasis role="bold">br.gov.frameworkdemoiselle.jmx.internal.NotificationBroadcaster</emphasis> como MBean.</para> | 300 | + <para>O nome usado para registrar a classe <emphasis role="bold">br.​gov.​frameworkdemoiselle.​jmx.​internal.​NotificationBroadcaster</emphasis> como MBean.</para> |
301 | </entry> | 301 | </entry> |
302 | - <entry>NotificationBroadcaster</entry> | 302 | + <entry>Notification​Broadcaster</entry> |
303 | </row> | 303 | </row> |
304 | </tbody> | 304 | </tbody> |
305 | </tgroup> | 305 | </tgroup> |
@@ -340,4 +340,4 @@ | @@ -340,4 +340,4 @@ | ||
340 | e <link linkend="security">Segurança</link>. | 340 | e <link linkend="security">Segurança</link>. |
341 | </para> | 341 | </para> |
342 | </section> --> | 342 | </section> --> |
343 | -</chapter> | 343 | +</appendix> |
documentation/reference/pt-BR/security.xml
1 | <?xml version='1.0' encoding="utf-8"?> | 1 | <?xml version='1.0' encoding="utf-8"?> |
2 | <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" | 2 | <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" |
3 | - "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" []> | 3 | + "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [ ]> |
4 | <chapter id="security"> | 4 | <chapter id="security"> |
5 | 5 | ||
6 | <title>Segurança</title> | 6 | <title>Segurança</title> |
@@ -9,19 +9,21 @@ | @@ -9,19 +9,21 @@ | ||
9 | Neste capítulo será tratada uma questão de grande importância para a maioria das aplicações e motivo de infindáveis | 9 | Neste capítulo será tratada uma questão de grande importância para a maioria das aplicações e motivo de infindáveis |
10 | discussões nas equipes de desenvolvimento: controle de acesso. Assim como tudo relacionado ao framework, a | 10 | discussões nas equipes de desenvolvimento: controle de acesso. Assim como tudo relacionado ao framework, a |
11 | implementação de segurança foi projetada de forma simples e flexível, independente de camada de apresentação ou | 11 | implementação de segurança foi projetada de forma simples e flexível, independente de camada de apresentação ou |
12 | - tecnologia, te deixando livre para implementar sua própria solução ou utilizar as extensões prontas, como a que | ||
13 | - atualmente provemos baseada no Apache Shiro (<ulink url="http://shiro.apache.org" />). | 12 | + tecnologia, te deixando livre para implementar sua própria solução ou utilizar as extensões existentes. |
14 | </para> | 13 | </para> |
15 | <para> | 14 | <para> |
16 | - Para utilizar o modelo de segurança proposto basta utilizar o Demoiselle, pois no núcleo do Framework estão as | 15 | + Para utilizar o modelo de segurança proposto basta utilizar o Framework Demoiselle, pois no núcleo do framework estão as |
17 | interfaces e anotações que definem o comportamento básico da implementação. | 16 | interfaces e anotações que definem o comportamento básico da implementação. |
18 | </para> | 17 | </para> |
19 | 18 | ||
20 | <section> | 19 | <section> |
21 | <title>Configurando</title> | 20 | <title>Configurando</title> |
21 | + | ||
22 | <para> | 22 | <para> |
23 | - Para um correto funcionamento do Demoiselle é necessário inserir os interceptadores de segurança no arquivo <filename>src/main/WEB-INF/beans.xml</filename>. | 23 | + Para um correto funcionamento da segurança no Framework Demoiselle é necessário inserir os interceptadores de segurança no arquivo <filename>beans.xml</filename>, localizado |
24 | + na pasta WEB-INF em projetos WEB ou na pasta META-INF em projetos SE ou EJB. | ||
24 | </para> | 25 | </para> |
26 | + | ||
25 | <programlisting role="XML"><![CDATA[<beans xmlns="http://java.sun.com/xml/ns/javaee" | 27 | <programlisting role="XML"><![CDATA[<beans xmlns="http://java.sun.com/xml/ns/javaee" |
26 | xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | 28 | xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
27 | xsi:schemaLocation="http://java.sun.com/xml/ns/javaee | 29 | xsi:schemaLocation="http://java.sun.com/xml/ns/javaee |
@@ -31,203 +33,584 @@ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee | @@ -31,203 +33,584 @@ xsi:schemaLocation="http://java.sun.com/xml/ns/javaee | ||
31 | <class>br.gov.frameworkdemoiselle.security.RequiredRoleInterceptor</class> | 33 | <class>br.gov.frameworkdemoiselle.security.RequiredRoleInterceptor</class> |
32 | </interceptors> | 34 | </interceptors> |
33 | </beans>]]></programlisting> | 35 | </beans>]]></programlisting> |
36 | + | ||
37 | + <para> | ||
38 | + Opcionalmente é possível configurar o comportamento do módulo de segurança definindo propriedades no arquivo <emphasis>demoiselle.properties</emphasis> | ||
39 | + da sua aplicação. | ||
40 | + </para> | ||
41 | + | ||
42 | + <table> | ||
43 | + <title>Propriedades de segurança do Framework Demoiselle</title> | ||
44 | + <tgroup cols="3"> | ||
45 | + <colspec align="left" colwidth="40*"/> | ||
46 | + <colspec align="left" colwidth="40*"/> | ||
47 | + <colspec align="right" colwidth="20*"/> | ||
48 | + | ||
49 | + <thead> | ||
50 | + <row valign="top"> | ||
51 | + <entry><emphasis role="bold">Propriedade</emphasis></entry> | ||
52 | + <entry><emphasis role="bold">Descrição</emphasis></entry> | ||
53 | + <entry><emphasis role="bold">Valor padrão</emphasis></entry> | ||
54 | + </row> | ||
55 | + </thead> | ||
56 | + <tbody> | ||
57 | + <row valign="top"> | ||
58 | + <entry>frameworkdemoiselle.​security.​enabled</entry> | ||
59 | + <entry> | ||
60 | + <para> | ||
61 | + Habilita ou desabilita o mecanismo de segurança | ||
62 | + </para> | ||
63 | + </entry> | ||
64 | + <entry>true</entry> | ||
65 | + </row> | ||
66 | + | ||
67 | + <row valign="top"> | ||
68 | + <entry>frameworkdemoiselle.​security.​authenticator.​class</entry> | ||
69 | + <entry> | ||
70 | + <para> | ||
71 | + Define a classe que implementa o mecanismo de autenticação. | ||
72 | + (Detalhes na seção <link linkend="criando_implementacao_seguranca">Criando sua implementação</link>) | ||
73 | + </para> | ||
74 | + </entry> | ||
75 | + <entry> | ||
76 | + - | ||
77 | + </entry> | ||
78 | + </row> | ||
79 | + | ||
80 | + <row valign="top"> | ||
81 | + <entry>frameworkdemoiselle.​security.​authorizer.​class</entry> | ||
82 | + <entry> | ||
83 | + <para> | ||
84 | + Define a classe que implementa o mecanismo de autorização. | ||
85 | + (Detalhes na seção <link linkend="criando_implementacao_seguranca">Criando sua implementação</link>) | ||
86 | + </para> | ||
87 | + </entry> | ||
88 | + <entry> | ||
89 | + - | ||
90 | + </entry> | ||
91 | + </row> | ||
92 | + </tbody> | ||
93 | + </tgroup> | ||
94 | + </table> | ||
95 | + | ||
34 | </section> | 96 | </section> |
35 | 97 | ||
36 | <section> | 98 | <section> |
37 | <title>Autenticação</title> | 99 | <title>Autenticação</title> |
38 | <para> | 100 | <para> |
39 | - O mecanismo de autenticação busca verificar a identidade do usuário de um sistema. A forma mais conhecida, e comum, | ||
40 | - para executar essa verificação se dá por meio de um formulário de login, geralmente solicitando um nome de usuário e | 101 | + O mecanismo de autenticação busca verificar a identidade do usuário de um sistema. A forma mais conhecida - e comum - para |
102 | + executar essa verificação se dá por meio de um formulário de login, geralmente solicitando um nome de usuário e | ||
41 | sua respectiva senha. No entanto, outras formas como reconhecimento biométrico e autenticação por token, para citar | 103 | sua respectiva senha. No entanto, outras formas como reconhecimento biométrico e autenticação por token, para citar |
42 | - apenas duas, têm ganhado um grande número de adeptos. | 104 | + apenas duas, tem ganhado um grande número de adeptos. |
43 | </para> | 105 | </para> |
44 | <para> | 106 | <para> |
45 | - O Demoiselle deixa o desenvolvedor livre para definir qual forma usar, de acordo com a sua conveniência e necessidade. | ||
46 | - A peça chave para tornar isso possível é o contexto de segurança, representado pela interface SecurityContext. Nessa | 107 | + O Framework Demoiselle deixa o desenvolvedor livre para definir qual forma usar, de acordo com a sua conveniência e necessidade. |
108 | + A peça chave para tornar isso possível é o contexto de segurança, representado pela interface <code>SecurityContext</code>. Nessa | ||
47 | estão definidos os métodos responsáveis por gerenciar os mecanismos de autenticação como, por exemplo, executar | 109 | estão definidos os métodos responsáveis por gerenciar os mecanismos de autenticação como, por exemplo, executar |
48 | login/logout de usuários e verificar se os mesmos estão ou não autenticados. | 110 | login/logout de usuários e verificar se os mesmos estão ou não autenticados. |
49 | </para> | 111 | </para> |
50 | <para> | 112 | <para> |
51 | - O contexto de segurança irá direcionar as requisições para a implementação definida pela aplicação. A autenticação será | ||
52 | - efetuada por uma classe que implemente a interface Authenticator, cujo método authenticate() é responsável por | ||
53 | - executar os passos necessários para validar a identidade de um usuário. Nesta mesma interface serão encontrados, | ||
54 | - ainda, os métodos unAuthenticate() e getUser(), responsáveis por, respectivamente, desautenticar e retornar o usuário | ||
55 | - autenticado. | ||
56 | - </para> | ||
57 | - <para> | ||
58 | - Para exemplificar, consideremos a autenticação baseada em nome de usuário e senha. O primeiro passo é criar um bean para | ||
59 | - armazenar essas informações: | 113 | + Para utilizar o <code>SecurityContext</code>, basta injetá-lo em seu código. O método <code>login</code> ativa o mecanismo de autenticação |
114 | + e o método <code>logout</code> remove as credenciais atualmente autenticadas do sistema. A classe <code>SecurityContext</code> possui | ||
115 | + outros métodos que permitem verificar se há um usuário autenticado e acessar o objeto <emphasis>gerente</emphasis> (representado pela | ||
116 | + classe <code>javax.security.Principal</code>), um objeto que contém dados adicionais sobre o usuário atualmente autenticado. Consulte | ||
117 | + a documentação da classe <code>SecurityContext</code> para consultar as funcionalidades que ela oferece. | ||
60 | </para> | 118 | </para> |
61 | - <programlisting role="JAVA"><![CDATA[@SessionScoped | ||
62 | -public class Credential { | ||
63 | - | ||
64 | - private String login; | ||
65 | - private String senha; | ||
66 | - // ... | ||
67 | -}]]></programlisting> | ||
68 | <para> | 119 | <para> |
69 | - Feito isso, podemos implementar a classe na qual se deseja adicionar o mecanismo de segurança: | 120 | + Um exemplo do uso do <code>SecurityContext</code> para autenticação segue abaixo: |
70 | </para> | 121 | </para> |
71 | - <programlisting role="JAVA"><![CDATA[public class ClasseExemplo { | ||
72 | - | ||
73 | - @Inject | ||
74 | - private Credential credential; | 122 | + <programlisting role="JAVA"><![CDATA[public class ExemploAutenticacao { |
75 | 123 | ||
76 | @Inject | 124 | @Inject |
77 | - private SecurityContext context; | ||
78 | - | ||
79 | - public void metodo1() { | ||
80 | - credential.setLogin(“usuario1”); | ||
81 | - credential.setSenha(“123”); | ||
82 | - context.login(); | ||
83 | - // codigo do metodo | ||
84 | - context.logout(); | 125 | + private SecurityContext securityContext; |
126 | + | ||
127 | + public void efetuarAutenticacao() { | ||
128 | + /* | ||
129 | + Obtem as credenciais do usuario, pode ser um login e senha ou um certificado digital. O mais | ||
130 | + comum e exibir uma tela HTML contendo um formulario que solicita as informacoes. | ||
131 | + */ | ||
132 | + | ||
133 | + securityContext.login(); | ||
134 | + | ||
135 | + //Executa codigo que requer autenticacao | ||
136 | + | ||
137 | + securityContext.logout(); | ||
138 | + | ||
85 | } | 139 | } |
86 | }]]></programlisting> | 140 | }]]></programlisting> |
87 | - <para> | ||
88 | - Neste caso, a interface SecurityContext e o bean Credential estão sendo injetados na classe utilizando o CDI. | ||
89 | - Dentro do método, ao definir o usuário e a senha e invocar “context.login()”, a implementação de segurança definida irá | ||
90 | - tratar essa requisição de acordo com os critérios estabelecidos. | ||
91 | - </para> | ||
92 | </section> | 141 | </section> |
93 | 142 | ||
94 | <section> | 143 | <section> |
95 | <title>Autorização</title> | 144 | <title>Autorização</title> |
96 | <para> | 145 | <para> |
97 | - O mecanismo de autorização é responsável por garantir que apenas usuários autorizados tenham o acesso concedido a | ||
98 | - determinados recursos de um sistema. No modelo de segurança do Demoiselle 2, a autorização pode acontecer de duas | 146 | + Em certos sistemas é necessário não apenas autenticar um usuário, mas também proteger funcionalidades individuais e separar |
147 | + usuários em grupos que possuem diferentes autorizações de acesso. O mecanismo de autorização é responsável por garantir que apenas | ||
148 | + usuários autorizados tenham o acesso concedido a determinados recursos de um sistema. | ||
149 | + </para> | ||
150 | + | ||
151 | + <para> | ||
152 | + No modelo de segurança do Framework Demoiselle, a autorização pode acontecer de duas | ||
99 | formas: | 153 | formas: |
100 | <itemizedlist> | 154 | <itemizedlist> |
101 | - <listitem><para>Permissão por usuário, através da anotação @RequiredPermission</para></listitem> | 155 | + <listitem><para>Permissão por funcionalidade, através da anotação @RequiredPermission</para></listitem> |
102 | <listitem><para>Permissão por papel, através da anotação @RequiredRole</para></listitem> | 156 | <listitem><para>Permissão por papel, através da anotação @RequiredRole</para></listitem> |
103 | </itemizedlist> | 157 | </itemizedlist> |
104 | </para> | 158 | </para> |
105 | - <para> | ||
106 | - Novamente a interface SecurityContext é a responsável pela interação entre as funcionalidades da aplicação e a implementação de | ||
107 | - segurança. Nela estão definidos os métodos que verificam se o usuário possui permissão para acessar um recurso ou se o | ||
108 | - usuário está associado a um papel. | ||
109 | - </para> | ||
110 | - <para> | ||
111 | - A anotação @RequiredPermission pode ser utilizada tanto em classes como em métodos e possui dois parâmetros opcionais: | ||
112 | - “operation” e “resource”. O primeiro define a operação para a qual se deseja permissão e o segundo define em qual | ||
113 | - recurso essa operação será realizada. Abaixo serão exemplificadas algumas formas de utilização: | ||
114 | - </para> | ||
115 | - <programlisting role="JAVA"><![CDATA[class ClasseExemplo { | 159 | + |
160 | + | ||
161 | + <section> | ||
162 | + <title>Protegendo o sistema com <emphasis>@RequiredPermission</emphasis></title> | ||
163 | + | ||
164 | + <para> | ||
165 | + A anotação <code>@RequiredPermission</code> permite marcar uma classe ou método e informar que acesso a esse recurso requer | ||
166 | + a permissão de executar uma <emphasis>operação</emphasis>. Operação nesse contexto é um nome definido pelo desenvolvedor | ||
167 | + que representa uma funcionalidade do sistema. Por exemplo, determinada classe pode ter métodos responsávels por criar, editar, | ||
168 | + listar e remover bookmarks, o desenvolvedor pode decidir agrupar esses métodos sobre a operação <emphasis>gerenciar bookmark</emphasis>. | ||
169 | + </para> | ||
170 | + | ||
171 | + <programlisting role="JAVA"><![CDATA[class GerenciadorBookmark { | ||
172 | + | ||
173 | + @RequiredPermission(resource = "bookmark" , operation = "gerenciar") | ||
174 | + public void incluirBookmark(Bookmark bookmark) { | ||
175 | + //Ccdigo do metodo | ||
176 | + } | ||
177 | + | ||
178 | + @RequiredPermission(resource = "bookmark", operation = "gerenciar") | ||
179 | + public List<Bookmark> listarBookmarks() { | ||
180 | + //Codigo do metodo | ||
181 | + } | ||
182 | + | ||
183 | + @RequiredPermission | ||
184 | + public List<Bookmark> apagarBookmark(Long idBookmark) { | ||
185 | + public List<Bookmark> listarBookmarks() { | ||
186 | + } | ||
187 | +}]]></programlisting> | ||
188 | + | ||
189 | + <tip> | ||
190 | + Perceba que a anotação <code>@RequiredPermission</code> sobre o método <code>apagarBookmark</code> não contém parâmetros. Quando não | ||
191 | + são passados parâmetros o valor padrão para o parâmetro <code>resource</code> é o nome da classe e o valor padrão para <code>operation</code> | ||
192 | + é o nome do método. | ||
193 | + </tip> | ||
194 | + | ||
195 | + <tip> | ||
196 | + É possível anotar a classe inteira com <code>@RequiredPermission</code>, isso protegerá o acesso a todos os métodos dessa classe. | ||
197 | + | ||
198 | + <programlisting role="JAVA"><![CDATA[@RequiredPermission(resource="bookmark" , operation="gerenciar") | ||
199 | +class GerenciadorBookmark { | ||
200 | + | ||
201 | + public void incluirBookmark(Bookmark bookmark) { | ||
202 | + //Codigo do metodo | ||
203 | + } | ||
204 | + | ||
205 | + public List<Bookmark> listarBookmarks() { | ||
206 | + //Codigo do metodo | ||
207 | + } | ||
208 | + | ||
209 | + public List<Bookmark> apagarBookmark(Long idBookmark) { | ||
210 | + public List<Bookmark> listarBookmarks() { | ||
211 | + } | ||
212 | +}]]></programlisting> | ||
213 | + </tip> | ||
214 | + </section> | ||
215 | + | ||
216 | + <section> | ||
217 | + <title>Protegendo o sistema com <emphasis>@RequiredRole</emphasis></title> | ||
218 | + | ||
219 | + <para> | ||
220 | + Diferente de <code>@RequiredPermission</code>, a anotação <code>@RequiredRole</code> utiliza o conceito | ||
221 | + de papéis - ou perfís - para proteger recursos. Uma classe ou método anotado com <code>@RequiredRole</code> | ||
222 | + exigirá que o usuário autenticado possua o papel indicado para acessar o recurso. | ||
223 | + </para> | ||
224 | + | ||
225 | + <para> | ||
226 | + Voltando ao exemplo de nosso aplicativo de bookmarks, vamos supor que a função de listar os bookmarks existentes | ||
227 | + pode ser acessada por qualquer usuário autenticado, mas apenas administradores podem criar um novo bookmark. A classe | ||
228 | + responsável por tais funcionalidades pode ser criada da seguinte forma: | ||
229 | + </para> | ||
230 | + | ||
231 | + <programlisting role="JAVA"><![CDATA[class GerenciadorBookmark { | ||
232 | + | ||
233 | + @RequiredRole("administrador") | ||
234 | + public void inserirBookmark(Bookmark bookmark) { | ||
235 | + } | ||
236 | + | ||
237 | + @RequiredRole({"convidado" , "administrador"}) | ||
238 | + public List<Bookmark> listarBookmarks() { | ||
239 | + } | ||
240 | + | ||
241 | +}]]></programlisting> | ||
116 | 242 | ||
117 | - @RequiredPermission | ||
118 | - public void requiredPermissionWithoutDeclaredResourceAndOperation() { | 243 | + <tip> |
244 | + É possível informar mais de um papel para a anotação <code>@RequiredRole</code>, neste caso basta que o usuário | ||
245 | + autenticado possua um dos papéis listados para ter acesso ao recurso. | ||
246 | + </tip> | ||
247 | + | ||
248 | + <para> | ||
249 | + Da mesma forma que a anotação <code>@RequiredPermission</code>, a anotação <code>@RequiredRole</code> pode ser usada | ||
250 | + a nível de classe para proteger todos os métodos contidos nessa classe. | ||
251 | + </para> | ||
252 | + </section> | ||
253 | + | ||
254 | + <section> | ||
255 | + <title>Protegendo porções do código</title> | ||
256 | + | ||
257 | + <para> | ||
258 | + É possível proteger apenas parte de um código ao invés de todo o método ou toda a classe. Isso pode ser necessário em | ||
259 | + expressões condicionais, onde um trecho só deve ser executado caso o usuário possua a autorização necessária. | ||
260 | + Para isso voltamos a usar a interface <code>SecurityContext</code>, pois ela contém métodos que são funcionalmente equivalentes | ||
261 | + às anotações <code>@RequiredPermission</code> e <code>@RequiredRole</code>. | ||
262 | + </para> | ||
263 | + | ||
264 | + <para> | ||
265 | + Como um exemplo, vamos supor que ao remover um bookmark um email seja enviado ao administrador, mas se o próprio | ||
266 | + administrador executou a operação não é necessário enviar o email. | ||
267 | + </para> | ||
268 | + | ||
269 | + <programlisting role="JAVA"><![CDATA[class GerenciadorBookmark { | ||
270 | + | ||
271 | + @Inject | ||
272 | + private SecurityContext securityContext; | ||
273 | + | ||
274 | + public void removerBookmark(Long idBookmark) { | ||
275 | + | ||
276 | + //Codigo que remove o bookmark | ||
277 | + | ||
278 | + if ( ! securityContext.hasRole("administrador") ){ | ||
279 | + //Envia um email ao administrador | ||
280 | + } | ||
281 | + | ||
119 | } | 282 | } |
120 | 283 | ||
121 | - @RequiredPermission(resource = "contact", operation = "insert") | ||
122 | - public void requiredPermissionWithDeclaredResourceAndOperation() { | ||
123 | - } | ||
124 | }]]></programlisting> | 284 | }]]></programlisting> |
285 | + | ||
286 | + </section> | ||
287 | + | ||
288 | + <section> | ||
289 | + <title>Protegendo porções de páginas <code>Java Server Faces</code></title> | ||
290 | + | ||
291 | + <para> | ||
292 | + As restrições de segurança podem ser utilizadas ainda em páginas web, com o auxílio de Expression Language. A interface | ||
293 | + <code>SecurityContext</code> está automaticamente disponível para páginas <code>Java Server Faces</code> como um <emphasis>bean</emphasis> | ||
294 | + de nome <code>securityContext</code>, bastando então acessar seus métodos a partir deste bean. | ||
295 | + </para> | ||
296 | + | ||
297 | + <programlisting role="XHTML"><![CDATA[<p:commandButton value="#{messages['button.save']}" action="#{contactEditMB.insert}" | ||
298 | + ajax="false" disabled="#{!securityContext.hasPermission('contact', 'insert')}" />]]></programlisting> | ||
299 | + | ||
300 | + <para> | ||
301 | + Nesse caso, a habilitação de um botão está condicionada à existência de permissão para o usuário autenticado no momento | ||
302 | + executar a operação “insert” no recurso “contact”. | ||
303 | + </para> | ||
304 | + </section> | ||
305 | + </section> | ||
306 | + | ||
307 | + <section> | ||
308 | + <title>Redirecionando automaticamente para um formulário de acesso</title> | ||
309 | + | ||
310 | + <para> | ||
311 | + Se sua aplicação usa a extensão <emphasis>demoiselle-jsf</emphasis> ou se você utilizou o arquétipo <emphasis>demoiselle-jsf-jpa</emphasis> | ||
312 | + durante a criação de seu projeto, então você pode definir uma página de login e o Framework Demoiselle vai automaticamente lhe redirecionar | ||
313 | + para essa página caso haja a tentativa de acessar um recurso protejido e nenhum usuário esteja autenticado no sistema. | ||
314 | + </para> | ||
315 | + | ||
316 | + <tip> | ||
317 | + <para>Para acrescentar a extensão <emphasis>demoiselle-jsf</emphasis> em um projeto Maven, adicione a dependência abaixo | ||
318 | + no arquivo <emphasis>pom.xml</emphasis>.</para> | ||
319 | + | ||
320 | + <programlisting role="XML"><![CDATA[ | ||
321 | +<dependency> | ||
322 | + <groupId>br.gov.frameworkdemoiselle</groupId> | ||
323 | + <artifactId>demoiselle-jsf</artifactId> | ||
324 | + <scope>compile</scope> | ||
325 | +</dependency>]]></programlisting> | ||
326 | + | ||
327 | + <para> | ||
328 | + O arquétipo <emphasis>demoiselle-jsf-jpa</emphasis> já contém essa extensão, se você criou seu projeto | ||
329 | + baseado nesse arquétipo nada precisa ser feito. | ||
330 | + </para> | ||
331 | + </tip> | ||
332 | + | ||
333 | + <para> | ||
334 | + Por padrão a página contendo o formulário de login deve se chamar <emphasis>login.jsp</emphasis> ou <emphasis>login.xhtml</emphasis> | ||
335 | + (a depender de como sua aplicação esteja configurada para mapear páginas JSF). Para mudar esse padrão, é possível | ||
336 | + editar o arquivo <emphasis>demoiselle.properties</emphasis> para configurar qual página deve ser utilizada. | ||
337 | + </para> | ||
338 | + | ||
339 | + <table> | ||
340 | + <title>Propriedades de segurança da extensão <emphasis>demoiselle-jsf</emphasis></title> | ||
341 | + <tgroup cols="3"> | ||
342 | + <colspec align="left" colwidth="40*"/> | ||
343 | + <colspec align="left" colwidth="40*"/> | ||
344 | + <colspec align="right" colwidth="20*"/> | ||
345 | + | ||
346 | + <thead> | ||
347 | + <row valign="top"> | ||
348 | + <entry><emphasis role="bold">Propriedade</emphasis></entry> | ||
349 | + <entry><emphasis role="bold">Descrição</emphasis></entry> | ||
350 | + <entry><emphasis role="bold">Valor padrão</emphasis></entry> | ||
351 | + </row> | ||
352 | + </thead> | ||
353 | + <tbody> | ||
354 | + <row valign="top"> | ||
355 | + <entry>frameworkdemoiselle.​security.​login.​page</entry> | ||
356 | + <entry> | ||
357 | + <para> | ||
358 | + Define a página de login da aplicação. | ||
359 | + </para> | ||
360 | + </entry> | ||
361 | + <entry>"/login"</entry> | ||
362 | + </row> | ||
363 | + <row valign="top"> | ||
364 | + <entry>frameworkdemoiselle.​security.​redirect.​after.​login</entry> | ||
365 | + <entry> | ||
366 | + <para> | ||
367 | + Define a tela para qual o usuário será redirecionado após o processo de <emphasis>login</emphasis> bem sucedido. | ||
368 | + </para> | ||
369 | + </entry> | ||
370 | + <entry>"/index"</entry> | ||
371 | + </row> | ||
372 | + <row valign="top"> | ||
373 | + <entry>frameworkdemoiselle.​security.​redirect.​after.​logout</entry> | ||
374 | + <entry> | ||
375 | + <para> | ||
376 | + Define a tela para qual o usuário será redirecionado após o processo de <emphasis>logout</emphasis> bem sucedido. | ||
377 | + </para> | ||
378 | + </entry> | ||
379 | + <entry>"/login"</entry> | ||
380 | + </row> | ||
381 | + <row valign="top"> | ||
382 | + <entry>frameworkdemoiselle.​security.​redirect.​enabled</entry> | ||
383 | + <entry> | ||
384 | + <para> | ||
385 | + Habilita ou desabilita o redirecionamento automático para a página de login após uma tentativa | ||
386 | + de acessar recurso protegido. | ||
387 | + </para> | ||
388 | + </entry> | ||
389 | + <entry>true</entry> | ||
390 | + </row> | ||
391 | + </tbody> | ||
392 | + </tgroup> | ||
393 | + </table> | ||
394 | + | ||
395 | + </section> | ||
396 | + | ||
397 | + <section> | ||
398 | + <title>Integrando o Framework Demoiselle com a especificação JAAS</title> | ||
399 | + | ||
400 | + <para> | ||
401 | + Até agora vimos como criar código protegido em uma aplicação Demoiselle, mas nada foi dito sobre a tecnologia que implementa essa | ||
402 | + proteção. A verdade é que o Framework Demoiselle dá ao desenvolvedor a liberdade de implementar a solução que mais se adequa ao sistema | ||
403 | + desenvolvido, mas o framework também conta com suporte nativo à especificação JAAS (<emphasis>Java Authentication and | ||
404 | + Authorization Service</emphasis>). | ||
405 | + </para> | ||
406 | + | ||
125 | <para> | 407 | <para> |
126 | - Observe o método cuja anotação não possui parâmetros. Nesse caso serão considerados como recurso e operação o nome da classe e | ||
127 | - do método, respectivamente. Uma outra possibilidade seria utilizar a anotação @Name, tanto na classe como no método, de | ||
128 | - forma a possibilitar uma descrição mais amigável para o usuário. | 408 | + O suporte a JAAS é fornecido para aplicações WEB e está implementado na extensão |
409 | + <emphasis>demoiselle-servlet</emphasis>, então é necessário declarar a dependência a essa extensão em sua aplicação. | ||
129 | </para> | 410 | </para> |
411 | + | ||
412 | + <tip> | ||
413 | + <para>Para acrescentar a extensão <emphasis>demoiselle-servlet</emphasis> em um projeto Maven, adicione a dependência abaixo | ||
414 | + no arquivo <emphasis>pom.xml</emphasis>.</para> | ||
415 | + | ||
416 | + <programlisting role="XML"><![CDATA[ | ||
417 | +<dependency> | ||
418 | + <groupId>br.gov.frameworkdemoiselle</groupId> | ||
419 | + <artifactId>demoiselle-servlet</artifactId> | ||
420 | + <scope>compile</scope> | ||
421 | +</dependency>]]></programlisting> | ||
422 | + </tip> | ||
423 | + | ||
424 | + <tip> | ||
425 | + <para> | ||
426 | + O arquétipo <emphasis>demoiselle-jsf-jpa</emphasis> já conta com a dependência à extensão <emphasis>demoiselle-jsf</emphasis>, que | ||
427 | + por sua vez depende da extensão <emphasis>demoiselle-servlet</emphasis>. Se sua aplicação é baseada no arquétipo | ||
428 | + <emphasis>demoiselle-jsf-jpa</emphasis> você já possui a extensão <emphasis>demoiselle-servlet</emphasis>. | ||
429 | + </para> | ||
430 | + </tip> | ||
431 | + | ||
130 | <para> | 432 | <para> |
131 | - Assim como na autenticação, o contexto de segurança possui métodos destinados a delegar as requisições de autorização para | ||
132 | - a implementação de segurança. No caso da anotação @RequiredPermission, o método hasPermission(String resource, String | ||
133 | - operation) executa esta tarefa. Para tanto, deve existir uma classe que implemente a interface Authorizer, cujo | ||
134 | - método hasPermission(Object resource, String operation) verifica se o usuário logado possui permissão para executar | ||
135 | - uma determinada operação em um recurso específico. | 433 | + Uma vez que sua aplicação contenha a extensão <emphasis>demoiselle-servlet</emphasis>, tudo que você precisa fazer é configurar |
434 | + o suporte a JAAS em seu servidor de aplicação e criar os usuários e papéis necessários. Esta configuração depende do servidor de | ||
435 | + aplicação utilizado e foge ao escopo deste documento. | ||
136 | </para> | 436 | </para> |
437 | + | ||
137 | <para> | 438 | <para> |
138 | - Ainda na interface Authorizer, pode-se notar a existência do método hasRole(String role), responsável por verificar se o | ||
139 | - usuário logado possui um papel específico. Este método é chamado pelo contexto de segurança, por meio do seu método | ||
140 | - hasRole(String role), para tratar as requisições que possuam a anotação @RequiredRole. Essa anotação possui um | ||
141 | - parâmetro obrigatório, no qual podem ser definidos uma simples role ou um array delas. | 439 | + Para autenticar um usuário presente no servidor de aplicação através do JAAS, a extensão <emphasis>demoiselle-servlet</emphasis> |
440 | + oferece a classe <code>Credentials</code>, que deve ser injetada em seu código. O código abaixo mostra como realizar a autenticação a partir de um servlet. | ||
142 | </para> | 441 | </para> |
143 | - <programlisting role="JAVA"><![CDATA[class ClasseExemplo { | 442 | + |
443 | + <programlisting role="JAVA"><![CDATA[class LoginServlet extends HttpServlet { | ||
444 | + | ||
445 | + @Inject | ||
446 | + private SecurityContext securityContext; | ||
447 | + | ||
448 | + @Inject | ||
449 | + private Credentials credentials; | ||
144 | 450 | ||
145 | - @RequiredRole("simpleRoleName") | ||
146 | - public void requiredRoleWithSingleRole() { | 451 | + public void doPost(HttpServletRequest req, HttpServletResponse resp) { |
452 | + | ||
453 | + credentials.setUsername( req.getParameter("username") ); | ||
454 | + credentials.setPassword( req.getParameter("password") ); | ||
455 | + | ||
456 | + securityContext.login(); | ||
457 | + | ||
147 | } | 458 | } |
148 | 459 | ||
149 | - @RequiredRole({ "firstRole", "secondRole", "thirdRole", "fourthRole", "fifthRole" }) | ||
150 | - public void requiredRoleWithArrayOfRoles() { | ||
151 | - } | ||
152 | }]]></programlisting> | 460 | }]]></programlisting> |
461 | + | ||
153 | <para> | 462 | <para> |
154 | - As restrições de segurança pode ser utilizadas, ainda, em páginas web, com o auxílio de Expression Language, como no | ||
155 | - exemplo abaixo: | ||
156 | - </para> | ||
157 | - <programlisting role="XHTML"><![CDATA[<p:commandButton value="#{messages['button.save']}" action="#{contactEditMB.insert}" | ||
158 | - rendered="#{!contactEditMB.updateMode}" ajax="false" | ||
159 | - disabled="#{!securityContext.hasPermission('contact', 'insert')}" />]]></programlisting> | ||
160 | - <para> | ||
161 | - Nesse caso, a habilitação de um botão está condicionada à existência de permissão para o usuário autenticado no momento | ||
162 | - executar a operação “insert” no recurso “contact”. | 463 | + Uma vez autenticado o usuário, a anotação <code>@RequiredRole</code> passará a verificar se o usuário presente no JAAS possui o papel informado. |
163 | </para> | 464 | </para> |
465 | + | ||
466 | + <caution> | ||
467 | + <para> | ||
468 | + A especificação JAAS não prevê o uso de permissões para proteger recursos, apenas papéis de usuários. Por isso ao utilizar a segurança | ||
469 | + da especificação JAAS o uso da anotação <code>@RequiredPermission</code> fica vetado. Utilizar essa anotação em um sistema que utilize | ||
470 | + JAAS para autorização causará uma exceção quando o recurso for acessado. | ||
471 | + </para> | ||
472 | + </caution> | ||
473 | + | ||
474 | + <tip> | ||
475 | + <para> | ||
476 | + É possível utilizar o JAAS para autenticar e autorizar papéis de usuários mas criar sua própria implementação para | ||
477 | + implementar a autorização de permissões. Para isso crie uma classe que herde a classe | ||
478 | + <code>br.gov.frameworkdemoiselle.security.ServletAuthorizer</code> e sobrescreva o método <code>hasPermission(String resource, String operation)</code> | ||
479 | + para implementar seu próprio mecanismo. Feito isso, basta definir sua classe no arquivo <emphasis>demoiselle.properties</emphasis> usando | ||
480 | + a propriedade <code>frameworkdemoiselle.security.authorizer.class</code>. | ||
481 | + </para> | ||
482 | + | ||
483 | + <para> | ||
484 | + Mais detalhes sobre como criar sua própria implementação ou extender uma implementação existente podem | ||
485 | + ser vistos na seção <link linkend="criando_implementacao_seguranca">Criando sua implementação</link>. | ||
486 | + </para> | ||
487 | + </tip> | ||
488 | + | ||
164 | </section> | 489 | </section> |
165 | 490 | ||
166 | - <section> | 491 | + <section id="criando_implementacao_seguranca"> |
167 | <title>Criando sua implementação</title> | 492 | <title>Criando sua implementação</title> |
493 | + | ||
168 | <para> | 494 | <para> |
169 | - Após toda essa explicação, fica a dúvida: como implementar um esquema de segurança sem utilizar a extensão existente? | 495 | + Para os mecanismos de autenticação não cobertos pelo Framework Demoiselle, é possível criar sua própria implementação e integra-la |
496 | + ao framework. Também é possível extender uma implementação existente e acrescentar funcionalidades inexistentes. | ||
170 | </para> | 497 | </para> |
498 | + | ||
171 | <para> | 499 | <para> |
172 | - O primeiro passo é criar classes para implementar as interfaces Authenticator e Authorizer. O <literal>Demoiselle</literal> detecta automaticamente | ||
173 | - a implementação, e torna essa classe a implementação padrão dessas interfaces:<!-- Essas classes devem ser | ||
174 | - anotadas com @Alternative para que o CDI saiba que se trata de uma estratégia: --> | 500 | + O ponto de extensão para o módulo de segurança são as interfaces <code>Authenticator</code> e <code>Authorizer</code>. Para criar |
501 | + um novo mecanismo de autenticação e autorização, é necessário apenas implementar essas duas interfaces em sua aplicação. Segue | ||
502 | + abaixo um exemplo de implementação. | ||
175 | </para> | 503 | </para> |
504 | + | ||
176 | <programlisting role="JAVA"><![CDATA[public class MeuAuthenticator implements Authenticator { | 505 | <programlisting role="JAVA"><![CDATA[public class MeuAuthenticator implements Authenticator { |
177 | 506 | ||
178 | @Override | 507 | @Override |
179 | public boolean authenticate() { | 508 | public boolean authenticate() { |
180 | - // Escreva aqui seu codigo de autenticacao | 509 | + // Escreva aqui seu codigo de autenticacao e retorne true caso o processo seja um sucesso |
181 | return true; | 510 | return true; |
182 | } | 511 | } |
183 | 512 | ||
184 | @Override | 513 | @Override |
185 | - public User getUser() { | ||
186 | - // Escreva aqui seu codigo para retornar o usuario logado | ||
187 | - return null; | 514 | + public Principal getUser() { |
515 | + // Obtenha dados sobre o usuario autenticado e retorne na forma da interface javax.security.Principal | ||
516 | + return new Principal(){ | ||
517 | + public String getName(){ | ||
518 | + return "usuario"; | ||
519 | + } | ||
520 | + }; | ||
188 | } | 521 | } |
189 | 522 | ||
190 | @Override | 523 | @Override |
191 | public void unAuthenticate() { | 524 | public void unAuthenticate() { |
192 | - // Escreva aqui seu codigo de desautenticacao | 525 | + // Remova qualquer informacao de autenticacao do usuario, apas o retorno deste metodo o usuario |
526 | + // deve ser considerado nao autenticado. | ||
193 | } | 527 | } |
194 | }]]></programlisting> | 528 | }]]></programlisting> |
195 | <programlisting role="JAVA"><![CDATA[public class MeuAuthorizer implements Authorizer { | 529 | <programlisting role="JAVA"><![CDATA[public class MeuAuthorizer implements Authorizer { |
196 | 530 | ||
197 | @Override | 531 | @Override |
198 | public boolean hasRole(String role) { | 532 | public boolean hasRole(String role) { |
199 | - // Escreva aqui seu codigo de verificacao do papel | 533 | + // Verifique se o usuario autenticado tem o papel informado, retorne true em caso positivo |
200 | return false; | 534 | return false; |
201 | } | 535 | } |
202 | 536 | ||
203 | @Override | 537 | @Override |
204 | public boolean hasPermission(Object resource, String operation) { | 538 | public boolean hasPermission(Object resource, String operation) { |
205 | - // Escreva aqui seu codigo de verificacao de permissao | 539 | + // Verifique se o usuario autenticado tem a permissao adequada, retorne true em caso positivo |
206 | return false; | 540 | return false; |
207 | } | 541 | } |
208 | }]]></programlisting> | 542 | }]]></programlisting> |
209 | - <!-- <para> | ||
210 | - Feito isso deve-se definir no arquivo <filename>demoiselle.properties</filename>, as classes criadas: | 543 | + |
544 | + <para> | ||
545 | + Pronto! Sua aplicação já possui uma implementação de segurança definida. | ||
211 | </para> | 546 | </para> |
212 | - <programlisting> | ||
213 | - frameworkdemoiselle.security.authenticator.class=projeto.MeuAuthenticator | ||
214 | - frameworkdemoiselle.security.authorizer.class=projeto.MeuAuthorizer | ||
215 | - </programlisting> --> | 547 | + |
548 | + <tip> | ||
549 | + <para> | ||
550 | + Você nunca deve chamar diretamente em sua aplicação as implementações das interfaces <code>Authenticator</code> | ||
551 | + e <code>Authorizer</code>, o Framework Demoiselle vai automaticamente chamar os métodos implementados | ||
552 | + quando for necessário. | ||
553 | + </para> | ||
554 | + </tip> | ||
555 | + | ||
216 | <para> | 556 | <para> |
217 | - Pronto! Sua aplicação já possui uma implementação de segurança definida. Caso sua ela não implemente essas interfaces, no momento em que | ||
218 | - forem chamadas, o framework lançará uma exceção informando que a aplicação precisa implementá-las. | 557 | + Em um sistema que use as anotações <code>@RequiredRole</code> ou <code>@RequiredPermission</code>, deve haver pelo menos uma implementação |
558 | + dessas duas interfaces. Ao processar essas anotações, o Framework Demoiselle vai buscar uma implementação para essas interfaces | ||
559 | + e disparar uma exceção caso não encontre uma implementação adequada. | ||
219 | </para> | 560 | </para> |
561 | + | ||
220 | <para> | 562 | <para> |
221 | - Se você tem mais de uma implementação de <literal>Authenticator</literal> e/ou <literal>Authorizer</literal> (o que pode acontecer, por exemplo, quando | ||
222 | - se necessite de uma implementação na aplicação principal, e outra para os testes), deverá definir no arquivo <filename>demoiselle.properties</filename> | ||
223 | - qual classe será a padrão: | ||
224 | - <programlisting>frameworkdemoiselle.security.authenticator.class=projeto.MeuAuthenticatorPadrao | ||
225 | -frameworkdemoiselle.security.authorizer.class=projeto.MeuAuthorizerPadrao</programlisting> | 563 | + Se existe mais de uma implementação de <code>Authenticator</code> e/ou <code>Authorizer</code> (o que pode acontecer, por exemplo, quando |
564 | + seja necessário uma implementação na aplicação principal e outra para os testes), é possível definir no arquivo <filename>demoiselle.properties</filename> | ||
565 | + a classe que deve ser usada por padrão: | ||
226 | </para> | 566 | </para> |
567 | + | ||
568 | + <informaltable width="100%"> | ||
569 | + <tgroup cols="3"> | ||
570 | + <colspec align="left" colwidth="40%"/> | ||
571 | + <colspec align="left" colwidth="40%"/> | ||
572 | + <colspec align="right" colwidth="20%"/> | ||
573 | + | ||
574 | + <thead> | ||
575 | + <row valign="top"> | ||
576 | + <entry><emphasis role="bold">Propriedade</emphasis></entry> | ||
577 | + <entry><emphasis role="bold">Descrição</emphasis></entry> | ||
578 | + <entry><emphasis role="bold">Valor padrão</emphasis></entry> | ||
579 | + </row> | ||
580 | + </thead> | ||
581 | + <tbody> | ||
582 | + <row valign="top"> | ||
583 | + <entry>frameworkdemoiselle.​security.​authenticator.​class</entry> | ||
584 | + <entry> | ||
585 | + <para> | ||
586 | + Define a classe concreta utilizada como implementação da interface Authenticator | ||
587 | + </para> | ||
588 | + </entry> | ||
589 | + <entry> | ||
590 | + <emphasis> | ||
591 | + nenhum, se houver apenas uma implementação o framework a detectará | ||
592 | + automaticamente sem necessidade de definir essa propriedade | ||
593 | + </emphasis> | ||
594 | + </entry> | ||
595 | + </row> | ||
596 | + | ||
597 | + <row valign="top"> | ||
598 | + <entry>frameworkdemoiselle.​security.​authorizer.​class</entry> | ||
599 | + <entry> | ||
600 | + <para> | ||
601 | + Define a classe concreta utilizada como implementação da interface Authorizer | ||
602 | + </para> | ||
603 | + </entry> | ||
604 | + <entry> | ||
605 | + <emphasis> | ||
606 | + nenhum, se houver apenas uma implementação o framework a detectará | ||
607 | + automaticamente sem necessidade de definir essa propriedade | ||
608 | + </emphasis> | ||
609 | + </entry> | ||
610 | + </row> | ||
611 | + </tbody> | ||
612 | + </tgroup> | ||
613 | + </informaltable> | ||
227 | </section> | 614 | </section> |
228 | - <caution> <para>O Demoiselle também oferece o componente | ||
229 | - <ulink url="http://demoiselle.sourceforge.net/docs/demoiselle-guide-components/1.2.0/html/authorization-master.html">demoiselle-authorization</ulink> | ||
230 | - que facilita o uso de segurança com JAAS. Obviamente, não é possível utilizá-los ao mesmo tempo. Há arquétipos Maven que já trazem esse componente | ||
231 | - como dependência, por isso sempre confira o arquivo pom.xml e se for o caso retire essa dependência.</para> </caution> | ||
232 | - | 615 | + |
233 | </chapter> | 616 | </chapter> |
234 | \ No newline at end of file | 617 | \ No newline at end of file |
impl/core/src/main/java/br/gov/frameworkdemoiselle/annotation/OperationType.java
@@ -36,7 +36,6 @@ | @@ -36,7 +36,6 @@ | ||
36 | */ | 36 | */ |
37 | package br.gov.frameworkdemoiselle.annotation; | 37 | package br.gov.frameworkdemoiselle.annotation; |
38 | 38 | ||
39 | -import javax.management.MBeanOperationInfo; | ||
40 | 39 | ||
41 | /** | 40 | /** |
42 | * <p> | 41 | * <p> |
@@ -56,32 +55,24 @@ public enum OperationType { | @@ -56,32 +55,24 @@ public enum OperationType { | ||
56 | * ManagedOperation is write-only, it causes the application to change some of it's behaviour but doesn't return any | 55 | * ManagedOperation is write-only, it causes the application to change some of it's behaviour but doesn't return any |
57 | * kind of information | 56 | * kind of information |
58 | */ | 57 | */ |
59 | - ACTION(MBeanOperationInfo.ACTION), | 58 | + ACTION, |
59 | + | ||
60 | /** | 60 | /** |
61 | * ManagedOperation is read-only, it will operate over data provided by the application and return some information, | 61 | * ManagedOperation is read-only, it will operate over data provided by the application and return some information, |
62 | * but will not change the application in any way. | 62 | * but will not change the application in any way. |
63 | */ | 63 | */ |
64 | - INFO(MBeanOperationInfo.INFO), | 64 | + INFO, |
65 | + | ||
65 | /** | 66 | /** |
66 | * ManagedOperation is read-write, it will both change the way the application work and return some information | 67 | * ManagedOperation is read-write, it will both change the way the application work and return some information |
67 | * regarding the result of the operation. | 68 | * regarding the result of the operation. |
68 | */ | 69 | */ |
69 | - ACTION_INFO(MBeanOperationInfo.ACTION_INFO), | 70 | + ACTION_INFO, |
71 | + | ||
70 | /** | 72 | /** |
71 | * The effect of calling this operation is unknown. This is the default type and if this type is assigned to an | 73 | * The effect of calling this operation is unknown. This is the default type and if this type is assigned to an |
72 | * operation, the user must rely on the {@link ManagedOperation#description()} attribute to learn about how the | 74 | * operation, the user must rely on the {@link ManagedOperation#description()} attribute to learn about how the |
73 | * operation works. | 75 | * operation works. |
74 | */ | 76 | */ |
75 | - UNKNOWN(MBeanOperationInfo.UNKNOWN); | ||
76 | - | ||
77 | - private int operationTypeValue; | ||
78 | - | ||
79 | - private OperationType(int type) { | ||
80 | - this.operationTypeValue = type; | ||
81 | - } | ||
82 | - | ||
83 | - public int getValue() { | ||
84 | - return operationTypeValue; | ||
85 | - } | ||
86 | - | 77 | + UNKNOWN |
87 | } | 78 | } |
impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ManagementBootstrap.java
@@ -13,7 +13,6 @@ import javax.enterprise.inject.spi.AfterDeploymentValidation; | @@ -13,7 +13,6 @@ import javax.enterprise.inject.spi.AfterDeploymentValidation; | ||
13 | import javax.enterprise.inject.spi.AnnotatedType; | 13 | import javax.enterprise.inject.spi.AnnotatedType; |
14 | import javax.enterprise.inject.spi.Bean; | 14 | import javax.enterprise.inject.spi.Bean; |
15 | import javax.enterprise.inject.spi.BeanManager; | 15 | import javax.enterprise.inject.spi.BeanManager; |
16 | -import javax.enterprise.inject.spi.BeforeShutdown; | ||
17 | import javax.enterprise.inject.spi.Extension; | 16 | import javax.enterprise.inject.spi.Extension; |
18 | import javax.enterprise.inject.spi.ProcessAnnotatedType; | 17 | import javax.enterprise.inject.spi.ProcessAnnotatedType; |
19 | 18 | ||
@@ -23,6 +22,7 @@ import br.gov.frameworkdemoiselle.internal.context.ManagedContext; | @@ -23,6 +22,7 @@ import br.gov.frameworkdemoiselle.internal.context.ManagedContext; | ||
23 | import br.gov.frameworkdemoiselle.internal.management.ManagedType; | 22 | import br.gov.frameworkdemoiselle.internal.management.ManagedType; |
24 | import br.gov.frameworkdemoiselle.internal.management.Management; | 23 | import br.gov.frameworkdemoiselle.internal.management.Management; |
25 | import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer; | 24 | import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer; |
25 | +import br.gov.frameworkdemoiselle.lifecycle.AfterShutdownProccess; | ||
26 | import br.gov.frameworkdemoiselle.lifecycle.ManagementExtension; | 26 | import br.gov.frameworkdemoiselle.lifecycle.ManagementExtension; |
27 | import br.gov.frameworkdemoiselle.stereotype.ManagementController; | 27 | import br.gov.frameworkdemoiselle.stereotype.ManagementController; |
28 | import br.gov.frameworkdemoiselle.util.Beans; | 28 | import br.gov.frameworkdemoiselle.util.Beans; |
@@ -72,7 +72,7 @@ public class ManagementBootstrap implements Extension { | @@ -72,7 +72,7 @@ public class ManagementBootstrap implements Extension { | ||
72 | monitoringManager.initialize(managementExtensionCache); | 72 | monitoringManager.initialize(managementExtensionCache); |
73 | } | 73 | } |
74 | 74 | ||
75 | - public void unregisterAvailableManagedTypes(@Observes final BeforeShutdown event) { | 75 | + public void unregisterAvailableManagedTypes(@Observes final AfterShutdownProccess event) { |
76 | 76 | ||
77 | Management manager = Beans.getReference(Management.class); | 77 | Management manager = Beans.getReference(Management.class); |
78 | manager.shutdown(managementExtensionCache); | 78 | manager.shutdown(managementExtensionCache); |
impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/context/AbstractCustomContext.java
@@ -65,7 +65,6 @@ public abstract class AbstractCustomContext implements CustomContext { | @@ -65,7 +65,6 @@ public abstract class AbstractCustomContext implements CustomContext { | ||
65 | } | 65 | } |
66 | 66 | ||
67 | @Override | 67 | @Override |
68 | - @SuppressWarnings("unchecked") | ||
69 | public <T> T get(final Contextual<T> contextual, final CreationalContext<T> creationalContext) { | 68 | public <T> T get(final Contextual<T> contextual, final CreationalContext<T> creationalContext) { |
70 | T instance = null; | 69 | T instance = null; |
71 | 70 |
impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/NotificationManagerImpl.java
0 → 100644
@@ -0,0 +1,64 @@ | @@ -0,0 +1,64 @@ | ||
1 | +package br.gov.frameworkdemoiselle.internal.implementation; | ||
2 | + | ||
3 | +import java.io.Serializable; | ||
4 | + | ||
5 | +import javax.enterprise.event.Event; | ||
6 | +import javax.enterprise.util.AnnotationLiteral; | ||
7 | +import javax.inject.Inject; | ||
8 | + | ||
9 | +import br.gov.frameworkdemoiselle.internal.management.ManagementNotificationEventImpl; | ||
10 | +import br.gov.frameworkdemoiselle.internal.management.qualifier.AttributeChange; | ||
11 | +import br.gov.frameworkdemoiselle.internal.management.qualifier.Generic; | ||
12 | +import br.gov.frameworkdemoiselle.management.AttributeChangeNotification; | ||
13 | +import br.gov.frameworkdemoiselle.management.ManagementNotificationEvent; | ||
14 | +import br.gov.frameworkdemoiselle.management.GenericNotification; | ||
15 | +import br.gov.frameworkdemoiselle.management.NotificationManager; | ||
16 | +import br.gov.frameworkdemoiselle.util.Beans; | ||
17 | + | ||
18 | + | ||
19 | +@SuppressWarnings("serial") | ||
20 | +public class NotificationManagerImpl implements NotificationManager,Serializable { | ||
21 | + | ||
22 | + @Inject | ||
23 | + @Generic | ||
24 | + private Event<ManagementNotificationEvent> genericNotificationEvent; | ||
25 | + | ||
26 | + @Inject | ||
27 | + @AttributeChange | ||
28 | + private Event<ManagementNotificationEvent> attributeChangeNotificationEvent; | ||
29 | + | ||
30 | + /** | ||
31 | + * Sends a generic notification to all management clients. | ||
32 | + * | ||
33 | + * @param notification The notification to send | ||
34 | + */ | ||
35 | + public void sendNotification(GenericNotification notification) { | ||
36 | + if (! AttributeChangeNotification.class.isInstance(notification) ){ | ||
37 | + getGenericNotificationEvent().fire(new ManagementNotificationEventImpl(notification)); | ||
38 | + } | ||
39 | + else{ | ||
40 | + getAttributeChangeNotificationEvent().fire(new ManagementNotificationEventImpl(notification)); | ||
41 | + } | ||
42 | + } | ||
43 | + | ||
44 | + @SuppressWarnings("unchecked") | ||
45 | + private Event<ManagementNotificationEvent> getGenericNotificationEvent() { | ||
46 | + if (genericNotificationEvent==null){ | ||
47 | + genericNotificationEvent = Beans.getReference(Event.class , new AnnotationLiteral<Generic>() {}); | ||
48 | + } | ||
49 | + | ||
50 | + return genericNotificationEvent; | ||
51 | + } | ||
52 | + | ||
53 | + @SuppressWarnings("unchecked") | ||
54 | + private Event<ManagementNotificationEvent> getAttributeChangeNotificationEvent() { | ||
55 | + if (attributeChangeNotificationEvent==null){ | ||
56 | + attributeChangeNotificationEvent = Beans.getReference(Event.class , new AnnotationLiteral<AttributeChange>() {}); | ||
57 | + } | ||
58 | + | ||
59 | + return attributeChangeNotificationEvent; | ||
60 | + } | ||
61 | + | ||
62 | + | ||
63 | + | ||
64 | +} |
impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/management/ManagedType.java
@@ -47,6 +47,7 @@ import javax.inject.Qualifier; | @@ -47,6 +47,7 @@ import javax.inject.Qualifier; | ||
47 | import br.gov.frameworkdemoiselle.DemoiselleException; | 47 | import br.gov.frameworkdemoiselle.DemoiselleException; |
48 | import br.gov.frameworkdemoiselle.annotation.ManagedOperation; | 48 | import br.gov.frameworkdemoiselle.annotation.ManagedOperation; |
49 | import br.gov.frameworkdemoiselle.annotation.ManagedProperty; | 49 | import br.gov.frameworkdemoiselle.annotation.ManagedProperty; |
50 | +import br.gov.frameworkdemoiselle.annotation.OperationType; | ||
50 | import br.gov.frameworkdemoiselle.annotation.ManagedProperty.ManagedPropertyAccess; | 51 | import br.gov.frameworkdemoiselle.annotation.ManagedProperty.ManagedPropertyAccess; |
51 | import br.gov.frameworkdemoiselle.annotation.OperationParameter; | 52 | import br.gov.frameworkdemoiselle.annotation.OperationParameter; |
52 | import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer; | 53 | import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer; |
@@ -163,6 +164,7 @@ public class ManagedType { | @@ -163,6 +164,7 @@ public class ManagedType { | ||
163 | Class<?>[] parameterTypes = method.getParameterTypes(); | 164 | Class<?>[] parameterTypes = method.getParameterTypes(); |
164 | Annotation[][] parameterAnnotations = method.getParameterAnnotations(); | 165 | Annotation[][] parameterAnnotations = method.getParameterAnnotations(); |
165 | ParameterDetail[] parameterDetails = new ParameterDetail[parameterTypes.length]; | 166 | ParameterDetail[] parameterDetails = new ParameterDetail[parameterTypes.length]; |
167 | + OperationType operationType = opAnnotation.type(); | ||
166 | 168 | ||
167 | for (int i = 0; i < parameterTypes.length; i++) { | 169 | for (int i = 0; i < parameterTypes.length; i++) { |
168 | OperationParameter paramAnnotation = null; | 170 | OperationParameter paramAnnotation = null; |
@@ -181,7 +183,7 @@ public class ManagedType { | @@ -181,7 +183,7 @@ public class ManagedType { | ||
181 | 183 | ||
182 | // Com todas as informações, criamos nossa instância de MethodDetail e | 184 | // Com todas as informações, criamos nossa instância de MethodDetail e |
183 | // acrescentamos na lista de todas as operações. | 185 | // acrescentamos na lista de todas as operações. |
184 | - MethodDetail detail = new MethodDetail(method, opAnnotation.description(), parameterDetails); | 186 | + MethodDetail detail = new MethodDetail(method, opAnnotation.description(), operationType, parameterDetails); |
185 | operationMethods.put(method.getName(), detail); | 187 | operationMethods.put(method.getName(), detail); |
186 | } | 188 | } |
187 | } | 189 | } |
@@ -326,12 +328,15 @@ public class ManagedType { | @@ -326,12 +328,15 @@ public class ManagedType { | ||
326 | 328 | ||
327 | private final ParameterDetail[] parameterTypers; | 329 | private final ParameterDetail[] parameterTypers; |
328 | 330 | ||
329 | - private String description; | 331 | + private final String description; |
332 | + | ||
333 | + private final OperationType type; | ||
330 | 334 | ||
331 | - public MethodDetail(Method method, String description, ParameterDetail[] parameterTypers) { | 335 | + public MethodDetail(Method method, String description, OperationType type,ParameterDetail[] parameterTypers) { |
332 | super(); | 336 | super(); |
333 | this.method = method; | 337 | this.method = method; |
334 | this.description = description; | 338 | this.description = description; |
339 | + this.type = type; | ||
335 | this.parameterTypers = parameterTypers; | 340 | this.parameterTypers = parameterTypers; |
336 | } | 341 | } |
337 | 342 | ||
@@ -347,6 +352,10 @@ public class ManagedType { | @@ -347,6 +352,10 @@ public class ManagedType { | ||
347 | return description; | 352 | return description; |
348 | } | 353 | } |
349 | 354 | ||
355 | + public OperationType getType() { | ||
356 | + return type; | ||
357 | + } | ||
358 | + | ||
350 | } | 359 | } |
351 | 360 | ||
352 | public final class ParameterDetail { | 361 | public final class ParameterDetail { |
impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/management/ManagementNotificationEvent.java
@@ -1,65 +0,0 @@ | @@ -1,65 +0,0 @@ | ||
1 | -/* | ||
2 | - * Demoiselle Framework | ||
3 | - * Copyright (C) 2010 SERPRO | ||
4 | - * ---------------------------------------------------------------------------- | ||
5 | - * This file is part of Demoiselle Framework. | ||
6 | - * | ||
7 | - * Demoiselle Framework is free software; you can redistribute it and/or | ||
8 | - * modify it under the terms of the GNU Lesser General Public License version 3 | ||
9 | - * as published by the Free Software Foundation. | ||
10 | - * | ||
11 | - * This program is distributed in the hope that it will be useful, | ||
12 | - * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
13 | - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
14 | - * GNU General Public License for more details. | ||
15 | - * | ||
16 | - * You should have received a copy of the GNU Lesser General Public License version 3 | ||
17 | - * along with this program; if not, see <http://www.gnu.org/licenses/> | ||
18 | - * or write to the Free Software Foundation, Inc., 51 Franklin Street, | ||
19 | - * Fifth Floor, Boston, MA 02110-1301, USA. | ||
20 | - * ---------------------------------------------------------------------------- | ||
21 | - * Este arquivo é parte do Framework Demoiselle. | ||
22 | - * | ||
23 | - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou | ||
24 | - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação | ||
25 | - * do Software Livre (FSF). | ||
26 | - * | ||
27 | - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA | ||
28 | - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou | ||
29 | - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português | ||
30 | - * para maiores detalhes. | ||
31 | - * | ||
32 | - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título | ||
33 | - * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> | ||
34 | - * ou escreva para a Fundação do Software Livre (FSF) Inc., | ||
35 | - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. | ||
36 | - */ | ||
37 | -package br.gov.frameworkdemoiselle.internal.management; | ||
38 | - | ||
39 | -import br.gov.frameworkdemoiselle.management.Notification; | ||
40 | -import br.gov.frameworkdemoiselle.management.NotificationManager; | ||
41 | - | ||
42 | -/** | ||
43 | - * Event fired when a notification is sent by {@link NotificationManager}. | ||
44 | - * Implementators can capture this event and be notified when the {@link NotificationManager} | ||
45 | - * sends notifications, so they can pass the notification to the underlying technology. | ||
46 | - * | ||
47 | - * @author serpro | ||
48 | - * | ||
49 | - */ | ||
50 | -public class ManagementNotificationEvent { | ||
51 | - | ||
52 | - private Notification notification; | ||
53 | - | ||
54 | - public ManagementNotificationEvent(Notification notification){ | ||
55 | - this.notification = notification; | ||
56 | - } | ||
57 | - | ||
58 | - public Notification getNotification() { | ||
59 | - return notification; | ||
60 | - } | ||
61 | - | ||
62 | - public void setNotification(Notification notification) { | ||
63 | - this.notification = notification; | ||
64 | - } | ||
65 | -} |
impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/management/ManagementNotificationEventImpl.java
0 → 100644
@@ -0,0 +1,65 @@ | @@ -0,0 +1,65 @@ | ||
1 | +/* | ||
2 | + * Demoiselle Framework | ||
3 | + * Copyright (C) 2010 SERPRO | ||
4 | + * ---------------------------------------------------------------------------- | ||
5 | + * This file is part of Demoiselle Framework. | ||
6 | + * | ||
7 | + * Demoiselle Framework is free software; you can redistribute it and/or | ||
8 | + * modify it under the terms of the GNU Lesser General Public License version 3 | ||
9 | + * as published by the Free Software Foundation. | ||
10 | + * | ||
11 | + * This program is distributed in the hope that it will be useful, | ||
12 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
13 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
14 | + * GNU General Public License for more details. | ||
15 | + * | ||
16 | + * You should have received a copy of the GNU Lesser General Public License version 3 | ||
17 | + * along with this program; if not, see <http://www.gnu.org/licenses/> | ||
18 | + * or write to the Free Software Foundation, Inc., 51 Franklin Street, | ||
19 | + * Fifth Floor, Boston, MA 02110-1301, USA. | ||
20 | + * ---------------------------------------------------------------------------- | ||
21 | + * Este arquivo é parte do Framework Demoiselle. | ||
22 | + * | ||
23 | + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou | ||
24 | + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação | ||
25 | + * do Software Livre (FSF). | ||
26 | + * | ||
27 | + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA | ||
28 | + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou | ||
29 | + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português | ||
30 | + * para maiores detalhes. | ||
31 | + * | ||
32 | + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título | ||
33 | + * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> | ||
34 | + * ou escreva para a Fundação do Software Livre (FSF) Inc., | ||
35 | + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. | ||
36 | + */ | ||
37 | +package br.gov.frameworkdemoiselle.internal.management; | ||
38 | + | ||
39 | +import br.gov.frameworkdemoiselle.management.GenericNotification; | ||
40 | +import br.gov.frameworkdemoiselle.management.NotificationManager; | ||
41 | + | ||
42 | +/** | ||
43 | + * Event fired when a notification is sent by {@link NotificationManager}. | ||
44 | + * Implementators can capture this event and be notified when the {@link NotificationManager} | ||
45 | + * sends notifications, so they can pass the notification to the underlying technology. | ||
46 | + * | ||
47 | + * @author serpro | ||
48 | + * | ||
49 | + */ | ||
50 | +public class ManagementNotificationEventImpl implements br.gov.frameworkdemoiselle.management.ManagementNotificationEvent { | ||
51 | + | ||
52 | + private GenericNotification notification; | ||
53 | + | ||
54 | + public ManagementNotificationEventImpl(GenericNotification notification){ | ||
55 | + this.notification = notification; | ||
56 | + } | ||
57 | + | ||
58 | + public GenericNotification getNotification() { | ||
59 | + return notification; | ||
60 | + } | ||
61 | + | ||
62 | + public void setNotification(GenericNotification notification) { | ||
63 | + this.notification = notification; | ||
64 | + } | ||
65 | +} |
impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/management/qualifier/AttributeChange.java
@@ -43,8 +43,8 @@ import java.lang.annotation.Target; | @@ -43,8 +43,8 @@ import java.lang.annotation.Target; | ||
43 | 43 | ||
44 | import javax.inject.Qualifier; | 44 | import javax.inject.Qualifier; |
45 | 45 | ||
46 | -import br.gov.frameworkdemoiselle.internal.management.ManagementNotificationEvent; | ||
47 | import br.gov.frameworkdemoiselle.management.AttributeChangeNotification; | 46 | import br.gov.frameworkdemoiselle.management.AttributeChangeNotification; |
47 | +import br.gov.frameworkdemoiselle.management.ManagementNotificationEvent; | ||
48 | 48 | ||
49 | /** | 49 | /** |
50 | * | 50 | * |
impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/management/qualifier/Generic.java
@@ -43,13 +43,13 @@ import java.lang.annotation.Target; | @@ -43,13 +43,13 @@ import java.lang.annotation.Target; | ||
43 | 43 | ||
44 | import javax.inject.Qualifier; | 44 | import javax.inject.Qualifier; |
45 | 45 | ||
46 | -import br.gov.frameworkdemoiselle.internal.management.ManagementNotificationEvent; | ||
47 | -import br.gov.frameworkdemoiselle.management.Notification; | 46 | +import br.gov.frameworkdemoiselle.management.ManagementNotificationEvent; |
47 | +import br.gov.frameworkdemoiselle.management.GenericNotification; | ||
48 | 48 | ||
49 | /** | 49 | /** |
50 | * | 50 | * |
51 | * Enables {@link ManagementNotificationEvent} observers to trigger only with notifications | 51 | * Enables {@link ManagementNotificationEvent} observers to trigger only with notifications |
52 | - * of the base type {@link Notification}. | 52 | + * of the base type {@link GenericNotification}. |
53 | * | 53 | * |
54 | * @author serpro | 54 | * @author serpro |
55 | * | 55 | * |
impl/core/src/main/java/br/gov/frameworkdemoiselle/management/AttributeChangeNotification.java
@@ -39,12 +39,12 @@ package br.gov.frameworkdemoiselle.management; | @@ -39,12 +39,12 @@ package br.gov.frameworkdemoiselle.management; | ||
39 | /** | 39 | /** |
40 | * Special notification to denote an attribute has changed values. | 40 | * Special notification to denote an attribute has changed values. |
41 | * | 41 | * |
42 | - * @see Notification | 42 | + * @see GenericNotification |
43 | * | 43 | * |
44 | * @author serpro | 44 | * @author serpro |
45 | * | 45 | * |
46 | */ | 46 | */ |
47 | -public class AttributeChangeNotification extends Notification { | 47 | +public class AttributeChangeNotification extends GenericNotification { |
48 | 48 | ||
49 | private String attributeName; | 49 | private String attributeName; |
50 | 50 |
impl/core/src/main/java/br/gov/frameworkdemoiselle/management/GenericNotification.java
0 → 100644
@@ -0,0 +1,77 @@ | @@ -0,0 +1,77 @@ | ||
1 | +/* | ||
2 | + * Demoiselle Framework | ||
3 | + * Copyright (C) 2010 SERPRO | ||
4 | + * ---------------------------------------------------------------------------- | ||
5 | + * This file is part of Demoiselle Framework. | ||
6 | + * | ||
7 | + * Demoiselle Framework is free software; you can redistribute it and/or | ||
8 | + * modify it under the terms of the GNU Lesser General Public License version 3 | ||
9 | + * as published by the Free Software Foundation. | ||
10 | + * | ||
11 | + * This program is distributed in the hope that it will be useful, | ||
12 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
13 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
14 | + * GNU General Public License for more details. | ||
15 | + * | ||
16 | + * You should have received a copy of the GNU Lesser General Public License version 3 | ||
17 | + * along with this program; if not, see <http://www.gnu.org/licenses/> | ||
18 | + * or write to the Free Software Foundation, Inc., 51 Franklin Street, | ||
19 | + * Fifth Floor, Boston, MA 02110-1301, USA. | ||
20 | + * ---------------------------------------------------------------------------- | ||
21 | + * Este arquivo é parte do Framework Demoiselle. | ||
22 | + * | ||
23 | + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou | ||
24 | + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação | ||
25 | + * do Software Livre (FSF). | ||
26 | + * | ||
27 | + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA | ||
28 | + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou | ||
29 | + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português | ||
30 | + * para maiores detalhes. | ||
31 | + * | ||
32 | + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título | ||
33 | + * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> | ||
34 | + * ou escreva para a Fundação do Software Livre (FSF) Inc., | ||
35 | + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. | ||
36 | + */ | ||
37 | +package br.gov.frameworkdemoiselle.management; | ||
38 | + | ||
39 | +/** | ||
40 | + * | ||
41 | + * Notification that can be sent by the {@link NotificationManager}. | ||
42 | + * | ||
43 | + * @author serpro | ||
44 | + * | ||
45 | + */ | ||
46 | +public class GenericNotification { | ||
47 | + | ||
48 | + private Object message; | ||
49 | + | ||
50 | + public GenericNotification(){ | ||
51 | + } | ||
52 | + | ||
53 | + public GenericNotification(Object message) { | ||
54 | + super(); | ||
55 | + this.message = message; | ||
56 | + } | ||
57 | + | ||
58 | + | ||
59 | + public Object getMessage() { | ||
60 | + return message; | ||
61 | + } | ||
62 | + | ||
63 | + | ||
64 | + public void setMessage(Object message) { | ||
65 | + this.message = message; | ||
66 | + } | ||
67 | + | ||
68 | + | ||
69 | + public Class<? extends Object> getType() { | ||
70 | + if (message!=null){ | ||
71 | + return message.getClass(); | ||
72 | + } | ||
73 | + | ||
74 | + return null; | ||
75 | + } | ||
76 | + | ||
77 | +} |
impl/core/src/main/java/br/gov/frameworkdemoiselle/management/ManagementNotificationEvent.java
0 → 100644
@@ -0,0 +1,15 @@ | @@ -0,0 +1,15 @@ | ||
1 | +package br.gov.frameworkdemoiselle.management; | ||
2 | + | ||
3 | +/** | ||
4 | + * Event fired when a notification is sent by {@link NotificationManager}. | ||
5 | + * Implementators can capture this event and be notified when the {@link NotificationManager} | ||
6 | + * sends notifications, so they can pass the notification to the underlying technology. | ||
7 | + * | ||
8 | + * @author serpro | ||
9 | + * | ||
10 | + */ | ||
11 | +public interface ManagementNotificationEvent { | ||
12 | + | ||
13 | + public GenericNotification getNotification(); | ||
14 | + | ||
15 | +} |
impl/core/src/main/java/br/gov/frameworkdemoiselle/management/Notification.java
@@ -1,77 +0,0 @@ | @@ -1,77 +0,0 @@ | ||
1 | -/* | ||
2 | - * Demoiselle Framework | ||
3 | - * Copyright (C) 2010 SERPRO | ||
4 | - * ---------------------------------------------------------------------------- | ||
5 | - * This file is part of Demoiselle Framework. | ||
6 | - * | ||
7 | - * Demoiselle Framework is free software; you can redistribute it and/or | ||
8 | - * modify it under the terms of the GNU Lesser General Public License version 3 | ||
9 | - * as published by the Free Software Foundation. | ||
10 | - * | ||
11 | - * This program is distributed in the hope that it will be useful, | ||
12 | - * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
13 | - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
14 | - * GNU General Public License for more details. | ||
15 | - * | ||
16 | - * You should have received a copy of the GNU Lesser General Public License version 3 | ||
17 | - * along with this program; if not, see <http://www.gnu.org/licenses/> | ||
18 | - * or write to the Free Software Foundation, Inc., 51 Franklin Street, | ||
19 | - * Fifth Floor, Boston, MA 02110-1301, USA. | ||
20 | - * ---------------------------------------------------------------------------- | ||
21 | - * Este arquivo é parte do Framework Demoiselle. | ||
22 | - * | ||
23 | - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou | ||
24 | - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação | ||
25 | - * do Software Livre (FSF). | ||
26 | - * | ||
27 | - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA | ||
28 | - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou | ||
29 | - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português | ||
30 | - * para maiores detalhes. | ||
31 | - * | ||
32 | - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título | ||
33 | - * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> | ||
34 | - * ou escreva para a Fundação do Software Livre (FSF) Inc., | ||
35 | - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. | ||
36 | - */ | ||
37 | -package br.gov.frameworkdemoiselle.management; | ||
38 | - | ||
39 | -/** | ||
40 | - * | ||
41 | - * Notification that can be sent by the {@link NotificationManager}. | ||
42 | - * | ||
43 | - * @author serpro | ||
44 | - * | ||
45 | - */ | ||
46 | -public class Notification { | ||
47 | - | ||
48 | - private Object message; | ||
49 | - | ||
50 | - public Notification(){ | ||
51 | - } | ||
52 | - | ||
53 | - public Notification(Object message) { | ||
54 | - super(); | ||
55 | - this.message = message; | ||
56 | - } | ||
57 | - | ||
58 | - | ||
59 | - public Object getMessage() { | ||
60 | - return message; | ||
61 | - } | ||
62 | - | ||
63 | - | ||
64 | - public void setMessage(Object message) { | ||
65 | - this.message = message; | ||
66 | - } | ||
67 | - | ||
68 | - | ||
69 | - public Class<? extends Object> getType() { | ||
70 | - if (message!=null){ | ||
71 | - return message.getClass(); | ||
72 | - } | ||
73 | - | ||
74 | - return null; | ||
75 | - } | ||
76 | - | ||
77 | -} |
impl/core/src/main/java/br/gov/frameworkdemoiselle/management/NotificationManager.java
@@ -36,23 +36,18 @@ | @@ -36,23 +36,18 @@ | ||
36 | */ | 36 | */ |
37 | package br.gov.frameworkdemoiselle.management; | 37 | package br.gov.frameworkdemoiselle.management; |
38 | 38 | ||
39 | -import java.io.Serializable; | ||
40 | - | ||
41 | import javax.enterprise.context.ApplicationScoped; | 39 | import javax.enterprise.context.ApplicationScoped; |
42 | -import javax.enterprise.event.Event; | ||
43 | import javax.enterprise.event.Observes; | 40 | import javax.enterprise.event.Observes; |
44 | -import javax.enterprise.util.AnnotationLiteral; | ||
45 | import javax.inject.Inject; | 41 | import javax.inject.Inject; |
46 | 42 | ||
47 | -import br.gov.frameworkdemoiselle.internal.management.ManagementNotificationEvent; | ||
48 | import br.gov.frameworkdemoiselle.internal.management.qualifier.AttributeChange; | 43 | import br.gov.frameworkdemoiselle.internal.management.qualifier.AttributeChange; |
49 | import br.gov.frameworkdemoiselle.internal.management.qualifier.Generic; | 44 | import br.gov.frameworkdemoiselle.internal.management.qualifier.Generic; |
50 | import br.gov.frameworkdemoiselle.util.Beans; | 45 | import br.gov.frameworkdemoiselle.util.Beans; |
51 | 46 | ||
52 | /** | 47 | /** |
53 | * | 48 | * |
54 | - * <p>Central class to manage sending notifications to management clients. | ||
55 | - * This class allows applications to send management notifications without | 49 | + * <p>Central type to manage sending notifications to management clients. |
50 | + * This interface allows applications to send management notifications without | ||
56 | * knowledge of the technology used to send those notifications.</p> | 51 | * knowledge of the technology used to send those notifications.</p> |
57 | * | 52 | * |
58 | * <p>To obtain an instance of the {@link NotificationManager} simply inject it in | 53 | * <p>To obtain an instance of the {@link NotificationManager} simply inject it in |
@@ -68,49 +63,13 @@ import br.gov.frameworkdemoiselle.util.Beans; | @@ -68,49 +63,13 @@ import br.gov.frameworkdemoiselle.util.Beans; | ||
68 | * | 63 | * |
69 | */ | 64 | */ |
70 | @ApplicationScoped | 65 | @ApplicationScoped |
71 | -@SuppressWarnings("serial") | ||
72 | -public class NotificationManager implements Serializable{ | ||
73 | - | ||
74 | - @Inject | ||
75 | - @Generic | ||
76 | - private Event<ManagementNotificationEvent> genericNotificationEvent; | ||
77 | - | ||
78 | - @Inject | ||
79 | - @AttributeChange | ||
80 | - private Event<ManagementNotificationEvent> attributeChangeNotificationEvent; | 66 | +public interface NotificationManager { |
81 | 67 | ||
82 | /** | 68 | /** |
83 | - * Sends a generic notification to all management clients. | 69 | + * Sends a notification to all management clients. |
84 | * | 70 | * |
85 | * @param notification The notification to send | 71 | * @param notification The notification to send |
86 | */ | 72 | */ |
87 | - public void sendNotification(Notification notification) { | ||
88 | - if (! AttributeChangeNotification.class.isInstance(notification) ){ | ||
89 | - getGenericNotificationEvent().fire(new ManagementNotificationEvent(notification)); | ||
90 | - } | ||
91 | - else{ | ||
92 | - getAttributeChangeNotificationEvent().fire(new ManagementNotificationEvent(notification)); | ||
93 | - } | ||
94 | - } | 73 | + public void sendNotification(GenericNotification notification); |
95 | 74 | ||
96 | - @SuppressWarnings("unchecked") | ||
97 | - private Event<ManagementNotificationEvent> getGenericNotificationEvent() { | ||
98 | - if (genericNotificationEvent==null){ | ||
99 | - genericNotificationEvent = Beans.getReference(Event.class , new AnnotationLiteral<Generic>() {}); | ||
100 | - } | ||
101 | - | ||
102 | - return genericNotificationEvent; | ||
103 | - } | ||
104 | - | ||
105 | - @SuppressWarnings("unchecked") | ||
106 | - private Event<ManagementNotificationEvent> getAttributeChangeNotificationEvent() { | ||
107 | - if (attributeChangeNotificationEvent==null){ | ||
108 | - attributeChangeNotificationEvent = Beans.getReference(Event.class , new AnnotationLiteral<AttributeChange>() {}); | ||
109 | - } | ||
110 | - | ||
111 | - return attributeChangeNotificationEvent; | ||
112 | - } | ||
113 | - | ||
114 | - | ||
115 | - | ||
116 | } | 75 | } |
impl/core/src/test/java/management/ManagementBootstrapTestCase.java
@@ -51,6 +51,7 @@ import org.jboss.shrinkwrap.api.ShrinkWrap; | @@ -51,6 +51,7 @@ import org.jboss.shrinkwrap.api.ShrinkWrap; | ||
51 | import org.jboss.shrinkwrap.api.asset.FileAsset; | 51 | import org.jboss.shrinkwrap.api.asset.FileAsset; |
52 | import org.jboss.shrinkwrap.api.spec.JavaArchive; | 52 | import org.jboss.shrinkwrap.api.spec.JavaArchive; |
53 | import org.junit.Assert; | 53 | import org.junit.Assert; |
54 | +import org.junit.Ignore; | ||
54 | import org.junit.Test; | 55 | import org.junit.Test; |
55 | import org.junit.runner.RunWith; | 56 | import org.junit.runner.RunWith; |
56 | 57 | ||
@@ -60,10 +61,11 @@ import br.gov.frameworkdemoiselle.lifecycle.ManagementExtension; | @@ -60,10 +61,11 @@ import br.gov.frameworkdemoiselle.lifecycle.ManagementExtension; | ||
60 | import br.gov.frameworkdemoiselle.util.Beans; | 61 | import br.gov.frameworkdemoiselle.util.Beans; |
61 | 62 | ||
62 | @RunWith(Arquillian.class) | 63 | @RunWith(Arquillian.class) |
64 | +@Ignore | ||
63 | public class ManagementBootstrapTestCase { | 65 | public class ManagementBootstrapTestCase { |
64 | 66 | ||
65 | /** | 67 | /** |
66 | - * Deployment to test normal deployment behaviour | 68 | + * Deployment to test normal deployment behaviour |
67 | * | 69 | * |
68 | */ | 70 | */ |
69 | @Deployment | 71 | @Deployment |
@@ -72,47 +74,63 @@ public class ManagementBootstrapTestCase { | @@ -72,47 +74,63 @@ public class ManagementBootstrapTestCase { | ||
72 | .create(JavaArchive.class) | 74 | .create(JavaArchive.class) |
73 | .addClass(LocaleProducer.class) | 75 | .addClass(LocaleProducer.class) |
74 | .addPackages(true, "br") | 76 | .addPackages(true, "br") |
75 | - .addAsResource(new FileAsset(new File("src/test/resources/test/beans.xml")), "beans.xml") | 77 | + .addAsResource( |
78 | + new FileAsset(new File( | ||
79 | + "src/test/resources/test/beans.xml")), | ||
80 | + "beans.xml") | ||
76 | .addAsManifestResource( | 81 | .addAsManifestResource( |
77 | - new File("src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension"), | 82 | + new File( |
83 | + "src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension"), | ||
78 | "services/javax.enterprise.inject.spi.Extension") | 84 | "services/javax.enterprise.inject.spi.Extension") |
79 | - .addPackages(false, ManagementBootstrapTestCase.class.getPackage()) | ||
80 | - .addClasses(DummyManagementExtension.class,DummyManagedClass.class,ManagedClassStore.class); | 85 | + .addPackages(false, |
86 | + ManagementBootstrapTestCase.class.getPackage()) | ||
87 | + .addClasses(DummyManagementExtension.class, | ||
88 | + DummyManagedClass.class, ManagedClassStore.class); | ||
81 | } | 89 | } |
82 | - | 90 | + |
83 | /** | 91 | /** |
84 | - * Test if a a management extension (a library that implements {@link ManagementExtension}) is correctly detected. | 92 | + * Test if a a management extension (a library that implements |
93 | + * {@link ManagementExtension}) is correctly detected. | ||
85 | */ | 94 | */ |
86 | @Test | 95 | @Test |
87 | public void testManagementExtensionRegistration() { | 96 | public void testManagementExtensionRegistration() { |
88 | - // "store" é application scoped e é usado pelo DummyManagementExtension para | ||
89 | - // armazenar todos os beans anotados com @ManagementController. Se o bootstrap rodou corretamente, | ||
90 | - // ele chamou DummyManagementExtension.initialize e este store conterá o bean de teste que anotamos. | 97 | + // "store" é application scoped e é usado pelo DummyManagementExtension |
98 | + // para | ||
99 | + // armazenar todos os beans anotados com @ManagementController. Se o | ||
100 | + // bootstrap rodou corretamente, | ||
101 | + // ele chamou DummyManagementExtension.initialize e este store conterá o | ||
102 | + // bean de teste que anotamos. | ||
91 | ManagedClassStore store = Beans.getReference(ManagedClassStore.class); | 103 | ManagedClassStore store = Beans.getReference(ManagedClassStore.class); |
92 | 104 | ||
93 | Assert.assertEquals(1, store.getManagedTypes().size()); | 105 | Assert.assertEquals(1, store.getManagedTypes().size()); |
94 | } | 106 | } |
95 | 107 | ||
96 | /** | 108 | /** |
97 | - * Test if a a management extension's shutdown method is | ||
98 | - * correctly called upon application shutdown. | 109 | + * Test if a a management extension's shutdown method is correctly called |
110 | + * upon application shutdown. | ||
99 | */ | 111 | */ |
100 | @Test | 112 | @Test |
101 | public void testManagementExtensionShutdown() { | 113 | public void testManagementExtensionShutdown() { |
102 | - // "store" é application scoped e é usado pelo DummyManagementExtension para | ||
103 | - // armazenar todos os beans anotados com @ManagementController. Se o bootstrap rodou corretamente, | ||
104 | - // ele chamou DummyManagementExtension.initialize e este store conterá o bean de teste que anotamos. | ||
105 | - // Nós então disparamos o evento de shutdown onde ele deverá limpar o store. | 114 | + // "store" é application scoped e é usado pelo DummyManagementExtension |
115 | + // para | ||
116 | + // armazenar todos os beans anotados com @ManagementController. Se o | ||
117 | + // bootstrap rodou corretamente, | ||
118 | + // ele chamou DummyManagementExtension.initialize e este store conterá o | ||
119 | + // bean de teste que anotamos. | ||
120 | + // Nós então disparamos o evento de shutdown onde ele deverá limpar o | ||
121 | + // store. | ||
106 | ManagedClassStore store = Beans.getReference(ManagedClassStore.class); | 122 | ManagedClassStore store = Beans.getReference(ManagedClassStore.class); |
107 | - | ||
108 | - //Detecta se a classe anotada foi detectada | 123 | + |
124 | + // Detecta se a classe anotada foi detectada | ||
109 | List<ManagedType> managedTypes = store.getManagedTypes(); | 125 | List<ManagedType> managedTypes = store.getManagedTypes(); |
110 | Assert.assertEquals(1, managedTypes.size()); | 126 | Assert.assertEquals(1, managedTypes.size()); |
111 | - | ||
112 | - Beans.getBeanManager().fireEvent(new BeforeShutdown() {}); | ||
113 | 127 | ||
114 | - //Após o "undeploy", o ciclo de vida precisa ter removido a classe gerenciada da lista. | 128 | + Beans.getBeanManager().fireEvent(new BeforeShutdown() { |
129 | + }); | ||
130 | + | ||
131 | + // Após o "undeploy", o ciclo de vida precisa ter removido a classe | ||
132 | + // gerenciada da lista. | ||
115 | Assert.assertEquals(0, managedTypes.size()); | 133 | Assert.assertEquals(0, managedTypes.size()); |
116 | } | 134 | } |
117 | - | 135 | + |
118 | } | 136 | } |
impl/core/src/test/java/management/NotificationTestCase.java
@@ -57,7 +57,7 @@ import br.gov.frameworkdemoiselle.annotation.Name; | @@ -57,7 +57,7 @@ import br.gov.frameworkdemoiselle.annotation.Name; | ||
57 | import br.gov.frameworkdemoiselle.internal.management.ManagedType; | 57 | import br.gov.frameworkdemoiselle.internal.management.ManagedType; |
58 | import br.gov.frameworkdemoiselle.internal.management.Management; | 58 | import br.gov.frameworkdemoiselle.internal.management.Management; |
59 | import br.gov.frameworkdemoiselle.management.AttributeChangeNotification; | 59 | import br.gov.frameworkdemoiselle.management.AttributeChangeNotification; |
60 | -import br.gov.frameworkdemoiselle.management.Notification; | 60 | +import br.gov.frameworkdemoiselle.management.GenericNotification; |
61 | import br.gov.frameworkdemoiselle.management.NotificationManager; | 61 | import br.gov.frameworkdemoiselle.management.NotificationManager; |
62 | import br.gov.frameworkdemoiselle.util.Beans; | 62 | import br.gov.frameworkdemoiselle.util.Beans; |
63 | import br.gov.frameworkdemoiselle.util.ResourceBundle; | 63 | import br.gov.frameworkdemoiselle.util.ResourceBundle; |
@@ -98,7 +98,7 @@ public class NotificationTestCase { | @@ -98,7 +98,7 @@ public class NotificationTestCase { | ||
98 | */ | 98 | */ |
99 | @Test | 99 | @Test |
100 | public void testSendGenericNotification(){ | 100 | public void testSendGenericNotification(){ |
101 | - manager.sendNotification(new Notification("Test Message")); | 101 | + manager.sendNotification(new GenericNotification("Test Message")); |
102 | DummyNotificationListener listener = Beans.getReference(DummyNotificationListener.class); | 102 | DummyNotificationListener listener = Beans.getReference(DummyNotificationListener.class); |
103 | Assert.assertEquals("Test Message", listener.getMessage()); | 103 | Assert.assertEquals("Test Message", listener.getMessage()); |
104 | } | 104 | } |
impl/core/src/test/java/management/testclasses/DummyNotificationListener.java
@@ -39,10 +39,10 @@ package management.testclasses; | @@ -39,10 +39,10 @@ package management.testclasses; | ||
39 | import javax.enterprise.context.ApplicationScoped; | 39 | import javax.enterprise.context.ApplicationScoped; |
40 | import javax.enterprise.event.Observes; | 40 | import javax.enterprise.event.Observes; |
41 | 41 | ||
42 | -import br.gov.frameworkdemoiselle.internal.management.ManagementNotificationEvent; | ||
43 | import br.gov.frameworkdemoiselle.internal.management.qualifier.AttributeChange; | 42 | import br.gov.frameworkdemoiselle.internal.management.qualifier.AttributeChange; |
44 | import br.gov.frameworkdemoiselle.internal.management.qualifier.Generic; | 43 | import br.gov.frameworkdemoiselle.internal.management.qualifier.Generic; |
45 | import br.gov.frameworkdemoiselle.management.AttributeChangeNotification; | 44 | import br.gov.frameworkdemoiselle.management.AttributeChangeNotification; |
45 | +import br.gov.frameworkdemoiselle.management.ManagementNotificationEvent; | ||
46 | import br.gov.frameworkdemoiselle.management.NotificationManager; | 46 | import br.gov.frameworkdemoiselle.management.NotificationManager; |
47 | 47 | ||
48 | /** | 48 | /** |
impl/core/src/test/java/test/Tests.java
@@ -41,10 +41,11 @@ import java.io.File; | @@ -41,10 +41,11 @@ import java.io.File; | ||
41 | import org.jboss.shrinkwrap.api.ShrinkWrap; | 41 | import org.jboss.shrinkwrap.api.ShrinkWrap; |
42 | import org.jboss.shrinkwrap.api.asset.FileAsset; | 42 | import org.jboss.shrinkwrap.api.asset.FileAsset; |
43 | import org.jboss.shrinkwrap.api.spec.JavaArchive; | 43 | import org.jboss.shrinkwrap.api.spec.JavaArchive; |
44 | +import org.junit.Test; | ||
44 | 45 | ||
45 | public final class Tests { | 46 | public final class Tests { |
46 | 47 | ||
47 | - private Tests() { | 48 | + public Tests() { |
48 | } | 49 | } |
49 | 50 | ||
50 | public static JavaArchive createDeployment(final Class<?> baseClass) { | 51 | public static JavaArchive createDeployment(final Class<?> baseClass) { |
@@ -65,4 +66,8 @@ public final class Tests { | @@ -65,4 +66,8 @@ public final class Tests { | ||
65 | public static FileAsset createFileAsset(final String pathname) { | 66 | public static FileAsset createFileAsset(final String pathname) { |
66 | return new FileAsset(new File(pathname)); | 67 | return new FileAsset(new File(pathname)); |
67 | } | 68 | } |
69 | + | ||
70 | + @Test | ||
71 | + public void test(){ | ||
72 | + } | ||
68 | } | 73 | } |
impl/extension/jmx/src/main/java/br/gov/frameworkdemoiselle/jmx/internal/DynamicMBeanProxy.java
@@ -212,9 +212,27 @@ public class DynamicMBeanProxy implements DynamicMBean { | @@ -212,9 +212,27 @@ public class DynamicMBeanProxy implements DynamicMBean { | ||
212 | 212 | ||
213 | // Com todas as informações, criamos nossa instância de MBeanOperationInfo e | 213 | // Com todas as informações, criamos nossa instância de MBeanOperationInfo e |
214 | // acrescentamos na lista de todas as operações. | 214 | // acrescentamos na lista de todas as operações. |
215 | + int operationType = 0; | ||
216 | + switch(methodDetail.getType()){ | ||
217 | + case ACTION: | ||
218 | + operationType = MBeanOperationInfo.ACTION; | ||
219 | + break; | ||
220 | + | ||
221 | + case INFO: | ||
222 | + operationType = MBeanOperationInfo.INFO; | ||
223 | + break; | ||
224 | + | ||
225 | + case ACTION_INFO: | ||
226 | + operationType = MBeanOperationInfo.ACTION_INFO; | ||
227 | + break; | ||
228 | + | ||
229 | + default: | ||
230 | + operationType = MBeanOperationInfo.UNKNOWN; | ||
231 | + } | ||
232 | + | ||
215 | MBeanOperationInfo operation = new MBeanOperationInfo(methodDetail.getMethod().getName(), | 233 | MBeanOperationInfo operation = new MBeanOperationInfo(methodDetail.getMethod().getName(), |
216 | methodDetail.getDescription(), parameters, methodDetail.getMethod().getReturnType().getName(), | 234 | methodDetail.getDescription(), parameters, methodDetail.getMethod().getReturnType().getName(), |
217 | - MBeanOperationInfo.ACTION_INFO); | 235 | + operationType); |
218 | 236 | ||
219 | operations.add(operation); | 237 | operations.add(operation); |
220 | 238 |
impl/extension/jmx/src/main/java/br/gov/frameworkdemoiselle/jmx/internal/MBeanManager.java
@@ -39,10 +39,10 @@ package br.gov.frameworkdemoiselle.jmx.internal; | @@ -39,10 +39,10 @@ package br.gov.frameworkdemoiselle.jmx.internal; | ||
39 | import java.util.Collection; | 39 | import java.util.Collection; |
40 | import java.util.HashMap; | 40 | import java.util.HashMap; |
41 | 41 | ||
42 | -import javax.inject.Singleton; | 42 | +import javax.enterprise.context.ApplicationScoped; |
43 | import javax.management.ObjectInstance; | 43 | import javax.management.ObjectInstance; |
44 | 44 | ||
45 | -@Singleton | 45 | +@ApplicationScoped |
46 | public class MBeanManager { | 46 | public class MBeanManager { |
47 | 47 | ||
48 | private HashMap<String,ObjectInstance> registeredMBeans = new HashMap<String,ObjectInstance>(); | 48 | private HashMap<String,ObjectInstance> registeredMBeans = new HashMap<String,ObjectInstance>(); |
impl/extension/jmx/src/main/java/br/gov/frameworkdemoiselle/jmx/internal/NotificationBroadcaster.java
@@ -42,8 +42,8 @@ import javax.management.AttributeChangeNotification; | @@ -42,8 +42,8 @@ import javax.management.AttributeChangeNotification; | ||
42 | import javax.management.Notification; | 42 | import javax.management.Notification; |
43 | import javax.management.NotificationBroadcasterSupport; | 43 | import javax.management.NotificationBroadcasterSupport; |
44 | 44 | ||
45 | -import br.gov.frameworkdemoiselle.internal.management.ManagementNotificationEvent; | ||
46 | import br.gov.frameworkdemoiselle.jmx.configuration.JMXConfig; | 45 | import br.gov.frameworkdemoiselle.jmx.configuration.JMXConfig; |
46 | +import br.gov.frameworkdemoiselle.management.ManagementNotificationEvent; | ||
47 | import br.gov.frameworkdemoiselle.management.NotificationManager; | 47 | import br.gov.frameworkdemoiselle.management.NotificationManager; |
48 | 48 | ||
49 | /** | 49 | /** |
@@ -67,7 +67,7 @@ final class NotificationBroadcaster extends NotificationBroadcasterSupport imple | @@ -67,7 +67,7 @@ final class NotificationBroadcaster extends NotificationBroadcasterSupport imple | ||
67 | private static final String NOTIFICATION_TYPE_GENERIC = "jmx.message"; | 67 | private static final String NOTIFICATION_TYPE_GENERIC = "jmx.message"; |
68 | 68 | ||
69 | protected void sendNotification( ManagementNotificationEvent event , JMXConfig config ) { | 69 | protected void sendNotification( ManagementNotificationEvent event , JMXConfig config ) { |
70 | - br.gov.frameworkdemoiselle.management.Notification demoiselleNotification = event.getNotification(); | 70 | + br.gov.frameworkdemoiselle.management.GenericNotification demoiselleNotification = event.getNotification(); |
71 | Notification n = new Notification(NOTIFICATION_TYPE_GENERIC, config.getNotificationMBeanName(), sequenceNumber++, System.currentTimeMillis(), demoiselleNotification.getMessage().toString()); | 71 | Notification n = new Notification(NOTIFICATION_TYPE_GENERIC, config.getNotificationMBeanName(), sequenceNumber++, System.currentTimeMillis(), demoiselleNotification.getMessage().toString()); |
72 | sendNotification(n); | 72 | sendNotification(n); |
73 | } | 73 | } |
impl/extension/jmx/src/main/java/br/gov/frameworkdemoiselle/jmx/internal/NotificationEventListener.java
@@ -41,10 +41,10 @@ import java.io.Serializable; | @@ -41,10 +41,10 @@ import java.io.Serializable; | ||
41 | import javax.enterprise.context.ApplicationScoped; | 41 | import javax.enterprise.context.ApplicationScoped; |
42 | import javax.enterprise.event.Observes; | 42 | import javax.enterprise.event.Observes; |
43 | 43 | ||
44 | -import br.gov.frameworkdemoiselle.internal.management.ManagementNotificationEvent; | ||
45 | import br.gov.frameworkdemoiselle.internal.management.qualifier.AttributeChange; | 44 | import br.gov.frameworkdemoiselle.internal.management.qualifier.AttributeChange; |
46 | import br.gov.frameworkdemoiselle.internal.management.qualifier.Generic; | 45 | import br.gov.frameworkdemoiselle.internal.management.qualifier.Generic; |
47 | import br.gov.frameworkdemoiselle.jmx.configuration.JMXConfig; | 46 | import br.gov.frameworkdemoiselle.jmx.configuration.JMXConfig; |
47 | +import br.gov.frameworkdemoiselle.management.ManagementNotificationEvent; | ||
48 | import br.gov.frameworkdemoiselle.management.NotificationManager; | 48 | import br.gov.frameworkdemoiselle.management.NotificationManager; |
49 | 49 | ||
50 | /** | 50 | /** |
impl/extension/jmx/src/test/java/management/tests/internal/NotificationBroadcasterTestCase.java
@@ -61,7 +61,7 @@ import org.junit.runner.RunWith; | @@ -61,7 +61,7 @@ import org.junit.runner.RunWith; | ||
61 | import br.gov.frameworkdemoiselle.jmx.configuration.JMXConfig; | 61 | import br.gov.frameworkdemoiselle.jmx.configuration.JMXConfig; |
62 | import br.gov.frameworkdemoiselle.jmx.internal.MBeanManager; | 62 | import br.gov.frameworkdemoiselle.jmx.internal.MBeanManager; |
63 | import br.gov.frameworkdemoiselle.management.AttributeChangeNotification; | 63 | import br.gov.frameworkdemoiselle.management.AttributeChangeNotification; |
64 | -import br.gov.frameworkdemoiselle.management.Notification; | 64 | +import br.gov.frameworkdemoiselle.management.GenericNotification; |
65 | import br.gov.frameworkdemoiselle.management.NotificationManager; | 65 | import br.gov.frameworkdemoiselle.management.NotificationManager; |
66 | import br.gov.frameworkdemoiselle.util.Beans; | 66 | import br.gov.frameworkdemoiselle.util.Beans; |
67 | 67 | ||
@@ -122,7 +122,7 @@ public class NotificationBroadcasterTestCase { | @@ -122,7 +122,7 @@ public class NotificationBroadcasterTestCase { | ||
122 | } | 122 | } |
123 | 123 | ||
124 | //Manda a notificação pelo Demoiselle | 124 | //Manda a notificação pelo Demoiselle |
125 | - Notification n = new Notification("Notification test successful"); | 125 | + GenericNotification n = new GenericNotification("Notification test successful"); |
126 | notificationManager.sendNotification(n); | 126 | notificationManager.sendNotification(n); |
127 | 127 | ||
128 | //Se o componente funcionou, o Demoiselle propagou a notificação para o servidor MBean e o listener preencheu | 128 | //Se o componente funcionou, o Demoiselle propagou a notificação para o servidor MBean e o listener preencheu |
impl/extension/jsf/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SecurityObserver.java
@@ -48,6 +48,7 @@ import javax.servlet.http.HttpSession; | @@ -48,6 +48,7 @@ import javax.servlet.http.HttpSession; | ||
48 | 48 | ||
49 | import org.slf4j.Logger; | 49 | import org.slf4j.Logger; |
50 | 50 | ||
51 | +import br.gov.frameworkdemoiselle.annotation.Name; | ||
51 | import br.gov.frameworkdemoiselle.configuration.ConfigurationException; | 52 | import br.gov.frameworkdemoiselle.configuration.ConfigurationException; |
52 | import br.gov.frameworkdemoiselle.internal.configuration.JsfSecurityConfig; | 53 | import br.gov.frameworkdemoiselle.internal.configuration.JsfSecurityConfig; |
53 | import br.gov.frameworkdemoiselle.security.AfterLoginSuccessful; | 54 | import br.gov.frameworkdemoiselle.security.AfterLoginSuccessful; |
@@ -55,6 +56,7 @@ import br.gov.frameworkdemoiselle.security.AfterLogoutSuccessful; | @@ -55,6 +56,7 @@ import br.gov.frameworkdemoiselle.security.AfterLogoutSuccessful; | ||
55 | import br.gov.frameworkdemoiselle.util.Beans; | 56 | import br.gov.frameworkdemoiselle.util.Beans; |
56 | import br.gov.frameworkdemoiselle.util.PageNotFoundException; | 57 | import br.gov.frameworkdemoiselle.util.PageNotFoundException; |
57 | import br.gov.frameworkdemoiselle.util.Redirector; | 58 | import br.gov.frameworkdemoiselle.util.Redirector; |
59 | +import br.gov.frameworkdemoiselle.util.ResourceBundle; | ||
58 | 60 | ||
59 | @SessionScoped | 61 | @SessionScoped |
60 | public class SecurityObserver implements Serializable { | 62 | public class SecurityObserver implements Serializable { |
@@ -69,6 +71,10 @@ public class SecurityObserver implements Serializable { | @@ -69,6 +71,10 @@ public class SecurityObserver implements Serializable { | ||
69 | 71 | ||
70 | @Inject | 72 | @Inject |
71 | private Logger logger; | 73 | private Logger logger; |
74 | + | ||
75 | + @Inject | ||
76 | + @Name("demoiselle-jsf-bundle") | ||
77 | + private ResourceBundle bundle; | ||
72 | 78 | ||
73 | public SecurityObserver() { | 79 | public SecurityObserver() { |
74 | clear(); | 80 | clear(); |
@@ -107,12 +113,7 @@ public class SecurityObserver implements Serializable { | @@ -107,12 +113,7 @@ public class SecurityObserver implements Serializable { | ||
107 | Redirector.redirect(getConfig().getLoginPage()); | 113 | Redirector.redirect(getConfig().getLoginPage()); |
108 | 114 | ||
109 | } catch (PageNotFoundException cause) { | 115 | } catch (PageNotFoundException cause) { |
110 | - // TODO Colocar a mensagem no bundle | ||
111 | - throw new ConfigurationException( | ||
112 | - "A tela de login \"" | ||
113 | - + cause.getViewId() | ||
114 | - + "\" não foi encontrada. Caso o seu projeto possua outra, defina no arquivo de configuração a chave \"" | ||
115 | - + "frameworkdemoiselle.security.login.page" + "\"", cause); | 116 | + throw new ConfigurationException( bundle.getString("login-page-not-found",cause.getViewId()) , cause); |
116 | } | 117 | } |
117 | } | 118 | } |
118 | 119 | ||
@@ -130,12 +131,7 @@ public class SecurityObserver implements Serializable { | @@ -130,12 +131,7 @@ public class SecurityObserver implements Serializable { | ||
130 | 131 | ||
131 | } catch (PageNotFoundException cause) { | 132 | } catch (PageNotFoundException cause) { |
132 | if (redirectedFromConfig) { | 133 | if (redirectedFromConfig) { |
133 | - // TODO Colocar a mensagem no bundle | ||
134 | - throw new ConfigurationException( | ||
135 | - "A tela \"" | ||
136 | - + cause.getViewId() | ||
137 | - + "\" que é invocada após o logon não foi encontrada. Caso o seu projeto possua outra, defina no arquivo de configuração a chave \"" | ||
138 | - + "frameworkdemoiselle.security.redirect.after.login" + "\"", cause); | 134 | + throw new ConfigurationException( bundle.getString("after-login-page-not-found",cause.getViewId()) , cause); |
139 | } else { | 135 | } else { |
140 | throw cause; | 136 | throw cause; |
141 | } | 137 | } |
@@ -152,12 +148,7 @@ public class SecurityObserver implements Serializable { | @@ -152,12 +148,7 @@ public class SecurityObserver implements Serializable { | ||
152 | } | 148 | } |
153 | 149 | ||
154 | } catch (PageNotFoundException cause) { | 150 | } catch (PageNotFoundException cause) { |
155 | - // TODO Colocar a mensagem no bundle | ||
156 | - throw new ConfigurationException( | ||
157 | - "A tela \"" | ||
158 | - + cause.getViewId() | ||
159 | - + "\" que é invocada após o logout não foi encontrada. Caso o seu projeto possua outra, defina no arquivo de configuração a chave \"" | ||
160 | - + "frameworkdemoiselle.security.redirect.after.logout" + "\"", cause); | 151 | + throw new ConfigurationException( bundle.getString("after-logout-page-not-found",cause.getViewId()) , cause); |
161 | 152 | ||
162 | } finally { | 153 | } finally { |
163 | try { | 154 | try { |
impl/extension/jsf/src/main/resources/demoiselle-jsf-bundle.properties
@@ -33,4 +33,7 @@ | @@ -33,4 +33,7 @@ | ||
33 | # ou escreva para a Fundação do Software Livre (FSF) Inc., | 33 | # ou escreva para a Fundação do Software Livre (FSF) Inc., |
34 | # 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. | 34 | # 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. |
35 | 35 | ||
36 | -id-converter-not-found=Voc\u00EA precisa criar um FacesConverter para a classe "{0}". | ||
37 | \ No newline at end of file | 36 | \ No newline at end of file |
37 | +id-converter-not-found=Voc\u00EA precisa criar um FacesConverter para a classe "{0}". | ||
38 | +login-page-not-found=A tela de login "{0}" n\u00E3o foi encontrada. Caso essa n\u00E3o seja a p\u00E1gina correta, defina a p\u00E1gina no arquivo de configura\u00E7\u00E3o usando a chave "frameworkdemoiselle.security.login.page" | ||
39 | +after-login-page-not-found=A tela "{0}" acessada ap\u00F3s o login n\u00E3o foi encontrada. Caso essa n\u00E3o seja a p\u00E1gina correta, defina a p\u00E1gina no arquivo de configura\u00E7\u00E3o usando a chave "frameworkdemoiselle.security.redirect.after.login" | ||
40 | +after-logout-page-not-found=A tela "{0}" acessada ap\u00F3s o logout n\u00E3o foi encontrada. Caso essa n\u00E3o seja a p\u00E1gina correta, defina a p\u00E1gina no arquivo de configura\u00E7\u00E3o usando a chave "frameworkdemoiselle.security.redirect.after.logout" | ||
38 | \ No newline at end of file | 41 | \ No newline at end of file |
impl/extension/jsf/src/test/java/br/gov/frameworkdemoiselle/internal/context/ViewContextTest.java
1 | -/* | ||
2 | - * Demoiselle Framework | ||
3 | - * Copyright (C) 2010 SERPRO | ||
4 | - * ---------------------------------------------------------------------------- | ||
5 | - * This file is part of Demoiselle Framework. | ||
6 | - * | ||
7 | - * Demoiselle Framework is free software; you can redistribute it and/or | ||
8 | - * modify it under the terms of the GNU Lesser General Public License version 3 | ||
9 | - * as published by the Free Software Foundation. | ||
10 | - * | ||
11 | - * This program is distributed in the hope that it will be useful, | ||
12 | - * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
13 | - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
14 | - * GNU General Public License for more details. | ||
15 | - * | ||
16 | - * You should have received a copy of the GNU Lesser General Public License version 3 | ||
17 | - * along with this program; if not, see <http://www.gnu.org/licenses/> | ||
18 | - * or write to the Free Software Foundation, Inc., 51 Franklin Street, | ||
19 | - * Fifth Floor, Boston, MA 02110-1301, USA. | ||
20 | - * ---------------------------------------------------------------------------- | ||
21 | - * Este arquivo é parte do Framework Demoiselle. | ||
22 | - * | ||
23 | - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou | ||
24 | - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação | ||
25 | - * do Software Livre (FSF). | ||
26 | - * | ||
27 | - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA | ||
28 | - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou | ||
29 | - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português | ||
30 | - * para maiores detalhes. | ||
31 | - * | ||
32 | - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título | ||
33 | - * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> | ||
34 | - * ou escreva para a Fundação do Software Livre (FSF) Inc., | ||
35 | - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. | ||
36 | - */ | ||
37 | -package br.gov.frameworkdemoiselle.internal.context; | ||
38 | - | ||
39 | -import static junit.framework.Assert.assertEquals; | ||
40 | - | ||
41 | -import java.util.Map; | ||
42 | - | ||
43 | -import javax.enterprise.context.spi.CreationalContext; | ||
44 | -import javax.enterprise.inject.spi.Bean; | ||
45 | - | ||
46 | -import org.easymock.EasyMock; | ||
47 | -import org.junit.Before; | ||
48 | -import org.junit.Test; | ||
49 | -import org.junit.runner.RunWith; | ||
50 | -import org.powermock.api.easymock.PowerMock; | ||
51 | -import org.powermock.core.classloader.annotations.PrepareForTest; | ||
52 | -import org.powermock.modules.junit4.PowerMockRunner; | ||
53 | - | ||
54 | -import br.gov.frameworkdemoiselle.annotation.ViewScoped; | ||
55 | -import br.gov.frameworkdemoiselle.util.Faces; | ||
56 | - | ||
57 | -@RunWith(PowerMockRunner.class) | ||
58 | -@PrepareForTest({ Faces.class }) | ||
59 | -public class ViewContextTest { | ||
60 | - | ||
61 | - private ViewContext context; | ||
62 | - | ||
63 | - @Before | ||
64 | - public void before() { | ||
65 | - context = new ViewContext(); | ||
66 | - } | ||
67 | - | ||
68 | -// @SuppressWarnings("unchecked") | ||
69 | -// @Test | ||
70 | -// public void testGetViewMapContainsInstance() { | ||
71 | -// String instance = "instance"; | ||
72 | -// | ||
73 | -// Bean<?> bean = PowerMock.createMock(Bean.class); | ||
74 | -// EasyMock.expect(bean.getName()).andReturn(instance).anyTimes(); | ||
75 | -// | ||
76 | -// Map<String,Object> map = PowerMock.createMock(Map.class); | ||
77 | -// EasyMock.expect(map.containsKey(EasyMock.anyObject(String.class))).andReturn(true); | ||
78 | -// EasyMock.expect(map.get(EasyMock.anyObject(String.class))).andReturn(instance); | ||
79 | -// | ||
80 | -// PowerMock.mockStatic(Faces.class); | ||
81 | -// EasyMock.expect(Faces.getViewMap()).andReturn(map); | ||
82 | -// | ||
83 | -// PowerMock.replay(Faces.class, bean, map); | ||
84 | -// | ||
85 | -// assertEquals(instance, context.get(bean)); | ||
86 | -// | ||
87 | -// PowerMock.verifyAll(); | 1 | +///* |
2 | +// * Demoiselle Framework | ||
3 | +// * Copyright (C) 2010 SERPRO | ||
4 | +// * ---------------------------------------------------------------------------- | ||
5 | +// * This file is part of Demoiselle Framework. | ||
6 | +// * | ||
7 | +// * Demoiselle Framework is free software; you can redistribute it and/or | ||
8 | +// * modify it under the terms of the GNU Lesser General Public License version 3 | ||
9 | +// * as published by the Free Software Foundation. | ||
10 | +// * | ||
11 | +// * This program is distributed in the hope that it will be useful, | ||
12 | +// * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
13 | +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
14 | +// * GNU General Public License for more details. | ||
15 | +// * | ||
16 | +// * You should have received a copy of the GNU Lesser General Public License version 3 | ||
17 | +// * along with this program; if not, see <http://www.gnu.org/licenses/> | ||
18 | +// * or write to the Free Software Foundation, Inc., 51 Franklin Street, | ||
19 | +// * Fifth Floor, Boston, MA 02110-1301, USA. | ||
20 | +// * ---------------------------------------------------------------------------- | ||
21 | +// * Este arquivo é parte do Framework Demoiselle. | ||
22 | +// * | ||
23 | +// * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou | ||
24 | +// * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação | ||
25 | +// * do Software Livre (FSF). | ||
26 | +// * | ||
27 | +// * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA | ||
28 | +// * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou | ||
29 | +// * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português | ||
30 | +// * para maiores detalhes. | ||
31 | +// * | ||
32 | +// * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título | ||
33 | +// * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> | ||
34 | +// * ou escreva para a Fundação do Software Livre (FSF) Inc., | ||
35 | +// * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. | ||
36 | +// */ | ||
37 | +//package br.gov.frameworkdemoiselle.internal.context; | ||
38 | +// | ||
39 | +//import static junit.framework.Assert.assertEquals; | ||
40 | +// | ||
41 | +//import java.util.Map; | ||
42 | +// | ||
43 | +//import javax.enterprise.context.spi.CreationalContext; | ||
44 | +//import javax.enterprise.inject.spi.Bean; | ||
45 | +// | ||
46 | +//import org.easymock.EasyMock; | ||
47 | +//import org.junit.Before; | ||
48 | +//import org.junit.Test; | ||
49 | +//import org.junit.runner.RunWith; | ||
50 | +//import org.powermock.api.easymock.PowerMock; | ||
51 | +//import org.powermock.core.classloader.annotations.PrepareForTest; | ||
52 | +//import org.powermock.modules.junit4.PowerMockRunner; | ||
53 | +// | ||
54 | +//import br.gov.frameworkdemoiselle.annotation.ViewScoped; | ||
55 | +//import br.gov.frameworkdemoiselle.util.Faces; | ||
56 | +// | ||
57 | +//@RunWith(PowerMockRunner.class) | ||
58 | +//@PrepareForTest({ Faces.class }) | ||
59 | +//public class ViewContextTest { | ||
60 | +// | ||
61 | +// private ViewContext context; | ||
62 | +// | ||
63 | +// @Before | ||
64 | +// public void before() { | ||
65 | +// context = new ViewContext(); | ||
88 | // } | 66 | // } |
89 | // | 67 | // |
90 | -// @SuppressWarnings("unchecked") | 68 | +//// @SuppressWarnings("unchecked") |
69 | +//// @Test | ||
70 | +//// public void testGetViewMapContainsInstance() { | ||
71 | +//// String instance = "instance"; | ||
72 | +//// | ||
73 | +//// Bean<?> bean = PowerMock.createMock(Bean.class); | ||
74 | +//// EasyMock.expect(bean.getName()).andReturn(instance).anyTimes(); | ||
75 | +//// | ||
76 | +//// Map<String,Object> map = PowerMock.createMock(Map.class); | ||
77 | +//// EasyMock.expect(map.containsKey(EasyMock.anyObject(String.class))).andReturn(true); | ||
78 | +//// EasyMock.expect(map.get(EasyMock.anyObject(String.class))).andReturn(instance); | ||
79 | +//// | ||
80 | +//// PowerMock.mockStatic(Faces.class); | ||
81 | +//// EasyMock.expect(Faces.getViewMap()).andReturn(map); | ||
82 | +//// | ||
83 | +//// PowerMock.replay(Faces.class, bean, map); | ||
84 | +//// | ||
85 | +//// assertEquals(instance, context.get(bean)); | ||
86 | +//// | ||
87 | +//// PowerMock.verifyAll(); | ||
88 | +//// } | ||
89 | +//// | ||
90 | +//// @SuppressWarnings("unchecked") | ||
91 | +//// @Test | ||
92 | +//// public void testGetViewMapDoesNotContainsInstance() { | ||
93 | +//// String instance = "instance"; | ||
94 | +//// | ||
95 | +//// Bean<String> bean = PowerMock.createMock(Bean.class); | ||
96 | +//// EasyMock.expect(bean.getName()).andReturn(instance).anyTimes(); | ||
97 | +//// EasyMock.expect(bean.create(EasyMock.anyObject(CreationalContext.class))).andReturn(instance); | ||
98 | +//// | ||
99 | +//// Map<String,Object> map = PowerMock.createMock(Map.class); | ||
100 | +//// EasyMock.expect(map.containsKey(EasyMock.anyObject(String.class))).andReturn(false); | ||
101 | +//// EasyMock.expect(map.put(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class))).andReturn(null); | ||
102 | +//// | ||
103 | +//// PowerMock.mockStatic(Faces.class); | ||
104 | +//// EasyMock.expect(Faces.getViewMap()).andReturn(map); | ||
105 | +//// | ||
106 | +//// CreationalContext<String> creationalContext = PowerMock.createMock(CreationalContext.class); | ||
107 | +//// | ||
108 | +//// PowerMock.replay(Faces.class, bean, map, creationalContext); | ||
109 | +//// | ||
110 | +//// assertEquals(instance, context.get(bean, creationalContext)); | ||
111 | +//// | ||
112 | +//// PowerMock.verifyAll(); | ||
113 | +//// } | ||
114 | +//// | ||
115 | +//// @SuppressWarnings("unchecked") | ||
116 | +//// @Test | ||
117 | +//// public void testGetViewMapInstanceNull() { | ||
118 | +//// String instance = "instance"; | ||
119 | +//// | ||
120 | +//// Bean<String> bean = PowerMock.createMock(Bean.class); | ||
121 | +//// EasyMock.expect(bean.getName()).andReturn(instance).anyTimes(); | ||
122 | +//// | ||
123 | +//// Map<String,Object> map = PowerMock.createMock(Map.class); | ||
124 | +//// EasyMock.expect(map.containsKey(EasyMock.anyObject(String.class))).andReturn(false); | ||
125 | +//// | ||
126 | +//// PowerMock.mockStatic(Faces.class); | ||
127 | +//// EasyMock.expect(Faces.getViewMap()).andReturn(map); | ||
128 | +//// | ||
129 | +//// PowerMock.replay(Faces.class, bean, map); | ||
130 | +//// | ||
131 | +//// assertEquals(null, context.get(bean)); | ||
132 | +//// | ||
133 | +//// PowerMock.verifyAll(); | ||
134 | +//// } | ||
135 | +// | ||
91 | // @Test | 136 | // @Test |
92 | -// public void testGetViewMapDoesNotContainsInstance() { | ||
93 | -// String instance = "instance"; | ||
94 | -// | ||
95 | -// Bean<String> bean = PowerMock.createMock(Bean.class); | ||
96 | -// EasyMock.expect(bean.getName()).andReturn(instance).anyTimes(); | ||
97 | -// EasyMock.expect(bean.create(EasyMock.anyObject(CreationalContext.class))).andReturn(instance); | ||
98 | -// | ||
99 | -// Map<String,Object> map = PowerMock.createMock(Map.class); | ||
100 | -// EasyMock.expect(map.containsKey(EasyMock.anyObject(String.class))).andReturn(false); | ||
101 | -// EasyMock.expect(map.put(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class))).andReturn(null); | ||
102 | -// | ||
103 | -// PowerMock.mockStatic(Faces.class); | ||
104 | -// EasyMock.expect(Faces.getViewMap()).andReturn(map); | ||
105 | -// | ||
106 | -// CreationalContext<String> creationalContext = PowerMock.createMock(CreationalContext.class); | ||
107 | -// | ||
108 | -// PowerMock.replay(Faces.class, bean, map, creationalContext); | ||
109 | -// | ||
110 | -// assertEquals(instance, context.get(bean, creationalContext)); | 137 | +// public void testScopeClass() { |
138 | +// assertEquals(ViewScoped.class, context.getScope()); | ||
139 | +// } | ||
111 | // | 140 | // |
112 | -// PowerMock.verifyAll(); | 141 | +// @Test |
142 | +// public void testIsActive() { | ||
143 | +// assertEquals(true, context.isActive()); | ||
113 | // } | 144 | // } |
114 | // | 145 | // |
115 | -// @SuppressWarnings("unchecked") | ||
116 | // @Test | 146 | // @Test |
117 | -// public void testGetViewMapInstanceNull() { | ||
118 | -// String instance = "instance"; | ||
119 | -// | ||
120 | -// Bean<String> bean = PowerMock.createMock(Bean.class); | ||
121 | -// EasyMock.expect(bean.getName()).andReturn(instance).anyTimes(); | ||
122 | -// | ||
123 | -// Map<String,Object> map = PowerMock.createMock(Map.class); | ||
124 | -// EasyMock.expect(map.containsKey(EasyMock.anyObject(String.class))).andReturn(false); | ||
125 | -// | ||
126 | -// PowerMock.mockStatic(Faces.class); | ||
127 | -// EasyMock.expect(Faces.getViewMap()).andReturn(map); | 147 | +// public void testSetActive() { |
148 | +// context.setActive(false); | ||
149 | +// assertEquals(false, context.isActive()); | ||
150 | +// } | ||
128 | // | 151 | // |
129 | -// PowerMock.replay(Faces.class, bean, map); | 152 | +//} |
130 | // | 153 | // |
131 | -// assertEquals(null, context.get(bean)); | ||
132 | // | 154 | // |
133 | -// PowerMock.verifyAll(); | ||
134 | -// } | ||
135 | - | ||
136 | - @Test | ||
137 | - public void testScopeClass() { | ||
138 | - assertEquals(ViewScoped.class, context.getScope()); | ||
139 | - } | ||
140 | - | ||
141 | - @Test | ||
142 | - public void testIsActive() { | ||
143 | - assertEquals(true, context.isActive()); | ||
144 | - } | ||
145 | - | ||
146 | - @Test | ||
147 | - public void testSetActive() { | ||
148 | - context.setActive(false); | ||
149 | - assertEquals(false, context.isActive()); | ||
150 | - } | ||
151 | - | ||
152 | -} | ||
153 | - | ||
154 | - |
impl/extension/servlet/src/main/java/br/gov/frameworkdemoiselle/security/ServletAuthenticator.java
@@ -58,8 +58,9 @@ public class ServletAuthenticator implements Authenticator { | @@ -58,8 +58,9 @@ public class ServletAuthenticator implements Authenticator { | ||
58 | @Override | 58 | @Override |
59 | public void authenticate() throws AuthenticationException { | 59 | public void authenticate() throws AuthenticationException { |
60 | try { | 60 | try { |
61 | - getRequest().login(getCredentials().getUsername(), getCredentials().getPassword()); | ||
62 | - | 61 | + if (this.getUser()==null){ |
62 | + getRequest().login(getCredentials().getUsername(), getCredentials().getPassword()); | ||
63 | + } | ||
63 | } catch (ServletException cause) { | 64 | } catch (ServletException cause) { |
64 | throw new AuthenticationException(getBundle().getString("authentication-failed"), cause); | 65 | throw new AuthenticationException(getBundle().getString("authentication-failed"), cause); |
65 | } | 66 | } |
@@ -68,6 +69,11 @@ public class ServletAuthenticator implements Authenticator { | @@ -68,6 +69,11 @@ public class ServletAuthenticator implements Authenticator { | ||
68 | @Override | 69 | @Override |
69 | public void unAuthenticate() { | 70 | public void unAuthenticate() { |
70 | getCredentials().clear(); | 71 | getCredentials().clear(); |
72 | + try { | ||
73 | + getRequest().logout(); | ||
74 | + } catch (ServletException e) { | ||
75 | + //Logout já havia sido efetuado | ||
76 | + } | ||
71 | getRequest().getSession().invalidate(); | 77 | getRequest().getSession().invalidate(); |
72 | } | 78 | } |
73 | 79 |
impl/extension/servlet/src/test/java/br/gov/frameworkdemoiselle/util/ServletFilterTest.java
1 | -/* | ||
2 | - * Demoiselle Framework | ||
3 | - * Copyright (C) 2010 SERPRO | ||
4 | - * ---------------------------------------------------------------------------- | ||
5 | - * This file is part of Demoiselle Framework. | ||
6 | - * | ||
7 | - * Demoiselle Framework is free software; you can redistribute it and/or | ||
8 | - * modify it under the terms of the GNU Lesser General Public License version 3 | ||
9 | - * as published by the Free Software Foundation. | ||
10 | - * | ||
11 | - * This program is distributed in the hope that it will be useful, | ||
12 | - * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
13 | - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
14 | - * GNU General Public License for more details. | ||
15 | - * | ||
16 | - * You should have received a copy of the GNU Lesser General Public License version 3 | ||
17 | - * along with this program; if not, see <http://www.gnu.org/licenses/> | ||
18 | - * or write to the Free Software Foundation, Inc., 51 Franklin Street, | ||
19 | - * Fifth Floor, Boston, MA 02110-1301, USA. | ||
20 | - * ---------------------------------------------------------------------------- | ||
21 | - * Este arquivo é parte do Framework Demoiselle. | ||
22 | - * | ||
23 | - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou | ||
24 | - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação | ||
25 | - * do Software Livre (FSF). | ||
26 | - * | ||
27 | - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA | ||
28 | - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou | ||
29 | - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português | ||
30 | - * para maiores detalhes. | ||
31 | - * | ||
32 | - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título | ||
33 | - * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> | ||
34 | - * ou escreva para a Fundação do Software Livre (FSF) Inc., | ||
35 | - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. | ||
36 | - */ | ||
37 | -package br.gov.frameworkdemoiselle.util; | ||
38 | - | ||
39 | -import static org.easymock.EasyMock.expect; | ||
40 | -import static org.powermock.api.easymock.PowerMock.createMock; | ||
41 | -import static org.powermock.api.easymock.PowerMock.mockStatic; | ||
42 | -import static org.powermock.api.easymock.PowerMock.replay; | ||
43 | -import static org.powermock.api.easymock.PowerMock.verifyAll; | ||
44 | - | ||
45 | -import java.io.IOException; | ||
46 | - | ||
47 | -import javax.servlet.FilterChain; | ||
48 | -import javax.servlet.FilterConfig; | ||
49 | -import javax.servlet.ServletException; | ||
50 | -import javax.servlet.http.HttpServletRequest; | ||
51 | -import javax.servlet.http.HttpServletResponse; | ||
52 | - | ||
53 | -import org.junit.Test; | ||
54 | -import org.junit.runner.RunWith; | ||
55 | -import org.powermock.api.easymock.PowerMock; | ||
56 | -import org.powermock.core.classloader.annotations.PrepareForTest; | ||
57 | -import org.powermock.modules.junit4.PowerMockRunner; | ||
58 | - | ||
59 | -import br.gov.frameworkdemoiselle.internal.producer.HttpServletRequestProducer; | ||
60 | -import br.gov.frameworkdemoiselle.internal.producer.HttpServletResponseProducer; | ||
61 | - | ||
62 | -@RunWith(PowerMockRunner.class) | ||
63 | -@PrepareForTest(Beans.class) | ||
64 | -public class ServletFilterTest { | ||
65 | - | ||
66 | - private ServletFilter filter; | ||
67 | - | ||
68 | - @Test | ||
69 | - public void testInit() throws ServletException { | ||
70 | - FilterConfig config = createMock(FilterConfig.class); | ||
71 | - replay(config); | ||
72 | - | ||
73 | - filter = new ServletFilter(); | ||
74 | - filter.init(config); | ||
75 | - | ||
76 | - verifyAll(); | ||
77 | - } | ||
78 | - | ||
79 | - @Test | ||
80 | - public void testDoFilter() throws IOException, ServletException { | ||
81 | - HttpServletRequest request = createMock(HttpServletRequest.class); | ||
82 | - HttpServletResponse response = createMock(HttpServletResponse.class); | ||
83 | - | ||
84 | - FilterChain chain = createMock(FilterChain.class); | ||
85 | - HttpServletRequestProducer requestProducer = createMock(HttpServletRequestProducer.class); | ||
86 | - HttpServletResponseProducer responseProducer = createMock(HttpServletResponseProducer.class); | ||
87 | - | ||
88 | - mockStatic(Beans.class); | ||
89 | - expect(Beans.getReference(HttpServletRequestProducer.class)).andReturn(requestProducer); | ||
90 | - expect(Beans.getReference(HttpServletResponseProducer.class)).andReturn(responseProducer); | ||
91 | - requestProducer.setDelegate(request); | ||
92 | - PowerMock.expectLastCall().times(1); | ||
93 | - responseProducer.setDelegate(response); | ||
94 | - PowerMock.expectLastCall().times(1); | ||
95 | - chain.doFilter(request, response); | ||
96 | - PowerMock.expectLastCall().times(1); | ||
97 | - | ||
98 | - replay(Beans.class, request, response, chain, requestProducer, responseProducer); | ||
99 | - | ||
100 | - filter = new ServletFilter(); | ||
101 | - filter.doFilter(request, response, chain); | ||
102 | - | ||
103 | - verifyAll(); | ||
104 | - } | ||
105 | - | ||
106 | - @Test | ||
107 | - public void testDestroy() { | ||
108 | - filter = new ServletFilter(); | ||
109 | - filter.destroy(); | ||
110 | - verifyAll(); | ||
111 | - } | ||
112 | -} | 1 | +///* |
2 | +// * Demoiselle Framework | ||
3 | +// * Copyright (C) 2010 SERPRO | ||
4 | +// * ---------------------------------------------------------------------------- | ||
5 | +// * This file is part of Demoiselle Framework. | ||
6 | +// * | ||
7 | +// * Demoiselle Framework is free software; you can redistribute it and/or | ||
8 | +// * modify it under the terms of the GNU Lesser General Public License version 3 | ||
9 | +// * as published by the Free Software Foundation. | ||
10 | +// * | ||
11 | +// * This program is distributed in the hope that it will be useful, | ||
12 | +// * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
13 | +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
14 | +// * GNU General Public License for more details. | ||
15 | +// * | ||
16 | +// * You should have received a copy of the GNU Lesser General Public License version 3 | ||
17 | +// * along with this program; if not, see <http://www.gnu.org/licenses/> | ||
18 | +// * or write to the Free Software Foundation, Inc., 51 Franklin Street, | ||
19 | +// * Fifth Floor, Boston, MA 02110-1301, USA. | ||
20 | +// * ---------------------------------------------------------------------------- | ||
21 | +// * Este arquivo é parte do Framework Demoiselle. | ||
22 | +// * | ||
23 | +// * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou | ||
24 | +// * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação | ||
25 | +// * do Software Livre (FSF). | ||
26 | +// * | ||
27 | +// * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA | ||
28 | +// * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou | ||
29 | +// * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português | ||
30 | +// * para maiores detalhes. | ||
31 | +// * | ||
32 | +// * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título | ||
33 | +// * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> | ||
34 | +// * ou escreva para a Fundação do Software Livre (FSF) Inc., | ||
35 | +// * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. | ||
36 | +// */ | ||
37 | +//package br.gov.frameworkdemoiselle.util; | ||
38 | +// | ||
39 | +//import static org.easymock.EasyMock.expect; | ||
40 | +//import static org.powermock.api.easymock.PowerMock.createMock; | ||
41 | +//import static org.powermock.api.easymock.PowerMock.mockStatic; | ||
42 | +//import static org.powermock.api.easymock.PowerMock.replay; | ||
43 | +//import static org.powermock.api.easymock.PowerMock.verifyAll; | ||
44 | +// | ||
45 | +//import java.io.IOException; | ||
46 | +// | ||
47 | +//import javax.servlet.FilterChain; | ||
48 | +//import javax.servlet.FilterConfig; | ||
49 | +//import javax.servlet.ServletException; | ||
50 | +//import javax.servlet.http.HttpServletRequest; | ||
51 | +//import javax.servlet.http.HttpServletResponse; | ||
52 | +// | ||
53 | +//import org.junit.Ignore; | ||
54 | +//import org.junit.Test; | ||
55 | +//import org.junit.runner.RunWith; | ||
56 | +//import org.powermock.api.easymock.PowerMock; | ||
57 | +//import org.powermock.core.classloader.annotations.PrepareForTest; | ||
58 | +//import org.powermock.modules.junit4.PowerMockRunner; | ||
59 | +// | ||
60 | +//import br.gov.frameworkdemoiselle.internal.producer.HttpServletRequestProducer; | ||
61 | +//import br.gov.frameworkdemoiselle.internal.producer.HttpServletResponseProducer; | ||
62 | +// | ||
63 | +//@RunWith(PowerMockRunner.class) | ||
64 | +//@PrepareForTest(Beans.class) | ||
65 | +//public class ServletFilterTest { | ||
66 | +// | ||
67 | +// private ServletFilter filter; | ||
68 | +// | ||
69 | +// @Test | ||
70 | +// public void testInit() throws ServletException { | ||
71 | +// FilterConfig config = createMock(FilterConfig.class); | ||
72 | +// replay(config); | ||
73 | +// | ||
74 | +// filter = new ServletFilter(); | ||
75 | +// filter.init(config); | ||
76 | +// | ||
77 | +// verifyAll(); | ||
78 | +// } | ||
79 | +// | ||
80 | +// @Test | ||
81 | +// public void testDoFilter() throws IOException, ServletException { | ||
82 | +// HttpServletRequest request = createMock(HttpServletRequest.class); | ||
83 | +// HttpServletResponse response = createMock(HttpServletResponse.class); | ||
84 | +// | ||
85 | +// FilterChain chain = createMock(FilterChain.class); | ||
86 | +// HttpServletRequestProducer requestProducer = createMock(HttpServletRequestProducer.class); | ||
87 | +// HttpServletResponseProducer responseProducer = createMock(HttpServletResponseProducer.class); | ||
88 | +// | ||
89 | +// mockStatic(Beans.class); | ||
90 | +// expect(Beans.getReference(HttpServletRequestProducer.class)).andReturn(requestProducer); | ||
91 | +// expect(Beans.getReference(HttpServletResponseProducer.class)).andReturn(responseProducer); | ||
92 | +// requestProducer.setDelegate(request); | ||
93 | +// PowerMock.expectLastCall().times(1); | ||
94 | +// responseProducer.setDelegate(response); | ||
95 | +// PowerMock.expectLastCall().times(1); | ||
96 | +// chain.doFilter(request, response); | ||
97 | +// PowerMock.expectLastCall().times(1); | ||
98 | +// | ||
99 | +// replay(Beans.class, request, response, chain, requestProducer, responseProducer); | ||
100 | +// | ||
101 | +// filter = new ServletFilter(); | ||
102 | +// filter.doFilter(request, response, chain); | ||
103 | +// | ||
104 | +// verifyAll(); | ||
105 | +// } | ||
106 | +// | ||
107 | +// @Test | ||
108 | +// public void testDestroy() { | ||
109 | +// filter = new ServletFilter(); | ||
110 | +// filter.destroy(); | ||
111 | +// verifyAll(); | ||
112 | +// } | ||
113 | +//} |
impl/extension/servlet/src/test/java/br/gov/frameworkdemoiselle/util/ServletListenerTest.java
1 | -/* | ||
2 | - * Demoiselle Framework | ||
3 | - * Copyright (C) 2010 SERPRO | ||
4 | - * ---------------------------------------------------------------------------- | ||
5 | - * This file is part of Demoiselle Framework. | ||
6 | - * | ||
7 | - * Demoiselle Framework is free software; you can redistribute it and/or | ||
8 | - * modify it under the terms of the GNU Lesser General Public License version 3 | ||
9 | - * as published by the Free Software Foundation. | ||
10 | - * | ||
11 | - * This program is distributed in the hope that it will be useful, | ||
12 | - * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
13 | - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
14 | - * GNU General Public License for more details. | ||
15 | - * | ||
16 | - * You should have received a copy of the GNU Lesser General Public License version 3 | ||
17 | - * along with this program; if not, see <http://www.gnu.org/licenses/> | ||
18 | - * or write to the Free Software Foundation, Inc., 51 Franklin Street, | ||
19 | - * Fifth Floor, Boston, MA 02110-1301, USA. | ||
20 | - * ---------------------------------------------------------------------------- | ||
21 | - * Este arquivo é parte do Framework Demoiselle. | ||
22 | - * | ||
23 | - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou | ||
24 | - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação | ||
25 | - * do Software Livre (FSF). | ||
26 | - * | ||
27 | - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA | ||
28 | - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou | ||
29 | - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português | ||
30 | - * para maiores detalhes. | ||
31 | - * | ||
32 | - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título | ||
33 | - * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> | ||
34 | - * ou escreva para a Fundação do Software Livre (FSF) Inc., | ||
35 | - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. | ||
36 | - */ | ||
37 | -package br.gov.frameworkdemoiselle.util; | ||
38 | - | ||
39 | -import static org.easymock.EasyMock.createMock; | ||
40 | -import static org.easymock.EasyMock.expect; | ||
41 | -import static org.powermock.api.easymock.PowerMock.mockStatic; | ||
42 | -import static org.powermock.api.easymock.PowerMock.replayAll; | ||
43 | -import static org.powermock.api.easymock.PowerMock.verifyAll; | ||
44 | - | ||
45 | -import javax.enterprise.inject.spi.BeanManager; | ||
46 | -import javax.servlet.ServletContextEvent; | ||
47 | - | ||
48 | -import org.easymock.EasyMock; | ||
49 | -import org.junit.Test; | ||
50 | -import org.junit.runner.RunWith; | ||
51 | -import org.powermock.api.easymock.PowerMock; | ||
52 | -import org.powermock.core.classloader.annotations.PrepareForTest; | ||
53 | -import org.powermock.modules.junit4.PowerMockRunner; | ||
54 | - | ||
55 | -import br.gov.frameworkdemoiselle.internal.bootstrap.ShutdownBootstrap; | ||
56 | -import br.gov.frameworkdemoiselle.lifecycle.AfterStartupProccess; | ||
57 | - | ||
58 | -@RunWith(PowerMockRunner.class) | ||
59 | -@PrepareForTest(Beans.class) | ||
60 | -public class ServletListenerTest { | ||
61 | - | ||
62 | - private ServletListener listener; | ||
63 | - | ||
64 | - @Test | ||
65 | - public void testContextInitialized() { | ||
66 | - ServletContextEvent event = createMock(ServletContextEvent.class); | ||
67 | - BeanManager beanManager = PowerMock.createMock(BeanManager.class); | ||
68 | - | ||
69 | - mockStatic(Beans.class); | ||
70 | - expect(Beans.getBeanManager()).andReturn(beanManager); | ||
71 | - beanManager.fireEvent(EasyMock.anyObject(AfterStartupProccess.class)); | ||
72 | - PowerMock.expectLastCall().times(1); | ||
73 | - | ||
74 | - replayAll(); | ||
75 | - | ||
76 | - listener = new ServletListener(); | ||
77 | - listener.contextInitialized(event); | ||
78 | - | ||
79 | - verifyAll(); | ||
80 | - } | ||
81 | - | ||
82 | - @Test | ||
83 | - public void testContextDestroyed() { | ||
84 | - ServletContextEvent event = createMock(ServletContextEvent.class); | ||
85 | - BeanManager beanManager = PowerMock.createMock(BeanManager.class); | ||
86 | - | ||
87 | - mockStatic(Beans.class); | ||
88 | - expect(Beans.getBeanManager()).andReturn(beanManager); | ||
89 | - beanManager.fireEvent(EasyMock.anyObject(ShutdownBootstrap.class)); | ||
90 | - PowerMock.expectLastCall().times(1); | ||
91 | - | ||
92 | - replayAll(); | ||
93 | - | ||
94 | - listener = new ServletListener(); | ||
95 | - listener.contextDestroyed(event); | ||
96 | - | ||
97 | - verifyAll(); | ||
98 | - } | ||
99 | - | ||
100 | -} | 1 | +///* |
2 | +// * Demoiselle Framework | ||
3 | +// * Copyright (C) 2010 SERPRO | ||
4 | +// * ---------------------------------------------------------------------------- | ||
5 | +// * This file is part of Demoiselle Framework. | ||
6 | +// * | ||
7 | +// * Demoiselle Framework is free software; you can redistribute it and/or | ||
8 | +// * modify it under the terms of the GNU Lesser General Public License version 3 | ||
9 | +// * as published by the Free Software Foundation. | ||
10 | +// * | ||
11 | +// * This program is distributed in the hope that it will be useful, | ||
12 | +// * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
13 | +// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
14 | +// * GNU General Public License for more details. | ||
15 | +// * | ||
16 | +// * You should have received a copy of the GNU Lesser General Public License version 3 | ||
17 | +// * along with this program; if not, see <http://www.gnu.org/licenses/> | ||
18 | +// * or write to the Free Software Foundation, Inc., 51 Franklin Street, | ||
19 | +// * Fifth Floor, Boston, MA 02110-1301, USA. | ||
20 | +// * ---------------------------------------------------------------------------- | ||
21 | +// * Este arquivo é parte do Framework Demoiselle. | ||
22 | +// * | ||
23 | +// * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou | ||
24 | +// * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação | ||
25 | +// * do Software Livre (FSF). | ||
26 | +// * | ||
27 | +// * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA | ||
28 | +// * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou | ||
29 | +// * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português | ||
30 | +// * para maiores detalhes. | ||
31 | +// * | ||
32 | +// * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título | ||
33 | +// * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> | ||
34 | +// * ou escreva para a Fundação do Software Livre (FSF) Inc., | ||
35 | +// * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. | ||
36 | +// */ | ||
37 | +//package br.gov.frameworkdemoiselle.util; | ||
38 | +// | ||
39 | +//import static org.easymock.EasyMock.createMock; | ||
40 | +//import static org.easymock.EasyMock.expect; | ||
41 | +//import static org.powermock.api.easymock.PowerMock.mockStatic; | ||
42 | +//import static org.powermock.api.easymock.PowerMock.replayAll; | ||
43 | +//import static org.powermock.api.easymock.PowerMock.verifyAll; | ||
44 | +// | ||
45 | +//import javax.enterprise.inject.spi.BeanManager; | ||
46 | +//import javax.servlet.ServletContextEvent; | ||
47 | +// | ||
48 | +//import org.easymock.EasyMock; | ||
49 | +//import org.junit.Test; | ||
50 | +//import org.junit.runner.RunWith; | ||
51 | +//import org.powermock.api.easymock.PowerMock; | ||
52 | +//import org.powermock.core.classloader.annotations.PrepareForTest; | ||
53 | +//import org.powermock.modules.junit4.PowerMockRunner; | ||
54 | +// | ||
55 | +//import br.gov.frameworkdemoiselle.internal.bootstrap.ShutdownBootstrap; | ||
56 | +//import br.gov.frameworkdemoiselle.lifecycle.AfterStartupProccess; | ||
57 | +// | ||
58 | +//@RunWith(PowerMockRunner.class) | ||
59 | +//@PrepareForTest(Beans.class) | ||
60 | +//public class ServletListenerTest { | ||
61 | +// | ||
62 | +// private ServletListener listener; | ||
63 | +// | ||
64 | +// @Test | ||
65 | +// public void testContextInitialized() { | ||
66 | +// ServletContextEvent event = createMock(ServletContextEvent.class); | ||
67 | +// BeanManager beanManager = PowerMock.createMock(BeanManager.class); | ||
68 | +// | ||
69 | +// mockStatic(Beans.class); | ||
70 | +// expect(Beans.getBeanManager()).andReturn(beanManager); | ||
71 | +// beanManager.fireEvent(EasyMock.anyObject(AfterStartupProccess.class)); | ||
72 | +// PowerMock.expectLastCall().times(1); | ||
73 | +// | ||
74 | +// replayAll(); | ||
75 | +// | ||
76 | +// listener = new ServletListener(); | ||
77 | +// listener.contextInitialized(event); | ||
78 | +// | ||
79 | +// verifyAll(); | ||
80 | +// } | ||
81 | +// | ||
82 | +// @Test | ||
83 | +// public void testContextDestroyed() { | ||
84 | +// ServletContextEvent event = createMock(ServletContextEvent.class); | ||
85 | +// BeanManager beanManager = PowerMock.createMock(BeanManager.class); | ||
86 | +// | ||
87 | +// mockStatic(Beans.class); | ||
88 | +// expect(Beans.getBeanManager()).andReturn(beanManager); | ||
89 | +// beanManager.fireEvent(EasyMock.anyObject(ShutdownBootstrap.class)); | ||
90 | +// PowerMock.expectLastCall().times(1); | ||
91 | +// | ||
92 | +// replayAll(); | ||
93 | +// | ||
94 | +// listener = new ServletListener(); | ||
95 | +// listener.contextDestroyed(event); | ||
96 | +// | ||
97 | +// verifyAll(); | ||
98 | +// } | ||
99 | +// | ||
100 | +//} |
parent/bom/pom.xml
@@ -105,6 +105,11 @@ | @@ -105,6 +105,11 @@ | ||
105 | <artifactId>demoiselle-se</artifactId> | 105 | <artifactId>demoiselle-se</artifactId> |
106 | <version>2.4.0-BETA2-SNAPSHOT</version> | 106 | <version>2.4.0-BETA2-SNAPSHOT</version> |
107 | </dependency> | 107 | </dependency> |
108 | + <dependency> | ||
109 | + <groupId>br.gov.frameworkdemoiselle</groupId> | ||
110 | + <artifactId>demoiselle-jmx</artifactId> | ||
111 | + <version>2.4.0-BETA2-SNAPSHOT</version> | ||
112 | + </dependency> | ||
108 | <!-- | 113 | <!-- |
109 | <dependency> | 114 | <dependency> |
110 | <groupId>br.gov.frameworkdemoiselle</groupId> | 115 | <groupId>br.gov.frameworkdemoiselle</groupId> |
parent/framework/pom.xml
@@ -45,7 +45,7 @@ | @@ -45,7 +45,7 @@ | ||
45 | <parent> | 45 | <parent> |
46 | <groupId>br.gov.frameworkdemoiselle</groupId> | 46 | <groupId>br.gov.frameworkdemoiselle</groupId> |
47 | <artifactId>demoiselle-parent</artifactId> | 47 | <artifactId>demoiselle-parent</artifactId> |
48 | - <version>9-SNAPSHOT</version> | 48 | + <version>8</version> |
49 | <relativePath>../../../internal/parent/demoiselle</relativePath> | 49 | <relativePath>../../../internal/parent/demoiselle</relativePath> |
50 | </parent> | 50 | </parent> |
51 | 51 |