Commit 19073105b5ab6e15a278e58857b20c3612d413cc

Authored by Emerson Oliveira
2 parents f32b3319 6c692bd5
Exists in master

Merge branch '2.4.0' of git@github.com:demoiselle/framework.git into 2.4.0

Showing 26 changed files with 1694 additions and 20 deletions   Show diff stats
impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/bootstrap/ManagementBootstrap.java
1 1 package br.gov.frameworkdemoiselle.internal.bootstrap;
2 2  
  3 +import java.lang.reflect.Modifier;
3 4 import java.util.ArrayList;
4 5 import java.util.Collections;
5 6 import java.util.List;
  7 +import java.util.Locale;
6 8 import java.util.Set;
7 9  
8 10 import javax.enterprise.event.Observes;
... ... @@ -15,13 +17,16 @@ import javax.enterprise.inject.spi.BeforeShutdown;
15 17 import javax.enterprise.inject.spi.Extension;
16 18 import javax.enterprise.inject.spi.ProcessAnnotatedType;
17 19  
  20 +import br.gov.frameworkdemoiselle.DemoiselleException;
18 21 import br.gov.frameworkdemoiselle.internal.context.ContextManager;
19 22 import br.gov.frameworkdemoiselle.internal.context.ManagedContext;
20 23 import br.gov.frameworkdemoiselle.internal.management.ManagedType;
21 24 import br.gov.frameworkdemoiselle.internal.management.Management;
  25 +import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer;
22 26 import br.gov.frameworkdemoiselle.lifecycle.ManagementExtension;
23 27 import br.gov.frameworkdemoiselle.stereotype.ManagementController;
24 28 import br.gov.frameworkdemoiselle.util.Beans;
  29 +import br.gov.frameworkdemoiselle.util.ResourceBundle;
25 30  
26 31 public class ManagementBootstrap implements Extension {
27 32  
... ... @@ -43,8 +48,14 @@ public class ManagementBootstrap implements Extension {
43 48  
44 49 @SuppressWarnings("unchecked")
45 50 public void registerAvailableManagedTypes(@Observes final AfterDeploymentValidation event,BeanManager beanManager) {
  51 + ResourceBundle bundle = ResourceBundleProducer.create("demoiselle-core-bundle", Locale.getDefault());
  52 +
46 53 Management monitoringManager = Beans.getReference(Management.class);
47 54 for (AnnotatedType<?> type : types) {
  55 + if (type.getJavaClass().isInterface() || Modifier.isAbstract(type.getJavaClass().getModifiers()) ){
  56 + throw new DemoiselleException(bundle.getString("management-abstract-class-defined" , type.getJavaClass().getCanonicalName()));
  57 + }
  58 +
48 59 ManagedType managedType = new ManagedType(type.getJavaClass());
49 60 monitoringManager.addManagedType(managedType);
50 61 }
... ...
impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/management/ManagedType.java
... ... @@ -39,8 +39,11 @@ package br.gov.frameworkdemoiselle.internal.management;
39 39 import java.lang.annotation.Annotation;
40 40 import java.lang.reflect.Field;
41 41 import java.lang.reflect.Method;
  42 +import java.util.ArrayList;
42 43 import java.util.TreeMap;
43 44  
  45 +import javax.inject.Qualifier;
  46 +
44 47 import br.gov.frameworkdemoiselle.DemoiselleException;
45 48 import br.gov.frameworkdemoiselle.annotation.ManagedOperation;
46 49 import br.gov.frameworkdemoiselle.annotation.ManagedProperty;
... ... @@ -60,6 +63,8 @@ import br.gov.frameworkdemoiselle.util.ResourceBundle;
60 63 public class ManagedType {
61 64  
62 65 private Class<?> type;
  66 +
  67 + private Annotation[] qualifiers;
63 68  
64 69 private TreeMap<String, FieldDetail> fields;
65 70  
... ... @@ -83,6 +88,7 @@ public class ManagedType {
83 88 fields = new TreeMap<String, FieldDetail>();
84 89 operationMethods = new TreeMap<String, MethodDetail>();
85 90 this.description = type.getAnnotation(ManagementController.class).description();
  91 + this.qualifiers = getQualifierAnnotations(type);
86 92  
87 93 initialize();
88 94 }
... ... @@ -102,6 +108,18 @@ public class ManagedType {
102 108 public TreeMap<String, MethodDetail> getOperationMethods() {
103 109 return operationMethods;
104 110 }
  111 +
  112 + /**
  113 + * <p>Return a (possibly empty) list of all qualifiers this type have. Qualifiers
  114 + * are any annotations marked as {@link Qualifier}.</p>
  115 + *
  116 + * <p>This method returns the true list of qualifiers. If implementators change this list, it will
  117 + * affect future calls of this method. This is so that resources can be spared by not creating many instances of this list.</p>
  118 + *
  119 + */
  120 + public Annotation[] getQualifiers(){
  121 + return this.qualifiers;
  122 + }
105 123  
106 124 private void initialize() {
107 125 // Para cada atributo verifica se ele está anotado com ManagedProperty e extrai as informações dele (método get, set e
... ... @@ -224,6 +242,33 @@ public class ManagedType {
224 242  
225 243 return setterMethod;
226 244 }
  245 +
  246 + /**
  247 + * Indicates another {@link ManagedType} represents the same {@link Class} as this one. This method also supports a
  248 + * {@link Class} as a parameter, in this case it will return <code>true</code> if the passed class is exactly the
  249 + * same Java class represented by this {@link ManagedType}.
  250 + */
  251 + @Override
  252 + public boolean equals(Object other) {
  253 + if (other == null) {
  254 + return false;
  255 + }
  256 +
  257 + return ((ManagedType) other).getType().getCanonicalName().equals(this.getType().getCanonicalName());
  258 + }
  259 +
  260 + private synchronized Annotation[] getQualifierAnnotations(Class<?> beanClass){
  261 + Annotation[] annotations = beanClass.getAnnotations();
  262 + ArrayList<Annotation> qualifiers = new ArrayList<Annotation>(annotations.length);
  263 +
  264 + for (int i=0; i<annotations.length; i++){
  265 + if (annotations[i].annotationType().getAnnotation(Qualifier.class) != null){
  266 + qualifiers.add(annotations[i]);
  267 + }
  268 + }
  269 +
  270 + return qualifiers.toArray(new Annotation[0]);
  271 + }
227 272  
228 273 public final class FieldDetail {
229 274  
... ... @@ -317,18 +362,4 @@ public class ManagedType {
317 362 return parameterDescription;
318 363 }
319 364 }
320   -
321   - /**
322   - * Indicates another {@link ManagedType} represents the same {@link Class} as this one. This method also supports a
323   - * {@link Class} as a parameter, in this case it will return <code>true</code> if the passed class is exactly the
324   - * same Java class represented by this {@link ManagedType}.
325   - */
326   - @Override
327   - public boolean equals(Object other) {
328   - if (other == null) {
329   - return false;
330   - }
331   -
332   - return ((ManagedType) other).getType().getCanonicalName().equals(this.getType().getCanonicalName());
333   - }
334 365 }
... ...
impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/management/Management.java
... ... @@ -129,7 +129,7 @@ public class Management {
129 129 activateContexts(managedType.getType());
130 130  
131 131 try {
132   - Object delegate = Beans.getReference(managedType.getType());
  132 + Object delegate = Beans.getReference(managedType.getType() , managedType.getQualifiers());
133 133 MethodDetail method = managedType.getOperationMethods().get(actionName);
134 134  
135 135 if (method != null) {
... ... @@ -179,7 +179,7 @@ public class Management {
179 179 activateContexts(managedType.getType());
180 180  
181 181 try {
182   - Object delegate = Beans.getReference(managedType.getType());
  182 + Object delegate = Beans.getReference(managedType.getType() , managedType.getQualifiers());
183 183  
184 184 return getterMethod.invoke(delegate, (Object[]) null);
185 185 } catch (Exception e) {
... ... @@ -227,7 +227,7 @@ public class Management {
227 227 // Obtém uma instância da classe gerenciada, lembrando que
228 228 // classes
229 229 // anotadas com @ManagementController são sempre singletons.
230   - Object delegate = Beans.getReference(managedType.getType());
  230 + Object delegate = Beans.getReference(managedType.getType() , managedType.getQualifiers() );
231 231  
232 232 // Se houver um validador anexado à propriedade alterada, executa o validador sobre
233 233 // o novo valor.
... ... @@ -343,5 +343,6 @@ public class Management {
343 343  
344 344 return this.validator;
345 345 }
  346 +
346 347  
347 348 }
... ...
impl/core/src/main/java/br/gov/frameworkdemoiselle/stereotype/ManagementController.java
... ... @@ -49,12 +49,14 @@ import javax.enterprise.inject.Stereotype;
49 49 import javax.enterprise.util.Nonbinding;
50 50  
51 51 /**
52   - * <p>Identifies a <b>management controller</b> class. What it means is that an external client can manage the application
  52 + * <p>Identifies a <b>management controller</b> bean. What it means is that an external client can manage the application
53 53 * this class is in by reading or writing it's attributes and calling it's operations.</p>
54 54 * <p>
55 55 * Only fields annotated with {@link br.gov.frameworkdemoiselle.annotation.ManagedProperty} or
56 56 * methods annotated with {@link br.gov.frameworkdemoiselle.annotation.ManagedOperation} will be exposed
57 57 * to clients.</p>
  58 + * <p>Only bean implementations (concrete classes) can be management controllers. It's a runtime error to mark an interface
  59 + * or abstract class with this annotation.</p>
58 60 * <p>This stereotype only defines a class as managed, you need to choose an extension that will expose this managed class
59 61 * to external clients using any technology available. One example is the Demoiselle JMX extension, that will expose
60 62 * managed classes as MBeans.</p>
... ...
impl/core/src/main/resources/demoiselle-core-bundle.properties
... ... @@ -102,8 +102,9 @@ user-has-role=Usu\u00E1rio {0} possui a(s) role(s)\: {1}
102 102 authenticator-not-defined=Nenhum mecanismo de autentica\u00E7\u00E3o foi definido. Para utilizar {0} \u00E9 preciso definir a propriedade frameworkdemoiselle.security.authenticator.class como mecanismo de autentica\u00E7\u00E3o desejado no arquivo demoiselle.properties.
103 103  
104 104 management-notification-attribute-changed=O atributo [{0}] da classe gerenciada [{1}] foi alterado
105   -management-null-class-defined=A classe gerenciada informada n\u00E3o pode ser nula
106   -management-no-annotation-found=Classe {0} precisa ser anotada com @Managed
  105 +management-null-class-defined=O controlador de gerenciamento informado n\u00E3o pode ser [null]
  106 +management-abstract-class-defined=O controlador de gerenciamento [{0}] precisa ser uma classe concreta
  107 +management-no-annotation-found=Classe {0} precisa ser anotada com @ManagementController
107 108 management-invalid-property-no-getter-setter=Falha ao inicializar classe gerenciada {0}, n\u00E3o foi encontrado um m\u00E9todo get ou m\u00E9todo set para a propriedade {1}
108 109 management-invalid-property-as-operation=Falha ao inicializar classe gerenciada {0}, n\u00E3o \u00E9 poss\u00EDvel declarar uma propriedade cujo m\u00E9todo get ou set \u00E9 uma opera\u00E7\u00E3o
109 110 management-introspection-error=Erro ao ler atributos da classe gerenciada {0}
... ...
impl/extension/jmx/.gitignore 0 → 100644
... ... @@ -0,0 +1,9 @@
  1 +/.settings
  2 +/hsql:..tmp
  3 +/target
  4 +/.classpath
  5 +/.project
  6 +/hsql:..lck
  7 +/hsql:..log
  8 +/hsql:..properties
  9 +/hsql:..script
... ...
impl/extension/jmx/pom.xml 0 → 100644
... ... @@ -0,0 +1,131 @@
  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 +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  38 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  39 + <modelVersion>4.0.0</modelVersion>
  40 +
  41 + <artifactId>demoiselle-jmx</artifactId>
  42 + <name>Demoiselle Framework JMX Extension</name>
  43 + <description>Demoiselle Framework JMX Extension</description>
  44 +
  45 + <parent>
  46 + <artifactId>demoiselle-extension-parent</artifactId>
  47 + <groupId>br.gov.frameworkdemoiselle</groupId>
  48 + <version>2.4.0-BETA2-SNAPSHOT</version>
  49 + <relativePath>../../../parent/extension</relativePath>
  50 + </parent>
  51 +
  52 + <dependencies>
  53 + <!-- Depends on demoiselle-core -->
  54 + <dependency>
  55 + <groupId>br.gov.frameworkdemoiselle</groupId>
  56 + <artifactId>demoiselle-core</artifactId>
  57 + </dependency>
  58 +
  59 + <!-- Test dependencies -->
  60 + <dependency>
  61 + <groupId>junit</groupId>
  62 + <artifactId>junit</artifactId>
  63 + <scope>test</scope>
  64 + </dependency>
  65 + <dependency>
  66 + <groupId>org.jboss.arquillian.junit</groupId>
  67 + <artifactId>arquillian-junit-container</artifactId>
  68 + <scope>test</scope>
  69 + </dependency>
  70 + <dependency>
  71 + <groupId>org.jboss.shrinkwrap.resolver</groupId>
  72 + <artifactId>shrinkwrap-resolver-impl-maven</artifactId>
  73 + <version>2.0.0-beta-3</version>
  74 + <scope>test</scope>
  75 + </dependency>
  76 + <dependency>
  77 + <groupId>org.jboss.weld.se</groupId>
  78 + <artifactId>weld-se-core</artifactId>
  79 + <scope>test</scope>
  80 + </dependency>
  81 + <dependency>
  82 + <groupId>org.jboss.arquillian.container</groupId>
  83 + <artifactId>arquillian-weld-se-embedded-1.1</artifactId>
  84 + <scope>test</scope>
  85 + </dependency>
  86 + <dependency>
  87 + <groupId>org.hibernate</groupId>
  88 + <artifactId>hibernate-validator</artifactId>
  89 + <scope>test</scope>
  90 + </dependency>
  91 + </dependencies>
  92 +
  93 + <repositories>
  94 + <repository>
  95 + <id>sonatype-nexus-snapshots</id>
  96 + <name>Sonatype Nexus Snapshots</name>
  97 + <url>https://oss.sonatype.org/content/repositories/snapshots</url>
  98 + <snapshots>
  99 + <enabled>true</enabled>
  100 + </snapshots>
  101 + <releases>
  102 + <enabled>false</enabled>
  103 + </releases>
  104 + </repository>
  105 + <repository>
  106 + <id>sonatype-nexus-releases</id>
  107 + <name>Sonatype Nexus Releases</name>
  108 + <url>https://oss.sonatype.org/content/repositories/releases</url>
  109 + <snapshots>
  110 + <enabled>false</enabled>
  111 + </snapshots>
  112 + <releases>
  113 + <enabled>true</enabled>
  114 + </releases>
  115 + </repository>
  116 + </repositories>
  117 +
  118 + <url>http://www.frameworkdemoiselle.gov.br</url>
  119 +
  120 + <organization>
  121 + <name>SERPRO - Serviço Federal de Processamento de Dados</name>
  122 + <url>http://www.serpro.gov.br</url>
  123 + </organization>
  124 +
  125 + <licenses>
  126 + <license>
  127 + <name>GNU Lesser General Public License, Version 3</name>
  128 + <url>http://www.gnu.org/licenses/lgpl-3.0.txt</url>
  129 + </license>
  130 + </licenses>
  131 +</project>
0 132 \ No newline at end of file
... ...
impl/extension/jmx/src/main/java/br/gov/frameworkdemoiselle/jmx/bootstrap/JMXManagementExtension.java 0 → 100644
... ... @@ -0,0 +1,108 @@
  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.jmx.bootstrap;
  38 +
  39 +import java.util.List;
  40 +
  41 +import javax.management.ObjectInstance;
  42 +
  43 +import br.gov.frameworkdemoiselle.annotation.Name;
  44 +import br.gov.frameworkdemoiselle.internal.management.ManagedType;
  45 +import br.gov.frameworkdemoiselle.jmx.configuration.JMXConfig;
  46 +import br.gov.frameworkdemoiselle.jmx.internal.DynamicMBeanProxy;
  47 +import br.gov.frameworkdemoiselle.jmx.internal.MBeanHelper;
  48 +import br.gov.frameworkdemoiselle.jmx.internal.MBeanManager;
  49 +import br.gov.frameworkdemoiselle.jmx.internal.NotificationEventListener;
  50 +import br.gov.frameworkdemoiselle.lifecycle.ManagementExtension;
  51 +import br.gov.frameworkdemoiselle.util.Beans;
  52 +
  53 +public class JMXManagementExtension implements ManagementExtension {
  54 +
  55 + public void registerNotificationMBean(){
  56 + MBeanManager mbeanManager = Beans.getReference(MBeanManager.class);
  57 + JMXConfig configuration = Beans.getReference(JMXConfig.class);
  58 +
  59 + StringBuffer notificationMBeanName = new StringBuffer()
  60 + .append( configuration.getNotificationDomain()!=null ? configuration.getNotificationDomain() : "br.gov.frameworkdemoiselle.jmx" )
  61 + .append(":name=")
  62 + .append(configuration.getNotificationMBeanName());
  63 +
  64 + if (mbeanManager.findMBeanInstance(notificationMBeanName.toString()) == null){
  65 + NotificationEventListener listener = Beans.getReference(NotificationEventListener.class);
  66 +
  67 + ObjectInstance instance = MBeanHelper.register(listener.createNotificationBroadcaster(), notificationMBeanName.toString());
  68 + mbeanManager.storeRegisteredMBean(instance);
  69 + }
  70 + }
  71 +
  72 + @Override
  73 + public void initialize(List<ManagedType> managedTypes) {
  74 + MBeanManager manager = Beans.getReference(MBeanManager.class);
  75 + JMXConfig configuration = Beans.getReference(JMXConfig.class);
  76 +
  77 + for (ManagedType type : managedTypes) {
  78 + DynamicMBeanProxy beanProxy = new DynamicMBeanProxy(type);
  79 +
  80 + Name nameAnnotation = type.getType().getAnnotation(Name.class);
  81 + String mbeanName = nameAnnotation != null ? nameAnnotation.value() : type.getType().getSimpleName();
  82 +
  83 + StringBuffer name = new StringBuffer()
  84 + .append( configuration.getMbeanDomain()!=null ? configuration.getMbeanDomain() : type.getType().getPackage().getName() )
  85 + .append(":name=")
  86 + .append( mbeanName );
  87 +
  88 +
  89 + if (manager.findMBeanInstance(name.toString()) == null){
  90 + ObjectInstance instance = MBeanHelper.register(beanProxy, name.toString());
  91 + manager.storeRegisteredMBean(instance);
  92 + }
  93 + }
  94 +
  95 + registerNotificationMBean();
  96 + }
  97 +
  98 + @Override
  99 + public void shutdown(List<ManagedType> managedTypes) {
  100 + MBeanManager manager = Beans.getReference(MBeanManager.class);
  101 + for (ObjectInstance instance : manager.listRegisteredMBeans()){
  102 + MBeanHelper.unregister(instance.getObjectName());
  103 + }
  104 +
  105 + manager.cleanRegisteredMBeans();
  106 + }
  107 +
  108 +}
... ...
impl/extension/jmx/src/main/java/br/gov/frameworkdemoiselle/jmx/configuration/JMXConfig.java 0 → 100644
... ... @@ -0,0 +1,118 @@
  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.jmx.configuration;
  38 +
  39 +import javax.management.NotificationBroadcaster;
  40 +
  41 +import br.gov.frameworkdemoiselle.annotation.Name;
  42 +import br.gov.frameworkdemoiselle.configuration.Configuration;
  43 +
  44 +@Configuration(prefix = "frameworkdemoiselle.management.jmx.")
  45 +public class JMXConfig {
  46 +
  47 + @Name("mbean.domain")
  48 + private String mbeanDomain;
  49 +
  50 + @Name("notification.domain")
  51 + private String notificationDomain;
  52 +
  53 + @Name("notification.name")
  54 + private String notificationMBeanName = "NotificationBroadcaster";
  55 +
  56 + /**
  57 + * </p>The domain to register all {@link Managed} classes found during boot.</p>
  58 + *
  59 + * <p>The full name of a MBean has the format of <code>domain:name=MBeanName</code> (ex: <code>br.gov.frameworkdemoiselle.jmx:name=NotificationBroadcaster</code>), this
  60 + * parameter is the "domain" portion of the full name.</p>
  61 + *
  62 + * <p>The default is <code>null</code> and when is set to <code>null</code>, all {@link Managed} classes will use it's own package as the domain.</p>
  63 + *
  64 + */
  65 + public String getMbeanDomain() {
  66 + return mbeanDomain;
  67 + }
  68 +
  69 + /**
  70 + * @see #getMbeanDomain()
  71 + */
  72 + public void setMbeanDomain(String mbeanDomain) {
  73 + this.mbeanDomain = mbeanDomain;
  74 + }
  75 +
  76 + /**
  77 + * <p>The name the {@link NotificationBroadcaster} MBean will be registered to. The full name
  78 + * of a MBean has the format of <code>domain:name=MBeanName</code> (ex: <code>br.gov.frameworkdemoiselle.jmx:name=NotificationBroadcaster</code>), this
  79 + * parameter is the ":name=MBeanName" portion without the ":name=".</p>
  80 + *
  81 + * <p>The default is the value returned by {@link Class#getSimpleName()} when called from the {@link NotificationBroadcaster} class.</p>
  82 + *
  83 + * @see #getMbeanDomain()
  84 + */
  85 + public String getNotificationMBeanName() {
  86 + return notificationMBeanName;
  87 + }
  88 +
  89 + /**
  90 + * @see #getNotificationMBeanName()
  91 + */
  92 + public void setNotificationMBeanName(String notificationMBeanName) {
  93 + this.notificationMBeanName = notificationMBeanName;
  94 + }
  95 +
  96 + /**
  97 + * </p>The domain to register the {@link NotificationBroadcaster} MBean.</p>
  98 + *
  99 + * <p>The full name of a MBean has the format of <code>domain:name=MBeanName</code> (ex: <code>br.gov.frameworkdemoiselle.jmx:name=NotificationBroadcaster</code>), this
  100 + * parameter is the "domain" portion of the full name.</p>
  101 + *
  102 + * <p>The default is <code>br.gov.frameworkdemoiselle.jmx</code>.</p>
  103 + *
  104 + */
  105 + public String getNotificationDomain() {
  106 + return notificationDomain;
  107 + }
  108 +
  109 + /**
  110 + * @see #getNotificationDomain()
  111 + */
  112 + public void setNotificationDomain(String notificationDomain) {
  113 + this.notificationDomain = notificationDomain;
  114 + }
  115 +
  116 +
  117 +
  118 +}
... ...
impl/extension/jmx/src/main/java/br/gov/frameworkdemoiselle/jmx/internal/DynamicMBeanProxy.java 0 → 100644
... ... @@ -0,0 +1,239 @@
  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.jmx.internal;
  38 +
  39 +import java.util.ArrayList;
  40 +import java.util.Locale;
  41 +import java.util.Map.Entry;
  42 +
  43 +import javax.management.Attribute;
  44 +import javax.management.AttributeList;
  45 +import javax.management.AttributeNotFoundException;
  46 +import javax.management.DynamicMBean;
  47 +import javax.management.InvalidAttributeValueException;
  48 +import javax.management.MBeanAttributeInfo;
  49 +import javax.management.MBeanException;
  50 +import javax.management.MBeanInfo;
  51 +import javax.management.MBeanOperationInfo;
  52 +import javax.management.MBeanParameterInfo;
  53 +import javax.management.ReflectionException;
  54 +
  55 +import br.gov.frameworkdemoiselle.DemoiselleException;
  56 +import br.gov.frameworkdemoiselle.internal.management.ManagedType;
  57 +import br.gov.frameworkdemoiselle.internal.management.ManagedType.FieldDetail;
  58 +import br.gov.frameworkdemoiselle.internal.management.ManagedType.MethodDetail;
  59 +import br.gov.frameworkdemoiselle.internal.management.ManagedType.ParameterDetail;
  60 +import br.gov.frameworkdemoiselle.internal.management.Management;
  61 +import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer;
  62 +import br.gov.frameworkdemoiselle.stereotype.ManagementController;
  63 +import br.gov.frameworkdemoiselle.util.Beans;
  64 +import br.gov.frameworkdemoiselle.util.ResourceBundle;
  65 +
  66 +/**
  67 + * <p>
  68 + * This class is a MBean that gets registered everytime you mark a class with {@link ManagementController}. It dynamicaly reads the
  69 + * fields and operations contained in a {@link ManagementController} class and exposes them to the MBean server. Everytime a client
  70 + * tries to call an operation or read/write a property inside a ManagementController class, this class will call the appropriate
  71 + * method and pass the result to the MBean client.
  72 + * </p>
  73 + *
  74 + * @author SERPRO
  75 + */
  76 +public class DynamicMBeanProxy implements DynamicMBean {
  77 +
  78 + private MBeanInfo delegateInfo;
  79 +
  80 + private ManagedType managedType;
  81 +
  82 + private ResourceBundle bundle = ResourceBundleProducer.create("demoiselle-jmx-bundle", Locale.getDefault());
  83 +
  84 + public DynamicMBeanProxy(ManagedType type) {
  85 + if (type == null) {
  86 + throw new NullPointerException(bundle.getString("mbean-null-type-defined"));
  87 + }
  88 + managedType = type;
  89 + }
  90 +
  91 + @Override
  92 + public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException {
  93 + // Se o bean ainda não foi lido para determinar seus atributos, o faz agora.
  94 + if (delegateInfo == null) {
  95 + initializeMBeanInfo();
  96 + }
  97 +
  98 + Management manager = Beans.getReference(Management.class);
  99 + return manager.getProperty(managedType, attribute);
  100 + }
  101 +
  102 + @Override
  103 + public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException,
  104 + MBeanException, ReflectionException {
  105 +
  106 + // Se o bean ainda não foi lido para determinar seus atributos, o faz agora.
  107 + if (delegateInfo == null) {
  108 + initializeMBeanInfo();
  109 + }
  110 +
  111 + Management manager = Beans.getReference(Management.class);
  112 + manager.setProperty(managedType, attribute.getName(), attribute.getValue());
  113 + }
  114 +
  115 + @Override
  116 + public AttributeList getAttributes(String[] attributes) {
  117 + if (attributes != null) {
  118 + AttributeList list = new AttributeList();
  119 + for (String attribute : attributes) {
  120 + try {
  121 + Object value = getAttribute(attribute);
  122 + list.add(new Attribute(attribute, value));
  123 + } catch (Throwable t) {
  124 + }
  125 + }
  126 +
  127 + return list;
  128 + }
  129 +
  130 + return null;
  131 + }
  132 +
  133 + @Override
  134 + public AttributeList setAttributes(AttributeList attributes) {
  135 + AttributeList settedAttributes = new AttributeList();
  136 + if (attributes != null) {
  137 + for (Attribute attribute : attributes.asList()) {
  138 + try {
  139 + setAttribute(attribute);
  140 +
  141 + // A razão para separarmos a criação do atributo de sua adição na lista é que
  142 + // caso a obtenção do novo valor do atributo dispare uma exceção então o atributo não será
  143 + // adicionado na lista de atributos que foram afetados.
  144 + Attribute attributeWithNewValue = new Attribute(attribute.getName(),
  145 + getAttribute(attribute.getName()));
  146 + settedAttributes.add(attributeWithNewValue);
  147 + } catch (Throwable t) {
  148 + }
  149 + }
  150 + }
  151 +
  152 + return settedAttributes;
  153 + }
  154 +
  155 + @Override
  156 + public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException,
  157 + ReflectionException {
  158 +
  159 + // Se o bean ainda não foi lido para determinar seus atributos, o faz agora.
  160 + if (this.delegateInfo == null) {
  161 + initializeMBeanInfo();
  162 + }
  163 +
  164 + Management manager = Beans.getReference(Management.class);
  165 + return manager.invoke(managedType, actionName, params);
  166 + }
  167 +
  168 + /**
  169 + * Initialize the Managed information for this instance of Managed
  170 + */
  171 + private void initializeMBeanInfo() {
  172 + // Aqui vamos armazenar nossos atributos
  173 + ArrayList<MBeanAttributeInfo> attributes = new ArrayList<MBeanAttributeInfo>();
  174 +
  175 + // Aqui vamos armazenar nossas operações
  176 + ArrayList<MBeanOperationInfo> operations = new ArrayList<MBeanOperationInfo>();
  177 +
  178 + // Para cada propriedade descoberta no ManagementController, cria um attributeInfo correspondente
  179 + for (Entry<String, FieldDetail> fieldEntry : managedType.getFields().entrySet()) {
  180 +
  181 + try {
  182 +
  183 + MBeanAttributeInfo attributeInfo = new MBeanAttributeInfo(fieldEntry.getKey(), fieldEntry.getValue()
  184 + .getDescription(), fieldEntry.getValue().getGetterMethod(), fieldEntry.getValue()
  185 + .getSetterMethod());
  186 + attributes.add(attributeInfo);
  187 +
  188 + } catch (javax.management.IntrospectionException e) {
  189 + throw new DemoiselleException(bundle.getString("mbean-introspection-error", managedType.getType()
  190 + .getSimpleName()));
  191 + }
  192 + }
  193 +
  194 + // Para cada operação descoberta no ManagementController, cria um operationInfo correspondente
  195 + for (Entry<String, MethodDetail> methodEntry : managedType.getOperationMethods().entrySet()) {
  196 +
  197 + MethodDetail methodDetail = methodEntry.getValue();
  198 +
  199 + ParameterDetail[] parameterTypes = methodDetail.getParameterTypers();
  200 +
  201 + MBeanParameterInfo[] parameters = parameterTypes.length > 0 ? new MBeanParameterInfo[parameterTypes.length]
  202 + : null;
  203 +
  204 + if (parameters != null) {
  205 +
  206 + for (int i = 0; i < parameterTypes.length; i++) {
  207 +
  208 + parameters[i] = new MBeanParameterInfo(parameterTypes[i].getParameterName(), parameterTypes[i]
  209 + .getParameterType().getCanonicalName(), parameterTypes[i].getParameterDescription());
  210 + }
  211 + }
  212 +
  213 + // Com todas as informações, criamos nossa instância de MBeanOperationInfo e
  214 + // acrescentamos na lista de todas as operações.
  215 + MBeanOperationInfo operation = new MBeanOperationInfo(methodDetail.getMethod().getName(),
  216 + methodDetail.getDescription(), parameters, methodDetail.getMethod().getReturnType().getName(),
  217 + MBeanOperationInfo.ACTION_INFO);
  218 +
  219 + operations.add(operation);
  220 +
  221 + }
  222 +
  223 + // Por fim criamos nosso bean info.
  224 + delegateInfo = new MBeanInfo(managedType.getType().getCanonicalName(), managedType.getDescription(),
  225 + attributes.toArray(new MBeanAttributeInfo[0]), null, operations.toArray(new MBeanOperationInfo[0]),
  226 + null);
  227 +
  228 + }
  229 +
  230 + @Override
  231 + public MBeanInfo getMBeanInfo() {
  232 + if (delegateInfo == null) {
  233 + initializeMBeanInfo();
  234 + }
  235 +
  236 + return delegateInfo;
  237 + }
  238 +
  239 +}
... ...
impl/extension/jmx/src/main/java/br/gov/frameworkdemoiselle/jmx/internal/MBeanHelper.java 0 → 100644
... ... @@ -0,0 +1,121 @@
  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.jmx.internal;
  38 +
  39 +import java.lang.management.ManagementFactory;
  40 +import java.util.Locale;
  41 +
  42 +import javax.management.MBeanServer;
  43 +import javax.management.ObjectInstance;
  44 +import javax.management.ObjectName;
  45 +
  46 +import org.slf4j.Logger;
  47 +
  48 +import br.gov.frameworkdemoiselle.DemoiselleException;
  49 +import br.gov.frameworkdemoiselle.internal.producer.LoggerProducer;
  50 +import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer;
  51 +import br.gov.frameworkdemoiselle.util.ResourceBundle;
  52 +
  53 +/**
  54 + * Class with common tools for registering MBeans into an Managed server
  55 + *
  56 + * @author SERPRO
  57 + */
  58 +public class MBeanHelper {
  59 +
  60 + private static final Logger logger = LoggerProducer.create(MBeanHelper.class);
  61 +
  62 + private static ResourceBundle bundle = ResourceBundleProducer.create("demoiselle-jmx-bundle", Locale.getDefault());
  63 +
  64 + private static final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
  65 +
  66 + // @Inject
  67 + // @Name("demoiselle-monitoring-bundle")
  68 + // private ResourceBundle bundle;
  69 +
  70 + /**
  71 + * Return the MBean Server instance.
  72 + *
  73 + * @return MBeanServer
  74 + */
  75 + public static final MBeanServer getMBeanServer() {
  76 + return server;
  77 + }
  78 +
  79 + /**
  80 + * Register a given managed bean (MBean) with the specified name.
  81 + *
  82 + * @param mbean
  83 + * the managed bean to register
  84 + * @param name
  85 + * the name under which to register the bean
  86 + * @return the object name of the mbean, for later deregistration
  87 + */
  88 + public static ObjectInstance register(final Object mbean, final String name) {
  89 +
  90 + logger.info(bundle.getString("mbean-registration",name));
  91 +
  92 + ObjectInstance instance = null;
  93 + try {
  94 + ObjectName objectName = new ObjectName(name);
  95 + instance = server.registerMBean(mbean, objectName);
  96 + } catch (Exception e) {
  97 + logger.error(bundle.getString("mbean-registration-error",name),e);
  98 + throw new DemoiselleException(bundle.getString("mbean-registration-error",name), e);
  99 + }
  100 +
  101 + return instance;
  102 + }
  103 +
  104 + /**
  105 + * Remove the registration of a mbean.
  106 + *
  107 + * @param objectName
  108 + * the name of the bean to unregister
  109 + */
  110 + public static void unregister(final ObjectName objectName) {
  111 +
  112 + logger.info(bundle.getString("mbean-deregistration",objectName.getCanonicalName()));
  113 +
  114 + try {
  115 + server.unregisterMBean(objectName);
  116 + } catch (Exception e) {
  117 + logger.error(bundle.getString("mbean-deregistration",objectName.getCanonicalName()),e);
  118 + throw new DemoiselleException(bundle.getString("mbean-deregistration",objectName.getCanonicalName()), e);
  119 + }
  120 + }
  121 +}
... ...
impl/extension/jmx/src/main/java/br/gov/frameworkdemoiselle/jmx/internal/MBeanManager.java 0 → 100644
... ... @@ -0,0 +1,67 @@
  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.jmx.internal;
  38 +
  39 +import java.util.Collection;
  40 +import java.util.HashMap;
  41 +
  42 +import javax.inject.Singleton;
  43 +import javax.management.ObjectInstance;
  44 +
  45 +@Singleton
  46 +public class MBeanManager {
  47 +
  48 + private HashMap<String,ObjectInstance> registeredMBeans = new HashMap<String,ObjectInstance>();
  49 +
  50 + public void storeRegisteredMBean(ObjectInstance instance){
  51 + registeredMBeans.put(instance.getObjectName().getCanonicalName(),instance);
  52 + }
  53 +
  54 + public Collection<ObjectInstance> listRegisteredMBeans(){
  55 + return registeredMBeans.values();
  56 + }
  57 +
  58 + public ObjectInstance findMBeanInstance(String name){
  59 + ObjectInstance instance = registeredMBeans.get(name);
  60 + return instance;
  61 + }
  62 +
  63 + public void cleanRegisteredMBeans(){
  64 + registeredMBeans.clear();
  65 + }
  66 +
  67 +}
... ...
impl/extension/jmx/src/main/java/br/gov/frameworkdemoiselle/jmx/internal/NotificationBroadcaster.java 0 → 100644
... ... @@ -0,0 +1,86 @@
  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.jmx.internal;
  38 +
  39 +import java.io.Serializable;
  40 +
  41 +import javax.management.AttributeChangeNotification;
  42 +import javax.management.Notification;
  43 +import javax.management.NotificationBroadcasterSupport;
  44 +
  45 +import br.gov.frameworkdemoiselle.internal.management.ManagementNotificationEvent;
  46 +import br.gov.frameworkdemoiselle.jmx.configuration.JMXConfig;
  47 +import br.gov.frameworkdemoiselle.management.NotificationManager;
  48 +
  49 +/**
  50 + * Implementation of the {@link NotificationBroadcaster} MBean.
  51 + * When the {@link NotificationManager} sends an event, a {@link NotificationEventListener} captures the notification and uses
  52 + * this MBean to send it as a JMX notification.
  53 + *
  54 + * @author serpro
  55 + *
  56 + */
  57 +final class NotificationBroadcaster extends NotificationBroadcasterSupport implements NotificationBroadcasterMBean,Serializable {
  58 +
  59 + private static final long serialVersionUID = 1L;
  60 +
  61 + private int sequenceNumber = 1;
  62 +
  63 + /*public static final String NOTIFICATION_DEFAULT_MBEAN_NAME = NotificationBroadcaster.class.getPackage().getName()
  64 + +":name="
  65 + +NotificationBroadcaster.class.getSimpleName();*/
  66 +
  67 + private static final String NOTIFICATION_TYPE_GENERIC = "jmx.message";
  68 +
  69 + protected void sendNotification( ManagementNotificationEvent event , JMXConfig config ) {
  70 + br.gov.frameworkdemoiselle.management.Notification demoiselleNotification = event.getNotification();
  71 + Notification n = new Notification(NOTIFICATION_TYPE_GENERIC, config.getNotificationMBeanName(), sequenceNumber++, System.currentTimeMillis(), demoiselleNotification.getMessage().toString());
  72 + sendNotification(n);
  73 + }
  74 +
  75 + protected void sendAttributeChangedMessage( ManagementNotificationEvent event , JMXConfig config ) {
  76 + br.gov.frameworkdemoiselle.management.AttributeChangeNotification demoiselleNotification = (br.gov.frameworkdemoiselle.management.AttributeChangeNotification)event.getNotification();
  77 +
  78 + AttributeChangeNotification n = new AttributeChangeNotification(config.getNotificationMBeanName(), sequenceNumber++
  79 + , System.currentTimeMillis(), demoiselleNotification.getMessage().toString()
  80 + , demoiselleNotification.getAttributeName(), demoiselleNotification.getAttributeType().getSimpleName()
  81 + , demoiselleNotification.getOldValue(), demoiselleNotification.getNewValue());
  82 +
  83 + sendNotification(n);
  84 + }
  85 +
  86 +}
... ...
impl/extension/jmx/src/main/java/br/gov/frameworkdemoiselle/jmx/internal/NotificationBroadcasterMBean.java 0 → 100644
... ... @@ -0,0 +1,48 @@
  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.jmx.internal;
  38 +
  39 +
  40 +
  41 +/**
  42 + * MBean interface responsible for sending MBean notifications to remote clients.
  43 + *
  44 + * @author serpro
  45 + *
  46 + */
  47 +interface NotificationBroadcasterMBean {
  48 +}
... ...
impl/extension/jmx/src/main/java/br/gov/frameworkdemoiselle/jmx/internal/NotificationEventListener.java 0 → 100644
... ... @@ -0,0 +1,80 @@
  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.jmx.internal;
  38 +
  39 +import java.io.Serializable;
  40 +
  41 +import javax.enterprise.context.ApplicationScoped;
  42 +import javax.enterprise.event.Observes;
  43 +
  44 +import br.gov.frameworkdemoiselle.internal.management.ManagementNotificationEvent;
  45 +import br.gov.frameworkdemoiselle.internal.management.qualifier.AttributeChange;
  46 +import br.gov.frameworkdemoiselle.internal.management.qualifier.Generic;
  47 +import br.gov.frameworkdemoiselle.jmx.configuration.JMXConfig;
  48 +import br.gov.frameworkdemoiselle.management.NotificationManager;
  49 +
  50 +/**
  51 + * Listens to {@link NotificationManager} notification events and proxies them
  52 + * to a {@link NotificationBroadcaster} MBean. This MBean will send the notification to
  53 + * any JMX clients connected and listening.
  54 + *
  55 + * @author serpro
  56 + *
  57 + */
  58 +@ApplicationScoped
  59 +@SuppressWarnings("serial")
  60 +public class NotificationEventListener implements Serializable {
  61 +
  62 + private NotificationBroadcaster notificationBroadcaster;
  63 +
  64 + public void sendNotification( @Observes @Generic ManagementNotificationEvent event , JMXConfig config ) {
  65 + createNotificationBroadcaster().sendNotification(event,config);
  66 + }
  67 +
  68 + public void sendAttributeChangedMessage( @Observes @AttributeChange ManagementNotificationEvent event , JMXConfig config ) {
  69 + createNotificationBroadcaster().sendAttributeChangedMessage(event, config);
  70 + }
  71 +
  72 + public NotificationBroadcaster createNotificationBroadcaster(){
  73 + if (notificationBroadcaster==null){
  74 + notificationBroadcaster = new NotificationBroadcaster();
  75 + }
  76 +
  77 + return notificationBroadcaster;
  78 + }
  79 +
  80 +}
... ...
impl/extension/jmx/src/main/resources/META-INF/beans.xml 0 → 100644
... ... @@ -0,0 +1,4 @@
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3 + xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
  4 +</beans>
0 5 \ No newline at end of file
... ...
impl/extension/jmx/src/main/resources/demoiselle-jmx-bundle.properties 0 → 100644
... ... @@ -0,0 +1,8 @@
  1 +mbean-null-type-defined=A classe do MBean n\u00E3o pode ser null
  2 +mbean-introspection-error=Erro ao ler atributos do MBean {0}
  3 +mbean-registration=Registrando novo MBean usando o nome\: {0}
  4 +mbean-registration-error=Falha ao registrar MBean usando o nome\: {0}
  5 +mbean-deregistration=Removendo MBean de nome: {0}
  6 +mbean-deregistration-error=Falha ao remover MBean de nome: {0}
  7 +mbean-notification-registration=Registrando NotificationBroadcaster usando o nome\: {0}
  8 +mbean-notification-registration-error=Falha ao registrar NotificationBroadcaster usando o nome\: {0}
0 9 \ No newline at end of file
... ...
impl/extension/jmx/src/test/java/management/LocaleProducer.java 0 → 100644
... ... @@ -0,0 +1,51 @@
  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 management;
  38 +
  39 +import java.util.Locale;
  40 +
  41 +import javax.enterprise.inject.Default;
  42 +import javax.enterprise.inject.Produces;
  43 +
  44 +public class LocaleProducer {
  45 +
  46 + @Default
  47 + @Produces
  48 + public Locale create() {
  49 + return Locale.getDefault();
  50 + }
  51 +}
... ...
impl/extension/jmx/src/test/java/management/domain/ManagedTestClass.java 0 → 100644
... ... @@ -0,0 +1,73 @@
  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 management.domain;
  38 +
  39 +import br.gov.frameworkdemoiselle.annotation.ManagedOperation;
  40 +import br.gov.frameworkdemoiselle.annotation.ManagedProperty;
  41 +import br.gov.frameworkdemoiselle.annotation.Name;
  42 +import br.gov.frameworkdemoiselle.annotation.OperationParameter;
  43 +import br.gov.frameworkdemoiselle.annotation.OperationType;
  44 +import br.gov.frameworkdemoiselle.stereotype.ManagementController;
  45 +
  46 +/**
  47 + * Classe usada para testar se o registro de classes Managed
  48 + * como MBeans está funcionando.
  49 + *
  50 + * @author SERPRO
  51 + *
  52 + */
  53 +@ManagementController
  54 +@Name("ManagedTest")
  55 +public class ManagedTestClass {
  56 +
  57 + @ManagedProperty(description="Atributo de teste para testar registro de MBean")
  58 + private String attribute;
  59 +
  60 + public String getAttribute() {
  61 + return attribute;
  62 + }
  63 +
  64 + public void setAttribute(String attribute) {
  65 + this.attribute = attribute;
  66 + }
  67 +
  68 + @ManagedOperation(type=OperationType.ACTION_INFO,description="Test Operation")
  69 + public String operation(@OperationParameter(name="parameter") String parameter){
  70 + return "Operation called with parameter="+parameter+". Current attribute value is "+attribute;
  71 + }
  72 +
  73 +}
... ...
impl/extension/jmx/src/test/java/management/tests/internal/DynamicMBeanProxyTestCase.java 0 → 100644
... ... @@ -0,0 +1,185 @@
  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 management.tests.internal;
  38 +
  39 +import java.io.File;
  40 +import java.lang.management.ManagementFactory;
  41 +
  42 +import javax.management.Attribute;
  43 +import javax.management.MBeanServer;
  44 +import javax.management.MalformedObjectNameException;
  45 +import javax.management.ObjectName;
  46 +
  47 +import junit.framework.Assert;
  48 +import management.LocaleProducer;
  49 +import management.domain.ManagedTestClass;
  50 +
  51 +import org.jboss.arquillian.container.test.api.Deployment;
  52 +import org.jboss.arquillian.junit.Arquillian;
  53 +import org.jboss.shrinkwrap.api.ShrinkWrap;
  54 +import org.jboss.shrinkwrap.api.asset.FileAsset;
  55 +import org.jboss.shrinkwrap.api.exporter.ZipExporter;
  56 +import org.jboss.shrinkwrap.api.spec.JavaArchive;
  57 +import org.junit.Test;
  58 +import org.junit.runner.RunWith;
  59 +
  60 +import br.gov.frameworkdemoiselle.jmx.internal.MBeanManager;
  61 +import br.gov.frameworkdemoiselle.util.Beans;
  62 +
  63 +@RunWith(Arquillian.class)
  64 +public class DynamicMBeanProxyTestCase {
  65 +
  66 + @Deployment
  67 + public static JavaArchive createDeployment() {
  68 + JavaArchive mainDeployment = ShrinkWrap.create(JavaArchive.class);
  69 + mainDeployment
  70 + .addPackages(true, "br")
  71 + .addAsResource(new FileAsset(new File("src/test/resources/test/beans.xml")), "beans.xml")
  72 + .addAsResource(new FileAsset(new File("src/test/resources/configuration/demoiselle.properties")),"demoiselle.properties")
  73 + .addPackages(false, DynamicMBeanProxyTestCase.class.getPackage())
  74 + .addClasses(LocaleProducer.class, ManagedTestClass.class);
  75 +
  76 + mainDeployment.as(ZipExporter.class).exportTo(
  77 + new File("/home/81986912515/myPackage.jar"), true);
  78 +
  79 + return mainDeployment;
  80 + }
  81 +
  82 + /**
  83 + * Testa se o bootstrap está corretamente carregando e registrando classes anotadas com {@link Managed} como MBeans.
  84 + */
  85 + @Test
  86 + public void testMBeanInitialization() {
  87 + MBeanManager manager = Beans.getReference(MBeanManager.class);
  88 +
  89 + Assert.assertNotNull(manager);
  90 + Assert.assertNotNull(manager.listRegisteredMBeans());
  91 +
  92 + // O componente demoiselle-jmx sempre tem pelo menos um MBean, que é
  93 + // o NotificationBroadcaster. Qualquer classe gerenciada criada pelo usuário
  94 + // será adicionada a ela, então esperamos 2 MBeans aqui.
  95 + Assert.assertEquals(2, manager.listRegisteredMBeans().size());
  96 +
  97 + }
  98 +
  99 + @Test
  100 + public void testAttributeWrite() {
  101 +
  102 + MBeanServer server = ManagementFactory.getPlatformMBeanServer();
  103 +
  104 + ObjectName name = null;
  105 + try {
  106 + name = new ObjectName("br.gov.frameworkdemoiselle.jmx.domain:name=ManagedTest");
  107 + } catch (MalformedObjectNameException e) {
  108 + Assert.fail();
  109 + }
  110 +
  111 + try {
  112 + server.setAttribute(name, new Attribute("attribute", "New Value"));
  113 + } catch (Exception e) {
  114 + Assert.fail(e.getMessage());
  115 + }
  116 +
  117 + }
  118 +
  119 + @Test
  120 + public void testAttributeRead() {
  121 +
  122 + MBeanServer server = ManagementFactory.getPlatformMBeanServer();
  123 +
  124 + ObjectName name = null;
  125 + try {
  126 + name = new ObjectName("br.gov.frameworkdemoiselle.jmx.domain:name=ManagedTest");
  127 + } catch (MalformedObjectNameException e) {
  128 + Assert.fail();
  129 + }
  130 +
  131 + try {
  132 + server.setAttribute(name, new Attribute("attribute", "New Value"));
  133 +
  134 + Object info = server.getAttribute(name, "attribute");
  135 +
  136 + Assert.assertEquals("New Value", info);
  137 + } catch (Exception e) {
  138 + Assert.fail();
  139 + }
  140 +
  141 + }
  142 +
  143 + @Test
  144 + public void testOperationInvocation() {
  145 +
  146 + MBeanServer server = ManagementFactory.getPlatformMBeanServer();
  147 +
  148 + ObjectName name = null;
  149 + try {
  150 + name = new ObjectName("br.gov.frameworkdemoiselle.jmx.domain:name=ManagedTest");
  151 + } catch (MalformedObjectNameException e) {
  152 + Assert.fail();
  153 + }
  154 +
  155 + try {
  156 + server.setAttribute(name, new Attribute("attribute", "Defined Value"));
  157 +
  158 + Object info = server.invoke(name, "operation", new Object[] { "Test" }, new String[] { "String" });
  159 + Assert.assertEquals("Operation called with parameter=Test. Current attribute value is Defined Value", info);
  160 + } catch (Exception e) {
  161 + Assert.fail();
  162 + }
  163 +
  164 + }
  165 +
  166 + @Test
  167 + public void testTryWriteOverReadOnly() {
  168 +
  169 + MBeanServer server = ManagementFactory.getPlatformMBeanServer();
  170 +
  171 + ObjectName name = null;
  172 + try {
  173 + name = new ObjectName("br.gov.frameworkdemoiselle.jmx.domain:name=ManagedTest");
  174 + } catch (MalformedObjectNameException e) {
  175 + Assert.fail();
  176 + }
  177 +
  178 + try {
  179 + server.setAttribute(name, new Attribute("attribute", "New Value"));
  180 + } catch (Exception e) {
  181 + Assert.fail(e.getMessage());
  182 + }
  183 +
  184 + }
  185 +}
... ...
impl/extension/jmx/src/test/java/management/tests/internal/NotificationBroadcasterTestCase.java 0 → 100644
... ... @@ -0,0 +1,208 @@
  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 management.tests.internal;
  38 +
  39 +import java.io.File;
  40 +import java.lang.management.ManagementFactory;
  41 +
  42 +import javax.management.InstanceNotFoundException;
  43 +import javax.management.MBeanServer;
  44 +import javax.management.MalformedObjectNameException;
  45 +import javax.management.NotificationListener;
  46 +import javax.management.ObjectInstance;
  47 +import javax.management.ObjectName;
  48 +
  49 +import junit.framework.Assert;
  50 +import management.LocaleProducer;
  51 +import management.domain.ManagedTestClass;
  52 +
  53 +import org.jboss.arquillian.container.test.api.Deployment;
  54 +import org.jboss.arquillian.junit.Arquillian;
  55 +import org.jboss.shrinkwrap.api.ShrinkWrap;
  56 +import org.jboss.shrinkwrap.api.asset.FileAsset;
  57 +import org.jboss.shrinkwrap.api.spec.JavaArchive;
  58 +import org.junit.Test;
  59 +import org.junit.runner.RunWith;
  60 +
  61 +import br.gov.frameworkdemoiselle.jmx.configuration.JMXConfig;
  62 +import br.gov.frameworkdemoiselle.jmx.internal.MBeanManager;
  63 +import br.gov.frameworkdemoiselle.management.AttributeChangeNotification;
  64 +import br.gov.frameworkdemoiselle.management.Notification;
  65 +import br.gov.frameworkdemoiselle.management.NotificationManager;
  66 +import br.gov.frameworkdemoiselle.util.Beans;
  67 +
  68 +@RunWith(Arquillian.class)
  69 +public class NotificationBroadcasterTestCase {
  70 +
  71 + @Deployment
  72 + public static JavaArchive createDeployment() {
  73 + JavaArchive mainDeployment = ShrinkWrap.create(JavaArchive.class);
  74 + mainDeployment
  75 + .addPackages(true, "br")
  76 + .addAsResource(new FileAsset(new File("src/test/resources/test/beans.xml")), "beans.xml")
  77 + .addAsResource(new FileAsset(new File("src/test/resources/configuration/demoiselle.properties")),
  78 + "demoiselle.properties").addPackages(false, DynamicMBeanProxyTestCase.class.getPackage())
  79 + .addClasses(LocaleProducer.class, ManagedTestClass.class);
  80 +
  81 + return mainDeployment;
  82 + }
  83 +
  84 + /**
  85 + * Testa o envio de uma mensagem para clientes conectados
  86 + */
  87 + @Test
  88 + public void sendMessageTest(){
  89 + JMXConfig config = Beans.getReference(JMXConfig.class);
  90 +
  91 + //Este será o lado cliente. Este manager é usado para enviar notificações a partir do código da aplicação
  92 + NotificationManager notificationManager = Beans.getReference(NotificationManager.class);
  93 +
  94 + //Obtém o servidor MBean onde anexaremos um listener para a notificação
  95 + MBeanServer server = ManagementFactory.getPlatformMBeanServer();
  96 +
  97 + //Aqui obtemos o MBean de notificações já registrado pelo bootstrap
  98 + StringBuffer notificationMBeanName = new StringBuffer()
  99 + .append( config.getNotificationDomain()!=null ? config.getNotificationDomain() : "br.gov.frameworkdemoiselle.jmx" )
  100 + .append(":name=")
  101 + .append( config.getNotificationMBeanName());
  102 +
  103 + ObjectName name = null;
  104 + try {
  105 + name = new ObjectName(notificationMBeanName.toString());
  106 + } catch (MalformedObjectNameException e) {
  107 + Assert.fail();
  108 + }
  109 +
  110 + //StringBuffer vazio
  111 + StringBuffer notificationBuffer = new StringBuffer();
  112 +
  113 + //Este notification listener será chamado quando o Demoiselle enviar a notificação e vai colocar
  114 + //a mensagem enviada em "notificationBuffer"
  115 + NotificationListener listener = new TestNotificationListener(notificationBuffer);
  116 +
  117 + try {
  118 + //Anexa o listener no servidor MBean
  119 + server.addNotificationListener(name,listener,null,null);
  120 + } catch (InstanceNotFoundException e) {
  121 + Assert.fail();
  122 + }
  123 +
  124 + //Manda a notificação pelo Demoiselle
  125 + Notification n = new Notification("Notification test successful");
  126 + notificationManager.sendNotification(n);
  127 +
  128 + //Se o componente funcionou, o Demoiselle propagou a notificação para o servidor MBean e o listener preencheu
  129 + //o StringBuffer com nossa mensagem.
  130 + Assert.assertEquals("Notification test successful", notificationBuffer.toString());
  131 +
  132 + }
  133 +
  134 + /**
  135 + * Testa o envio de uma mensagem de mudança de atributo para clientes conectados
  136 + */
  137 + @Test
  138 + public void sendAttributeChangedMessageTest(){
  139 + JMXConfig config = Beans.getReference(JMXConfig.class);
  140 +
  141 + //Obtém o servidor MBean onde anexaremos um listener para a notificação
  142 + MBeanServer server = ManagementFactory.getPlatformMBeanServer();
  143 +
  144 + NotificationManager notificationManager = Beans.getReference(NotificationManager.class);
  145 + MBeanManager mBeanManager = Beans.getReference(MBeanManager.class);
  146 +
  147 + //Aqui obtemos o MBean de notificações já registrado pelo bootstrap
  148 + StringBuffer notificationMBeanName = new StringBuffer()
  149 + .append( config.getNotificationDomain()!=null ? config.getNotificationDomain() : "br.gov.frameworkdemoiselle.jmx" )
  150 + .append(":name=")
  151 + .append( config.getNotificationMBeanName());
  152 + ObjectInstance instance = mBeanManager.findMBeanInstance(notificationMBeanName.toString());
  153 +
  154 + //StringBuffer vazio
  155 + StringBuffer notificationBuffer = new StringBuffer();
  156 +
  157 + //Este notification listener será chamado quando o Demoiselle enviar a notificação e vai colocar
  158 + //a mensagem enviada em "notificationBuffer"
  159 + NotificationListener listener = new TestNotificationListener(notificationBuffer);
  160 +
  161 + try {
  162 + //Anexa o listener no servidor MBean
  163 + server.addNotificationListener(instance.getObjectName(),listener,null,null);
  164 + } catch (InstanceNotFoundException e) {
  165 + Assert.fail();
  166 + }
  167 +
  168 + //Manda a notificação pelo Demoiselle
  169 + AttributeChangeNotification notification = new AttributeChangeNotification("Attribute Changed","name",String.class,"Demoiselle 1","Demoiselle 2");
  170 + notificationManager.sendNotification(notification);
  171 +
  172 + //Se o componente funcionou, o Demoiselle propagou a notificação para o servidor MBean e o listener preencheu
  173 + //o StringBuffer com nossa mensagem.
  174 + Assert.assertEquals("Attribute Changed: name = Demoiselle 2", notificationBuffer.toString());
  175 +
  176 + }
  177 +
  178 + /**
  179 + * Implementação do {@link NotificationListener} do Java que vai por qualquer notificação recebida em um StringBuffer.
  180 + *
  181 + * @author serpro
  182 + *
  183 + */
  184 + class TestNotificationListener implements NotificationListener {
  185 +
  186 + StringBuffer message;
  187 +
  188 + public TestNotificationListener(StringBuffer testMessage){
  189 + this.message = testMessage;
  190 + }
  191 +
  192 + @Override
  193 + public void handleNotification(javax.management.Notification notification, Object handback) {
  194 + if (message!=null){
  195 + message.append(notification.getMessage());
  196 +
  197 + if (notification instanceof javax.management.AttributeChangeNotification){
  198 + message.append(": ")
  199 + .append( ((javax.management.AttributeChangeNotification)notification).getAttributeName() )
  200 + .append(" = ")
  201 + .append(((javax.management.AttributeChangeNotification)notification).getNewValue());
  202 + }
  203 + }
  204 + }
  205 +
  206 + }
  207 +
  208 +}
... ...
impl/extension/jmx/src/test/resources/META-INF/beans.xml 0 → 100644
... ... @@ -0,0 +1,11 @@
  1 +<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2 + xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
  3 +
  4 + <interceptors>
  5 + <class>br.gov.frameworkdemoiselle.transaction.TransactionalInterceptor</class>
  6 + <class>br.gov.frameworkdemoiselle.security.RequiredPermissionInterceptor</class>
  7 + <class>br.gov.frameworkdemoiselle.security.RequiredRoleInterceptor</class>
  8 + <class>br.gov.frameworkdemoiselle.exception.ExceptionHandlerInterceptor</class>
  9 + </interceptors>
  10 +
  11 +</beans>
... ...
impl/extension/jmx/src/test/resources/arquillian.xml 0 → 100644
... ... @@ -0,0 +1,27 @@
  1 +<!-- Demoiselle Framework Copyright (C) 2010 SERPRO ============================================================================
  2 + This file is part of Demoiselle Framework. Demoiselle Framework is free software;
  3 + you can redistribute it and/or modify it under the terms of the GNU Lesser
  4 + General Public License version 3 as published by the Free Software Foundation.
  5 + This program is distributed in the hope that it will be useful, but WITHOUT
  6 + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  7 + FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  8 + You should have received a copy of the GNU Lesser General Public License
  9 + version 3 along with this program; if not, see <http://www.gnu.org/licenses
  10 + /> or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
  11 + Floor, Boston, MA 02110-1301, USA. ============================================================================
  12 + Este arquivo é parte do Framework Demoiselle. O Framework Demoiselle é um
  13 + software livre; você pode redistribuí-lo e/ou modificá-lo dentro dos termos
  14 + da GNU LGPL versão 3 como publicada pela Fundação do Software Livre (FSF).
  15 + Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA
  16 + GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou APLICAÇÃO
  17 + EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português para maiores
  18 + detalhes. Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título
  19 + "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses
  20 + /> ou escreva para a Fundação do Software Livre (FSF) Inc., 51 Franklin St,
  21 + Fifth Floor, Boston, MA 02111-1301, USA. -->
  22 +
  23 +<arquillian xmlns="http://jboss.org/schema/arquillian"
  24 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  25 + xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
  26 +
  27 +</arquillian>
0 28 \ No newline at end of file
... ...
impl/extension/jmx/src/test/resources/configuration/demoiselle.properties 0 → 100644
... ... @@ -0,0 +1 @@
  1 +frameworkdemoiselle.management.jmx.mbean.domain=br.gov.frameworkdemoiselle.jmx.domain
0 2 \ No newline at end of file
... ...
impl/extension/jmx/src/test/resources/log4j.properties 0 → 100755
... ... @@ -0,0 +1,42 @@
  1 +# Demoiselle Framework
  2 +# Copyright (C) 2010 SERPRO
  3 +# ----------------------------------------------------------------------------
  4 +# This file is part of Demoiselle Framework.
  5 +#
  6 +# Demoiselle Framework is free software; you can redistribute it and/or
  7 +# modify it under the terms of the GNU Lesser General Public License version 3
  8 +# as published by the Free Software Foundation.
  9 +#
  10 +# This program is distributed in the hope that it will be useful,
  11 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
  12 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13 +# GNU General Public License for more details.
  14 +#
  15 +# You should have received a copy of the GNU Lesser General Public License version 3
  16 +# along with this program; if not, see <http://www.gnu.org/licenses/>
  17 +# or write to the Free Software Foundation, Inc., 51 Franklin Street,
  18 +# Fifth Floor, Boston, MA 02110-1301, USA.
  19 +# ----------------------------------------------------------------------------
  20 +# Este arquivo é parte do Framework Demoiselle.
  21 +#
  22 +# O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou
  23 +# modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação
  24 +# do Software Livre (FSF).
  25 +#
  26 +# Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA
  27 +# GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou
  28 +# APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português
  29 +# para maiores detalhes.
  30 +#
  31 +# Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título
  32 +# "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/>
  33 +# ou escreva para a Fundação do Software Livre (FSF) Inc.,
  34 +# 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA.
  35 +
  36 +log4j.rootCategory=INFO, stdout
  37 +
  38 +log4j.logger.br.gov.frameworkdemoiselle=TRACE
  39 +
  40 +log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  41 +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  42 +log4j.appender.stdout.layout.ConversionPattern=%-5p [%c{1}] %m%n
... ...
impl/extension/jmx/src/test/resources/test/beans.xml 0 → 100644
... ... @@ -0,0 +1,11 @@
  1 +<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2 + xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
  3 +
  4 + <interceptors>
  5 + <class>br.gov.frameworkdemoiselle.transaction.TransactionalInterceptor</class>
  6 + <class>br.gov.frameworkdemoiselle.security.RequiredPermissionInterceptor</class>
  7 + <class>br.gov.frameworkdemoiselle.security.RequiredRoleInterceptor</class>
  8 + <class>br.gov.frameworkdemoiselle.exception.ExceptionHandlerInterceptor</class>
  9 + </interceptors>
  10 +
  11 +</beans>
... ...