• Calling a JMX Bean method in JBoss with an example of clearing JMS Queue
    Dec 13, 2011

    I needed to empty one JMS (Java Message Service) queue in JBoss 4.2.2, but I found out that JMS does not have a standard way to delete messages and empty the queue, and emptying a queue is provider-dependent operation. So I figured out that in JBoss 4.2.2 I will need to call removeAllMessages() method from Management Bean (MBean) that is associated with the queue that we want to empty. So here are the steps:

    1. First go to JMX Console of your JBoss server, located at most probably http://localhost:8080/jmx-console and find the MBean associated with the queue you want to empty. It should have attributes similar to this:

      MBean Name: 
      Domain Name: jboss.mq.destination
      service: Queue
      name: elchinsSuperJMSQueue
      
      MBean Java Class: org.jboss.mq.server.jmx.Queue
      

      We will need this information for later steps.

    2. Now we need to find the suiting MBean for JMS queues, then instantiate it, and call the necessary method as it is very nicely documented in Papo's log. The MBean interface that has methods for JMS queues in JBoss is org.jboss.mq.server.jmx.QueueMBean.

    3. Lets get coding!

      Get the reference for JBoss's MBeanServer:

      MBeanServer server = MBeanServerLocator.locateJBoss();
      

      this should also work with locate() instead of locateJBoss(). Now we need to create the MBean object that will be for exactly our JMS queue.

      ObjectName objectName = new ObjectName("jboss.mq.destination:name=elchinsSuperJMSQueue, service=Queue");
      

      now, create a proxy instance for the object from MBeanServer,

      QueueMBean queueMBean = (QueueMBean) MBeanServerInvocationHandler.newProxyInstance(
              server, objectName, org.jboss.mq.server.jmx.QueueMBean.class, false);
      

      and finally call the method

      queueMBean.removeAllMessages();
      
    Read more...
  • @Override annotation in Java 5 vs 6
    Aug 23, 2011

    I was porting a Java 6 project to Java 5 today due to requirements, and I came up with a feature difference that I was not aware of before. @Override annotation was introduced in Java 5 to mark methods that have to override methods from superclass, and to give compiler error when such overrides do not occur. However only since Java 6 you can use @Override in order to mark methods that implement the methods from interface, thus putting @Override in a method that implements method of the interface, will result in compile error in Java 5. It was somehow forgotten to be put in Java SE 6 API documentation, but was promised to be fixed in Java 7 API documentation. Blog entry from Oracle: http://blogs.oracle.com/ahe/entry/override_snafu

    Read more...
  • Lazy Generification
    Jul 14, 2011

    Every developer had faced a dilemma of whether making something generic for a better code design, or not wasting time on it. And even though theoretically there are many guidelines how to effectively write generic code, there are some visible failures done about it. For example, had someone ever seen any other type of Servlet other than HttpServlet?

    These days I had a task to develop few servlets that would have similar functionality, though not identical. Initially I did not make them generic, since I was seeing them as doing quite separate operations. However after adding third servlet of that type, I realized that it is time to make a generic servlet that would combine the common functionality. Thus, I made a generic servlet after(!) I already developed concrete implementations.

    And then it came to EJBs backing these servlets. Initially I made separate EJBs for each servlet, which would have serve the necessary back-end calls. However after making a generic servlet, I decided to put back-end calls in that generic servlet, since they were same. This however caused a problem in a way that I would have to have each type of EJB for every servlet type. So it was a time to combine two existing EJBs that I used to have into one - to combine the functionality, rather than splitting them into different classes.

    So what I realized was that it is not mandatory to make things generic right in the beginning, it can also be done a bit later later, thus "lazily". And it can even be better to do it so, since you will have a better overview and feeling of the functionality. And also do not hesitate to remove generic features and combine functionality if necessary, because it can be very possible that it was redundant to do it.

    Read more...
  • Uninstalling Eclipse plugins from Eclipse 3.6 Helios
    May 20, 2011

    For some reason Eclipse decided to make it non-straightforward to uninstall plugins, there is no big button telling "Uninstall Old Software" similar to "Install New Software". Thus it becomes a bit tricky to remove installed plugins.

    • Open Help->Install New Software, and click on "What is already installed?" among under bunch of check-boxes below.

    • Select the plugins you want to uninstall from the list of software, and click "Uninstall" below. Note that Eclipse will check for dependencies in order to not delete any plugin required by another plugins to function. Thus you have to be certain that you don't have dependency issues.

    • Confirm the selection and uninstall, and wait for uninstall to complete.

    • Restart Eclipse when you are asked for it.

    • Almost done. The thing is what really happened was that the plugins you selected got disabled, and not actually removed from the disk. That is because Eclipse is really strong about not removing, but disabling their plugins as stated in Eclipse FAQ.

    • If you want to remove plugins from disk, you will have to go to "Installation History" tab, after opening Help->Install New Software, and then delete a plugin configuration that contained unnecessary plugins.

    • In "Installation History" tab you can also revert installation configurations, however once they are removed, they are unrecoverable.

    These instructions work for Eclipse Helios 3.6 Release 2, things can (and probably will) be different in future versions.

    Read more...
  • How NOT to write code examples in programming books
    May 16, 2011

    I am currently reading Java Web Services: Up and Running (Amazon), and only after reading a chapter I am amazed how horrible the code examples are. The code examples for the book can be downloaded from here.

    Coding conventions aside (you write createEndpoint in Java, not create_endpoint), the structure of the code is just tiring to follow. Its a good practice to split up the long methods to smaller functions, however if you have a code of lets say 10 lines, how does it make sense to split it up to functions each having 5 lines? On top of all, the code in programming book should be meant for learning(!), and not for applying cutting edge code structuring, thus it is really better to have a code in one place, rather than split up to different pages.

    So here are examples, only from chapter 1 that I've read so far:

    chapter1\ch01\soap\DemoSoap.java : - Funcions process_incoming_soap, extract_contents_and_print, extract_contents_and_print are only used once. What is the point of putting such a small code being put in a function, and being used once? - Functions create_soap_message and create_qname are used twice. Now, you may save a BIT of typing (and that is even disputable, since defining such a short function takes enough of lines), but is it really necessary to hinder the code in such way and obfuscate the understanding?

    chapter1\ch01\soap\TimePublisherMT.java: This was the file, after seeing which I've decided to write this post. create_endpoint and configure_endpoint are each one line! And what is the point of having a separate publishmethod? I don't want to be rude, but the only explanation I can come up for author to write such a code, would be for him to want to occupy more space in the book.

    And if the names of functions are supposed to give a hint about what those sequences of code do, why not to just write comments?

    Here is the version of TimePublisherMT.java I re-wrote using my recommendations:

    class TimePublisherMT { // MT for multithreaded
    
        public static void main(String[] args) {
            // create endpoint
    
            Endpoint endpoint = Endpoint.create(new TimeServerImpl());
    
            // configure endpoint
    
            endpoint.setExecutor(new MyThreadPool());
    
            // publish
    
            int port = 8888;
            endpoint.publish("http://localhost:" + port + "/ts");
            System.out.println("Publishing TimeServer on port " + port);
        }
    }

    and the old one, for comparison:

    class TimePublisherMT { // MT for multithreaded
    
        private Endpoint endpoint;
    
        public static void main(String[] args) {
            TimePublisherMT self = new TimePublisherMT();
            self.create_endpoint();
            self.configure_endpoint();
            self.publish();
        }
    
        private void create_endpoint() {
            endpoint = Endpoint.create(new TimeServerImpl());
        }
        private void configure_endpoint() {
            endpoint.setExecutor(new MyThreadPool());
        }
        private void publish() {
            int port = 8888;
            String url = "http://localhost:" + port + "/ts";
            endpoint.publish(url);
            System.out.println("Publishing TimeServer on port " + port);
        }
    }
    Read more...
  • Configuring Glassfish plugin in Maven
    May 11, 2011

    Today I had a problem with glassfish plugin for maven failing to deploy/redeploy my project, giving the following error:

    Unable to start domain "domain1". IOException: Cannot run program"C:\glassfishv3\glassfish\bin\asadmin": CreateProcess error=193, %1 is not a valid Win32-Application
    

    My operating system is Windows 7, and I have Glassfish 3.1 installed. The reason is that Windows tries to invoke bin\asadmin, which is not a Windows, but Linux executable. To solve this problem, you have to simply rename bin\asadmin in Glassfish installation directory to bin\asadmin.sh, and then Windows will make a call to asadmin.bat, as it should, instead of calling the Linux executable.

    Original solution found at: http://theo.vanarem.nl/2010/03/22/using-maven-glassfish-plugin-on-windows/

    Read more...
  • How I passed SCJD/OCMJD
    Mar 29, 2011

    At the end of last year I finally decided to register for Oracle Certified Master. Java Developer certification, do the assignment and hopefully pass it. I was "lucky" at that time that projects at my work position got stalled, so there was nothing to do, and I had a lot of time to do my own things. I tried to not lose that time but to use it to quickly developed OCMJD project and I am satisfied with my results, since I passed the certification in relatively short time. Here is my short timeline:

    • 15th of September 2010 - Registered for assignment
    • 4th of November 2010 - Sat for an essay.
    • 3rd of December 2010 - Submitted my assignment.
    • 7th of January 2011 - Received an email telling I passed.

    Preparations included going through Head First Design Patterns and Monkhouse's book for SCJD. I have also had a LOT of help from people in JavaRanch forum, one of my favorite forums with most helpful people.

    My project was URLyBird 1.1.1 and I would like to talk about how I implemented it. It was a no-brainer to me that overall architecture will be "thin client", since I am used to developing web-based applications, thus I prefer to follow that model.

    Data class

    I decided to split functions of Data class into two parts, one being data access part, and another being record locking part. Data access part dealt with functions of creating, deleting, updating, reading and searching records, and locking layer deals with locking and unlocking records. Both of these parts have interfaces and implementing classes, in order to be able to switch implementations. There classes are not expected to be synchronized, and Data class has its own record locking mechanism (with Map of ReadWriteLocks, and master ReadWriteLock to read/write to this map). Note that this is a separate locking mechanism and has nothing to do with locking done in implementation of data access class.

    Data layer

    This class is composed of an interface that defines methods necessary for data access, and an implementation class. An implementation class implements the data access interface with file-based database, and has its own locking mechanism to read/write/update/delete records. Since I used RandomAccessFile to read and write to the file, I needed seek point to be stable, thus whenever I needed to perform file operations, I synchronized over the RandomAccessFile instance that I used. File-based implementation of data access also had a map that would map record numbers to record positions in the file. That would allow us to reuse file positions, as it was required for me, without having to reuse record numbers (which can be dangerous if versions are not handled.). To map file positions to position in actual file, I used a static function, since length of every records was the same, and header size was known. I also had a separate Set for deleted positions, and when a request to create a new record was received, the code was first looking whether there is a deleted record that can be reused. During application start-up, the Map of record numbers to positions and Set of deleted records were filled in. Access to the Map of record numbers to positions and the Set of deleted records was synchronized with ReadWriteLock. Find method was special that it was expected to throw UnsupportedOperationException if underlying data store did not support easy search of data. File data store was such a case, thus its find method was throwing UnsupportedOperationException, which was handled by Data class, and Data class was using its simple search algorithm. Find method was left in such way in order to enable SQL-based data stores to be effectively used to search for records.

    Record locking

    Record locking sub-system consisted of an interface that defined methods for locking, unlocking and checking for locks, and the implementation class, which used a simple HashMap to store cookies for locked records. Access to this map was synchronized with ReentrantLock and Condition, in order to enable a given thread to wait for another record to be unlocked. For generating cookies I used java.util.Random class, and gave it System.currentTimeMillis() as a seed.

    Business layer

    This layer had methods that client layer would call, and also high-level business objects, such as Record with all the named fields, instead of array of Strings. I also made factory classes in order to convert from Record object to String array and record number. To achieve that I first made an abstract record factory class and used generics in order to denote the type to which I will be converting my Record class. My concrete implementation of this class in business layer was converting to and from Pair of String and integer. Pair was a custom class I wrote for this project that would contain two elements, left and right, similar to Pair from C++ STL. My main business class was called URLyBird, and contained methods for booking, searching and retrieving all records.

    Networking

    RMI, easier and cleaner. I also have never used it before, so I was keen to learn the new technology. I had a class to start and stop the server, which was called by server GUI. This class had an instance of URLyBird class to which the calls from client side were propagated. The method to start the server programmaticaly started RMI registry and binded my service to it. Stop method however only unbinded the service from RMI registry, but did not shut it down. I could not find any simple and straightforward way to programmatically shut down the RMI registry.

    GUI

    I decided NOT to implement MVC model, since I believed that it would be an over-complication for my project. GUI in my case made only two requests to back-end, and there wasn't much of a logic for controller part, so I decided to merge controller and view. Other than that I tried to keep my GUI as simple as possible, required JTable (with custom TableModel), fields for searching, buttons for searching and booking, no icons, and only tested it in Windows 7 OS. To connect to back-end part of my application I had connector classes which would extend my Connector interface. This interface had all the methods that GUI needed from back-end, such as bookRecord and listAllRecords, and it was the bridge between back-and-front ends. I also had dialogs for connection in the beginning, which would return instances of usable Connectors upon completion of user input (details about connection). Having a separate connection dialog would allow me in future enable re-connections to another servers or files easier, without having to restart client.
    This layer also had an implementation of abstract record factory I mentioned in business layer section, with only String array. The first element of array denoted the record number in String representation.

    Essay

    4 questions, but it was the only Sun exam so far that I only finished 2 minutes before the end of exam. Questions themselves were not really hard, however I took my time to correct my wording, and I did get stuck in one questions which asked me about my table model. I did not know what to write, since writing "I did it this way because it was done so in Monkhouse book" would definitely not give me a credit. I wrote general things which by my intuition, and I guess it seemed to work out. At the end of an exam I got 0% as report, which is completely normal with the way Prometric software is designed, so there is nothing to worry about it. You are filling "comments" section of each question, and none of the questions have answers, thus you have 0 points from each of them. The person in Prometric center will probably know nothing about it, but you can ask for verification if you get a strange look from the person about you getting 0% :)

    Misc:

    My package documentation went to package-info.java. Even thought it's only supported in Java 6, its preferred way over having an html file. The find method in Data class was using prefix-based search, and in business layer it is searching based on exact match. I have generated RMI stubs since my project explicitly stated that "You must provide all classes pre-installed so that no dynamic class downloading occurs". And it would for sure not hurt, so why to take a risk of not generating them. I have changed the indentation and formatting of DB.java interface to match Java Coding Convention, and I documented it in my choices.txt. I do not handle misuse of Data class, i.e. deadlock could occur if for example two threads A and B try to obtain locks and update records 1 and 2 in reverse order. I documented it in my choices file that handling such a care would over-complicate the design, and may not be reliable.

    Read more...

subscribe via RSS