KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > mx4j > examples > services > relation > RelationServiceExample


1 /**
2  * Copyright (C) The MX4J Contributors.
3  * All rights reserved.
4  *
5  * This software is distributed under the terms of the MX4J License version 1.0.
6  * See the terms of the MX4J License in the documentation provided with this software.
7  */

8 package mx4j.examples.services.relation;
9
10 import java.util.ArrayList JavaDoc;
11 import java.util.Iterator JavaDoc;
12 import java.util.List JavaDoc;
13 import java.util.Set JavaDoc;
14 import javax.management.MBeanServer JavaDoc;
15 import javax.management.MBeanServerFactory JavaDoc;
16 import javax.management.MBeanServerInvocationHandler JavaDoc;
17 import javax.management.ObjectInstance JavaDoc;
18 import javax.management.ObjectName JavaDoc;
19 import javax.management.Query JavaDoc;
20 import javax.management.relation.RelationServiceMBean JavaDoc;
21 import javax.management.relation.Role JavaDoc;
22 import javax.management.relation.RoleList JavaDoc;
23 import javax.management.relation.RoleResult JavaDoc;
24
25 import mx4j.log.Log;
26 import mx4j.log.Logger;
27
28 /**
29  * @version $Revision: 1.1 $
30  */

31
32 /**
33  * This class will demonstrate the use-case scenarios described in the docs, under chapter "examples" and sub-section RelationService
34  * Some methods will also use the MBeanProxy.
35  */

36 public class RelationServiceExample
37 {
38    private MBeanServer JavaDoc m_server = null;
39    private RelationServiceMBean JavaDoc m_proxy = null;
40    private String JavaDoc m_relationServiceClass = "javax.management.relation.RelationService";
41    private String JavaDoc m_libraryClassName = "mx4j.examples.services.relation.SimplePersonalLibrary";
42    private ObjectName JavaDoc m_libraryObjectName = null;
43    private ObjectName JavaDoc m_relationObjectName = null;
44    private SimplePersonalLibrary m_library = null;
45
46    public RelationServiceExample()
47    {
48       m_server = MBeanServerFactory.createMBeanServer("RelationExample");
49    }
50
51    public void setUpRelations()
52    {
53       // build the object name and register the relationService
54
try
55       {
56          System.out.println("Creating RelationService in the MBeanServer");
57          Object JavaDoc[] params = {new Boolean JavaDoc(true)};
58          String JavaDoc[] signature = {"boolean"};
59          m_relationObjectName = new ObjectName JavaDoc("relations:class=" + m_relationServiceClass);
60          m_server.createMBean(m_relationServiceClass, m_relationObjectName, null, params, signature);
61
62          // we will create the MBeanProxy now so we can make some simple calls through the proxy
63
m_proxy = (RelationServiceMBean JavaDoc)MBeanServerInvocationHandler.newProxyInstance(m_server, m_relationObjectName, RelationServiceMBean JavaDoc.class, false);
64          System.out.println("----------------------- done ----------------------------");
65
66          System.out.println("create the relationType");
67          String JavaDoc libraryTypeName = "personal_library";
68          m_library = new SimplePersonalLibrary(libraryTypeName);
69          // add it to the relationService
70
addRelationType();
71          printRelationTypeInfo();
72          System.out.println("----------------------- done ----------------------------");
73
74          System.out.println("create RelationId for the relationType");
75          String JavaDoc personalLibraryId = libraryTypeName + "_internal";
76          //....Done....
77
System.out.println("----------------------- done ----------------------------");
78
79          // we now need to build the Roles and MBeans that will represent those relations
80
String JavaDoc ownerClassName = "mx4j.examples.services.relation.SimpleOwner"; // create 2 instance of this
81
String JavaDoc bookClassName = "mx4j.examples.services.relation.SimpleBooks"; // create 5 instances of this
82

83          System.out.println("Creating MBeans to represent our relations");
84          ObjectName JavaDoc ownerName1 = new ObjectName JavaDoc("library:name=" + ownerClassName + "1");
85          ObjectName JavaDoc ownerName2 = new ObjectName JavaDoc("library:name=" + ownerClassName + "2");
86          ObjectName JavaDoc bookName1 = new ObjectName JavaDoc("library:name=" + bookClassName + "1");
87          ObjectName JavaDoc bookName2 = new ObjectName JavaDoc("library:name=" + bookClassName + "2");
88          ObjectName JavaDoc bookName3 = new ObjectName JavaDoc("library:name=" + bookClassName + "3");
89          ObjectName JavaDoc bookName4 = new ObjectName JavaDoc("library:name=" + bookClassName + "4");
90          ObjectName JavaDoc bookName5 = new ObjectName JavaDoc("library:name=" + bookClassName + "5");
91
92          m_server.createMBean(bookClassName, bookName1, null, new Object JavaDoc[]{"Lord of the rings"}, new String JavaDoc[]{"java.lang.String"});
93          m_server.createMBean(bookClassName, bookName2, null, new Object JavaDoc[]{"The Hobbit"}, new String JavaDoc[]{"java.lang.String"});
94          m_server.createMBean(bookClassName, bookName3, null, new Object JavaDoc[]{"Harry Potter"}, new String JavaDoc[]{"java.lang.String"});
95          m_server.createMBean(bookClassName, bookName4, null, new Object JavaDoc[]{"UML Distilled"}, new String JavaDoc[]{"java.lang.String"});
96          m_server.createMBean(bookClassName, bookName5, null, new Object JavaDoc[]{"Applying UML"}, new String JavaDoc[]{"java.lang.String"});
97
98          m_server.createMBean(ownerClassName, ownerName1, null, new Object JavaDoc[]{"Fred"}, new String JavaDoc[]{"java.lang.String"});
99          m_server.createMBean(ownerClassName, ownerName2, null, new Object JavaDoc[]{"Humpty Dumpty"}, new String JavaDoc[]{"java.lang.String"});
100          System.out.println("----------------------- done ----------------------------");
101
102          System.out.println("Build the roles");
103          // build our Lists of values for our first use case an owner registers and takes out one book
104
ArrayList JavaDoc ownerList = new ArrayList JavaDoc();
105          ownerList.add(ownerName1); // can only add owner to an owner role can only be 1
106
Role JavaDoc ownerRole = new Role JavaDoc("owner", ownerList);
107
108          System.out.println("created owner Role");
109
110          ArrayList JavaDoc bookList = new ArrayList JavaDoc();
111          // we can have between 1 and 4 books more than 4 invalidates out relation and less than 1 invalidates it
112
bookList.add(bookName1);
113          bookList.add(bookName2);
114          bookList.add(bookName3);
115          Role JavaDoc bookRole = new Role JavaDoc("books", bookList);
116
117          System.out.println("Created book role");
118          System.out.println("----------------------- done ----------------------------");
119
120          System.out.println("Creating the relation");
121          // add our roles to the RoleList
122
RoleList JavaDoc libraryList = new RoleList JavaDoc();
123          libraryList.add(ownerRole);
124          libraryList.add(bookRole);
125          // now to create the relation
126
createLibraryRelation(personalLibraryId, libraryTypeName, libraryList);
127          System.out.println("Getting all the related info");
128          printAllRelationInfo();
129          System.out.println("----------------------- done ----------------------------");
130
131          // borrow one book still within our stated quota
132
System.out.println("borrow a book we have 3 one more does not invalidate our relation");
133          borrowBooks(personalLibraryId, "books", bookName4);
134          ArrayList JavaDoc newBookList4 = getRoleValue(personalLibraryId, "books");
135          System.out.println("we now have 4 books: " + newBookList4.toString());
136          System.out.println("----------------------- done ----------------------------");
137
138          // remove 2 books from the MBeanServer an see if our owner has only 2 left
139
System.out.println("2 MBeans removed from the MBeanServer - no problem we still have a valid relation.");
140          m_server.unregisterMBean(bookName1);
141          m_server.unregisterMBean(bookName2);
142
143          ArrayList JavaDoc newBookList = getRoleValue(personalLibraryId, "books");
144          System.out.println("After removing the 2 MBeans we have only 2 Book MBeans left " + newBookList.toString());
145          System.out.println("----------------------- done ----------------------------");
146
147          // we will now demonstrate the unhappy scenarios.
148
//invalidate the relation and borrow too many books throws InvalidRoleValueException
149
// note we cannot add bookName1 or bookName2 as they have been unregistered from the MBeanServer
150
// register
151
System.out.println("Deregistering the last of our books from the MBeanServer");
152          m_server.unregisterMBean(bookName3);
153          m_server.unregisterMBean(bookName4);
154          System.out.println("----------------------- done ----------------------------");
155
156          System.out.println("Testing access by running queries: ");
157          System.out.println("The relation should have been removed and an exception of RelationNotFoundException returned");
158          testAllAccessQueries(personalLibraryId);
159          System.out.println("----------------------- done ----------------------------");
160
161       }
162       catch (Exception JavaDoc ex)
163       {
164          System.out.println("Could Not create the RelationService: " + ex);
165          ex.printStackTrace();
166       }
167    }
168
169    public void borrowBooks(String JavaDoc relationId, String JavaDoc roleName, ObjectName JavaDoc bookToAdd)
170    {
171       Logger logger = getLogger();
172       try
173       {
174          // get the old values
175
ArrayList JavaDoc oldRoleValue = getRoleValue(relationId, roleName);
176          ArrayList JavaDoc newRoleValue = (ArrayList JavaDoc)oldRoleValue.clone();
177          newRoleValue.add(bookToAdd);
178          // now we update the values
179
Role JavaDoc role = new Role JavaDoc(roleName, newRoleValue);
180          Object JavaDoc[] params1 = {relationId, role};
181          String JavaDoc[] signature1 = {"java.lang.String", "javax.management.relation.Role"};
182          m_server.invoke(m_relationObjectName, "setRole", params1, signature1);
183       }
184       catch (Exception JavaDoc ex)
185       {
186          logger.error("Unable to add a book");
187          ex.printStackTrace();
188       }
189    }
190
191    private void printList(List JavaDoc list)
192    {
193       for (Iterator JavaDoc i = list.iterator(); i.hasNext();)
194       {
195          System.out.println(">>>> Names representing roles: " + i.next());
196       }
197    }
198
199    private ArrayList JavaDoc getRoleValue(String JavaDoc relationId, String JavaDoc roleName)
200    {
201       Logger logger = getLogger();
202       try
203       {
204          Object JavaDoc[] params = {relationId, roleName};
205          String JavaDoc[] signature = {"java.lang.String", "java.lang.String"};
206          return ((ArrayList JavaDoc)(m_server.invoke(m_relationObjectName, "getRole", params, signature)));
207       }
208       catch (Exception JavaDoc ex)
209       {
210          logger.error("Unable to get the list of roles for ID: " + relationId);
211          return null;
212       }
213    }
214
215    public void endExample()
216    {
217       try
218       {
219          System.out.println("Cleaning up......");
220          // this query will return the set of mbeans which have a class attribute of "management*" which is our MBeans
221
Set JavaDoc mbeanSet = m_server.queryMBeans(null, Query.initialSubString(Query.classattr(), Query.value("management*")));
222          for (Iterator JavaDoc i = mbeanSet.iterator(); i.hasNext();)
223          {
224             m_server.unregisterMBean(((ObjectInstance JavaDoc)i.next()).getObjectName());
225          }
226          // release the relationService
227
m_server.unregisterMBean(m_relationObjectName);
228          // release the MBeanServer
229
MBeanServerFactory.releaseMBeanServer(m_server);
230          System.exit(0);
231       }
232       catch (Exception JavaDoc ex)
233       {
234          ex.printStackTrace();
235          System.exit(1);
236       }
237    }
238
239    private void addRelationType()
240    {
241       try
242       {
243          Object JavaDoc[] params = {m_library};
244          String JavaDoc[] signature = {"javax.management.relation.RelationType"};
245          m_server.invoke(m_relationObjectName, "addRelationType", params, signature);
246       }
247       catch (Exception JavaDoc ex)
248       {
249          ex.printStackTrace();
250       }
251    }
252
253    private void printRelationTypeInfo()
254    {
255       try
256       {
257          ArrayList JavaDoc relTypeNameList = (ArrayList JavaDoc)(m_server.getAttribute(m_relationObjectName, "AllRelationTypeNames"));
258          System.out.println("The RelationType Names found in the RelationService: " + relTypeNameList.toString());
259       }
260       catch (Exception JavaDoc ex)
261       {
262          ex.printStackTrace();
263       }
264    }
265
266    private void createLibraryRelation(String JavaDoc personalLibraryId, String JavaDoc libraryTypeName, RoleList JavaDoc libraryList)
267    {
268       Logger logger = getLogger();
269       try
270       {
271          Object JavaDoc[] params = {personalLibraryId, libraryTypeName, libraryList};
272          String JavaDoc[] signature = {"java.lang.String", "java.lang.String", "javax.management.relation.RoleList"};
273          m_server.invoke(m_relationObjectName, "createRelation", params, signature);
274       }
275       catch (Exception JavaDoc ex)
276       {
277          logger.error("Exception creating Library Relation: " + ex.getMessage());
278          ex.printStackTrace();
279       }
280    }
281
282    private void printAllRelationInfo()
283    {
284       Logger logger = getLogger();
285       try
286       {
287          ArrayList JavaDoc allRelationIds = (ArrayList JavaDoc)m_server.getAttribute(m_relationObjectName, "AllRelationIds");
288          for (Iterator JavaDoc i = allRelationIds.iterator(); i.hasNext();)
289          {
290             String JavaDoc currentRelationId = (String JavaDoc)i.next();
291             System.out.println("All RelationIds: " + currentRelationId);
292             testAllAccessQueries(currentRelationId);
293          }
294       }
295       catch (Exception JavaDoc ex)
296       {
297          logger.error("Unable to print the relations");
298          ex.printStackTrace();
299       }
300    }
301
302    private void testAllAccessQueries(String JavaDoc relationId)
303    {
304       Logger logger = getLogger();
305       // retrieve all roles
306
try
307       {
308          Object JavaDoc[] params = {relationId};
309          String JavaDoc[] signature = {"java.lang.String"};
310          RoleResult JavaDoc roleResult = (RoleResult JavaDoc)(m_server.invoke(m_relationObjectName, "getAllRoles", params, signature));
311          RoleList JavaDoc roleList = roleResult.getRoles();
312          for (Iterator JavaDoc i = roleList.iterator(); i.hasNext();)
313          {
314             Role JavaDoc currentRole = (Role JavaDoc)i.next();
315             System.out.println(">>>> role name: " + currentRole.getRoleName());
316             System.out.println(">>>> role values: " + currentRole.getRoleValue().toString());
317          }
318          System.out.println("No unresolved Roles roleUnresolved size: " + roleResult.getRolesUnresolved().size());
319       }
320       catch (Exception JavaDoc ex)
321       {
322          logger.error("Exception printing the results from relationId: " + relationId);
323          System.out.println("Printing the Exception message to validate exception: " + ex.getMessage());
324       }
325
326    }
327
328    private Logger getLogger()
329    {
330       return Log.getLogger(getClass().getName());
331    }
332
333    public static void main(String JavaDoc[] args)
334    {
335       RelationServiceExample example = new RelationServiceExample();
336       example.setUpRelations();
337       example.endExample();
338    }
339 }
Popular Tags