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 Languages Topics

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,905 Views
article thumbnail
Practical PHP Patterns: Value Object
Today comes a pattern that I have wanted to write about for a long time: the Value Object. A Value Object is conceptually a small simple object, but a fundamental piece of Domain-Driven Design and of object-oriented programming. Identity vs. equality The definition of a Value Object, that establishes if we can apply the pattern to a class, is the following: the equality of two Value Objects is not based on identity (them being the same object, checked with the operator ===), but on their content. An example of PHP built-in Value Object is the ArrayObject class, which is the object-oriented equivalent of an array. Two ArrayObjects are equal if they contain the same elements, not if they are the same identical object. Even if they were created in different places, as long as the contained scalars are equals (==) and the contained objects are identical (===), they are effectively "identical" for every purpose. In PHP, the == operator is used for equality testing, while the === for identity testing. Also custom equals() method can be created. Basically, the == operator checks that two scalars, like strings or integers, have the same value. When used on objects, it checks that their corresponding fields are equals. The === operator, when used between objects, returns true only if the two objects are actually the same (they refer to the same memory location and one reflects the changes made to another.) Scalars, as objects Other languages provide Value Objects also for basic values like strings and integers, while PHP limits itself to the ArrayObject and Date classes. Another example of a typical Value Object implementation is the Money class. Continuing with the Date example, we usually don't care if two Date objects are the same, but we care instead to know if they had the exact identical timestamp in their internals (which means they are effectively the same date.) On the contrary, if two Users are the same, they should be the same object (in the memory graph) which resides in a single memory location, or they should have an identity field (in databases) that allow us to distinguish univocally between two users. If you and I have the same name and address in the database, we are still not the same User. But if two Dates have the same day, month, and year, they are the same Date for us. This second kind of objects, whose equality is not based on an Identity Field, are Value Objects. For simplicity, ORMs automatically enforce the identity rules via an Identity Map. When you retrieve your own User object via Doctrine 2, you can be sure that only one instance would be created and handed to you, even if you ask for it a thousand times (obviously other instances would be created for different User objects, like mine or the Pope's one). In Domain-Driven Design The Value Object pattern is also a building block of Domain-Driven Design. In practice, it represents an object which is similar to a primitive type, but should be modelled after the domain's business rules. A Date cannot really be a primitive type: Date objects like Feb 31, 2010 or 2010-67-89 cannot exists and their creation should never be allowed. This is a reason why we may use objects even if we already have basic, old procedural types. Another advantage of objects if that they can add (or prohibit) behavior: we can add traits like immutability, or type hinting. There's no reason to modelling a string as a class in PHP, due to the lack of support from the str*() functions; however, if those strings are all Addresses or Phonenumbers... In fact, Value Objects are almost always immutable (not ArrayObject's case) so that they can be shared between other domain objects. The immutability solves the issues named aliasing bugs: if an User changes its date of birth, whose object is shared between other two users, they will reflect the change incorrectly. But if the Date is a Value Object, it is immutable and the User cannot simply change a field. Mutating a Value Object means creating a new one, often with a Factory Method on the Value Object itself, and place it in the reference field that pointed to the old object. In a sense, if transitions are required, they can be modelled with a mechanism similar to the State pattern, where the Value Object returns other instances of its class that can be substituted to the original reference. Garbage collecting will take care of abandoned Value Objects. To a certain extent, we can say that Value Objects are "passed by value" even if the object reference is passed by handler/reference/pointer like for everything else. No method can write over a Value Object you pass to it. The issues of using Value Objects extensively is that there is no support from database mapping tools yet. Maybe we will be able to hack some support with the custom types of Doctrine 2, which comprehend the native Date class, but real support (based on the JPA metadata schema) would come in further releases. Examples An example of Value object is presented here, and my choice fell onto the Paint class, an example treated in the Domain-Driven Design book in discussions about other patterns. On this Value Object we have little but useful behavior (methods such as equals(), and mix()), and of course immutability. red = $red; $this->green = $green; $this->blue = $blue; } /** * Getters expose the field of the Value Object we want to leave * accessible (often all). * There are no setters: once built, the Value Object is immutable. * @return integer */ public function getRed() { return $red; } public function getGreen() { return $green; } public function getBlue() { return $blue; } /** * Actually, confronting two objects with == would suffice. * @return boolean true if the two Paints are equal */ public function equals($object) { return get_class($object) == 'Paint' and $this->red == $object->red and $this->green == $object->green and $this->blue == $object->blue; } /** * Every kind of algorithm, just to expanding this example. * Since the objects are immutable, the resulting Paint is a brand * new object, which is returned. * @return Paint */ public function mix(Paint $another) { return new Paint($this->integerAverage($this->red, $another->red), $this->integerAverage($this->green, $another->green), $this->integerAverage($this->blue, $another->blue)); } private function integerAverage($a, $b) { return (int) (($a + $b) / 2); } } // client code $blue = new Paint(0, 0, 255); $red = new Paint(255, 0, 0); var_dump($blue->equals($red)); var_dump($violet = $blue->mix($red));
September 29, 2010
by Giorgio Sironi
· 24,368 Views · 1 Like
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,400 Views · 2 Likes
article thumbnail
Practical PHP Patterns: Registry
Fowler's definition for the Registry pattern is this one: A well known object that other ones can use to find related objects or service. This vague definition leaves open the possibility of abuse. Implementation The idea of a Registry is simple: providing a dynamic possibility for discovering collaborator objects, so that we not hardcode static calls to global objects like Singletons in each of them. In the testing environment, we can fill the Registry with mocks. However, the problem is that then we hardcode static calls to the Registry, which is an effective sinkhole for dependencies in the case of a general purpose implementation. You can't limit which objects of a Registry are accessed by a client, so depending on the Registry may mean depending on each stored component. In this scenario, the Registry becomes a Service Locator, the poor man's version of Dependency Injection. Fixing it My suggestion before implementing this pattern is thinking about how many of the registered objects would the ordinary client object actually need; maybe you can inject them directly. A constraint I'd like to set for Registry implementations is that all the contained objects should be of the same type (or of a Layer Supertype). With this limitation, incarnations of the Registry become very useful as they can be injected and passed around as a virtual collection of object, even if they do not exist/currently are in persistence/are not all in memory at the same time. If this reminds you of the Repository, you're right; the Repository pattern is a specialization of the Registry one, with this limitation written with blood in its contract in a night of full moon. This is what a Registry is supposed to be: not an hidden blackboard like Zend_Registry where you can practice accumulate and fire, and setup time-ticking bombs that will explode later. Here's an example from our test suite, which used Zend_Registry to set up the locale. One day, uncommenting a test would make another one fail (it used Zend_Registry, and the uncommented one messed with some keys). Fixing it takes some minutes (but it should have taken seconds). Scale that to a test suite with one thousands tests and you can easily destroy your tests isolation. Shortly, one test would pass when executed alone, but explode when the whole test suite (which maybe takes 15 minutes to run) because a previous test, whose identity you do not know, modified some global state. Good luck fixing that and grepping for 'Zend_Registry::'. Instead, a Registry can be a first-class citizen, an object that can be injected, by itself or hidden behind an interface of a composer, into any client object that sincerely needs access to the whole encapsulated collection. Why you now feel a generic Registry could be handy Lifecycle problems can create the need for a generic Registry. How do you access an object A from a client object B if A do not exist when B is created? Use a Registry. Of course, this solution does not go a long way: you're never sure that A would be created in time, and you should revise your design to discover why a long-lived object should hold a reference to a short-lived one. In fact, higher-level or injected Factories ara a similar, but more powerful solution. If B needs A, and A has the same lifecycle, simply inject it via a request-wide Factory. If B and A have a shorter lifecycle than the one of the request (for example they are view helpers that may not be used at all in certain requests, so they are instantiated only when needed in the presentation layer), provide a Factory that craates both and inject the Factory in the right scope. However, never inject a generic registry: it is a false solution. The Registry becomes a Service Locator, which is depended on by every piece of your application, and depends again on every piece of it. This is a benignuos form of what I call "hiding dependencies under the carpet", which can be solved by injecting the direct dependency instead of a provider. Examples Our code sample is the infamous Zend_Registry component from Zend Framework 1. It is a Singleton, and when testing controllers it is a typical resource that the testing harness must remember to reset between each test. My comments are in italic. offsetExists($index)) { require_once 'Zend/Exception.php'; throw new Zend_Exception("No entry is registered for key '$index'"); } return $instance->offsetGet($index); } /** * setter method, basically same as offsetSet(). * * This method can be called from an object of type Zend_Registry, or it * can be called statically. In the latter case, it uses the default * static instance stored in the class. * * @param string $index The location in the ArrayObject in which to store * the value. * @param mixed $value The object to store in the ArrayObject. * @return void */ public static function set($index, $value) { $instance = self::getInstance(); $instance->offsetSet($index, $value); } /** * Returns TRUE if the $index is a named value in the registry, * or FALSE if $index was not found in the registry. * * @param string $index * @return boolean */ public static function isRegistered($index) { if (self::$_registry === null) { return false; } return self::$_registry->offsetExists($index); } /** * Constructs a parent ArrayObject with default * ARRAY_AS_PROPS to allow acces as an object * * @param array $array data array * @param integer $flags ArrayObject flags */ public function __construct($array = array(), $flags = parent::ARRAY_AS_PROPS) { parent::__construct($array, $flags); } }
September 22, 2010
by Giorgio Sironi
· 7,997 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,757 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,833 Views
article thumbnail
How to Serialize Java.util.Date with Jackson JSON Processor / Spring 3.0
Learn how to serialize a java.util.Date object with Jackson JSON Processor – Spring MVC 3.
September 20, 2010
by Loiane Groner
· 277,811 Views · 8 Likes
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,159 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,555 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,234 Views
article thumbnail
Practical PHP Patterns: Mapper
The Mapper pattern is used to establish a communication between two subsystems, when the integration must be managed in a way to avoid creating mutual dependencies or even one-way dependencies between them. The classic example of this pattern is its specialization for data storage, the Data Mapper, which as you can see from the relative article translates data between an object graph and an external storage such as a relational database (most advanced ORMs like Doctrine 2 are Data Mappers), but also a document-oriented database or any other kind of persistent storage. The Mapper component is naturally dependent on both the subsystems it connect, but they are not aware at all of its existence. No additional hard dependencies are introduced from the subsystems towards other components. Following our example, Doctrine 2 borrows the Hibernate's approach to mapping: it parses annotations or unobtrusive XML files for specifying metadata on the object-oriented side, and uses a wrapped version of PDO (with ordinary database drivers) on the database side. Neither the database tables are aware of the existence of an object model, nor the objects are ideally aware of them being persisted into a tabular form. Client code The main issue in wiriting a Mapper, in all its specializations, is how to invoke it, since the connected subsystems do not know anything about it, nor they can instance it without a dependency being created. The most common solution is to use an higher-level layer that drives the three components at the same time. In PHP applications, this is usually a controller layer, which by default starts a transaction and commit it following the lifecycle of the served HTTP request. The domain objects are then passed to the Data Mapper's Facade or they depend on a set of Repository interfaces implemented with the aid of the Data Mapper. Another possible solution is to implement an Observer pattern, so that interfaces or abstractions in the two subsystems break the dependency. The Mapper implementation classes would realize these interfaces, but there is a trade-off produced by the introduction of interfaces in the subsystems. Mapper vs. Gateway In comparison, a Gateway is simpler to implement than a Mapper, although your mileage may vary depending on the domain and your requirements. Basically, a Mapper is more complex but by definition it has the benefit that neither of the two components depend on it. Thus the Mapper is even more decoupled than one of the two subsystems dependent on an interface or abstraction of a Gateway: in fact, you can simply throw it out the Mapper and the two subsystems will work as long as they can to fulfill their own responsibilities. Whereas, you can't remove a Gateway from an application without specifying an alternate implementation. This pattern is also different from a Mediator: no one of the objects at the same or at a lower layer of the Mapper is aware of it. Example The code sample is a simple Data Mapper that shuffles data between database and Twitter, just to shake the notion that all Data Mappers are ORMs. The code presented here is only a one-way implementation, since a bidirectional one would involve authentication and would increase too much the size of this article. The first side of the Mapper is a domain model built over the database (not represented here). The second side is Twitter's own web services instead, which we can be sure does not depend on our little in-memory database. connection = $connection; } /** * the only functionality I need from the feed */ public function synchronizeLastTweets(array $usernames) { foreach ($usernames as $username) { $endPoint = "http://twitter.com/statuses/user_timeline/{$username}.xml?count=1"; $buffer = file_get_contents($endPoint); $xml = new SimpleXMLElement($buffer); $this->_addTweet($xml->id, $username, $xml->status->text); } } public function _addTweet($id, $username, $text) { $stmt = $this->connection->prepare('INSERT INTO tweets (id, username, text) VALUES (:id, :username, :text)'); $stmt->bindValue(':id', $id, PDO::PARAM_STR); $stmt->bindValue(':username', $username, PDO::PARAM_STR); $stmt->bindValue(':text', $text, PDO::PARAM_STR); return $stmt->execute(); } } $pdo = new PDO('sqlite::memory:'); $pdo->exec('CREATE TABLE tweets (id INT NOT NULL, username VARCHAR(255) NOT NULL, text VARCHAR(255) NOT NULL, PRIMARY KEY(id))'); $mapper = new TwitterMapper($pdo); // higher-level layer $mapper->synchronizeLastTweets(array('giorgiosironi'));
September 13, 2010
by Giorgio Sironi
· 5,681 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,073 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,205 Views · 1 Like
article thumbnail
Practical PHP Patterns: Gateway
A fundamental trait of modern software is that it does not live in isolation, especially in the realm of web applications, which can easily interact with external resources like web services and databases. The majority of PHP applications must access external resources, that by architecture do not run in the same memory segment or programming language of their core Domain Model. There are many examples of these situations: web services like Google's or Yahoo! ones. Relational and NoSQL databases. The filesystem of the server. Other web and non-web applications for data interoperability. I'll call any instance of this external dependency a resource, which is an umbrella term for each item of this list. Motivation When you have to access an external resource, you get an API which you code may call. However accessing an API directly, like a PDO object or a HTTP request stream, presents many issues. First of all, your application ends up becoming very coupled to the particular product or application instance you're using. There is no room for change, since every resource has its specific API, unless it is a commodity like a relational database. More subtly, general purpose APIs are designed as catch-all interfaces for providing any functionality, and capturing any use case from every possible client. The entire set of methods becomes a possible requirement of your application, since you cannot instantly easily distinguish the primitives really called by your application from the one ignored. Moreover, the external resource may use data formats and models different from the ones used by your application. This is the case with relational database used as a storage for object models. Implementation There is an easy solution to these interaction problems, which I feel is never pushed enough. The Gateway pattern is this solution: wrap into a single object all the interaction specifical to the integrated resource, so that your object provides a specialized API of exactly what you want, as you want. This pattern is similar to the Facade classic one, but it is applied on other people's code instead of our own. You can also compare it to an Adapter, when the Adaptee is not even object-oriented or in the same process of your application's code. By the way, this pattern is specialized by many other ones, and it can be thought of as their superclass. Wrapping Wrapping is the mechanism used for this pattern's implementation. Only the functionality needed is really exposed from the Gateway. This minimalism help the Gateway in becoming the target of integration tests or pragmatic unit tests that exercise only the functionalities actually exposed and that may cause a regression. This pattern insulate the application layer or the Domain Model from external changes. The Hexagonal Architecture is really an evolution of this pattern applied systematically to every external resource, until only an in-memory object structure stands as the core domain, and every dependency is injected as an adapter for an application's port. A Gateway can also be implemented with more than one object (back end and front end) when the work to do is both on the protocol side (procedural vs. oo, XML vs. variables) and at the workflow side (different slicing of functionalities, APIs at the wrong level of abstraction fro your use case). Advantages I'll never get done with talking of the advantage of introducing a Gateway over an external dependency. You achieve greater insulation over the dependency: changes do not spread into your system and you can test them separately and efficiently. The system is also easier to read and understand as it does not pull in the whole complexity of the resource, but only the abstraction needed by client code. Disadvantages There's hardly any downside in coding up a Gateway class, unless you introduce a leaky abstraction. Peculiarity According to Fowler, this pattern is somewhat different from the other integration-related ones, and due to these differences it has earned a name and an article here. A Facade simplifies a complex API, and it is written by the developers of the resource used. A Gateway is written by the client code developers to simplify their own job. The Facade also implies a different interface, while Gateway can simply wrap it and transform it or hiding part of it. An Adapter alters an implementation to provide a new API. With a Gateway there may not be an existing interface, or if there is, the Adapter is part of the Gateway implementation, which comprehends a back end side. A Mediator separates different objects, but Gateway is much more specialized in separating two objects and keeping the dependency side (the external resource) not aware of being used. Example Today's example is a Gateway to a web service, in the form of the classic Twitter client. For simplicity and readability we'll deal only with a single operations that does not require authentication, badly implemented with OAuth by Twitter at the time of this writing. status->text; } } // having an object to represent Twitter means we can mock it, // pass it around, injecting it, composing it... $gateway = new TwitterGateway(); // client code echo $gateway->getLastTweet('giorgiosironi'), "\n";
September 9, 2010
by Giorgio Sironi
· 11,255 Views
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,046 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,707 Views · 3 Likes
article thumbnail
Let's Create... Our Own SQL Editor
Isn't it time you gained full control of your SQL work environment? Stop being limited by the tools foisted upon you and start creating your own. Not hard at all, either. Here's a complete tutorial for creating your very own SQL editor, which will look like this: OK. Now, let's create it from scratch. Start up NetBeans IDE and use this template to create a basis for your application. Just click through it and you'll have new folders and files on disk that represent your project: When you've clicked Next above, you'll be able to provide the name of your project: And when you click Finish, the Projects window will show you your application structure: You've now got a basic application that includes all the infrastructure you need (a module system, window system, file system, actions system, and more), without any content. Let's now add the content. Now right-click the "SQLEditor" node above (i.e., the orange icon) and choose Properties. In the Project Properties dialog, expand the "java" node and then include the SQL Editor: Click "Resolve" above and the IDE will include all the related modules. I.e., the SQL Editor module depends on other modules. Via the "Resolve" button, those dependencies will be identified and registered in your project. Next, let's include support for Java DB: Click "Resolve" again. Hurray, we're done. All the functionality for our own SQL editor is now available in our application. Now we'll add a new module, just so that we can perform a few tweaks to our application. In other words, this will be a branding module. Right-click the "Modules" node and choose "Add New": Name it something, such as "SQLBranding": Provide a unique identifier for your new module and make sure to include a layer.xml file, which you'll use to mask out the default menus and toolbars you don't need in your application: Click Finish above. Then right-click on the main package that is created in the module and choose New | Other. There you'll be able to create a new Module Install class, which will initialize the module when the application starts up: What we want is to force the Services window in the application (i.e., this is a window in NetBeans IDE for working with databases) to open when the application starts. So, we will provide code in the Module Install class (which you created above) for finding that window and opening it. The code we will need comes from the Window System API. Right-click the Libraries node in the module, as shown below, and choose "Add Module Dependency": Then browse to Window System API and click OK: Tip: In the Projects window, right-click the module's "Libraries" node. Choose "Add Dependency" and set a dependency on the "Window System API". That's what we need to use the window system code in the snippet below: Now, in the Module Install class, provide the following code: public class Installer extends ModuleInstall { @Override public void restored() { WindowManager.getDefault().invokeWhenUIReady( new Runnable() { @Override public void run() { TopComponent svcWindow = WindowManager.getDefault(). findTopComponent("services"); svcWindow.open(); svcWindow.requestActive(); } }); } } Now the window we need will be forced to open when the application starts. Let's turn to some other ancillary matters now. We can change the default splash screen, via "Branding", which is a menu item that you see when you right-click on the application's node in the Projects window, producing the Branding Editor below: And we can search all the strings in the modules that come from the NetBeans Platform, so that we can change the string "Services" to "Databases", for example. Or to some other custom string. You can also hide the menu items and toolbar buttons that you don't need and perform similar wrap-up tasks to really customize the application to your specific business needs. Let's now, just for fun, also include a file browser in our application. So, back in the Project Properties dialog of your application, choose Favorites under the "platform" node. While you're there, also enable the two AutoUpdate modules, so that the end user will be able to install plugins (i.e., new features and patches) that you or the community of your SQL editor will provide: The application is now complete. Let's create a ZIP distribution for our end users, while noticing we can also create a Mac distribution or one for web starting the application: After doing the above, the Files window shows your new ZIP distribution: If you prefer, you can also create an installer for your application: Once the application is unzipped or installed, click the launcher in the bin folder. Then you'll have the application with which this article started. Look in the Tools menu and, guess what? You find that you have a "Plugins" menu item, enabling extensions (i.e., features and patches) to be installed into the application. Many thanks to Tim Sparg from CoreFreight in Johannesburg for inspiring this article.
September 4, 2010
by Geertjan Wielenga
· 24,434 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,876 Views
article thumbnail
How to Copy Bean Properties With a Single Line of Code
This article shows how to copy multiple properties from one bean to another with a single line of code, even if the property names in the source and target beans are different. Copying properties from one bean is quite common especially if you are working with a lot of POJOs, for example working with JAXB objects. Lets walk through the following example where we want to copy all properties from the User object -> SystemUser object Example: source and target objects // source object that we want to copy the properties from public class User { private String first; private String last; private String address1; private String city; private String state; private String zip; private String phone; // getters and setters // ... } // target object that we want to copy the properties to public class SystemUser { private String firstName; private String lastName; private String phone; private String addressLine1; private String addressLine2; private String city; private String state; private String zip; // getters and setters // ... } Example continued: Preparing the objects // initializing the source object with example values User user = new User(); user.setFirst("John"); user.setLast("Smith"); user.setAddress1("555 Lincoln St"); user.setCity("Washington"); user.setState("DC"); user.setZip("00000"); user.setPhone("555-555-5555"); // creating an empty target object SystemUser systemUser = new SystemUser(); Approach 1: Traditional code for copying properties systemUser.setFirstName(user.getFirst()); systemUser.setLastName(user.getLast()); systemUser.setPhone(user.getPhone()); systemUser.setAddressLine1(user.getAddress1()); systemUser.setAddressLine2(user.getAddress2()); systemUser.setCity(user.getCity()); systemUser.setState(user.getState()); systemUser.setZipcode(user.getZip()); Approach 2: Single line code for copying properties copyProperties(user, systemUser, "first firstName", "last lastName", "phone", "address1 addressLine1", "address2 addressLine2", "city", "state", "zip zipcode"); Parameters user – the source object systemUser – the target object first firstName – indicates that the “first” property of the source object should be copied to the “firstName” property of the target object last lastName – indicates that the “last” property of the source object should be copied to the “lastName” property of the target object phone – indicates that the “phone” property of the source object should be copied to the “phone” property of the target object …. and so on The underlying code uses Apache Commons BeanUtils code to copy the property value from the source to the destination. You can download the copyProperties code from Google Code. Simply copy the code to your project. The code requires apache BeanUtils. If you are using maven, you can get BeanUtils by adding the following to your pom.xml commons-beanutils commons-beanutils 1.8.3 From http://www.vineetmanohar.com/2010/08/copy-map-bean-properties/
September 1, 2010
by Vineet Manohar
· 75,496 Views · 1 Like
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,449 Views · 11 Likes
  • Previous
  • ...
  • 449
  • 450
  • 451
  • 452
  • 453
  • 454
  • 455
  • 456
  • 457
  • 458
  • ...
  • 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
×