Path: blob/master/test/jdk/javax/management/mxbean/Basic.java
41152 views
/*1* Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.util.Collection;24import java.util.Date;25import java.util.HashMap;26import java.util.HashSet;27import java.util.List;28import java.util.Map;29import java.util.concurrent.Callable;30import java.util.concurrent.ExecutorService;31import java.util.concurrent.Executors;32import java.util.concurrent.Future;33import javax.management.Descriptor;34import javax.management.ImmutableDescriptor;35import javax.management.ListenerNotFoundException;36import javax.management.MBeanNotificationInfo;37import javax.management.MBeanRegistration;38import javax.management.MBeanServer;39import javax.management.Notification;40import javax.management.NotificationBroadcasterSupport;41import javax.management.NotificationEmitter;42import javax.management.NotificationFilter;43import javax.management.NotificationListener;44import javax.management.ObjectName;4546/**47* Class Basic48* Basic Description49*/50public class Basic implements BasicMXBean, NotificationEmitter,51MBeanRegistration {5253public static final String EXCEPTION_MESSAGE = "from Basic";54public static final String NOTIFICATION_MESSAGE = "from Basic";55/** Attribute : IntAtt */56private int intAtt = 0;57/** Attribute : IntegerAtt */58private Integer integerAtt = 0;59/** Attribute : BoolAtt */60private boolean boolAtt = false;61/** Attribute : BooleanAtt */62private Boolean booleanAtt = false;63/** Attribute : StringAtt */64private String stringAtt = null;65/** Attribute : DateAtt */66private Date dateAtt = null;67/** Attribute : ObjectNameAtt */68private ObjectName objectNameAtt = null;69/** Attribute : NotifDescriptorAsMapAtt */70private Map<String, String> notifDescriptorAsMapAtt = null;71/** Attribute : NotifDescriptorAtt */72private Descriptor notifDescriptorAtt = null;73/** Attribute : SqeParameter */74private SqeParameter sqeParameterAtt = null;7576/* Creates a new instance of Basic */77@SqeDescriptorKey("CONSTRUCTOR Basic")78public Basic() {79}8081/* Creates a new instance of Basic */82@SqeDescriptorKey("CONSTRUCTOR Basic")83public Basic(84@SqeDescriptorKey("CONSTRUCTOR PARAMETER SqeParameter") SqeParameter param) {85}8687/**88* Get int attribute89*/90public int getIntAtt() {91return intAtt;92}9394/**95* Set int attribute96*/97public void setIntAtt(int value) {98intAtt = value;99}100101/**102* Get Integer attribute103*/104public Integer getIntegerAtt() {105return integerAtt;106}107108/**109* Set Integer attribute110*/111public void setIntegerAtt(Integer value) {112integerAtt = value;113}114115/**116* Get boolean attribute117*/118public boolean getBoolAtt() {119return boolAtt;120}121122/**123* Set boolean attribute124*/125public void setBoolAtt(boolean value) {126boolAtt = value;127}128129/**130* Get Boolean attribute131*/132public Boolean getBooleanAtt() {133return booleanAtt;134}135136/**137* Set Boolean attribute138*/139public void setBooleanAtt(Boolean value) {140booleanAtt = value;141}142143/**144* Get String attribute145*/146public String getStringAtt() {147return stringAtt;148}149150/**151* Set String attribute152*/153public void setStringAtt(String value) {154stringAtt = value;155}156157/**158* Get Date attribute159*/160public Date getDateAtt() {161return dateAtt;162}163164/**165* Set Date attribute166*/167public void setDateAtt(Date value) {168dateAtt = value;169}170171/**172* Get ObjectName attribute173*/174public ObjectName getObjectNameAtt() {175return objectNameAtt;176}177178/**179* Set ObjectName attribute180*/181public void setObjectNameAtt(ObjectName value) {182objectNameAtt = value;183}184185/**186* Get SqeParameter attribute187*/188public SqeParameter getSqeParameterAtt() throws Exception {189if (sqeParameterAtt == null) {190sqeParameterAtt = new SqeParameter();191sqeParameterAtt.setGlop("INITIALIZED");192}193194return sqeParameterAtt;195}196197/**198* Set SqeParameter attribute199*/200public void setSqeParameterAtt(SqeParameter value) {201sqeParameterAtt = value;202}203204/**205* Get the Descriptor used to build the NotificationInfo206* of emitted notifications.207*/208public Map<String, String> getNotifDescriptorAsMapAtt() {209if (notifDescriptorAsMapAtt == null) {210initNotifDescriptorAtt();211}212213return notifDescriptorAsMapAtt;214}215216/**217* Set the Descriptor used to build the NotificationInfo218* of emitted notifications.219* <br>A Map<String, Object> would better fit Descriptor needs but then220* it is not convertible according the MXBean specification so the MBean221* registration fails.222* As we plan to test our custom Descriptor finds its way into223* the metadata of emitted notifications, String is good enough.224*/225public void setNotifDescriptorAsMapAtt(Map<String, String> value) {226notifDescriptorAsMapAtt = new HashMap<String, String>(value);227notifDescriptorAtt = new ImmutableDescriptor(value);228}229230/**231* Do nothing232*/233public void doNothing() {234// I said NOTHING !235}236237/**238* Do take SqeParameter as a parameter239*/240public void doWeird(SqeParameter param) {241}242243/**244* Throw an Exception245*/246public void throwException() throws Exception {247throw new Exception(EXCEPTION_MESSAGE);248}249250/**251* Throw an Error252*/253public void throwError() {254throw new InternalError(EXCEPTION_MESSAGE);255}256257/**258* Reset all attributes259*/260public void reset() {261intAtt = 0;262integerAtt = 0;263boolAtt = false;264booleanAtt = Boolean.FALSE;265stringAtt = null;266dateAtt = null;267objectNameAtt = null;268}269270/**271* Returns the weather for the coming days272* @param verbose <code>boolean</code> verbosity273* @throws java.lang.Exception <code>storm</code>274* @return <code>ObjectName</code>275*/276public Weather getWeather(boolean verbose)277throws java.lang.Exception {278return Weather.SUNNY;279}280281// Starting here are the 4 methods of MBeanRegistration interface.282// We use that to grab the ObjectName the MBean is registered with.283//284public ObjectName preRegister(MBeanServer server, ObjectName name)285throws Exception {286// Grab a reference on the MBeanServer we're registered in.287mbs = server;288// Compute the name we're registered with.289if (name != null) {290mbeanName = name;291return name;292} else {293mbeanName =294new ObjectName("sqe:type=" + Basic.class.getName());295return mbeanName;296}297}298299public void postRegister(Boolean registrationDone) {300// Do nothing301}302303public void preDeregister() throws Exception {304// Do nothing305}306307public void postDeregister() {308// Do nothing309}310311/**312* Send one Notification of the provided notifType type.313*/314public void sendNotification(String notifType) {315Notification notification = null;316317if (notifType.equals(NOTIF_TYPE_0)) {318notification = new Notification(NOTIF_TYPE_0,319mbeanName,320seqNumber,321NOTIFICATION_MESSAGE);322} else if (notifType.equals(NOTIF_TYPE_1)) {323notification = new SqeNotification(NOTIF_TYPE_1,324mbeanName,325seqNumber,326NOTIFICATION_MESSAGE);327}328329seqNumber++;330broadcaster.sendNotification(notification);331}332333/**334* That method starts a set of threads, each thread sends a given number of335* notifications.336* The number of threads can be set via the attribute numOfNotificationSenders.337* The number of notification sent by each thread can be set via338* the attribute numOfNotificationSenderLoops.339* Depending on the parameter customNotification we send either custom340* notification(s) or MBeanServer registration and unregistration notification(s).341* When customNotification=true the total number of notification(s) sent is342* (numOfNotificationSenders * numOfNotificationSenderLoops). They are343* sequentially of type NOTIF_TYPE_0 then NOTIF_TYPE_1 and so on.344*345* When customNotification=false the total number of notification(s) sent is346* (numOfNotificationSenders * numOfNotificationSenderLoops) registration347* notification(s)348* +349* (numOfNotificationSenders * numOfNotificationSenderLoops) unregistration350* notification(s)351*352* @throws java.lang.Exception353*/354public void sendNotificationWave(boolean customNotification) throws355Exception {356// Build the set of notification sender.357Collection<Callable<Integer>> tasks =358new HashSet<Callable<Integer>>(numOfNotificationSenders);359360for (int i = 1; i <= numOfNotificationSenders; i++) {361tasks.add(new NotifSender(numOfNotificationSenderLoops,362customNotification, i));363}364365// Start all notification sender in parallel.366ExecutorService execServ = null;367try {368execServ = Executors.newFixedThreadPool(numOfNotificationSenders);369List<Future<Integer>> taskHandlers = execServ.invokeAll(tasks);370checkNotifSenderThreadStatus(taskHandlers);371} finally {372if (!execServ.isShutdown()) {373execServ.shutdown();374}375}376}377378public void setNumOfNotificationSenders(int value) {379numOfNotificationSenders = value;380}381382public void setNumOfNotificationSenderLoops(int value) {383numOfNotificationSenderLoops = value;384}385386/**387* MBean Notification support388* You shouldn't update these methods389*/390// <editor-fold defaultstate="collapsed" desc=" Generated Code ">391public void addNotificationListener(NotificationListener listener,392NotificationFilter filter,393Object handback)394throws IllegalArgumentException {395broadcaster.addNotificationListener(listener, filter, handback);396}397398public MBeanNotificationInfo[] getNotificationInfo() {399if (notifDescriptorAtt == null) {400initNotifDescriptorAtt();401}402403return new MBeanNotificationInfo[]{404new MBeanNotificationInfo(new String[]{405NOTIF_TYPE_0406},407javax.management.Notification.class.getName(),408"Standard JMX Notification",409notifDescriptorAtt),410new MBeanNotificationInfo(new String[]{411NOTIF_TYPE_1412},413SqeNotification.class.getName(),414"SQE Notification",415notifDescriptorAtt)416};417}418419public void removeNotificationListener(NotificationListener listener)420throws ListenerNotFoundException {421broadcaster.removeNotificationListener(listener);422}423424public void removeNotificationListener(NotificationListener listener,425NotificationFilter filter,426Object handback)427throws ListenerNotFoundException {428broadcaster.removeNotificationListener(listener, filter, handback);429}430// </editor-fold>431private synchronized long getNextSeqNumber() {432return seqNumber++;433}434435private void initNotifDescriptorAtt() {436String key = "CRABE";437String value = "TAMBOUR";438notifDescriptorAtt =439new ImmutableDescriptor(new String[]{key + "=" + value});440notifDescriptorAsMapAtt =441new HashMap<String, String>();442notifDescriptorAsMapAtt.put(key, value);443}444445private void checkNotifSenderThreadStatus(446List<Future<Integer>> taskHandlers)447throws Exception {448String msgTag = "Basic::checkNotifSenderThreadStatus: ";449// Grab back status of each notification sender.450for (Future<Integer> f : taskHandlers) {451if (f.isCancelled()) {452String message = msgTag +453"---- ERROR : One thread has been cancelled";454System.out.println(message);455throw new RuntimeException(message);456} else {457Integer effectiveNumOfLoops = f.get();458459if (effectiveNumOfLoops != numOfNotificationSenderLoops) {460String message = msgTag + "---- ERROR : One thread did " +461effectiveNumOfLoops + " loops in place of " +462numOfNotificationSenderLoops;463System.out.println(message);464throw new RuntimeException(message);465}466}467}468}469//470private int numOfNotificationSenderLoops = 2;471private int numOfNotificationSenders = 13;472473private class NotifSender implements Callable<Integer> {474475private int cycles;476private boolean customNotification;477private int senderID;478479public NotifSender(int cycles, boolean customNotification, int id) {480this.cycles = cycles;481this.customNotification = customNotification;482this.senderID = id;483}484485public Integer call() throws Exception {486int callsDone = 0;487488try {489for (int i = 1; i <= cycles; i++) {490if (customNotification) {491if (i % 2 == 0) {492sendNotification(NOTIF_TYPE_0);493} else {494sendNotification(NOTIF_TYPE_1);495}496} else {497ObjectName mbeanName = new ObjectName("SQE:type=" +498mbeanClassName + ",senderID=" + senderID);499mbs.createMBean(mbeanClassName, mbeanName);500mbs.unregisterMBean(mbeanName);501}502callsDone++;503}504} catch (Exception e) {505System.out.println("NotifSender::call: (ERROR) Thread [" + senderID +506"] failed after " + callsDone + " cycles");507throw e;508}509510return Integer.valueOf(callsDone);511}512}513514//515private long seqNumber;516private final NotificationBroadcasterSupport broadcaster =517new NotificationBroadcasterSupport();518private ObjectName mbeanName;519private MBeanServer mbs;520private String mbeanClassName = "Simple";521522/**523* Notification types definitions. To use when creating JMX Notifications.524*/525public static final String NOTIF_TYPE_0 =526"sqe.notification.a.type";527public static final String NOTIF_TYPE_1 =528"sqe.notification.b.type";529}530531532