DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Popular Topics

article thumbnail
Mockito - Pros, Cons, and Best Practices
It's been almost 4 years since I wrote a blog post called "EasyMock - Pros, Cons, and Best Practices, and a lot has happened since. You don't hear about EasyMock much any more, and Mockito seems to have replaced it in mindshare. And for good reason: it is better. A Good Humane Interface for Stubbing Just like EasyMock, Mockito allows you to chain method calls together to produce less imperative looking code. Here's how you can make a Stub for the canonical Warehouse object: Warehouse mock = Mockito.mock(Warehouse.class); Mockito.when(mock.hasInventory(TALISKER, 50)). thenReturn(true); I know, I like a crazy formatting. Regardless, giving your System Under Test (SUT) indirect input couldn't be easier. There is no big advantage over EasyMock for stubbing behavior and passing a stub off to the SUT. Giving indirect input with mocks and then using standard JUnit asserts afterwards is simple with both tools, and both support the standard Hamcrest matchers. Class (not just Interface) Mocks Mockito allows you to mock out classes as well as interfaces. I know the EasyMock ClassExtensions allowed you to do this as well, but it is a little nicer to have it all in one package with Mockito. Supports Test Spies, not just Mocks There is a difference between spies and mocks. Stubs allow you to give indirect input to a test (the values are read but never written), Spies allow you to gather indirect output from a test (the mock is written to and verified, but does not give the test input), and Mocks are both (your object gives indirect input to your test through Stubbing and gathers indirect output through spying). The difference is illustrated between two code examples. In EasyMock, you only have mocks. You must set all input and output expectations before running the test, then verify afterwards. // arrange Warehouse mock = EasyMock.createMock(Warehouse.class); EasyMock.expect( mock.hasInventory(TALISKER, 50)). andReturn(true).once(); EasyMock.expect( mock.remove(TALISKER, 50)). andReturn(true).once(); EasyMock.replay(mock); //act Order order = new Order(TALISKER, 50); order.fill(warehouse); // assert EasyMock.verify(mock); That's a lot of code, and not all of it is needed. The arrange section is setting up a stub (the warehouse has inventory) and setting up a mock expectation (the remove method will be called later). The assertion in all this is actually the little verify() method at the end. The main point of this test is that remove() was called, but that information is buried in a nest of expectations. Mockito improves on this by throwing out both the record/playback mode and a generic verify() method. It is shorter and clearer this way: // arrange Warehouse mock = Mockito.mock(Warehouse.class); Mockito.when(mock.hasInventory(TALISKER, 50)). thenReturn(true); //act Order order = new Order(TALISKER, 50); order.fill(warehouse); // assert Mockito.verify(warehouse).remove(TALISKER, 50); The verify step with Mockito is spying on the results of the test, not recording and verifying. Less code and a clearer picture of what really is expected. Update: There is a separate Spy API you can use in Mockito as well: http://mockito.googlecode.com/svn/branches/1.8.3/javadoc/org/mockito/Mockito.html#13 Better Void Method Handling Mockito handles void methods better than EasyMock. The fluent API works fine with a void method, but in EasyMock there were some special methods you had to write. First, the Mockito code is fairly simple to read: // arrange Warehouse mock = Mockito.mock(Warehouse.class); //act Order order = new Order(TALISKER, 50); order.fill(warehouse); // assert Mockito.verify(warehouse).remove(TALISKER, 50); Here is the same in EasyMock. Not as good: // arrange Warehouse mock = EasyMock.createMock(Warehouse.class); mock.remove(TALISKER, 50); EasyMock.expectLastMethodCall().once(); EasyMock.replay(mock); //act Order order = new Order(TALISKER, 50); order.fill(warehouse); // assert EasyMock.verify(mock); Mock Object Organization Patterns Both Mockito and EasyMock suffer from difficult maintenance. What I said in my original EasyMock post holds true for Mockito: The method chaining style interface is easy to write, but I find it difficult to read. When a test other than the one I'm working on fails, it's often very difficult to determine what exactly is going on. I end up having to examine the production code and the test expectation code to diagnose the issue. Hand-rolled mock objects are much easier to diagnose when something breaks... This problem is especially nasty after refactoring expectation code to reduce duplication. For the life of me, I cannot follow expectation code that has been refactored into shared methods. Now, four years later, I have a solution that works well for me. With a little care you can make your mocks reusable, maintainable, and readable. This approach was battle tested over many months in an Enterprise Environment(tm). Create a private static method the first time you need a mock. Any important data needs to be passed in as a parameter. Using constants or "magic" fields hides important information and obfuscates tests. For example: User user = createMockUser("userID", "name"); ... assertEquals("userID", result.id()); assertEquals("name", result.name(); Everything important is visible and in the test, nothing important is hidden. You need to completely hide the replay state behind this factory method if you're still on EasyMock. The Mock framework in use is an implementation detail and try not to let it leak. Next, as your dependencies grow, be sure to always pass them in as factory method parameters. If you need a User and a Role object, then don't create one method that creates both mocks. One method instantiates one object, otherwise it is a parameter and compose your mock objects in the test method: User user = createMockUser( "userID", "name", createMockRole("role1"), createMockRole("role2") ); When each object type has a factory method, then it makes it much easier to compose the different types of objects together. Reuse. But you can only reuse the methods when they are simple and with few dependencies, otherwise they become too specific and difficult to understand. The first time you need to reuse one of these methods, then move the method to a utility class called "*Mocker", like UserMocker or RoleMocker. Follow a naming convention so that they are always easy to find. If you remembered to make the private factory methods static then moving them should be very simple. Your client code ends up looking like this, but you can use static imports to fix that: User user = UserMocker.createMockUser( "userID", "name", RoleMocker.createMockRole("role1"), RoleMocker.createMockRole("role2") ); User overloaded methods liberally. Don't create one giant method with every possible parameter in the parameter list. There are good reasons to avoid overloading in production, but this is test. Use overloading so that the test methods only display data relevant to that test and nothing more. Using Varargs can also help keep a clean test. Lastly, don't use constants. Constants hide the important information out of sight, at the top of the file where you can't see it or in a Mocker class. It's OK to use constants within the test case, but don't define constants in the Mockers, it just hides relevant information and makes the test harder to read later. Avoid Abstract Test Cases Managing mock objects within abstract test cases has been very difficult for me, especially when managing replay and record states. I've given up mixing mock objects and abstract TestCase objects. When something breaks it simply takes too long to diagnose. An alternative is to create custom assertion methods that can be reused. Beyond that, I've given up on Abstract TestCase objects anyway, on the grounds of preferring composition of inheritance. Don't Replace Asserts with Verify My original comments about EasyMock are still relevant for Mockito: The easiest methods to understand and test are methods that perform some sort of work. You run the method and then use asserts to make sure everything worked. In contrast, mock objects make it easy to test delegation, which is when some object other than the SUT is doing work. Delegation means the method's purpose is to produce a side-effect, not actually perform work. Side-effect code is sometimes needed, but often more difficult to understand and debug. In fact, some languages don't even allow it! If you're test code contains assert methods then you have a good test. If you're code doesn't contain asserts, and instead contains a long list of verify() calls, then you're relying on side effects. This is a unit-test bad smell, especially if there are several objects than need to be verified. Verifying several objects at the end of a unit test is like saying, "My test method needs to do several things: x, y, and z." The charter and responsibility of the method is no longer clear. This is a candidate for refactoring. No More All or Nothing Testing Mockito's verify() methods are much more flexible than EasyMock's. You can verify that only one or two methods on the mock were called, while EasyMock had just one coarse verify() method. With EasyMock I ended up littering the code with meaningless expectations, but not so in Mockito. This alone is reason enough to switch. Failure: Expected X received X For the most part, Mockito error messages are better than EasyMock's. However, you still sometimes see a failure that reads "Failure. Got X Expected X." Basically, this means that your toString() methods produce the same results but equals() does not. Every user who starts out gets confused by this message at some point. Be Warned. Don't Stop Handrolling Mocks Don't throw out hand-rolled mock objects. They have their place. Subclass and Override is a very useful technique for creating a testing seam, use it. Learn to Write an ArgumentMatcher Learn to write an ArgumentMatcher. There is a learning curve but it's over quickly. This post is long enough, so I won't give an example. That's it. See you again in 4 years when the next framework comes out! From http://hamletdarcy.blogspot.com/2010/09/mockito-pros-cons-and-best-practices.html
October 14, 2010
by Hamlet D'Arcy
· 57,084 Views
article thumbnail
5 Maven Tips
I have been working with Maven for 3 years now and over that time I have learned some tips and tricks that help me work faster with Maven. In this article, I am going to talk about 5 of those tips. Maven rf option Most of us work in a multi-module environment and it happens very often that a build fails at some module. It's a big pain to rerun the entire the build. To save you from going through this pain, Maven has an option called rf (i.e. resume) from which you can resume your build from the module where it failed. So, if your build failed at myproject-commons you can run the build from this module by typing: mvn -rf myproject-commons clean install Maven pl option This next Maven option helps you build specified reactor projects instead of building all projects. For example, if you need to build only two of your modules myproject-commons and myproject-service, you can type: mvn -pl myproject-commons,myproject-service clean install This command will only build commons and service projects. Maven Classpath ordering In Maven, dependencies are loaded in the order in which they are declared in the pom.xml. As of version 2.0.9, Maven introduced deterministic ordering of dependencies on the classpath. The ordering is now preserved from your pom, with dependencies added by inheritence added last. Knowing this can really help you while debugging NoClassDefFoundError. Recently, I faced NoClassDefFoundError: org/objectweb/asm/CodeVisitor while working on a story where cglib-2.1_3.jar was getting loaded before cglib-nodep-2.1_3.jar. And as cglib-2.1_3.jar does not have this CodeVisitor class I was getting the error. Maven Classifiers We all know about qualifiers groupId, artifactId, version that we use to describe a dependency but there is fourth qualifier called classifier. It allows distinguishing two artifacts that belong to the same POM but were built differently, and is appended to the filename after the version. For example, if you want to build two separate jars, one for Java 5 and another for Java 6, you can use classifier. It lets you locate your dependencies with the further level of granularity. junitjunittestjdk16 Dependency Version Ranges Have you ever worked with a library that releases too often when you want that you should always work with the latest without changing the pom. It can be done using dependency version changes. So, if you want to specify that you should always work with the version above a specified version, you will write: [1.1.0,) This line means that the version should always be greater than or equal to 1.1.0. You can read more about dependency version ranges at this link. These are my five tips. If you have any tips please share.
October 5, 2010
by Shekhar Gulati
· 65,985 Views · 5 Likes
article thumbnail
Disable Javascript error in WPF WebBrowser control
I work with WebBrowser control in WPF, and one of the most annoying problems I have with it, is that sometimes you browse sites that raise a lot of javascript errors and the control becomes unusable. Thanks to my friend Marco Campi, yesterday I solved the problem. Marco pointed me a link that does not deal with WebBrowser control, but uses a simple javascript script to disable error handling in a web page. This solution is really simple, and seems to me the right way to solve the problem. The key to the solution is handle the Navigated event raised from the WebBrowser control. First of all I have my WebBrowser control wrapped in a custom class to add functionalities, in that class I declare this constant. private const string DisableScriptError = @"function noError() { return true; } window.onerror = noError;"; This is the very same script of the previous article, then I handle the Navigated event. void browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { InjectDisableScript(); Actually I’m doing a lot of other things inside the Navigated event handler, but the very first one is injecting into the page the script that disable javascript error. private void InjectDisableScript() { HTMLDocumentClass doc = Browser.Document as HTMLDocumentClass; HTMLDocument doc2 = Browser.Document as HTMLDocument; //Questo crea lo script per la soprressione degli errori IHTMLScriptElement scriptErrorSuppressed = (IHTMLScriptElement)doc2.createElement("SCRIPT"); scriptErrorSuppressed.type = "text/javascript"; scriptErrorSuppressed.text = DisableScriptError; IHTMLElementCollection nodes = doc.getElementsByTagName("head"); foreach (IHTMLElement elem in nodes) { //Appendo lo script all'head cosi è attivo HTMLHeadElementClass head = (HTMLHeadElementClass)elem; head.appendChild((IHTMLDOMNode)scriptErrorSuppressed); } } This is the code that really solves the problem, the key is creating a IHTMLScriptElement with the script and injecting into the Head of the page, this effectively disables the javascript errors. I’ve not fully tested with a lot of sites to verify that is able to intercept all errors, but it seems to work very well with a lot of links that gave us a lot of problems in the past. Alk.
October 5, 2010
by Ricci Gian Maria
· 20,895 Views
article thumbnail
Java Barcode API
Originally Barcodes were 1D representation of data using width and spacing of bars. Common bar code types are UPC barcodes which are seen on product packages. There are 2D barcodes as well (they are still called Barcodes even though they don’t use bars). A common example of 2D bar code is QR code (shown on right) which is commonly used by mobile phone apps. You can read history and more info about Barcodes on Wikipedia. There is an open source Java library called ‘zxing’ (Zebra Crossing) which can read and write many differently types of bar codes formats. I tested zxing and it was able to read a barcode embedded in the middle of a 100 dpi grayscale busy text document! This article demonstrates how to use zxing to read and write bar codes from a Java program. Getting the library It would be nice if the jars where hosted in a maven repo somewhere, but there is no plan to do that (see Issue 88). Since I could not find the binaries available for download, I decided to download the source code and build the binaries, which was actually quite easy. The source code of the library is available on Google Code. At the time of writing, 1.6 is the latest version of zxing. 1. Download the release file ZXing-1.6.zip (which contains of mostly source files) from here. 2. Unzip the file in a local directory 3. You will need to build 2 jar files from the downloaded source: core.jar, javase.jar Building core.jar cd zxing-1.6/core mvn install cd zxing-1.6/core mvn install This will install the jar in your local maven repo. Though not required, you can also deploy it to your company’s private repo by using mvn:deploy or by manually uploading it to your maven repository. There is an ant script to build the jar as well. Building javase.jar Repeat the same procedure to get javase.jar cd zxing-1.6/javase mvn install cd zxing-1.6/javase mvn install Including the libraries in your project If you are using ant, add the core.jar and javase.jar to your project’s classpath. If you are using maven, add the following to your pom.xml. com.google.zxing core 1.6-SNAPSHOT com.google.zxing javase 1.6-SNAPSHOT com.google.zxing core 1.6-SNAPSHOT com.google.zxing javase 1.6-SNAPSHOT Once you have the jars included in your project’s classpath, you are now ready to read and write barcodes from java! Reading a Bar Code from Java You can read the bar code by first loading the image as an input stream and then calling this utility method. InputStream barCodeInputStream = new FileInputStream("file.jpg"); BufferedImage barCodeBufferedImage = ImageIO.read(barCodeInputStream); LuminanceSource source = new BufferedImageLuminanceSource(barCodeBufferedImage); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Reader reader = new MultiFormatReader(); Result result = reader.decode(bitmap); System.out.println("Barcode text is " + result.getText()); InputStream barCodeInputStream = new FileInputStream("file.jpg"); BufferedImage barCodeBufferedImage = ImageIO.read(barCodeInputStream); LuminanceSource source = new BufferedImageLuminanceSource(barCodeBufferedImage); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Reader reader = new MultiFormatReader(); Result result = reader.decode(bitmap); System.out.println("Barcode text is " + result.getText()); Writing a Bar Code from Java You can encode a small text string as follows: String text = "98376373783"; // this is the text that we want to encode int width = 400; int height = 300; // change the height and width as per your requirement // (ImageIO.getWriterFormatNames() returns a list of supported formats) String imageFormat = "png"; // could be "gif", "tiff", "jpeg" BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height); MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, new FileOutputStream(new File("qrcode_97802017507991.png"))); String text = "98376373783"; // this is the text that we want to encode int width = 400; int height = 300; // change the height and width as per your requirement // (ImageIO.getWriterFormatNames() returns a list of supported formats) String imageFormat = "png"; // could be "gif", "tiff", "jpeg" BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height); MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, new FileOutputStream(new File("qrcode_97802017507991.png"))); In the above example, the bar code for “97802017507991″ is written to the file “qrcode_97802017507991.png” (click to see the output). JavaDocs and Documentation The Javadocs are part of the downloaded zip file. You can find a list of supported bar code formats in the Javadocs. Open the following file to see the javadocs. zxing-1.6/docs/javadoc/index.html zxing-1.6/docs/javadoc/index.html From http://www.vineetmanohar.com/2010/09/java-barcode-api/
September 27, 2010
by Vineet Manohar
· 112,382 Views · 2 Likes
article thumbnail
How to Create JavaHelp in a Mavenized NetBeans Platform Application
There isn't a JavaHelp template for Maven-based NetBeans Platform modules, hence you need to set up JavaHelp yourself. It's a bit tricky, involving several different parts that can go wrong easily (which is why a JavaHelp template is so handy). Here's instructions on how to set up JavaHelp in your Maven-based NetBeans Platform modules. Do the following: In each module that needs to provide a JavaHelp set, add this line to the manifest: OpenIDE-Module-Requires: org.netbeans.api.javahelp.Help In the POM of the container project (i.e., NOT the application project and NOT a functionality module project), add the "dependencies" section in the definition of the "org.codehaus.mojo", while setting the "version" to 3.0: org.codehaus.mojo nbm-maven-plugin 3.0 true javax.help javahelp 2.0.02 ${brandingToken} foobar Note that the "version" is set to 3.0. I could not get JavaHelp to work for 3.1 or 3.2 (the default in 6.9+) and had to revert to 3.0. Maybe someone can correct me on this point somehow. Make sure that the POMs in the other projects (i.e., application project and functionality module projects) do not have their own definition of "org.codehaus.mojo". I.e., the container project should handle this definition for the whole application. You have now configured the application to use JavaHelp and have indicated each module that will provide JavaHelp. In each of those modules, you now need to provide JavaHelp content. The simplest approach for this is to create an Ant-based NetBeans Platform module. Then, use the wizard available for Ant-based NetBeans Platform projects for the creation of JavaHelp sets. Then copy the files that are generated into your Maven-based NetBeans Platform project: Note the following in the screenshot above. The "resources" folder contains the "module1-helpset.xml" file, which references the files in the "src/main/javahelp" folder by means of having the following content: And note that the "layer.xml" file above has this folder added: The folder "src/main/javahelp" is new, I created that myself, by copying that folder from the Ant-based NetBeans Platform module. That's the place where you will now create all your help topics within the Mavenized application. The Map file lists the identifying keys of the help topics, the TOC lists those keys that define the table of contents, and the Index does the same to define the index of the helpset. That's all you need. Now you have JavaHelp working in your Mavenized NetBeans Platform application:
September 25, 2010
by Geertjan Wielenga
· 13,427 Views
article thumbnail
How to Display Maven Project Version in Your Webapp Overview
sometimes it is useful to display the version of your web application, typically in the footer area of the web page. by displaying the version information, one can quickly determine which version of the app is running or users can use it for error reporting purposes. displaying the version is also useful when there are frequent automated releases using the maven release plugin and it is hard to track which version is actually deployed on a server. here’s an illustration of how version can be displayed in the footer. this article describes how to display the version of your maven project in your web application. step 1: create a view file to display the version first we will create a view file which will display the version. the view file could be a jsp, html, xhtml, a facelet or any format depending on your stack. in this example, we will create a jsp file which will print the version somewhere in the page. however, instead of the hardcoding an actual version, we put a special token ‘project_version’. we don’t want to hard code the version information as it will change from release to release. the special token will be replaced with actual maven project version when the app is packaged. create the following jsp. src/main/webapp/version.jsp here’s a simple file which displays the version information. project version is project_version step 2: add snippet to pom.xml the maven replacer plugin is a simple and useful plugin which can replaces tokens in file of your choice. add the following snippet of code to your pom.xml. com.google.code.maven-replacer-plugin maven-replacer-plugin 1.3.2 prepare-package replace target/myproject/version.jsp false project_version ${project.version} to test the above setup, you can run the following command: mvn prepare-package navigate to the following file. target/myproject/version.jsp the contents of this file will look something like this (assuming that your project version is 1.0-snapshot): project version is 1.0-snapshot when your application ships, the version.jsp file will always have the correct version. you can see the version by invoking the version.jsp page. http://localhost:8080/myproject/version.jsp note: your view file does not have to be a jsp, it can be any a view file suitable to your stack. it could be part of your footer which could be included at the bottom in each page. the special token can be changed from project_version to another value of your choice, just change it in the view file as well as the pom.xml instead of having the version contained in a view file, you could have the version in a properties file or a message bundle and then display a message from the message bundle on the view references maven replace plugin on google code from http://www.vineetmanohar.com/2010/09/how-to-display-maven-project-version-in-your-webapp
September 23, 2010
by Vineet Manohar
· 36,879 Views · 1 Like
article thumbnail
CheckThread - A Static Analysis Tool For Catching Java Concurrency Bugs
a few days back, i was browsing the web and found an interesting open source framework called checkthread . it is a static analysis tool for catching java concurrency bugs at compile time. static analysis tools are used to find out programming error in the code by analyzing their byte code. to me a tool aiming to catch concurrency bugs at compile time was worth spending time on. so, i decided to play with checkthread to find out its capabilities. checkthread requires developers to specify the thread policy in either xml or annotations. thread policy defines whether the piece of code (i.e. a method) is thread safe, not thread safe, or thread confined. thread confined means that this method is confined to a specific runtime thread. for example, the swing api must be invoked on the event-dispatch thread. prerequisite before you start: download eclipse plugin . put plugin in jar in eclipse plugins folder and restart eclipse. for more information refer here . download checkthread annotation jar . this jar is not present in any maven repository, so manually install the jar in your maven repository. mvn install:install-file -dfile=checkthread-annotations-1.0.9.jar -dgroupid=org.checkthread -dartifactid=checkthread-annotations -dversion=1.0.9 -dpackaging=jar checkthread capabilities let's look at an example: public class threadsafetyexample { final map helpermap = new hashmap(); public void addelementtomap() { helpermap.put("name", "shekhar"); } } this is a simple class which puts a key value pair in a map. is this code thread safe? no. lets test this class using multiple threads. in the unit test i am using countdownlatch for producing maximum parallelism. i talked about countdownlatch in an earlier article . @test public void regressiontest() throws exception{ for (int i = 1; i <= 100; i++) { system.out.println("runing "+i); addelementtomapwhenaccessedbymultiplethread(); } } public void addelementtomapwhenaccessedbymultiplethread() throws exception { final countdownlatch latch = new countdownlatch(1); final threadsafetyexample helper = new threadsafetyexample(); class mythread extends thread { @override public void run() { try { latch.await(); } catch (interruptedexception e) { } helper.addelementtomap(); } } int threadcount = 2000; mythread[] mythreads = new mythread[threadcount]; for (int i = 0; i < mythreads.length; i++) { mythreads[i] = new mythread(); mythreads[i].start(); } latch.countdown(); for (mythread mythread : mythreads) { mythread.join(); } assertequals(1, helper.helpermap.size()); } i am calling the method addelementtomapwhenaccessedbymultiplethread in a for loop because if you run the test only once it might not fail (thread timing). so, how can these types of errors be detected at compile time if most of the unit-tests and integration tests that we write do not test the code in multi-threaded environments? checkthread can help you out in such situations. checkthread can only help you if you annotate your method with threadsafe annotation. for example, lets apply @threadsafe annotation to the threadsafetyexample class: public class threadsafetyexample { final map helpermap = new hashmap(); @threadsafe public void addelementtomap() { helpermap.put("name", "shekhar"); } } now when you run the checkthread by pressing the button you will see a compile time error as shown below: as you can see in the above image, the tool shows the code where problems exist and descriptions of errors in the problems section. this can come in handy while writing multi threaded code. you just need to think about your contract, whether the method you have written should be thread safe or not. this was just a simple use case but it can also help you detect race conditions . have a look at this tool, maybe it can help you detect concurrency bugs.
September 21, 2010
by Shekhar Gulati
· 27,738 Views
article thumbnail
Naming Conventions for Parameterized Types
Parameterized types - the <> expressions that can be used in Java as of JDK 5 are not just for collections. I find myself frequently using them in APIs I design. They really do let you write things which are more generic in the non-Java sense of the word - and the result is more reusable code, which means less code overall, which means fewer bugs and things to test. The verbosity, and some of the weirdness of type-erasure are less than ideal, but used right, the benefits are worth the complexity. The standard (and somewhere recommended) naming convention for parameterized types is to use a single-letter name. That works fine in signatures that have only one such type. But in practice, single-letter names make code less self-describing, and if you're defining a class with more than one parameterized type, it can be confusing and hard to read. People other than me will have to call, understand and maintain my code - the more self-describing I can make it, the better. So I am looking for a naming convention that makes it obvious that something is a parameterized type, but allows for descriptive names. I am wondering if anybody else has run into this problem, and if there is any emerging consensus on naming generics. Do you work on a project that uses generics a lot? If so, what do you do? Here's an example. At the moment, I'm writing a generic (in both senses) class which simply limits the number of threads which can access some resource. It's basically a wrapper around a Semaphore which uses a Runnable-like object to ensure that the Semaphore is accessed correctly, and does some non-blocking statistic gathering about thread contention. So to access the scarce resource, you pass in a ResourceAccessor: public interface ResourceAccessor { public Result run (ProtectedResource resource, Argument argument); } The problem is that, when somebody looks at this interface, they will instantly get the idea that there are really classes they need to go find, which are called ProtectedResource, Argument and Result - and of course, no such classes exist - these are just names for generic types. The standard-naming-convention is worse: public interface ResourceAccessor { public S run (T resource, R argument); } Here, nobody could possibly figure out what on earth this class is for without extensive documentation - this is a really horrible idea. So I've concluded that the standard recommendations for generic type names are simply wrong for any non-trivial usage (I.e. Collection is fine, since there is one type and Collections are well-understood). You simply can't do this on a non-collection code structure you have invented, or people will just be confused and not use it. The best suggestion I've heard thus far is using $ as a prefix: public interface ResourceAccessor <$ProtectedResource, $Argument, $Result> { public $Result run ($ProtectedResource resource, $Argument argument); } I don't find this pretty, but I don't have any better ideas, and at least it makes it crystal-clear that there is something different about these names. Any thoughts? What do you do in this situation?
September 20, 2010
by Tim Boudreau
· 17,822 Views
article thumbnail
Commons Lang 3 -- Improved and Powerful StringEscapeUtils
In the first and second parts of this series I talked about some of the new features like enum and concurrency support that have been added in commons-lang 3. In this article, I am going to talk about a new package 'org.apache.commons.lang3.text.translate' which has been added in commons-lang 3. This package is added to fix problems in the design and implementation of the StringEscapeUtils class which exists in versions prior to 3.0. To make it clearer, let's first talk about the purpose of StringEscapeUtils class and the problems it had prior to version 3. Purpose of StringEscapeUtils StringEscapeUtils is a utility class which escapes and unescapes String for Java, JavaScript, HTML, XML, and SQL. For example, @Test public void test_StringEscapeUtils() { assertEquals("\\\\\\n\\t\\r", StringEscapeUtils.escapeJava("\\\n\t\r")); // escapes the Java String assertEquals("\\\n\t\r",StringEscapeUtils.unescapeJava("\\\\\\n\\t\\r")); //unescapes the Java String assertEquals("I didn\\'t say \\\"you to run!\\\"",StringEscapeUtils.escapeJavaScript("I didn't say \"you to run!\""));//escapes the Javascript assertEquals("<xml>", StringEscapeUtils.escapeXml(""));//escapes the xml } Problems with StringEscapeUtils There were a lot of problems in the StringEscapeUtils implementation prior to version3. Some of these were: The implementation was not extensible. Let's take an example of escapeJava, suppose we want to add support in the escapeJava method that it should start escaping single quotes. To add such support we would have to change the existing class code and another if condition which if satisfied will escape single quotes. So, the API was breaking the open-closed principle i.e. a class should be open for extension and closed for modification. It was not symmetric i.e. original should be equal to unescape(escape(original)) but it was not the case. StringEscapeUtils.escapeHtml() escapes multibyte characters like Chinese, Japanese etc. Issue 339 @Test public void testEscapeHiragana() { // Some random Japanese unicode characters String original = "\u304B\u304C\u3068"; String escaped = StringEscapeUtils.escapeHtml(original); assertEquals(original, escaped); } StringEscapeUtils.escapeHtml incorrectly converts unicode characters above U+00FFFF into 2 characters. Issue 480 @Test public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException { byte[] data = new byte[] { (byte) 0xF0, (byte) 0x9D, (byte) 0x8D,(byte) 0xA2 }; String original = new String(data, "UTF8"); String escaped = StringEscapeUtils.escapeHtml(original); assertEquals(original, escaped); } StringEscaper.escapeXml() escapes characters > 0x7f . Issue 66 @Test public void shouldNotEscapeValuesGreaterThan0x7f() { assertEquals("XML should not escape >0x7f values", "\u00A1",StringEscapeUtils.escapeXml("\u00A1")); } Solution -- Rewritten StringEscapeUtils In version 3.0, StringEscapeUtils is completely rewritten to fix all the bugs associated with this class and to provide a way for the user to customize the behavior of its methods. They have moved all the logic present in the StringEscapeUtils to the classes in the package 'org.apache.commons.lang3.text.translate'. Let's take an example of escapeJava function in StringEscapeUtils, escapeJava function does not contain any business logic, it just calls the translate method on CharSequenceTranslator reference. What they did can be best understood by looking at the code below public static final CharSequenceTranslator ESCAPE_JAVA = new AggregateTranslator(new LookupTranslator( new String[][] { {"\"", "\\\""}, {"\\", "\\\\"}, }),new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_ESCAPE()),UnicodeEscaper.outsideOf(32, 0x7f)); and in the escapeJava method public static final String escapeJava(String input) { return ESCAPE_JAVA.translate(input); } A constant of type CharSequenceTranslator was assigned an AggregateTranslator object. AggregateTranslator can take an array of translators, and it iterates over each of them. The LookupTranslator replaces the string at zeroth index with the string at the first index. UnicodeEscaper translates values outside the given range to unicode values. As you can see, you can very easily write your own escape methods. For example, if you want to add the support of escaping &, you can do it like this public static final CharSequenceTranslator ESCAPE_JAVA = new LookupTranslator( new String[][] { {"\"", "\\\""}, {"\\", "\\\\"}, }).with(new LookupTranslator( new String[][]{ {"&", "&"}, {"<", "<"} )).with( new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_ESCAPE()) ).with( UnicodeEscaper.outsideOf(32, 0x7f) ); StringEscapeUtils.escapeSql has been removed from the API as it was misleading developers to not use PreparedStatement.This method was not of much use as it was only escaping single quotes.
September 17, 2010
by Shekhar Gulati
· 71,143 Views · 2 Likes
article thumbnail
Exposing a POJO as a JMX MBean Easily With Spring
JMX is a great way to check or change state variables or invoke a method in a (remote) running application via a management GUI such as JConsole. And Spring makes it trivial to expose any POJO as a JMX MBean with only little configuration in a few minutes. The Spring JMX documentation is very good, however there are few points that I struggled with for a while and would therefore like to record here the right solutions. I needed to monitor a command-line java application using Spring 2.5 on IBM JVM 1.4 1.5 running on a server with a jconsole on Sun JVM 1.6 as the JMX client on my PC. All the XML snippets are from a Spring application-context.xml. If you haven’t used Spring before, read a tutorial on its configuration and dependency injection. Turning a POJO into an MBean JMX makes it possible to expose getters, setters and operations taking primitive or complex data types as parameters (though types other then few special ones require the client to have the classes). You tell Spring to expose a POJO as an MBean as follows: First you declare an instance of the POJO class – the myMBean (for other reasons I’ve an old-fashioned singleton and use JobPerformanceStats.instance() to access the bean). Next you declare an MBeanExporter with lazy-init=”false” and tell it about your bean. (There are also other ways to do it, including auto-discovery.) The bean will be then visible under its key, i.e. “bean:name=MyMBeanName”, which JConsole displays as “MyMBeanName”. Notice that the MBeanExporter only works under JVM 1.5+ because it uses the new java.lang.management package. Under 1.4 Spring would fail with java.lang.NoClassDefFoundError: javax/management/MBeanServerFactory at org.springframework.jmx.support.MBeanServerFactoryBean.createMBeanServer By default it will expose all public methods and attributes. You can change that in various ways, for example with the help of an interface. If you are not running in a container that already provides an MBean server, which is my case here, you must tell Spring to start one: Enabling remote access To make the MBean accessible from another machine, you must expose it to the world by declaring a ConnectorServerFactoryBean configured with an appropriate communication mechanism. Remote access over JMXMP By default the ConnectorServerFactoryBean exposes MBeans over JMXMP with the address service:jmx:jmxmp://localhost:9875 : However this protocol isn’t supported out of the box and you must include jmxremote_optional.jar, a part of OpenDMK, on the classpath of both the MBean application and the jconsole client to avoid the exception org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.jmx.support.ConnectorServerFactoryBean#0′ defined in class path resource [application-context.xml]: Invocation of init method failed; nested exception is java.net.MalformedURLException: Unsupported protocol: jmxmp Remote access over RMI Alternatively you can expose the MBeans over RMI, which has no additional dependencies: However there are also some catches you must avoid: You must start an RMI registry so that the connector can register the MBean there; it won’t start one for you You must make sure that the registry is started before the connector tries to use either by declaring it before the connector or by making this dependency explicit with the depends-on attribute If you don’t set it up correctly you will get an exception like org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.jmx.support.ConnectorServerFactoryBean#0′ defined in class path resource [application-context.xml]: Invocation of init method failed; nested exception is java.io.IOException: Cannot bind to URL [rmi://localhost:10099/jmxrmi]: javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: localhost; nested exception is: java.net.ConnectException: Connection refused: connect]. Local MBean server accessed over an SSH tunnel For increased security you may want to prefer not to expose your MBeans to remote access by making them accessible only from the local machine (127.0.0.1) and use na SSH tunnel so that a remote JConsole can access them as a local application. This is certainly possible but may be difficult because normally JMX goes over RMI, which uses two ports: one for the RMI Registry and another one for the actual service (MBean server here), which is usually chosen randomly at the runtime, and you’d need to tunnel both. Fortunately, Spring makes it possible to configure both the ports: Replace STUBPORT and REGISTRYPORT with suitable numbers and tunnel those two. Notice that the REGISTRYPORT number is same in the connector’s serviceUrl and in the RMI registry’s port attribute. WARNING: The configuration above actually doesn’t prevent direct access from a remote application. To really force the RMI registry to only listen for connection from the local host we would likely need to set – under Sun JVM without Spring – the system property com.sun.management.jmxremote. Additionally, to force the registry to use the IP 120.0.0.1, we’d need to set java.rmi.server.hostname=localhost (applies to Spring too). See this discussion about forcing local access. I’m not sure how to achieve the same result with Spring while still preserving the ability to specify both the RMI ports. Check also the JavaDoc for Spring’s RmiServiceExporter . Related posts and docs: Tunneling Debug and JMX for Alfresco (A. uses Spring)- see the second section, SSH Tunneling for JMX A custom tunneling RMI agent – uses a configured port instead of a random one Monitoring ActiveMQ Using JMX Over SSH JMX 1.2 specification and JMX 1.0 Remote API specification; from the JMX spec.: “The MBean server relies on protocol adaptors and connectors to make the agent accessible from management applications outside the agent’s JVM.” On the other hand, the Oracle JMX page reads that if you set com.sun.management.jmxremote (as opposed to …jmxremote.port), you make it possible “to monitor a local Java platform, that is, a JVM running on the same machine” – thus not necessarily from the same JVM. Connecting with JConsole Fire up JConsole and type the appropriate remote address, for example service:jmx:rmi:///jndi/rmi://your.server.com:10099/myconnector, if connecting to an application on the remote machine your.server.com accessible via RMI. Regarding the connection URL, if you have a a connector with the serviceUrl of "service:jmx:rmi://myhost:9999/jndi/rmi://localhost:10099/myconnector" then, from a client, you can use either service:jmx:rmi://myhost:9999/jndi/rmi://your.server.com:10099/myconnector or simply service:jmx:rmi:///jndi/rmi://your.server.com:10099/myconnector because, according to the JMX 1.2 Remote API specification (page 90): ... the hostname and port number # (myhost:9999 in the examples) are not used by the client and, if # present, are essentially comments. The connector server address # is actually stored in the serialized stub (/stub/ form) or in the # directory entry (/jndi/ form). IBM JVM, JConsole and JMX configuration The IBM JVM 5 SDK guide indicates that the IBM SDK also contains JConsole and recognizes the same JMX-related system properties, namely com.sun.management.jmxremote.* (though “com.sun.management.jmxremote” itself isn’t mentioned). Notice that the IBM JConsole is a bit different, for instance it’s missing the Local tab, which is replaced by specifying the command-line option connection=localhost (search the SDK guide for “JConsole monitoring tool Local tab”). Further improvements JVM 1.5: Exposing the MemoryMXBean Since Java 5.0 there is a couple of useful platform MBeans that provide information about the JVM, including also the java.lang.management.MemoryMXBean, that let you see the heap usage, invoke GC etc. You can make it available to JConsole and other JMX agents as follows (though there must be an easier way): Update: There indeed seems to be a better way of exposing the platform MBeans directly by replacing the Spring’s MBeanServerFactoryBean with java.lang.management.ManagementFactory using its factory-method getPlatformMBeanServer. Of course this requires JVM 1.5+. Improving security with password authentication Access to your MBeans over RMI may be protected with a password. According to a discussion, authentication is configured on the server connector: The passwd and access files follow the templates that can be found in the JDK/jre/lib/management folder. Summary Exposing a POJO as a MBean with Spring is easy, just don’t forget to start an MBean server and a connector. For JMXMP, include the jmxmp impl. jar on the classpath and for RMI make sure to start a RMI registry before the connector. From http://theholyjava.wordpress.com/2010/09/16/exposing-a-pojo-as-a-jmx-mbean-easily-with-spring/
September 17, 2010
by Jakub Holý
· 37,535 Views
article thumbnail
Throwing Undeclared Checked Exceptions
Sometimes checked exceptions can be a problem. For instance, recently I tried to implement some common logic to retry failing network operations and it resulted in a kind of command pattern on which, as usual, the execute() method throws java.lang.Exception. That complicated the caller code which has to catch and handle java.lang.Exception instead of the more specific exceptions... I knew that checked exceptions are enforced by the compiler, while in the virtual machine there is nothing preventing a checked exception to be thrown by a method not declaring it, so I started to check on internet how to implement this. I found two posts on Anders Noras's blog (#1 #2) on how to perform this magic. Method #1: the sun.misc.Unsafe class import java.lang.reflect.Field; import sun.misc.Unsafe; public class UnsafeSample { public void methodWithNoDeclaredExceptions( ) { Unsafe unsafe = getUnsafe(); unsafe.throwException( new Exception( "this should be checked" ) ); } private Unsafe getUnsafe() { try { Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); return (Unsafe) field.get(null); } catch(Exception e) { throw new RuntimeException(e); } } public static void main( String[] args ) { new UnsafeSample().methodWithNoDeclaredExceptions(); } } This makes use of internal Sun JRE libraries implementation classes. It could not work if you use a non Sun VM. And in fact it doesn't if you use GCJ (The GNU compiler for Java). The getUnsafe() method exposed above does some tricks to access a private field in the Unsafe class, because Unsafe.getUnsafe() can only be called by classes loaded by the bootstrap ClassLoader. See also the article Avoiding Checked Exceptions by Don Schwarz. Method #2: the Thread.stop(Exception) public class ThreadStopExample { @SuppressWarnings("deprecation") public void methodWithNoDeclaredExceptions( ) { Thread.currentThread().stop(new Exception( "this should be checked" )); } public static void main( String[] args ) { new ThreadStopExample().methodWithNoDeclaredExceptions(); } } This uses a deprecated method, but works. No portability issue, until the Java specification guys decide to remove the method. It could have some side effects on the current thread as we are calling stop(). I'm not sure. Method #3: using Class.newInstance() Look at the signature of java.lang.Class.newInstance() and compare it to Constructor.newInstance() public final class Class ... { public T newInstance() throws InstantiationException, IllegalAccessException } public final class Constructor ... { public T newInstance(Object ... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException } You see it? no InvocationTargetException! If you call SomeObject.class.newInstance() and the constructor throws an exception, the exception doesn't get wrapped into the InvocationTargetException (that is a checked exception). So you can write an utility class like this, to throw checked exceptions without needing to declare them on the method signature. public class Exceptions { private static Throwable throwable; private Exceptions() throws Throwable { throw throwable; } public static synchronized void spit(Throwable throwable) { Exceptions.throwable = throwable; try { Exceptions.class.newInstance(); } catch(InstantiationException e) { } catch(IllegalAccessException e) { } finally { Exceptions.throwable = null; } } } public class TestExceptionSpit { public static void main(String[] args) { Exceptions.spit(new Exception( "this should be checked" )); } } Internally the Class.newInstance() uses the sun.misc.Unsafe class, but in this case this technique is fully portable because you are not using any deprecated or internal method. In fact it works also with GCJ JVM. I tried to remove the synchronization stuff and the static field using an inner class, but it seems that the compiler does some strange trick translating the empty constructor in something else preventing Class.newInstace() to be used on that inner class. The behavior of the Class.newInstance() is also documented: "Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler." So your code is fully safe and compliant to the rules :) Method #4: the sun.corba.Bridge import java.rmi.RemoteException; public class Bridge { public void methodWithNoDeclaredExceptions( ) { sun.corba.Bridge.get().throwException(new RemoteException("bang!")); } public static void main( String[] args ) { new Bridge().methodWithNoDeclaredExceptions(); } } This is more or less the same as using the Unsafe.class. The difference is that in this case you don't need to do the reflection stuff to access the private field "theUnsafe", because the Bridge class is doing that for you. Still using an internal JRE class with same portability issues. Method #5: Generics The following example takes advantage of the fact that the compiler does not type check generics... import java.rmi.RemoteException; class Thrower { public static void spit(final Throwable exception) { class EvilThrower { @SuppressWarnings("unchecked") private void sneakyThrow(Throwable exception) throws T { throw (T) exception; } } new EvilThrower().sneakyThrow(exception); } } public class ThrowerSample { public static void main( String[] args ) { Thrower.spit(new RemoteException("go unchecked!")); } } Credits to "Harald" that posted a comment on Johannes Brodwall's blog. I personally think this last one is the best solution: it uses a feature of the compiler against itself. Conclusions I think that having checked exception in Java is better than not having it. I already expressed why I am in favor of checked exceptions here. It's a design decision, you can choose to make your exceptions checked or unchecked, if you want to force your client to handle them or not; you can't do that on .NET, where checked exceptions simply do not exist. Sometimes you have (or you have to write) methods throwing java.lang.Exception, and you get into the trap. So you may like to know that there is a dirty escape, and you can decide to use it or not... we saw that Sun is throwing undeclared checked exceptions in Class.newInstace(), ask yourself: if this is good for the JRE code, could it be good also for yours? Usually you can wrap checked exception into RuntimeExceptions but this doesn't simplify the client code, because the caller in case of needing has to catch the RuntimeException, unwrap the cause and deal with it. Maybe a new Java keyword to throw checked exception without requiring the caller to handle them could help: I recommend reading post on Ricky Clarkson's about checked exceptions. Finally I come to the decision to not use those tricks in my object doing the retry logic, and keep the messy catch logic on the caller code. In case of needing I will evaluate to use a Dynamic Proxy doing the retry logic and keeping its behavior transparent to the client. To those who wants unchecked exceptions in Java... well, there is the way to have it: the example with Generics is a clean way to have it. Use it if you want, at your own risk. Personally I would choose to use libraries with checked exceptions... Other related articles Friday Free Stuff by Chris Nokleberg, uses bytecode manipulation. Don't Try This at Home by Bob Lee, exposes some methods also covered above. From: http://en.newinstance.it/2008/11/17/throwing-undeclared-checked-exceptions/
September 15, 2010
by Luigi Viggiano
· 26,219 Views
article thumbnail
Java Swing Components Accordion Skinning Tutorial
Before we can begin skinning a JSCAccordion, we need to first decide on what look we want to achieve. After much searching I came across an attractive asp.net accordion which I though would make the perfect subject for this skinning tutorial. This tutorial will show you how to take the the default accordion and skin it to look like the asp.net accordion. Comparing the asp.net accordion to the standard JSCAccordion, one would imagine that it would take a lot of code to perform the transformation, however this is really not the case. There are a number of options available to us when going about skinning a JSCAccordion, some include extending the existing JSCAccordion, extending an existing AccordionUI, or lastly simply adjusting an accordion's settings in code. I will follow the last approach as I feel this will lead to a simpler demo, but all options are valid. Step 1: Create an instance of JSCAccordion The first step in our tutorial involves creating a new JSCAccordion and adding the required 'Mail', 'Notes' and 'Contacts' tabs. JSCAccordion accordion = new JSCAccordion(); accordion.addTab("Mail", new JLabel()); accordion.addTab("Notes", new JLabel()); accordion.addTab("Contacts", new JLabel()); Although it is possible to add any component to an accordion's tab, we will add a JLabel as they are naturally transparent (non opaque) and will allow us to easily see the tab's background. Step 2: Adjust basic settings on the JSCAccordion In order for us to achieve the layout of the asp.net accordion, we will need to change a few basic settings on the JSCAccordion. We need to change the orientation of the accordion to render vertically. The tab height must be set to 31 pixels. We need to disable the rendering of the accordion's shadows. The asp.net accordion has a border comprising a black then white rectangle. //lays out the accordion's tabs to move vertically. accordion.setTabOrientation(TabOrientation.VERTICAL); //adjusts the height of the tabs to be 31 pixels accordion.setTabHeight(31); //stops the accordion rendering its shadows accordion.setDrawShadow(false); //the asp.net accordion is framed with a black then white border accordion.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.BLACK), BorderFactory.createLineBorder(Color.WHITE)) ); Step 3: Adjusting settings on the SteelAccordionUI In the previous step, we adjusted settings found on the JSCAccordion, however in order to achieve our final look we will need to adjust some settings on the Accordion's UI. The default UI for the Accordion is the SteelAccordionUI, and it is this UI that we will now manipulate. In order to bring us one step closer to the asp.net accordion we will now set all the paddings on the SteelAccordionUI to zero. //we know the default UI for the accordion is the SteelAccordionUI //so we cast the UI to a SteelAccordionUI. SteelAccordionUI steelAccordionUI = (SteelAccordionUI) accordion.getUI(); //we set all the paddings to zero steelAccordionUI.setHorizontalBackgroundPadding(0); steelAccordionUI.setVerticalBackgroundPadding(0); steelAccordionUI.setHorizontalTabPadding(0); steelAccordionUI.setVerticalTabPadding(0); steelAccordionUI.setTabPadding(0) Setting all the paddings to zero yields us the following result. Step 4: Replace the background painter All components from Java Swing Components make use of painters to achieve their look and feel. A painter is a simple class that contains logic to paint (draw) a component. The advantage of keeping this logic in a painter is two fold, firstly its easy to write new painters and secondly all painters are interchangeable. The net result of this is that it becomes very easy to change how a component looks. The framework upon which all components from Java Swing Components relies includes some simple pre-optimized painters. Instead of creating a new painter from scratch, I will simply make use of existing painters. Having a look at the asp.net accordion, we can see that we need to draw a gradient from white to grey horizontally to form the background. In order to achieve this we will make use of the GradientColorPainter. This painter paints a simple gradient starting with the startColor and ending with the endColor in a specified direction. //we will replace the current background painter with a new //GradientColorPainter. GradientColorPainter backgroundPainter = new GradientColorPainter(); //paint gradient horizontally backgroundPainter.setGradientDirection(GradientDirection.HORIZONTAL); //start with white backgroundPainter.setStartColor(new Color(255,255,255)); //end with grey backgroundPainter.setEndColor(new Color(214,213,228)); //apply the painter to the accordion accordion.setBackgroundPainter(backgroundPainter); The result of applying the new background painter renders the following result. Step 5: Create a new AccordionTabRenderer The last step in our skinning process it to code an entirely new AccordionTabRenderer. An AccordionTabRenderer is an interface used by the accordion to 'rubber stamp' a single component for each of the tabs. It works exactly the same as TableCellRenderers on the standard Jtable. The AccordionTabRenderer interface has a single method getTabComponent. public JComponent getTabComponent(GetTabComponentParameter parameters); The JComponent returned by this method will be used to draw the accordion's tabs. It is the responsibility of the AccordionTabRenderer to read the information from the parameters argument and return an appropriately configured component. The advantage of using a renderer is that it saves memory by only making use of a single component for all the tabs and also allows the developer to return any component they want. The only thing to remember is that the component returned is painted on the screen, and is not added to the accordion as a normal component. For all intensive purposes it is being used as a rubber stamp. The easiest component to return for this tutorial would be a label, as it has text and an image, which is exactly what we need. We will create a class called a DemoAccordionTabRenderer that implements AccordionTabRenderer and extends JLabel. Whenever the getTabComponent method is invoked, it will return itself. In the constructor of our class we will load the three images required by the renderer. These images are retrieved in the constructor and not during the getTabComponent method as this would result in io every time a tab is drawn. Unfortunately I did not have access to the icons used in the asp.net accordion so I will be making use of some great icons from the Tango icon library instead. private ImageIcon mailImage; private ImageIcon notesImage; private ImageIcon contactsImage; public DemoAccordionTabRenderer() { try { //images are loaded in the constructor to improve performance. //loading images in the getTabComponent method will result in the images //being loaded every time a tab is drawn. mailImage = new ImageIcon(ImageIO.read(Thread.currentThread() .getContextClassLoader().getResourceAsStream("mail.png"))); notesImage = new ImageIcon(ImageIO.read(Thread.currentThread(). getContextClassLoader().getResourceAsStream("notes.png"))); contactsImage = new ImageIcon(ImageIO.read(Thread.currentThread(). getContextClassLoader().getResourceAsStream("contacts.png"))); } catch (IOException e) { e.printStackTrace(); } } Now for the most important method, the getTabComponent method. In this method we will read the information from the parameters argument and setup our renderer. @Override public JComponent getTabComponent(GetTabComponentParameter parameters) { //read the tabText from the parameter setText(parameters.tabText); //set the text color to white setForeground(Color.WHITE); //use a slightly smaller bold font setFont(getFont().deriveFont(Font.BOLD, 11f)); //create a border to help align the label setBorder(BorderFactory.createEmptyBorder(0,8,0,0)); //set the gap between the icon and the text to 8 pixels setIconTextGap(8); //set the appropriate image based on the tabText. if ("Mail".equals(parameters.tabText)) { setIcon(mailImage); } if ("Notes".equals(parameters.tabText)) { setIcon(notesImage); } if ("Contacts".equals(parameters.tabText)) { setIcon(contactsImage); } //returns itself, which extends JLabel return this; } The final step required to achieve the look of the asp.net accordion is to draw the appropriate background for the AccordionTabRenderer. There are a number of ways this can be achieved, the easiest being to simply override the paintComponent method of the AccordionTabRenderer. The background of the asp.net accordion's tabs is complex linear gradient comprising of a number of colours. In order to achieve the same look, I will be making use of the LinearGradientColorPainter from the Java Swing Components framework. This painter paints a number of gradients together based on a supplied array of colours and floats. The workings of the painter is beyond the scope of this tutorial, however additional information can be found in the Sun (Oracle) api javadocs of LinearGradientPaint. In the paintComponent method, we will paint the tab's background using our LinearGradientColorPainter and then simply call super.paintComponent() to paint the standard JLabel on top of the background. private LinearGradientColorPainter painter = new LinearGradientColorPainter(); @Override protected void paintComponent(Graphics g) { //setup the painter fractions painter.setColorFractions(new float[]{ 0.0f, 0.49f, 0.5f, 0.51f, 0.8f, 1.0f}); //setup the painter colors painter.setColors(new Color[]{ new Color(167,163,189),new Color(143,138,169), new Color(131,126,160),new Color(116,110,146), new Color(119,113,148), new Color(138,133,164)}); //paint the background painter.paint((Graphics2D) g, new Rectangle(0, 0, getWidth(), getHeight())); //original color on g is stored and then later reset //this is to prevent clobbering of the Graphics object. Color originalColor = g.getColor(); //paints a simple line on the bottom of the tab g.setColor(new Color(87,86,111)); g.drawLine(0, getHeight()-1, getWidth(), getHeight()-1); g.setColor(originalColor); //draws the label on top of the background we just painted. super.paintComponent(g); } The last step is to assign our custom AccordionTabRenderer to the accordion. //apply the new TabRenderer to the accordion. accordion.setVerticalAccordionTabRenderer(new DemoAccordionTabRenderer()); The final result of all our hard work can be seen in the image below. Although it may have felt like a lot of code, seeing all the code together really shows how easy the skinning process is. JSCAccordion accordion = new JSCAccordion(); accordion.addTab("Mail", new JLabel()); accordion.addTab("Notes", new JLabel()); accordion.addTab("Contacts", new JLabel()); //lays out the accordion's tabs to move vertically. accordion.setTabOrientation(TabOrientation.VERTICAL); //adjusts the height of the tabs to be 31 pixels accordion.setTabHeight(31); //stops the accordion rendering its shadows accordion.setDrawShadow(false); //the asp.net accordion has a border comprising a black then white border accordion.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK),BorderFactory.createLineBorder(Color.WHITE))); //we know the default UI for the accordion is the SteelAccordionUI SteelAccordionUI steelAccordionUI = (SteelAccordionUI) accordion.getUI(); //we set all the paddings to zero steelAccordionUI.setHorizontalBackgroundPadding(0); steelAccordionUI.setVerticalBackgroundPadding(0); steelAccordionUI.setHorizontalTabPadding(0); steelAccordionUI.setVerticalTabPadding(0); steelAccordionUI.setTabPadding(0); //we will replace the current background painter with a new //GradientColorPainter. GradientColorPainter backgroundPainter = new GradientColorPainter(); //paint gradient horizontally backgroundPainter.setGradientDirection(GradientDirection.HORIZONTAL); //start with white backgroundPainter.setStartColor(new Color(255,255,255)); //end with grey backgroundPainter.setEndColor(new Color(214,213,228)); //apply the painter to the accordion accordion.setBackgroundPainter(backgroundPainter); //apply the new TabRenderer to the accordion. accordion.setVerticalAccordionTabRenderer(new DemoAccordionTabRenderer()); This brings us to the end of the tutorial, for those of you who are made it this far, the final demo jar and source code have been attached to this article. Enjoy
September 13, 2010
by Rhiannon Liebowitz
· 34,064 Views · 2 Likes
article thumbnail
Java: Overriding Getters and Setters Design
Why do we keep instance variables private? We don’t want other classes to depend on them. Moreover it gives the flexibility to change a variable’s type or implementation on a whim or an impulse. Why, then programmers automatically add or override getters and setters to their objects, exposing their private variables as if they were public? Accessor methods Accessors (also known as getters and setters) are methods that let you read and write the value of an instance variable of an object. public class AccessorExample { private String attribute; public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } } Why Accessors? There are actually many good reasons to consider using accessors rather than directly exposing fields of a class Getter and Setter make API more stable. For instance, consider a field public in a class which is accessed by other classes. Now, later on, you want to add any extra logic while getting and setting the variable. This will impact the existing client that uses the API. So any changes to this public field will require a change to each class that refers it. On the contrary, with accessor methods, one can easily add some logic like cache some data, lazily initialize it later. Moreover, one can fire a property changed event if the new value is different from the previous value. All this will be seamless to the class that gets the value using accessor method. Should I have Accessor Methods for all my fields? Fields can be declared public for package-private or private nested class. Exposing fields in these classes produces less visual clutter compare to accessor-method approach, both in the class definition and in the client code that uses it. If a class is package-private or is a private nested class, there is nothing inherently wrong with exposing its data fields—assuming they do an adequate job of describing the abstraction provided by the class. Such code is restricted to the package where the class is declared, while the client code is tied to class internal representation. We can change it without modifying any code outside that package. Moreover, in the case of a private nested class, the scope of the change is further restricted to the enclosing class. Another example of a design that uses public fields is JavaSpace entry objects. Ken Arnold described the process they went through to decide to make those fields public instead of private with get and set methods here Now this sometimes makes people uncomfortable because they've been told not to have public fields; that public fields are bad. And often, people interpret those things religiously. But we're not a very religious bunch. Rules have reasons. And the reason for the private data rule doesn't apply in this particular case. It is a rare exception to the rule. I also tell people not to put public fields in their objects, but exceptions exist. This is an exception to the rule, because it is simpler and safer to just say it is a field. We sat back and asked: Why is the rule thus? Does it apply? In this case it doesn't. Private fields + Public accessors == encapsulation Consider the example below public class A { public int a; } Usually, this is considered bad coding practice as it violates encapsulation. The alternate approach is public class A { private int a; public void setA(int a) { this.a =a; } public int getA() { return this.a; } } It is argued that this encapsulates the attribute. Now is this really encapsulation? The fact is, Getters/setters have nothing to do with encapsulation. Here the data isn't more hidden or encapsulated than it was in a public field. Other objects still have intimate knowledge of the internals of the class. Changes made to the class might ripple out and enforce changes in dependent classes. Getter and setter in this way are generally breaking encapsulation. A truly well-encapsulated class has no setters and preferably no getters either. Rather than asking a class for some data and then compute something with it, the class should be responsible for computing something with its data and then return the result. Consider an example below, public class Screens { private Map screens = new HashMap(); public Map getScreens() { return screens; } public void setScreens(Map screens) { this.screens = screens; } // remaining code here } If we need to get a particular screen, we do code like below, Screen s = (Screen)screens.get(screenId); There are things worth noticing here.... The client needs to get an Object from the Map and casting it to the right type. Moreover, the worst is that any client of the Map has the power to clear it which may not be the case we usually want. An alternative implementation of the same logic is: public class Screens { private Map screens = new HashMap(); public Screen getById(String id) { return (Screen) screens.get(id); } // remaining code here } Here the Map instance and the interface at the boundary (Map) are hidden. Getters and Setters are highly Overused Creating private fields and then using the IDE to automatically generate getters and setters for all these fields is almost as bad as using public fields. One reason for the overuse is that in an IDE it’s just now a matter of few clicks to create these accessors. The completely meaningless getter/setter code is at times longer than the real logic in a class and you will read these functions many times even if you don't want to. All fields should be kept private, but with setters only when they make sense which makes object Immutable. Adding an unnecessary getter reveals internal structure, which is an opportunity for increased coupling. To avoid this, every time before adding the accessor, we should analyse if we can encapsulate the behaviour instead. Let’s take another example, public class Money { private double amount; public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } //client Money pocketMoney = new Money(); pocketMoney.setAmount(15d); double amount = pocketMoney.getAmount(); // we know its double pocketMoney.setAmount(amount + 10d); } With the above logic, later on, if we assume that double is not a right type to use and should use BigDecimal instead, then the existing client that uses this class also breaks. Let’s restructure the above example, public class Money { private BigDecimal amount; public Money(String amount) { this.amount = new BigDecimal(amount); } public void add(Money toAdd) { amount = amount.add(toAdd.amount); } // client Money balance1 = new Money("10.0"); Money balance2 = new Money("6.0"); balance1.add(balance2); } Now instead of asking for a value, the class has a responsibility to increase its own value. With this approach, the change request for any other datatype in future requires no change in the client code. Here not only the data is encapsulated but also the data which is stored, or even the fact that it exists at all. Conclusions Use of accessors to restrict direct access to field variable is preferred over the use of public fields, however, making getters and setter for each and every field is overkill. It also depends on the situation though, sometimes you just want a dumb data object. Accessors should be added to a field where they're really required. A class should expose larger behaviour which happens to use its state, rather than a repository of state to be manipulated by other classes. More Reading http://c2.com/cgi/wiki?TellDontAsk http://c2.com/cgi/wiki?AccessorsAreEvil Effective Java - See more at http://muhammadkhojaye.blogspot.co.uk/2010/10/getter-setter-to-use-or-not-to-use.html
September 10, 2010
by Muhammad Ali Khojaye
· 98,194 Views · 1 Like
article thumbnail
Server Centric Java Frameworks: Performance Comparison
These days we are used to AJAX-intensive, sophisticated web frameworks. These frameworks provide us desktop style development into the Single Page Interface (SPI) paradigm. As you know there are two main types of frameworks, client-centric and server-centric. Each approach has pros and cons. Testing the performance of Java server-centric frameworks In the server-centric view, state is managed in server. In some way the client is a sophisticated terminal of the server because most of visual decisions are taken on the server and some kind of visual rendering is done on the server (HTML generation as markup or embedded in JavaScript or more higher level code sent to the client). The main advantage is that data and visual rendering are together in the same memory space, avoiding custom client-server bridges for data communication and synchronization, typical of the client-centric approach. This article only reviews Java server-centric frameworks. In SPI, the web page is partially changed; that is, some HTML parts can be removed and some new HTML markup can be inserted. This approach obviously saves tons of bandwidth and computer power because the complete page is not rebuilt and not fully sent to the client when some page change happens. A server-centric framework to be effective must send to the client ONLY the markup going to be changed or equivalent instructions in some form, when some AJAX event hits the server. This article reviews how much effective most of the SPI Java web frameworks are on partial changes provided by the server. We are not interested in events with no server communication, that is, events with no (possible) server control. How they are going to be measured We are going to measure the amount of code that is sent to client regarding to the visual change performed in client. For instance for a minor visual change (some new data) in a component we expect not much code from server, that is, the new markup needed as plain HTML, or embedded in JavaScript, or some high level instructions containing the new data to be visualized. Otherwise something seems wrong for instance the complete component or page zone is rebuilt, wasting bandwidth and client power (and maybe server power). Because we will use public demos, we are not going to get a definitive and fine grain benchmark. But you will see very strong differences between frameworks. The testing technique is very easy and everybody can do it with no special infrastructure, we just need FireFox and FireBug. In this test FireFox 3.6.8 and FireBug 1.5.4 are used. The FireBug Console when "Show XMLHttpRequests" is enabled logs any AJAX request showing the server response. The process is simple: The Console will be enabled before loading the page with the demo. Some clicks will drive some concrete component to the desired state. A final click will perform a small change in the component being analyzed. Then we will copy the output code of the AJAX request (HTML, XML, JavaScript ...) sent from server. The more code the less effective, more bandwidth waste and client processing is needed. We cannot measure the server power used because we need a deep knowledge of how the framework works in server, said this we can easily "suspect" the more code generated in server the more server power is wasted. Frameworks tested RichFaces, IceFaces, MyFaces/Trinidad, OpenFaces, PrimeFaces, Vaadin, ZK, ItsNat ADF Faces is not tested because there is no longer a public live demo. Because ADF Faces is based on Trinidad, Trinidad analysis could be extrapolated to ADF Faces (?). Update: NO, ADF Faces are very different to Trinidad. Note before starting Some frameworks seem to perform very well (regarding to this kind of test), that is, the ratio between visual change and amount of code is acceptable, but in some concrete cases (components) they "miserably" fail. This article tries to measure bad performant components. RichFaces Console must be enabled, configured and open as seen before. Open this tree demo (Ajax switch type) Expand "Baccara" node Expand "Grand Collection" Collapse "Grand Collection" As you can see the child nodes below "Grand Collection" has been removed or hidden (FireBug's DOM inspector says they were removed). Grand Collection As you can see too much HTML code has been sent for not much of a visual change. A more severe performance penalty: Open the Extended Data Table Demo On "State Name" paste "Alaska" (paste the name from clipboard), one row is shown Paste "Alabama" replacing "Alaska" (again paste from clipboard selecting Alaska first), again one different row is shown. The answer (HTML code) is too big to put here, 3.474 bytes, if you inspect the result you will see a complete rewrite of the table including header. IceFaces Open the Calendar demo Click on any different day Something like this is the last AJAX response: The answer (XML with metadata) is really big, 6.452 bytes, for a simple day change according to visual changes. MyFaces/Trinidad Open this Tree Table Demo Expand node_0_0 Expand node_0_0_0 (node node_0_0_0_ is shown) Collapse node_0_0_0 (hides/removes node_0_0_0_0) The last AJAX response is too big to put here, 18.765 bytes, because is a complete rewrite of the tree component. Update: a live demo of ADF Faces components is here and they seem to work fine as expected, that is, the ratio between code sent to the client and visual change is "correct" (in spite of HTML layout is very verbose the code sent to the client is almost the same to be displayed). OpenFaces Open the Tree Table demo Expand "Re: Scalling an image" Expand the new child "Re: Scalling an image" The last AJAX response is Re: Scaling an imageChristian SmileAug 3, 2007" data="{"structureMap":{"0":"1"}" scripts="" /> This code is very reasonable according to the change (a new child node/table row). Nevertheless some component miserably fails: Open the Data Table demo Select "AK" as "State", resulting one row. Replace with "AR", resulting again a new row The last AJAX result is too big, 38.209 bytes, because is a complete rewrite of the table including headers. PrimeFaces The AJAX answers of all tested examples were very reasonable. Said this, PrimeFaces lacks of a "filtered table component" or similar, the Achilles's heel of other JSF implementations. Update: As Cagatay Civici (one of the fathers of PrimeFaces) points out, PrimeFaces has a filltered table, this component works fine regarding to the ratio of visual change/code sent to client (try to do the same tests as prvious frameworks). Vaadin This is the first non-JSF framework. Open the Tree single selection demo Select "Dell OptiPlex GX240" Click "Apply" button (no change is needed) This is the last AJAX answer: for(;;);[{"changes":[["change",{"format": "uidl","pid": "PID190"},["12",{"id": "PID190","immediate":true,"caption": "Hardware Inventory","selectmode": "single","nullselect":true,"v":{"action":"","selected":["2"],"expand":[],"collapse":[],"newitem":[]},["node",{"caption": "Desktops","key": "1","expanded":true,"al":["1","2"]},["leaf",{"caption": "Dell OptiPlex GX240","key": "2","selected":true,"al":["1","2"]}],["leaf",{"caption": "Dell OptiPlex GX260","key": "3","al":["1","2"]}],["leaf",{"caption": "Dell OptiPlex GX280","key": "4","al":["1","2"]}]],["node",{"caption": "Monitors","key": "5","expanded":true,"al":["1","2"]},["leaf",{"caption": "Benq T190HD","key": "6","al":["1","2"]}],["leaf",{"caption": "Benq T220HD","key": "7","al":["1","2"]}],["leaf",{"caption": "Benq T240HD","key": "8","al":["1","2"]}]],["node",{"caption": "Laptops","key": "9","expanded":true,"al":["1","2"]},["leaf",{"caption": "IBM ThinkPad T40","key": "10","al":["1","2"]}],["leaf",{"caption": "IBM ThinkPad T43","key": "11","al":["1","2"]}],["leaf",{"caption": "IBM ThinkPad T60","key": "12","al":["1","2"]}]],["actions",{},["action",{"caption": "Add child item","key": "1"}],["action",{"caption": "Delete","key": "2"}]]]]], "meta" : {}, "resources" : {}, "locales":[]}] It seems not very much, but if you review the code the entire tree is being rebuilt again. ZK Another non-JSF framework. In the last versions ZK embrace an hybrid approach, most of the visual logic is in client as JavaScript components, the server sends to the client high level commands to the high level client library (Vaadin is not different). I have not found a component sending too much code from client (according to the visual change) in ZK's demo. ItsNat The last framework studied, again a non-JSF framework. In ItsNat the server keeps the same DOM state as in client and through DOM mutation events any change to the DOM in server automatically generates the JavaScript necessary to update the client accordingly. Open the demo Click on the handler of "Core" folder, the child nodes (11) are hidden. Result code of the AJAX event: itsNatDoc.addNodeCache(["cn_10","cn_14","0,1,1,0,0",["cn_15","cn_16"]]); itsNatDoc.setAttribute2("cn_14","src","img/tree/tree_node_collapse.gif"); itsNatDoc.setAttribute2(["cn_15","cn_17","1"],"src","img/tree/tree_folder_close.gif"); itsNatDoc.setAttribute2(["cn_16","cn_18","1,0",["cn_19"]],"style","display:none"); itsNatDoc.setAttribute2(["cn_19","cn_20","1"],"style","display:none"); itsNatDoc.setAttribute2(["cn_19","cn_21","2"],"style","display:none"); itsNatDoc.setAttribute2(["cn_19","cn_22","3"],"style","display:none"); itsNatDoc.setAttribute2(["cn_19","cn_23","4"],"style","display:none"); itsNatDoc.setAttribute2(["cn_19","cn_24","5"],"style","display:none"); itsNatDoc.setAttribute2(["cn_19","cn_25","6"],"style","display:none"); itsNatDoc.setAttribute2(["cn_19","cn_26","7"],"style","display:none"); itsNatDoc.setAttribute2(["cn_19","cn_27","8"],"style","display:none"); itsNatDoc.setAttribute2(["cn_19","cn_28","9"],"style","display:none"); itsNatDoc.setAttribute2(["cn_19","cn_29","10"],"style","display:none"); No surprises. Another test Open this Tree demo Click on "Insert Child". A new child node ("Actors") is inserted and a new log message is added. AJAX result code: itsNatDoc.removeAttribute2(["cn_15","cn_39","13"],"style"); itsNatDoc.setInnerHTML2("cn_39"," clickjavax.swing.event.TreeModelEvent 13802934 path [Grey's Anatomy, Actors] indices [ 4 ] children [ Actors ]"); var child = itsNatDoc.doc.createElement("li"); itsNatDoc.setAttribute(child,"style","padding:1px;"); itsNatDoc.appendChild2(["cn_17","cn_40","0,1,1,1",["cn_41","cn_42"]],child); itsNatDoc.setInnerHTML(child,"Label\n \n "); itsNatDoc.setTextData2(["cn_40","cn_43","4,0,2,0",["cn_44","cn_45"]],null,"Actors"); itsNatDoc.setAttribute2(["cn_45","cn_46","0"],"style","display:none"); itsNatDoc.setAttribute2(["cn_45","cn_47","1"],"src","img/tree/gear.gif"); Again no surprises. And the Winner is... There is no winner because only some components have been tested. Having said this, apparently the only JSF implementation free of serious performance penalties is PrimeFaces. In non-JSF frameworks using a very high level JS library like in Vaadin or ZK (PrimeFaces?) helps very much to reduce the network bandwidth (in spite of the fact that some components in Vaadin have serious performance problems), this cannot be said for client performance because in ItsNat the exact JS DOM code is sent to the client. On the other side a high level JS library complicates custom component development (beyond composition) because the server does not help very much but this is another story, and another article.
September 7, 2010
by Jose Maria Arranz
· 23,032 Views
article thumbnail
Storing passwords in Java web application
First of all, you should never store passwords. Then why the heck am I writing this post? Okay, Let me rephrase the first sentence – You should never store passwords as plain text anywhere in your application. of course, for the obvious reasons. If you store passwords as plain text, in a database or in a log file, then even Rajinikanth couldn’t save your application getting **cked.. I mean hacked. (Btw, Rajinikanth is the Chuck Norris of India, if you are not aware of him) Then what’s the right way to deal with the asterisks? You could use encryption. But if there’s a way to encrypt it, then there should be a way to decrypt it. So, encryption is also vulnerable to hacker’s attack. Isn’t there a better solution to this? It’s there and it's known as Password Hashing. How password hashing works? In hashing, you take a input string (in our case, a password), add a salt to the string, generate the hash value (using SHA-1 algorithm for example), and store the hash value in DB. For matching passwords while login, you do the same hashing process again and match the hash value instead of matching plain passwords and authenticate users. Hashing is different from encryption. Because, encryption is two way, means that you can always decrypt the encrypted text to get the original text. But Hashing is one way, you can never get the original text from the hash value. Thus it gives more security than encryption. To generate hash, you can make use of any hashing algorithms out there – MD5, SHA-1, etc. Before generating a hash, adding a salt to the password will give added security. Salt is nothing but a simple text that is known only to you/your application. It can be “zebra” or “I’mGod” or anything you wish. Below, I’m giving a Java example of how to do password hashing in an login module. Password hashing example in Java This is simple example containing two methods – signup() and login(). As their names suggest, signup would store username and password in DB and login would check the credentials entered by user against the DB. Let’s dive into the code. package com.sandbox; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; public class PasswordHashingDemo { Map DB = new HashMap(); public static final String SALT = "my-salt-text"; public static void main(String args[]) { PasswordHashingDemo demo = new PasswordHashingDemo(); demo.signup("john", "dummy123"); // login should succeed. if (demo.login("john", "dummy123")) System.out.println("user login successfull."); // login should fail because of wrong password. if (demo.login("john", "blahblah")) System.out.println("User login successfull."); else System.out.println("user login failed."); } public void signup(String username, String password) { String saltedPassword = SALT + password; String hashedPassword = generateHash(saltedPassword); DB.put(username, hashedPassword); } public Boolean login(String username, String password) { Boolean isAuthenticated = false; // remember to use the same SALT value use used while storing password // for the first time. String saltedPassword = SALT + password; String hashedPassword = generateHash(saltedPassword); String storedPasswordHash = DB.get(username); if(hashedPassword.equals(storedPasswordHash)){ isAuthenticated = true; }else{ isAuthenticated = false; } return isAuthenticated; } public static String generateHash(String input) { StringBuilder hash = new StringBuilder(); try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] hashedBytes = sha.digest(input.getBytes()); char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; for (int idx = 0; idx < hashedBytes.length; ++idx) { byte b = hashedBytes[idx]; hash.append(digits[(b & 0xf0) >> 4]); hash.append(digits[b & 0x0f]); } } catch (NoSuchAlgorithmException e) { // handle error here. } return hash.toString(); } } So, that’s it. I guess the above code is self explanatory. Do let me know in case you have any doubts. From http://veerasundar.com/blog/2010/09/storing-passwords-in-java-web-application/
September 7, 2010
by Veera Sundar
· 81,696 Views · 3 Likes
article thumbnail
ExtJS, Spring MVC 3 and Hibernate 3.5: CRUD DataGrid Example
this tutorial will walk through how to implement a crud (create, read, update, delete) datagrid using extjs, spring mvc 3 and hibernate 3.5. what do we usually want to do with data? create (insert) read / retrieve (select) update (update) delete / destroy (delete) until extjs 3.0 we only could read data using a datagrid. if you wanted to update, insert or delete, you had to do some code to make these actions work. now extjs 3.0 (and newest versions) introduces the ext.data.writer, and you do not need all that work to have a crud grid. so… what do i need to add in my code to make all these things working together? in this example, i’m going to use json as data format exchange between the browser and the server. extjs code first, you need an ext.data.jsonwriter: // the new datawriter component. var writer = new ext.data.jsonwriter({ encode: true, writeallfields: true }); where writeallfields identifies that we want to write all the fields from the record to the database. if you have a fancy orm then maybe you can set this to false. in this example, i’m using hibernate, and we have saveorupate method – in this case, we need all fields to updated the object in database, so we have to ser writeallfields to true. this is my record type declaration: var contact = ext.data.record.create([ {name: 'id'}, { name: 'name', type: 'string' }, { name: 'phone', type: 'string' }, { name: 'email', type: 'string' }]); now you need to setup a proxy like this one: var proxy = new ext.data.httpproxy({ api: { read : 'contact/view.action', create : 'contact/create.action', update: 'contact/update.action', destroy: 'contact/delete.action' } }); fyi, this is how my reader looks like: var reader = new ext.data.jsonreader({ totalproperty: 'total', successproperty: 'success', idproperty: 'id', root: 'data', messageproperty: 'message' // <-- new "messageproperty" meta-data }, contact); the writer and the proxy (and the reader) can be hooked to the store like this: // typical store collecting the proxy, reader and writer together. var store = new ext.data.store({ id: 'user', proxy: proxy, reader: reader, writer: writer, // <-- plug a datawriter into the store just as you would a reader autosave: false // <-- false would delay executing create, update, //destroy requests until specifically told to do so with some [save] buton. }); where autosave identifies if you want the data in automatically saving mode (you do not need a save button, the app will send the actions automatically to the server). in this case, i implemented a save button, so every record with new or updated value will have a red mark on the cell left up corner). when the user alters a value in the grid, then a “save” event occurs (if autosave is true). upon the “save” event the grid determines which cells has been altered. when we have an altered cell, then the corresponding record is sent to the server with the ‘root’ from the reader around it. e.g if we read with root “data”, then we send back with root “data”. we can have several records being sent at once. when updating to the server (e.g multiple edits). and to make you life even easier, let’s use the roweditor plugin, so you can easily edit or add new records. all you have to do is to add the css and js files in your page: add the plugin on you grid declaration: var editor = new ext.ux.grid.roweditor({ savetext: 'update' }); // create grid var grid = new ext.grid.gridpanel({ store: store, columns: [ {header: "name", width: 170, sortable: true, dataindex: 'name', editor: { xtype: 'textfield', allowblank: false }, {header: "phone #", width: 150, sortable: true, dataindex: 'phone', editor: { xtype: 'textfield', allowblank: false }, {header: "email", width: 150, sortable: true, dataindex: 'email', editor: { xtype: 'textfield', allowblank: false })} ], plugins: [editor], title: 'my contacts', height: 300, width:610, frame:true, tbar: [{ iconcls: 'icon-user-add', text: 'add contact', handler: function(){ var e = new contact({ name: 'new guy', phone: '(000) 000-0000', email: '[email protected]' }); editor.stopediting(); store.insert(0, e); grid.getview().refresh(); grid.getselectionmodel().selectrow(0); editor.startediting(0); } },{ iconcls: 'icon-user-delete', text: 'remove contact', handler: function(){ editor.stopediting(); var s = grid.getselectionmodel().getselections(); for(var i = 0, r; r = s[i]; i++){ store.remove(r); } } },{ iconcls: 'icon-user-save', text: 'save all modifications', handler: function(){ store.save(); } }] }); java code finally, you need some server side code. controller: package com.loiane.web; @controller public class contactcontroller { private contactservice contactservice; @requestmapping(value="/contact/view.action") public @responsebody map view() throws exception { try{ list contacts = contactservice.getcontactlist(); return getmap(contacts); } catch (exception e) { return getmodelmaperror("error retrieving contacts from database."); } } @requestmapping(value="/contact/create.action") public @responsebody map create(@requestparam object data) throws exception { try{ list contacts = contactservice.create(data); return getmap(contacts); } catch (exception e) { return getmodelmaperror("error trying to create contact."); } } @requestmapping(value="/contact/update.action") public @responsebody map update(@requestparam object data) throws exception { try{ list contacts = contactservice.update(data); return getmap(contacts); } catch (exception e) { return getmodelmaperror("error trying to update contact."); } } @requestmapping(value="/contact/delete.action") public @responsebody map delete(@requestparam object data) throws exception { try{ contactservice.delete(data); map modelmap = new hashmap(3); modelmap.put("success", true); return modelmap; } catch (exception e) { return getmodelmaperror("error trying to delete contact."); } } private map getmap(list contacts){ map modelmap = new hashmap(3); modelmap.put("total", contacts.size()); modelmap.put("data", contacts); modelmap.put("success", true); return modelmap; } private map getmodelmaperror(string msg){ map modelmap = new hashmap(2); modelmap.put("message", msg); modelmap.put("success", false); return modelmap; } @autowired public void setcontactservice(contactservice contactservice) { this.contactservice = contactservice; } } some observations: in spring 3, we can get the objects from requests directly in the method parameters using @requestparam. i don’t know why, but it did not work with extjs. i had to leave as an object and to the json-object parser myself. that is why i’m using a util class – to parser the object from request into my pojo class. if you know how i can replace object parameter from controller methods, please, leave a comment, because i’d really like to know that! service class: package com.loiane.service; @service public class contactservice { private contactdao contactdao; private util util; @transactional(readonly=true) public list getcontactlist(){ return contactdao.getcontacts(); } @transactional public list create(object data){ list newcontacts = new arraylist(); list list = util.getcontactsfromrequest(data); for (contact contact : list){ newcontacts.add(contactdao.savecontact(contact)); } return newcontacts; } @transactional public list update(object data){ list returncontacts = new arraylist(); list updatedcontacts = util.getcontactsfromrequest(data); for (contact contact : updatedcontacts){ returncontacts.add(contactdao.savecontact(contact)); } return returncontacts; } @transactional public void delete(object data){ //it is an array - have to cast to array object if (data.tostring().indexof('[') > -1){ list deletecontacts = util.getlistidfromjson(data); for (integer id : deletecontacts){ contactdao.deletecontact(id); } } else { //it is only one object - cast to object/bean integer id = integer.parseint(data.tostring()); contactdao.deletecontact(id); } } @autowired public void setcontactdao(contactdao contactdao) { this.contactdao = contactdao; } @autowired public void setutil(util util) { this.util = util; } } contact class – pojo: package com.loiane.model; @jsonautodetect @entity @table(name="contact") public class contact { private int id; private string name; private string phone; private string email; @id @generatedvalue @column(name="contact_id") public int getid() { return id; } public void setid(int id) { this.id = id; } @column(name="contact_name", nullable=false) public string getname() { return name; } public void setname(string name) { this.name = name; } @column(name="contact_phone", nullable=false) public string getphone() { return phone; } public void setphone(string phone) { this.phone = phone; } @column(name="contact_email", nullable=false) public string getemail() { return email; } public void setemail(string email) { this.email = email; } } dao class: package com.loiane.dao; @repository public class contactdao implements icontactdao{ private hibernatetemplate hibernatetemplate; @autowired public void setsessionfactory(sessionfactory sessionfactory) { hibernatetemplate = new hibernatetemplate(sessionfactory); } @suppresswarnings("unchecked") @override public list getcontacts() { return hibernatetemplate.find("from contact"); } @override public void deletecontact(int id){ object record = hibernatetemplate.load(contact.class, id); hibernatetemplate.delete(record); } @override public contact savecontact(contact contact){ hibernatetemplate.saveorupdate(contact); return contact; } } util class: package com.loiane.util; @component public class util { public list getcontactsfromrequest(object data){ list list; //it is an array - have to cast to array object if (data.tostring().indexof('[') > -1){ list = getlistcontactsfromjson(data); } else { //it is only one object - cast to object/bean contact contact = getcontactfromjson(data); list = new arraylist(); list.add(contact); } return list; } private contact getcontactfromjson(object data){ jsonobject jsonobject = jsonobject.fromobject(data); contact newcontact = (contact) jsonobject.tobean(jsonobject, contact.class); return newcontact; } ) private list getlistcontactsfromjson(object data){ jsonarray jsonarray = jsonarray.fromobject(data); list newcontacts = (list) jsonarray.tocollection(jsonarray,contact.class); return newcontacts; } public list getlistidfromjson(object data){ jsonarray jsonarray = jsonarray.fromobject(data); list idcontacts = (list) jsonarray.tocollection(jsonarray,integer.class); return idcontacts; } } if you want to see all the code (complete project will all the necessary files to run this app), download it from my github repository: http://github.com/loiane/extjs-crud-grid-spring-hibernate this was a requested post. i’ve got a lot of comments from my previous crud grid example and some emails. i made some adjustments to current code, but the idea is still the same. i hope i was able answer all the questions. happy coding! from http://loianegroner.com/2010/09/extjs-spring-mvc-3-and-hibernate-3-5-crud-datagrid-example/
September 3, 2010
by Loiane Groner
· 100,928 Views · 1 Like
article thumbnail
Clojure: Mocking
An introduction to clojure.test is easy, but it doesn't take long before you feel like you need a mocking framework. As far as I know, you have 3 options. Take a look at Midje. I haven't gone down this path, but it looks like the most mature option if you're looking for a sophisticated solution. Go simple. Let's take an example where you want to call a function that computes a value and sends a response to a gateway. Your first implementation looks like the code below. (destructuring explained) (defn withdraw [& {:keys [balance withdrawal account-number]}] (gateway/process {:balance (- balance withdrawal) :withdrawal withdrawal :account-number account-number})) No, it's not pure. That's not the point. Let's pretend that this impure function is the right design and focus on how we would test it. You can change the code a bit and pass in the gateway/process function as an argument. Once you've changed how the code works you can test it by passing identity as the function argument in your tests. The full example is below. (ns gateway) (defn process [m] (println m)) (ns controller (:use clojure.test)) (defn withdraw [f & {:keys [balance withdrawal account-number]}] (f {:balance (- balance withdrawal) :withdrawal withdrawal :account-number account-number})) (withdraw gateway/process :balance 100 :withdrawal 22 :account-number 4) ;; => {:balance 78, :withdrawal 22, :account-number 4} (deftest withdraw-test (is (= {:balance 78, :withdrawal 22, :account-number 4} (withdraw identity :balance 100 :withdrawal 22 :account-number 4)))) (run-all-tests #"controller") If you run the previous example you will see the println output and the clojure.test output, verifying that our code is working as we expected. This simple solution of passing in your side effect function and using identity in your tests can often obviate any need for a mock. Solution 2 works well, but has the limitations that only one side-effecty function can be passed in and it's result must be used as the return value. Let's extend our example and say that we want to log a message if the withdrawal would cause insufficient funds. (Our gateway/process and log/write functions will simply println since this is only an example, but in production code their behavior would differ and both would be required) (ns gateway) (defn process [m] (println "gateway: " m)) (ns log) (defn write [m] (println "log: " m)) (ns controller (:use clojure.test)) (defn withdraw [& {:keys [balance withdrawal account-number]}] (let [new-balance (- balance withdrawal)] (if (> 0 new-balance) (log/write "insufficient funds") (gateway/process {:balance new-balance :withdrawal withdrawal :account-number account-number})))) (withdraw :balance 100 :withdrawal 22 :account-number 4) ;; => gateway: {:balance 78, :withdrawal 22, :account-number 4} (withdraw :balance 100 :withdrawal 220 :account-number 4) ;; => log: insufficient funds Our new withdraw implementation calls two functions that have side effects. We could pass in both functions, but that solution doesn't seem to scale very well as the number of passed functions grows. Also, passing in multiple functions tends to clutter the signature and make it hard to remember what is the valid order for the arguments. Finally, if we need withdraw to always return a map showing the balance and withdrawal amount, there would be no easy solution for verifying the string sent to log/write. Given our implementation of withdraw, writing a test that verifies that gateway/process and log/write are called correctly looks like a job for a mock. However, thanks to Clojure's binding function, it's very easy to redefine both of those functions to capture values that can later be tested. The following code rebinds both gateway/process and log/write to partial functions that capture whatever is passed to them in an atom that can easily be verified directly in the test. (ns gateway) (defn process [m] (println "gateway: " m)) (ns log) (defn write [m] (println "log: " m)) (ns controller (:use clojure.test)) (defn withdraw [& {:keys [balance withdrawal account-number]}] (let [new-balance (- balance withdrawal)] (if (> 0 new-balance) (log/write "insufficient funds") (gateway/process {:balance new-balance :withdrawal withdrawal :account-number account-number})))) (deftest withdraw-test (let [result (atom nil)] (binding [gateway/process (partial reset! result)] (withdraw :balance 100 :withdrawal 22 :account-number 4) (is (= {:balance 78, :withdrawal 22, :account-number 4} @result))))) (deftest withdraw-test (let [result (atom nil)] (binding [log/write (partial reset! result)] (withdraw :balance 100 :withdrawal 220 :account-number 4) (is (= "insufficient funds" @result))))) (run-all-tests #"controller") In general I use option 2 when I can get away with it, and option 3 where necessary. Option 3 adds enough additional code that I'd probably look into Midje quickly if I found myself writing a more than a few tests that way. However, I generally go out of my way to design pure functions, and I don't find myself needing either of these techniques very often. From http://blog.jayfields.com/2010/09/clojure-mocking.html
September 2, 2010
by Jay Fields
· 6,866 Views
article thumbnail
5 Important Points about Java Generics
Generics allows a type or method to operate on objects of various types while providing compile-time type safety, making Java a fully statically typed language.
August 31, 2010
by Shekhar Gulati
· 159,437 Views · 11 Likes
article thumbnail
How to Migrate from Ant to Maven: Project Structure
I’ve seen my fair share of projects migrating from Ant to Maven, and, for a complex project, this migration path can take some time. You have to worry about dependency management, project structure, and retraining an existing team to use Maven and understand the core concepts behind the tool. When you make the shift, you are often affecting development infrastructure for an existing project, and you need to take into account development environments as well as developer’s ideas about how code should be organized and stored in source control. In this post, I’m going to discuss a common pattern I’ve seen in Ant to Maven migrations: how to migrate the monolithic project. A Common Pattern: The Monolithic Project Ant projects which have evolved over many years often lack modular structure. While it is certainly possible to create the equivalent of a multi-module Maven project in Ant, the usual progression in an Ant project is to store all of your source in a single tree and use extra targets to selectively compile different packages. This approach is shown in the following figure. In the most extreme cases, there is a single project which contains an array of modules. Maybe you have an entire enterprise system all stored in a single project alongside a complex Ant build.xml file which contains a collection of tasks for each component. A monolithic Ant project usually produces a series of artifacts: a JAR containing some API for clients, a server-side web application, a utility library, etc. Developers have usually grown so accustomed to this approach that the idea of splitting up a complex system into a series of related submodules can see daunting. Moving to Maven: Do we need all these projects? One of the first questions I get in a Maven migration from Ant is whether it is really necessary to modularize a project. “Do we really need to create all these projects for Maven?” (Short answer: Yes, there is no avoiding this.) This is usually accompanied by a concern that Maven limits each project to producing a single artifact. These are two core assumptions of Maven: your projects will be modularized and each project should produce a single build artifact. Now, while these are core assumptions, there are ways around them, and I’ve even seen people go to extreme lengths in an attempt to preserve this single, monolithic project. You can create an elaborate set of profiles to modify the build depending on the context in which it is run, and you can attach extra build artifacts to a project using assemblies. Even though Maven makes assumptions about code layout and project structure, it can do just about anything, and in this case, it can be used to approximate the monolithic, combined Ant project. If you do this, if you try to trick Maven the first thing you’ll notice is that your monolithic project’s POM is going to be somewhat unwieldy: it is going to be massive. Instead of a simple, declarative picture of a project, you are going to have a POM that contains multiple assembly definitions. Each assembly definition is going to have to explicitly define the structure of your build artifacts and you are going to find yourself venturing into includes and excludes patterns for things like the Maven Compiler plugin. In other words, you are going to have to expend a huge amount of effort to bend Maven to your assumptions. If you do this, you really won’t be using “Maven”. You’ll be using your own interpretation of Maven, and once you go down this road, you are going to start having problems using standard tools designed for Maven. In short, don’t do this. Don’t try to bypass Maven’s approach to modularity with assemblies and profiles. If you do, you are going to find yourself “swimming upstream”, and your first hint is going to be the size and complexity of your POM files. I’ve certainly created some complex POMs in my time, but I only need to do this for projects that really require customization because they are doing something unique (see the POMs for the Maven book builds, they are large and extremely customized). If you are creating web applications, EARs, and simple Java applications you shouldn’t have large POMs. If you do, it is probably a sign that you have ventured too far “off the map”. While you might be building your project with “Maven”, there is likely something wrong with your approach. If you find yourself constantly challenging an assumption as basic as project modularity, then you need to either rethink using Maven entirely or rethink your project structure. Adopting Maven Means Adopting Modular Structure If you are going to adopt Maven, you must adopt a modular project structure. If you don’t you will be fighting an uphill battle with Maven and the tools that have been designed to work with it. You will be fighting not only with Maven, but you’ll be doing constant battle with your IDE and your repository manager. If you are moving from Ant to Maven, do you yourself a favor. Adopt a modular project structure. Don’t approach Maven as a “toolbox” like Ant with tasks and targets. Approach Maven as a framework with expectations and assumptions. If you do this, you’ll have a much easier time adopting the tool. From http://www.sonatype.com/people/2010/08/how-to-migrate-from-ant-to-maven-project-structure/
August 25, 2010
by Tim O'brien
· 27,633 Views · 1 Like
article thumbnail
Infinite scroll : Loading Content While Scrolling, Using Java and JQuery
Have you seen the infinite scrolling of content in some web pages? For example, in DZone.com when you scroll the page to the bottom, new links will be loaded automatically and it’ll give you the illusion that the page scrolls infinitely. Another good example is that Bing’s Image Search. The technique is not hard to implement. With the use of a single servlet and JSP, we can implement a basic functionality with infinite scroll. Before dive into code details, have a look at this demo to get a feel of it: Infinite Scroll Demo To implement this, we need a servlet which will serve the dynamic content and a JSP file which will have the UI and act as a client to receive the content. Below are the code for these two files. I’m leaving other common stuffs (like web.xml entry etc) to you. Code for Servlet: package com.vraa.demo; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class InfinitContentServlet extends HttpServlet { private static Integer counter = 1; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try { String resp = ""; for (int i = 1; i <= 10; i++) { resp += "" + counter++ + " This is the dynamic content served freshly from server"; } out.write(resp); } finally { out.close(); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } } Code for JSP file: Demo page: Infinite Scroll with Java and JQuery This page is a demo for loading new content while scrolling. Credits: Veera Sundar | veerasundar.com | @vraa 1Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. 2Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. 3Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. 4Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. 5Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. How it works? The secret behind this is the scrolltop property. By checking this value we can determine whether the scrollbar has reached near to the bottom or not. If it reached, send an AJAX request to server to get more content and append it to the page. Look at the following two lines which does this: $contentLoadTriggered = false; $("#content-box").scroll(function(){ if($("#content-box").scrollTop() >= ($("#content-wrapper").height() - $("#content-box").height()) && $contentLoadTriggered == false) { $contentLoadTriggered = true; $.get("infinitContentServlet", function(data){ $("#content-wrapper").append(data); $contentLoadTriggered = false; }); } }); From http://veerasundar.com/blog/2010/07/infinite-scroll-loading-content-while-scrolling-using-java-and-jquery/
August 12, 2010
by Veera Sundar
· 38,096 Views
  • Previous
  • ...
  • 561
  • 562
  • 563
  • 564
  • 565
  • 566
  • 567
  • 568
  • 569
  • 570
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×