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

article thumbnail
Why does Void class exist in JDK
I always try to bring some thing new and useful on this blog. This time we will understand the Void.class (which in itself looks something tricky) present in rt.jar. One can consider the java.lang.Void class as a wrapper for the keyword void. Some developers draw the analogy with the primitive data types int, long, short and byte etc. which have the wrapper classes as Integer, Long, Short and Byte receptively. But it should be kept in mind that unlike those wrappers Void class doesn't store a value of type void in itself and hence is not a wrapper in true essence. Purpose: The Void class according to javadoc exists because of the fact that some time we may need to represent the void keyword as an object. But at the same point we cannot create an instance of the Void class using the new operator. This is because the constructor in Void has been declared as private. Moreover the Void class is a final class which means that there is no way we can inherit this class. So the only purpose that remains for the existence of the Void class is reflection, where we can get the return type of a method as void. The following piece of code will demonstrate this purpose: public class Test { public static void main(String[] args) throws SecurityException, NoSuchMethodException { Class c1 = Test1.class.getMethod("Testt",null).getReturnType(); System.out.println(c1 == Void.TYPE); System.out.println(c1 == Void.class); } } class Test1{ public void Testt(){} } One can also use Void class in Generics to specify that you don't care about the specific type of object being used. For example: List list1; From http://extreme-java.blogspot.com/2011/04/void-class-java.html
May 3, 2011
by Sandeep Bhandari
· 23,773 Views · 2 Likes
article thumbnail
Reasons for Slow Database Performance
Usually there are scenarios where the application does not perform as expected. A simple web page which fetches data from database and displays optimizes it for mobiles should be fast and turnaround times should be less than 30 seconds on a good network connection. But still there are cases where these kinds of applications suffer the most performance issues. This is because the database in these cases is not designed by giving proper attention to the application requirements. You can change one application design even after delivery but changing the database design once a number of application have been integrated with it is like explosion. Here I am giving some points which should be kept in mind while designing application and database. Only basic idea is being provided. For details one can search each topic on the web as each point expands well to multiple articles. 1) Bind Variables: When a SQL query is sent to the database engine for processing and sending the result, it is compiled by the database compiler to get the tokens of the query. This involves parsing, optimizing and identifying the query. After a number of steps, the SQL query is passed to the database engine for processing. In a small application with a user base of less than 500, it is usually the same query which is executed more often than others. The use of bind variables helps in storing the compiled query once and executing it with different data at different times. For using bind variables, one needs to use PreparedStatement objects in Java. 2) Query is not well formed: Usually the same SQL query can be written in multiple ways. There are ways by which a query can be optimized to give the best performance. The corresponding SQL construct should be chosen depending upon requirement. I have scenarios where people have used WHERE clause instead of GROUP BY and are complaining of poor response times. Similarly Sub queries and Joins complement each other. 3) Database structure is not well defined/normalized: This is probably known to everybody that the database tables should be properly normalized as this is part of every DBMS course at graduation level. If the tables are not properly designed and normalized, anomalies set in. 4) Proper caching is not in place: Many applications make use of temporary caches on the application server to store the reference data or frequently accessed data as memory is less of an issue than the time with new generation servers. 5) Number of rows in the table too large: If the table itself has too much of data then the queries will take time to execute. Partitioning a table into multiple tables is recommended in these situations. For example: If a table has employee records of 1000000 employees then it could be split into 5 small tables each having 200000 rows. The advantage is we know beforehand in which smaller table to look for a particular employee code as the division of large table can be done on the employee id column. 6) Connections are not being pooled: If connections are not pooled then the each time a new connection is requested for a request to database. Maintaining a connection pool is much better than creating and destroying the connection for executing every SQL query. Of course, there are frameworks like Hibernate which take care of creating the connection pools and also allow the customization of these pools 7) Connections not closed/returned to pool in case of exceptions: When an exception occurs while performing database operations, it ought to be caught. Usually catching the exception is not the issue because SQLException is a checked exception but closing the connection is something that most of the times is left out. If the connection is not released, the same connection cannot be used for any other purpose till the connection is timed out. 8) Stored procedures for complex computations on database: Stored procedures are a good way to perform database intensive operations. This is because they are already compiled and there is less network trips for getting the same results as compared to SQL queries. From http://extreme-java.blogspot.com/2011/04/reasons-for-slow-database-performance.html
April 30, 2011
by Sandeep Bhandari
· 59,848 Views · 1 Like
article thumbnail
Fun With WebMatrix Helpers in ASP.NET MVC 3
it’s nearly the weekend, and it’s been long week, so let’s have a bit of fun… so i take it you’ve all had a chance to look at webmatrix? if you haven’t then you should really make the effort to have a play around with it. i will admit that i was a bit snobby about it when i first read about it, but it is actually a really great way to build small, simple web sites. for the uninitiated, here are a few useful links: the official site http://www.microsoft.com/web/webmatrix/ scott guthrie http://weblogs.asp.net/scottgu/archive/2010/07/06/introducing-webmatrix.aspx rob conery http://blog.wekeroad.com/microsoft/someone-hit-their-head scott hanselman http://www.hanselman.com/blog/hanseminutespodcast249onwebmatrixwithrobconery.aspx you can install webmatrix through the web platform installer . it has loads of really great features, which are much better explained in the links above than i could ever do, but the one that hit me immediately as being really fun was the webmatrix helpers feature and i wondered if there was a way to use them in mvc. well, webmatrix is built on asp.net, so it is actually a trivial task to add them to an asp.net mvc application. getting going there are loads of helpers available, today we are going to look at the microsoft web helpers. this package gives you the ability to quickly and easily add basic functionality for services such as twitter, bing, gravatar, facebook, google analytics and xbox live to your site. the awesomeness of nuget makes it easy to add the microsoft web helpers package to our project by typing: install-package microsoft-web-helpers into the the package manager console. next you will need to add references to webmatrix.data and webmatrix.webdata and set the “copy local” property to true for both of them. if you fail to do this step you will receive a compilation error, “the type or namespace name ‘simplemembershipprovider’ could not be found” in app_code\facebook.cshtml. and that’s it! you are now ready to start using the web helpers in your views. so let’s have a look at a few of them… gravatar you can add a gravatar image to your page by simply using the gravatar.gethtml() method in your razor view. for example: @gravatar.gethtml("[email protected]") displays this handsome chap (and no the glasses and bandito moustache are not real!): if the email address supplied to the method doesn’t have a corresponding gravatar account the default gravatar image will be returned, i.e. but you can also set the default image to be the url of any image you desire. for example, the following code: @gravatar.gethtml ("[email protected]", defaultimage: "http://blog.stevelydford.com/content/nograv.jpg") returns this stunning example of programmer art : optional parameters allow you to set the size of the image, the gravatar rating and a couple of other attributes . xbox live gamercard this is a very simple method which returns an xbox live gamercard. it has one parameter which is a string containing the required xbox live gametag. for example: @gamercard.gethtml("stinky53") returns this: which does nothing if not prove that i don’t get enough time to work on my gamerscore! microsoft bing web helpers has a bing class that enables you to easily let users google your site with bing . first, we need to add the following code to our razor view: @{ bing.sitetitle = ".net web stuff, mostly"; bing.siteurl = "http://blog.stevelydford.com"; } we can then use either the bing.searchbox() or bing.advancedsearchbox() methods to display a bing search box in our view. @bing.searchbox() displays a bing search box which takes the user to bing.com to displays it’s results: @bing.advancedsearchbox() displays a bing search box which renders a on your page containing the search results: analytics the analytics class of microsoft.web.helpers contains methods which generate scripts that enable a page to be tracked by google analytics, yahoo marketing solutions and/or statcounter. they all work in a very similar way and just require you to pass the method the relevant account details. for example: @analytics.getgooglehtml({your-analytics-webpropertyid-here}) @analytics.getyahoohtml({your-yahoo-accountid-here}) this will inject the necessary javascript into your view at runtime to enable tracking by the relevant service. twitter the microsoft.web.helpers namespace contains a twitter class with two methods – twitter.profile() and twitter.search(). twitter.profile() injects some javascript into your view which displays the feed for the twitter user specified in the username parameter: @twitter.profile("stevelydford") there are a whole raft of parameters, which allow you to customise the output in various ways, such as setting the width and height, colors, number of tweets returned, etc. a full list of these parameters can be found here . twitter.search() displays the twitter search results for the search string specified in the searchquery parameter: @twitter.search("london 2012") again, there are a bunch of optional parameters to allow you to customize the output to your requirements. when you use nuget to install the microsoft-web-helpers package a twittergoodies razor file is added to your app_code folder. this class contains helpers which provide additional twitter functionality. these helpers include twittergoodies.tweetbutton(), twittergoodies.followbutton(), twittergoodies.faves() and twittergoodies.list(), all of which can have their outputs customised using various optional parameters: @twittergoodies.tweetbutton (tweettext: "i'm reading steve lydford's blog", url:"http://blog.stevelydford.com") displays a tweet button which opens a new window to allow the user to send a tweet about your site. the url passed to the helper is automatically shortened using the twitter t.co url shortner: @twittergoodies.followbutton("stevelydford") displays a button which redirects them to twitter: @twittergoodies.list("stevelydford", "f1-4") displays a form which shows a public twitter list: there are a few other methods in the twittergoodies razor file, which you can view in app_code/twittergoodies.cshtml. facebook as well as the twittergoodies.cshtml page, the microsoft-web-helpers package also installs facebook.cshtml to your app_code directory. this file contains many useful facebook helpers. i will look at a couple here, a full list can be found on the facebookhelper codeplex site . one of the easiest to use out of the box is the facebook.likebutton() helper, which displays a ‘like’ button that either automatically ‘likes’ the url supplied, or opens a new facebook window ’on click’ if the user is not currently signed in: @facebook.likebutton("http://blog.stevelydford.com") next up is facebook.activityfeed() which displays stories when users ‘like’ content on a site or share content from a site on facebook. @facebook.acivityfeed("http://www.bbc.co.uk") most of the rest of the facebook helpers require initialization. in order to do this you will require a facebook application id. you can get one by browsing to http://www.facebook.com/developers/createapp.php and creating a new facebook application: when you are setting up your app ensure that you enter the url of your site, including the correct port number if you are working on localhost: you can then add the following code to your razor view to initialize: @{ facebook.initialize("{your-application-id-here}", "{your-application-secret-here}"); } then it’s just a matter of adding a couple of lines of code to the view to add facebook comments to the page: @facebook.getinitializationscripts() @facebook.comments() or, to show a facebook livestream to allow users of your site to communicate in real time: @facebook.livestream() conclusion this post shows just a small fraction of what can be achieved very quickly and very easily using webmatrix web helpers in an mvc application. the microsoft web helpers package makes it incredibly easy to add a whole load of functionality to you site for very little effort. have fun! let me know how you get on. go play….
April 29, 2011
by Steve Lydford
· 28,212 Views
article thumbnail
Modules and namespaces in JavaScript
JavaScript does not come with support for modules. This blog post examines patterns and APIs that provide such support. It is split into the following parts: Patterns for structuring modules. APIs for loading modules asynchronously. Related reading, background and sources. 1. Patterns for structuring modules A module fulfills two purposes: First, it holds content, by mapping identifiers to values. Second, it provides a namespace for those identifiers, to prevent them from clashing with identifiers in other modules. In JavaScript, modules are implemented via objects. Namespacing: A top-level module is put into a global variable. That variable is the namespace of the module content. Holding content: Each property of the module holds a value. Nesting modules: One achieves nesting by putting a module inside another one. Filling a module with content Approach 1: Object literal. var namespace = { func: function() { ... }, value: 123 }; Approach 2: Assigning to properties. var namespace = {}; namespace.func = function() { ... }; namespace.value = 123; Accessing the content in either approach: namespace.func(); console.log(namespace.value + 44); Assessment: Object literal. Pro: Elegant syntax. Con: As a single, sometimes very long syntactic construct, it imposes constraints on its contents. One must maintain the opening brace before the content and the closing brace after the content. And one must remember to not add a comma after the last property value. This makes it harder to move content around. Assigning to properties. Con: Redundant repetitions of the namespace identifier. The Module pattern: private data and initialization In the module pattern, one uses an Immediately-Invoked Function Expression (IIFE, [1]) to attach an environment to the module data. The bindings inside that environment can be accessed from the module, but not from outside. Another advantage is that the IIFE gives you a place to perform initializations. var namespace = function() { // set up private data var arr = []; // not visible outside for(var i=0; i<4; i++) { arr.push(i); } return { // read-only access via getter get values() { return arr; } }; }(); console.log(namespace.values); // [0,1,2,3] Comments: Con: Harder to read and harder to figure out what is going on. Con: Harder to patch. Every now and then, you can reuse existing code by patching it just a little. Yes, this breaks encapsulation, but it can also be very useful for temporary solutions. The module pattern makes such patching impossible (which may be a feature, depending on your taste). Alternative for private data: use a naming convention for private properties, e.g. all properties whose names start with an underscore are private. Variation: Namespace is a function parameter. var namespace = {}; (function(ns) { // (set up private data here) ns.func = function() { ... }; ns.value = 123; }(namespace)); Variation: this as the namespace identifier (cannot accidentally be assigned to). var namespace = {}; (function() { // (set up private data here) this.func = function() { ... }; this.value = 123; }).call(namespace); // hand in implicit parameter "this" Referring to sibling properties Use this. Con: hidden if you nest functions (which includes methods in nested objects). var namespace = { _value: 123; // private via naming convention getValue: function() { return this._value; } anObject: { aMethod: function() { // "this" does not point to the module here } } } Global access. Cons: makes it harder to rename the namespace, verbose for nested namespaces. var namespace = { _value: 123; // private via naming convention getValue: function() { return namespace._value; } } Custom identifier: The module pattern (see above) enables one to use a custom local identifier to refer to the current module. Module pattern with object literal: assign the object to a local variable before returning it. Module pattern with parameter: the parameter is the custom identifier. Private data and initialization for properties An IFEE can be used to attach private data and initialization code to an object. It can do the same for a single property. var ns = { getValue: function() { var arr = []; // not visible outside for(var i=0; i<4; i++) { arr.push(i); } return function() { // actual property value return arr; }; }() }; Read on for an application of this pattern. Types in object literals Problem: A JavaScript type is defined in two steps. First, define the constructor. Second, set up the prototype of the constructor. These two steps cannot be performed in object literals. There are two solutions: Use an inheritance API where constructor and prototype can be defined simultaneously [4]. Wrap the two parts of the type in an IIFE: var ns = { Type: function() { var constructor = function() { // ... }; constructor.prototype = { // ... }; return constructor; // value of Type }() }; Managing namespaces Use the same namespace in several files: You can spread out a module definition across several files. Each file contributes features to the module. If you create the namespace variable as follows then the order in which the files are loaded does not matter. Note that this pattern does not work with object literals. var namespace = namespace || {}; Nested namespaces: With multiple modules, one can avoid a proliferation of global names by creating a single global namespace and adding sub-modules to it. Further nesting is not advisable, because it adds complexity and is slower. You can use longer names if name clashes are an issue. var topns = topns || {}; topns.module1 = { // content } topns.module2 = { // content } YUI2 uses the following pattern to create nested namespaces. YAHOO.namespace("foo.bar"); YAHOO.foo.bar.doSomething = function() { ... }; 2. APIs for loading modules asynchronously Avoiding blocking: The content of a web page is processed sequentially. When a script tag is encountered that refers to a file, two steps happen: The file is downloaded. The file is interpreted. All browsers block the processing of subsequent content until (2) is finished, because everything is single-threaded and must be processed in order. Newer browsers perform some downloads in parallel, but rendering is still blocked [2]. This unnecessarily delays the initial display of a page. Modern module APIs provide a way around this by supporting asynchronous loading of modules. There are usually two parts to using such APIs: First one specifies what modules one would like to use. Second, one provides a callback that is invoked once all modules are ready. The goal of this section is not to be a comprehensive introduction, but rather to give you an overview of what is possible in the design space of JavaScript modules. 2.1. RequireJS RequireJS has been created as a standard for modules that work both on servers and in browsers. The RequireJS website explains the relationship between RequireJS and the earlier CommonJS standard for server-side modules [3]: CommonJS defines a module format. Unfortunately, it was defined without giving browsers equal footing to other JavaScript environments. Because of that, there are CommonJS spec proposals for Transport formats and an asynchronous require. RequireJS tries to keep with the spirit of CommonJS, with using string names to refer to dependencies, and to avoid modules defining global objects, but still allow coding a module format that works well natively in the browser. RequireJS implements the Asynchronous Module Definition (formerly Transport/C) proposal. If you have modules that are in the traditional CommonJS module format, then you can easily convert them to work with RequireJS. RequireJS projects have the following file structure: project-directory/ project.html legacy.js scripts/ main.js require.js helper/ util.js project.html: My Sample Project main.js: helper/util is resolved relative to data-main. legacy.js ends with .js and is assumed to not be in module format. The consequences are that its path is resolved relative to project.html and that there isn’t a function parameter to access its (module) contents. require(["helper/util", "legacy.js"], function(util) { //This function is called when scripts/helper/util.js is loaded. require.ready(function() { //This function is called when the page is loaded //(the DOMContentLoaded event) and when all required //scripts are loaded. }); }); Other features of RequireJS: Specify and use internationalization data. Load text files (e.g. to be used for HTML templating) Use JSONP service results for initial application setup. 2.2. YUI3 Version 3 of the YUI JavaScript framework brings its own module infrastructure. YUI3 modules are loaded asynchronously. The general pattern for using them is as follows. YUI().use('dd', 'anim', function(Y) { // Y.DD is available // Y.Anim is available }); Steps: Provide IDs “dd” and “anim” of the modules you want to load. Provide a callback to be invoked once all modules have been loaded. The parameter Y of the callback is the YUI namespace. This namespace contains the sub-namespaces DD and Anim for the modules. As you can see, the ID of a module and its namespace are usually different. Method YUI.add() allows you to register your own modules. YUI.add('mymodules-mod1', function(Y) { Y.namespace('mynamespace'); Y.mynamespace.Mod1 = function() { // expose an API }; }, '0.1.1' // module version ); YUI includes a loader for retrieving modules from external files. It is configured via a parameter to the API. The following example loads two modules: The built-in YUI module dd and the external module yui_flot that is available online. YUI({ modules: { yui2_yde_datasource: { // not used below fullpath: 'http://yui.yahooapis.com/datasource-min.js' }, yui_flot: { fullpath: 'http://bluesmoon.github.com/yui-flot/yui.flot.js' } } }).use('dd', 'yui_flot', function(Y) { // do stuff }); 2.3. Script loaders Similarly to RequireJS, script loaders are replacements for script tags that allow one to load JavaScript code asynchronously and in parallel. But they are usually simpler than RequireJS. Examples: LABjs: a relatively simple script loader. Use it instead of RequireJS if you need to load scripts in a precise order and you don't need to manage module dependencies. Background: “LABjs & RequireJS: Loading JavaScript Resources the Fun Way” describes the differences between LABjs and RequireJS. yepnope: A fast script loader that allows you to make the loading of some scripts contingent on the capabilities of the web browser. 3. Related reading, background and sources Related reading: A first look at the upcoming JavaScript modules Background: JavaScript variable scoping and its pitfalls Loading Scripts Without Blocking CommonJS Modules Lightweight JavaScript inheritance APIs Main sources of this post: Namespacing in JavaScript YUI2: A JavaScript Module Pattern YUI3: YUI Global Object How to get started with RequireJS From http://www.2ality.com/2011/04/modules-and-namespaces-in-javascript.html
April 29, 2011
by Axel Rauschmayer
· 18,576 Views
article thumbnail
Bootstrapping CDI in several environments
i feel like writing some posts about cdi (contexts and dependency injection). so this is the first one of a series of x posts ( 0 javax.enterprise cdi-api 1.0 provided an empty beans.xml will do to enable cdi you must have a beans.xml file in your project (under the meta-inf or web-inf). that’s because cdi needs to identify the beans in your classpath (this is called bean discovery) and build its internal metamodel. with the beans.xml file cdi knows it has beans to discover. so, for all the following examples i’ll make it simple and will leave this file completely empty. java ee 6 containers let’s start with the easiest possible environment : java ee 6 containers . why is it the simplest ? well, because you don’t have to do anything : cdi is part of java ee 6 as well as the web profile 1.0 so you don’t need to manually bootstrap it. let’s see how to inject a cdi bean within an ejb 3.1 and a servlet 3.0 . ejb 3.1 since ejb 3.1 you can use the ejbcontainer api to get an in-memory embedded ejb container and you can easily unit test your ejbs. so let’s write an ejb and a test class. first let’s have a look at the code of the ejb. as you can see, with version 3.1 an ejb is just a pojo : no inheritance, no interface, just one @stateless annotation. it gets a reference of the hello bean buy using the @inject annotation and uses it in the saysomething() method. @stateless public class mainejb31 { @inject hello hello; public string saysomething() { return hello.sayhelloworld(); } } you can now package the mainejb31, hello and world classes with the empty beans.xml file into a jar, deploy it to glassfish 3.x , and it will work. but if you don’t want to bother deploying it to glassfish and just unit test it, this is what you need to do : public class mainejbtest { private static ejbcontainer ec; private static context ctx; @beforeclass public static void initcontainer() throws exception { map properties = new hashmap(); properties.put(ejbcontainer.modules, new file("target/classes")); ec = ejbcontainer.createejbcontainer(properties); ctx = ec.getcontext(); } @afterclass public static void closecontainer() throws exception { if (ec != null) ec.close(); } @test public void shoulddisplayhelloworld() throws exception { // looks up the ejb mainejb31 mainejb = (mainejb31) ctx.lookup("java:global/classes/mainejb!org.antoniogoncalves.cdi.helloworld.mainejb"); assertequals("should say hello world !!!", "hello world !!!", mainejb.saysomething()); } } in the code above the method initcontainer() initializes the ejbcontainer. the shoulddisplayhelloworld() looks up the ejb (using the new portable jndi name ), invokes it and makes sure the saysomething() method returns hello world !!!. green test. that was pretty easy too. servlet 3.0 servlet 3.0 is part of java ee 6, so again, there is no needed configuration to bootstrap cdi. let’s use the new @webservlet annotation and write a very simple one that injects a reference of hello and displays an html page with hello world !!!. this is what the servlet looks like : @webservlet(urlpatterns = "/mainservlet") public class mainservlet30 extends httpservlet { @inject hello hello; @override protected void service(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception { resp.setcontenttype("text/html"); printwriter out = resp.getwriter(); out.println(""); out.println(""); out.println(""); out.println(saysomething()); out.println(""); out.println(""); out.close(); } public string saysomething() { return hello.sayhelloworld(); } } thanks to the @webservlet i don’t need any web.xml (it’s optional in servlet 3.0) to map the mainservlet30 to the /mainservlet url. you can now package the mainservlet30, hello and world classes with the empty beans.xml and no web.xml into a war, deploy it to glassfish 3.x , go to http://localhost:8080/bootstrapping-servlet30-1.0/mainservlet and it will work. unfortunately servlet 3.0 doesn’t have an api for the container (such as ejbcontainer). there is no servletcontainer api that would let you use an embedded servlet container in a standard way and, why not, easily unit test it. application client container not many people know it, but java ee (or even older j2ee versions) comes with an application client container (acc). it’s like an ejb or servlet container but for plain pojos. for example you can develop a swing application (yes, i’m sure that some of you still use swing), run it into the acc and get some extra services given by the container (security, naming, certain annotations…). glassfish v3 has an acc that you can launch in a command line : appclient -jar . so i thought, great, i can use cdi with acc the same way i use it within ejb or servlet container, no need to bootstrap anything, it’s all out of the box. i was wrong . as per the cdi specification (section 12.1), cdi is not required to support application client bean archives. so the glassfish application client container doesn’t support it. i haven’t tried the jboss acc , maybe it works. other containers the beauty of cdi is that it doesn’t require java ee 6 . you can use cdi with simple pojos in a java se environment, as well as some servlet 2.5 containers. of course it’s not as easy to bootstrap because you need a bit of configuration. but it then works fine (not always but). java se 6 ok, so until now there was nothing to do to bootstrap cdi. it is already bundled with the ejb 3.1 and servlet 3.0 containers of java ee 6 (and web profile). so the idea here is to use cdi in a simple java se environment. coming back to our hello and world classes, we need a pojo with an entry point that will bootstrap cdi so we can use injection to get those classes. in standard java se when we say entry point , we think of a public static void main(string[] args) method. well, we need something similar… but different. weld is the reference implementation of cdi. that means it implements the specification, the standard apis (mostly found in javax.inject and javax.enterprise.context packages) but also some proprietary code (in org.jboss.weld package). bootstrapping cdi in java se is not specified so you will need to use specific weld features. you can do that in two different flavors: by observing the containerinitialized event or using the programatic bootstrap api consisting of the weld and weldcontainer classes. the following code uses the containerinitialized event. as you can see, it uses the @observes annotation that i’ll explain in a future post. but the idea is that this class is listening to the event and processes the code once the event is triggered. import org.jboss.weld.environment.se.events.containerinitialized; import javax.enterprise.event.observes; import javax.inject.inject; public class mainjavase6 { @inject hello hello; public void saysomething(@observes containerinitialized event) { system.out.println(hello.sayhelloworld()); } } but who trigers the containerinitialized event ? well, it’s the org.jboss.weld.environment.se.startmain class. i’m using maven so a nice trick is to use the exec-maven-plugin to run the startmain class. download the code , have a look at the pom.xml and give it a try. the other possibility is to programmatically bootstrap the weld container. this can be handy in unit testing. the code below initializes the weld container (with new weld().initialize()) and then looks for the hello class (using weld.instance().select(hello.class).get()). import org.jboss.weld.environment.se.weld; import org.jboss.weld.environment.se.weldcontainer; import org.junit.beforeclass; import org.junit.test; import static junit.framework.assert.assertequals; public class hellotest { @test public void shoulddisplayhelloworld() { weldcontainer weld = new weld().initialize(); hello hello = weld.instance().select(hello.class).get(); assertequals("should say hello world !!!", "hello world !!!", hello.sayhelloworld()); } } execute the test with mvn test and it should be green. as you can see, there is a bit more work using cdi in a java se environment, but it’s not that complicated. tomcat 6.x ok, and what about your legacy servlet 2.5 containers ? the first one that comes in mind is tomcat 6.x ( note that tomcat 7.x will implement servlet 3.0 but is still in beta version at the time of writing this post ). weld provides support for tomcat but you need to configure it a bit to make cdi work. first of all, this is a servlet 2.5, not a 3.0. so the code of the servlet is slightly different from the one seen before (no annotation allowed) and of course, you need your good old web.xml file : public class mainservlet25 extends httpservlet { @inject hello hello; @override protected void service(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception { resp.setcontenttype("text/html"); printwriter out = resp.getwriter(); out.println(""); out.println(""); out.println(""); out.println(saysomething()); out.println(""); out.println(""); out.close(); } public string saysomething() { return hello.sayhelloworld(); } } because we don’t have a @webservlet annotation in servlet 2.5, we need to declare and map it in the web.xml (using the servlet and servlet-mapping tags). then, you need to explicitly specify the servlet listener to boot weld and control its interaction with requests (org.jboss.weld.environment.servlet.listener). tomcat has a read-only jndi, so weld can’t automatically bind the beanmanager extension spi. to bind the beanmanager into jndi, you should populate meta-inf/context.xml and make the beanmanager available to your deployment by adding it to your web.xml: mainservlet25 org.antoniogoncalves.cdi.bootstrapping.servlet.mainservlet25 mainservlet25 /mainservlet org.jboss.weld.environment.servlet.listener beanmanager javax.enterprise.inject.spi.beanmanager the meta-inf/context.xml file is an optional file which contains a context for a single tomcat web application. this can be used to define certain behaviours for your application, jndi resources and other settings. package all the files (mainservlet25, hello, world, meta-inf/context.xml, beans.xml and web.xml) into a war and deploy it into tomcat 6.x. go to http://localhost:8080/bootstrapping-servlet25-tomcat-1.0/mainservlet and you will see your hello world page. jetty 6.x another famous servlet 2.5 containers is jetty 6.x (at codehaus) and jetty 7.x ( note that jetty 8.x will implement servlet 3.0 but it’s still in experimental stage at the time of writing this post ). if you look at the weld documentation, there is actually support for jetty 6.x and 7.x . the code is the same one as tomcat (because it’s a servlet 2.5 container), but the configuration changes. with jetty you need to add two files under web-inf : jetty-env.xml and jetty-web.xml : beanmanager javax.enterprise.inject.spi.beanmanager org.jboss.weld.resources.managerobjectfactory true package all the files (mainservlet25, hello, world, web-inf/jetty-env.xml, web-inf/jetty-web.xml, beans.xml and web.xml) into a war and deploy it into jetty 6.x. go to http://localhost:8080/bootstrapping-servlet25-jetty6/mainservlet and you will see your hello world page. there was a mistake in the weld documentation so i couldn’t make it work. i started a thread on the weld forum and thanks to dan allen , pete muir and all the weld team, this was fixed and i managed to make it work. simple as posting an email to the forum . thanks for your help guys. spring 3.x here is the tricky part. spring 3.x implements the jsr 330 : dependency injection for java , which means that @inject works out of the box. but i didn’t find a way to integrate cdi with spring 3.x . the weld documentation mentions that because of its extension points, “ integration with third-party frameworks such as spring (…) was envisaged by the designers of cdi “. i did find this blog that simulates cdi features by enabling spring ones. what i didn’t find is a clear statement or roadmap on springsource about supporting cdi or not in future releases. the last trace of this topic is a comment on a long tss flaming thread . at that time (16 december 2009), juergen huller said “ with respect to implementing cdi on top of spring (…) trying to hammer it into the semantic frame of another framework such as cdi would be an exercise that is certainly achievable (…) but ultimately pointless “. but if you have any fresh news about it, let me know. conclusion as i said, this post is not about explaining cdi, i’ll do that in future posts. i just wanted to focus on how to bootstrap it in several environments so you can try by yourself. as you saw, it’s much simpler to use cdi within an ejb 3.1 or servlet 3.0 container in java ee 6. i’ve used glassfish 3.x but it should also work with other java ee 6 or web profile containers such as jboss 6 or resin . when you don’t use java ee 6, there is a bit more work to do. depending on your environment or servlet container you need some configuration to bootstrap weld. by the way, i’ve used weld because it’s the reference implementation, the one bunddled with glassfish and jboss. but you could also use openwebbeans , another cdi implementation. download the code , give it a try, and give me some feedback. from http://agoncal.wordpress.com/2011/01/12/bootstrapping-cdi-in-several-environments/
April 28, 2011
by Antonio Goncalves
· 31,478 Views
article thumbnail
Just say no to swapping!
Imagine you love to cook; it's an intense hobby of yours. Over time, you've accumulated many fun spices, but your pantry is too small, so, you rent an off-site storage facility, and move the less frequently used spice racks there. Problem solved! Suddenly you decide to cook this great new recipe. You head to the pantry to retrieve your Saffron, but it's not there! It was moved out to the storage facility and must now be retrieved (this is a hard page fault). No problem -- your neighbor volunteers to go fetch it for you. Unfortunately, the facility is ~2,900 miles away, all the way across the US, so it takes your friend 6 days to retrieve it! This assumes you normally take 7 seconds to retrieve a spice from the pantry; that your data was in main memory (~100 nanoseconds access time), not in the CPU's caches (which'd be maybe 10 nanoseconds); that your swap file is on a fast (say, WD Raptor) spinning-magnets hard drive with 5 millisecond average access time; and that your neighbor drives non-stop at 60 mph to the facility and back. Even worse, your neighbor drives a motorcycle, and so he can only retrieve one spice rack at a time. So, after waiting 6 days for the Saffron to come back, when you next go to the pantry to get some Paprika, it's also "swapped out" and you must wait another 6 days! It's possible that first spice rack also happened to have the Paprika but it's also likely it did not; that depends on your spice locality. Also, with each trip, your neighbor must pick a spice rack to move out to the facility, so that the returned spice rack has a place to go (it is a "swap", after all), so the Paprika could have just been swapped out! Sadly, it might easily be many weeks until you succeed in cooking your dish. Maybe in the olden days, when memory itself was a core of little magnets, swapping cost wasn't so extreme, but these days, as memory access time has improved drastically while hard drive access time hasn't budged, the disparity is now unacceptable. Swapping has become a badly leaking abstraction. When a typical process (say, your e-mail reader) has to "swap back in" after not being used for a while, it can hit 100s of such page faults, before finishing redrawing its window. It's an awful experience, though it has the fun side effect of letting you see, in slow motion, just what precise steps your email reader goes through when redrawing its window. Swapping is especially disastrous with JVM processes. See, the JVM generally won't do a full GC cycle until it has run out of its allowed heap, so most of your heap is likely occupied by not-yet-collected garbage. Since these pages aren't being touched (because they are garbage and thus unreferenced), the OS happily swaps them out. When GC finally runs, you have a ridiculous swap storm, pulling in all these pages only to then discover that they are in fact filled with garbage and should be discarded; this can easily make your GC cycle take many minutes! It'd be better if the JVM could work more closely with the OS so that GC would somehow run on-demand whenever the OS wants to start swapping so that, at least, we never swap out garbage. Until then, make sure you don't set your JVM's heap size too large! Just use an SSD... These days, many machines ship with solid state disks, which are an astounding (though still costly) improvement over spinning magnets; once you've used an SSD you can never go back; it's just one of life's many one-way doors. You might be tempted to declare that this problem is solved, since SSDs are so blazingly fast, right? Indeed, they are orders of magnitudes faster than spinning magnets, but they are still 2-3 orders of magnitude slower than main memory or CPU cache. The typical SSD might have 50 microsends access time, which equates to ~58 total miles of driving at 60 mph. Certainly a huge improvement, but still unacceptable if you want to cook your dish on time! Just add RAM... Another common workaround is to put lots of RAM in your machine, but this can easily back-fire: operating systems will happily swap out memory pages in favor of caching IO pages, so if you have any processes accessing lots of bytes (say, mencoder encoding a 50 GB bluray movie, maybe a virus checker or backup program, or even Lucene searching against a large index or doing a large merge), the OS will swap your pages out. This then means that the more RAM you have, the more swapping you get, and the problem only gets worse! Fortunately, some OS's let you control this behavior: on Linux, you can tune swappiness down to 0 (most Linux distros default this to a highish number); Windows also has a checkbox, under My Computer -> Properties -> Advanced -> Performance Settings -> Advanced -> Memory Usage, that lets you favor Programs or System Cache, that's likely doing something similar. There are low-level IO flags that these programs are supposed to use so that the OS knows not to cache the pages they access, but sometimes the processes fail to use them or cannot use them (for example, they are not yet exposed to Java), and even if they do, sometimes the OS ignores them! When swapping is OK If your computer never runs any interactive processes, ie, a process where a human is blocked (waiting) on the other end for something to happen, and only runs batch processes which tend to be active at different times, then swapping can be an overall win since it allows that process which is active to make nearly-full use of the available RAM. Net/net, over time, this will give greater overall throughput for the batch processes on the machine. But, remember that the server running your web-site is an interactive process; if your server processes (web/app server, database, search server, etc.) are stuck swapping, your site has for all intents and purposes become unusable to your users. This is a fixable problem Most processes have known data structures that consume substantial RAM, and in many cases these processes could easily discard and later regenerate their data structures in much less time than even a single page fault. Caches can simply be pruned or discarded since they will self-regenerate over time. These data structures should never be swapped out, since regeneration is far cheaper. Somehow the OS should ask each RAM-intensive and least-recently-accessed process to discard its data structures to free up RAM, instead of swapping out the pages occupied by the data structure. Of course, this would require a tighter interaction between the OS and processes than exists today; Java's SoftReference is close, except this only works within a single JVM, and does not interact with the OS. What can you do? Until this problem is solved for real, the simplest workaround is to disable swapping entirely, and stuff as much RAM as you can into the machine. RAM is cheap, memory modules are dense, and modern motherboards accept many modules. This is what I do. Of course, with this approach, when you run out of RAM stuff will start failing. If the software is well written, it'll fail gracefully: your browser will tell you it cannot open a new window or visit a new page. If it's poorly written it will simply crash, thus quickly freeing up RAM and hopefully not losing any data or corrupting any files in the process. Linux takes the simple draconian approach of picking a memory hogging process and SIGKILL'ing it. If you don't want to disable swapping you should at least tell the OS not to swap pages out for IO caching. Just say no to swapping!
April 27, 2011
by Michael Mccandless
· 26,098 Views
article thumbnail
Check if PHP is running in safe mode or not
Lately, I have been playing around with PHP configuration. And I realized that the runtime configurations do not change using ini_set function, if you are running PHP in the safe mode. A simple check in PHP can tell you this. Notice the code block below and which allows to check this. Next, time when you are going to change any configuration at runtime, I am sure you want to check this, before you could see that change working. Hope that helps. Stay digified !!
April 26, 2011
by Sachin Khosla
· 15,036 Views
article thumbnail
Turning Off Session Fixation Protection in Tomcat 7
Session fixation protection is a new feature that was introduced as part of the Apache Tomcat 7 release process, and has been backported and turned on by default in all versions from version 6.0.21 on. Session fixation happens when an attacker sends a link to the victim with a session ID included. The minute the victim authenticates the session in the link by logging in, the attacker is able to just click the session link and have full access to the intended victims account. According to Mark Thomas, release manager for Tomcat 7 and member of the Apache Security Committee, in an article on TomcatExpert.com today": Essentially, when a user authenticates their session, Tomcat will change the session ID. It does not destroy the previous session, rather it renames it so it is no longer found by that ID. So in our example above, Bob would try and log on with that session, and he would not be able to find it. Turning Off Session Fixation Protection Since it is turned on by default, the configuration is implicit inside of Tomcat. To turn it off, you will need to explicitly add the configuration and turn it off. First you will need to find the details of the specific type of authentication valve you are using in the Apache Tomcat Valve Configuration Documentation. Then you would need to navigate to the context.xml file for your application (not $CATALINA_BASE/conf/context.xml - that is the global context.xml that provides defaults for all web applications). Add the valve with the appropriate class for your authentication type (e.g., for basic authentication add a valve using class="org.apache.catalina.authenticator.BasicAuthenticator". Finally, set the parameter changeSessionIdOnAuthentication="false". When to Turn Off Session Fixation Protection Generally, this is not recommended. The Apache Security Team deemed this feature a basic enough protection that it should be afforded to all users implicitly. However, in some cases application specific behavior could break and the feature would need to be turned off until the functionality could be restored using the protection. For more information on the feature and when to use it, see the full article from Mark Thomas on TomcatExpert.com.
April 26, 2011
by Stacey Schneider
· 15,123 Views
article thumbnail
Exploring TDD in JavaScript with a small kata
A code kata is an exercise where you focus on your technique instead of on the final product of your mind and fingers. But a kata can also be used as a constant parameter, while other variables change, like in scientific experiments. For example, when learning a new programming language or framework, you can execute an old kata in order to explore it. I decided to perform a small and famous Kata that we used also during interviews to separate programmers from not programmers: the FizzBuzz kata. My goal was to learn how to setup a platform for Test-Driven Development in JavaScript, following the advice of the Test-Driven JavaScript Development book. The parameters that change from my habits are the tools for running tests and the programming language, but my IDE (Unix&Vim) remained fixed along with the Kata: Write a function that returns its numerical argument. But for multiples of three return Fizz instead of the number and for the multiples of five return Buzz. For numbers which are multiples of both three and five return FizzBuzz. Additional requirement: when passed a multiple of 7, return Bang; when passed a multiple of 5 and 7, return BuzzBang; and so on for all the combinations. As my tools for running the tests, I used JsTestDriver and Firefox, as suggested by the book Test-Driven JavaScript Development which I'm currently reading. JsTestDriver JsTestDriver will make you feel the joy of a green bar again. Download its jar, put it somewhere and add an alias in your .bashrc: export JSTESTDRIVER_HOME=~/bin alias jstestdriver="java -jar $JSTESTDRIVER_HOME/JsTestDriver-1.3.2.jar" Start the server: jstestdriver --port 4224 Point an open browser (I used Firefox) to localhost:4224. The browser will ping it via Ajax requests undefinitely to gather tests to run. Now we can use the command line to run tests, like you'll do with PHPUnit if you are a PHPer: jstestdriver --tests all The Kata I started with a simple function, fizzbuzz(), and a single test case. I never wrote a test with JsTestDriver before so I needed to gain some confidence and be sure the configuration file was correct. server: http://localhost:4224 load: - src/*.js - test/*.js In JsTestDriver, a Test case is created by passing to TestCase (global function provided by JsTestDriver) a map containing anonymous functions. TestCase("FizzBuzzTest", { "test should return Fizz when passed 3" : function () { assertEquals("Fizz", fizzbuzz(3)); } }); The functions whose names start with test will be executed; there are some reserved keywords like setUp which are used as hooks for fixture creation. Running the test with the alias command is really simple: jstestdriver --tests all I made the first test pass with fizzbuzz.js, a file containing a first version of the function (with a fake implementation): function fizzbuzz() { return 'Fizz'; } The result? A green bar (metaphorically green; all tests pass.) . Total 1 tests (Passed: 1; Fails: 0; Errors: 0) (0,00 ms) Firefox 4.0 Linux: Run 1 tests (Passed: 1; Fails: 0; Errors 0) (0,00 ms) You can capture more than one browser if you want to run test simultaneously in all of them, but it will probably slow down the TDD basic cycle. You can leave cross-browser testing for later. Going on After this first test, I went on adding new ones and making them pass, until I even converted the function to an object, for the sake of easy configuration (a function returning a function would be the same). Since I also needed to create the object in just one place, I started using setUp for the fixture creation: TestCase("FizzBuzzTest", { setUp : function () { this.fizzbuzz = new FizzBuzz({ 3 : 'Fizz', 5 : 'Buzz', 7 : 'Bang' }); }, "test should return the number when passed 1 or 2" : function () { assertEquals(1, this.fizzbuzz.accept(1)); assertEquals(2, this.fizzbuzz.accept(2)); }, "test should return Fizz when passed 3 or a multiple" : function () { assertEquals("Fizz", this.fizzbuzz.accept(3)); assertEquals("Fizz", this.fizzbuzz.accept(6)); }, "test should return Buzz when passed 5 or a multiple" : function () { assertEquals("Buzz", this.fizzbuzz.accept(5)); assertEquals("Buzz", this.fizzbuzz.accept(10)); }, "test should return FizzBuzz when passed a multiple of both 3 and 5" : function () { assertEquals("FizzBuzz", this.fizzbuzz.accept(15)); assertEquals("FizzBuzz", this.fizzbuzz.accept(30)); }, "test should return Bang when passed a multiple of 7" : function () { assertEquals("Bang", this.fizzbuzz.accept(7)); assertEquals("Bang", this.fizzbuzz.accept(14)); }, "test should return FizzBuzzBang when it is the case" : function () { assertEquals("FizzBuzzBang", this.fizzbuzz.accept(3*5*7)); } }); You can use this to share fixtures between the setUp and the different test methods: the test does not look different from JUnit and PHPUnit ones. Like in all xUnit testing frameworks, the setUp is executed on a brand new object for each test, to preserve isolation. I like a bit the way in which in JavaScript you can tear and put together objects: after all, it's called object-oriented programming, not class-oriented programming. I decided to use a small function constructor as you may infer from the test: function FizzBuzz(correspondences) { this.correspondences = correspondences; this.accept = function (number) { var result = ''; for (var divisor in this.correspondences) { if (number % divisor == 0) { result = result + this.correspondences[divisor]; } } if (result) { return result; } else { return number; } } } All the code is on Github, to see the intermediate steps of the Kata if you need them. You can also use the repository to try out your installation of JsTestDriver: a git pull followed by running the tests will confirm that it's working. Sometimes we don't test code in alien environments like JavaScript console or database queries because we don't know how; but a Kata which takes just two Pomodoros can solve the issue and let you enjoy a green bar even when working with a browser's interpreter.
April 21, 2011
by Giorgio Sironi
· 13,217 Views
article thumbnail
The built-in qualifiers @Default and @Any
• @Default - Whenever a bean or injection point does not explicitly declare a qualifier, the container assumes the qualifier @Default. • @Any – When you need to declare an injection point without specifying a qualifier, is useful to know that all beans have the @Any qualifier. This qualifier “belongs” to all beans and injection points (not applicable when @New is present) and when is explicitly specified you suppress the @Default qualifier. This is useful if you want to iterate over all beans with a certain bean type. The example presented in this post will prove how @Any qualifier works in a useful example. You will try to iterate over all beans with a certain bean type. For start, you define a new Java type, like below – a simple interface representing a Wilson tennis racquet type: package com.racquets; public interface WilsonType { public String getWilsonRacquetType(); } Now, three Wilson racquets will implement this interface – notice that no qualifier was specified: package com.racquets; public class Wilson339Racquet implements WilsonType{ @Override public String getWilsonRacquetType() { return ("Wilson BLX Six.One Tour 90 (339 gr)"); } } package com.racquets; public class Wilson319Racquet implements WilsonType { @Override public String getWilsonRacquetType() { return ("Wilson BLX Six.One Tour 90 (319 gr)"); } } package com.racquets; public class Wilson96Racquet implements WilsonType { @Override public String getWilsonRacquetType() { return ("Wilson BLX Pro Tour 96"); } } Next, you can use the @Any qualifier at injection point to iterate over all beans of type WilsonRacquet. An instance of each implementation is injected and the result of getWilsonRacquetType method is stored in an ArrayList: package com.racquets; import java.util.ArrayList; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Any; import javax.enterprise.inject.Instance; import javax.enterprise.inject.Produces; import javax.inject.Inject; import javax.inject.Named; @RequestScoped public class WilsonRacquetBean { private @Named @Produces ArrayList wilsons = new ArrayList(); @Inject void initWilsonRacquets(@Any Instance racquets) { for (WilsonType racquet : racquets) { wilsons.add(racquet.getWilsonRacquetType()); } } } From a JSF page, you can easily iterate over the ArrayList (notice here that the wilsons collection was annotated with @Named (allows JSF to have access to this field) and @Produces (as a simple explanation, a producer field suppress the getter method)): The built-in qualifiers @Default and @Any The output is in figure below: From http://e-blog-java.blogspot.com/2011/04/built-in-qualifiers-default-and-any.html
April 21, 2011
by A. Programmer
· 8,876 Views
article thumbnail
Don't Use JmsTemplate in Spring!
JmsTemplate is easy for simple message sending. What if we want to add headers, intercept or transform the message? Then we have to write more code. So, how do we solve this common task with more configurability in lieu of more code? First, lets review JMS in Spring. Spring JMS Options JmsTemplate – either to send and receive messages inline Use send()/convertAndSend() methods to send messages Use receive()/receiveAndConvert() methods to receive messages. BEWARE: these are blocking methods! If there is no message on the Destination, it will wait until a message is received or times out. MessageListenerContainer – Async JMS message receipt by polling JMS Destinations and directing messages to service methods or MDBs Both JmsTemplate and MessageListenerContainer have been successfully implemented in Spring applications, if we have to do something a little different, we introduce new code. What could possibly go wrong? Future Extensibility? On many projects new use-cases arise, such as: Route messages to different destinations, based on header values or contents? Log the message contents? Add header values? Buffer the messages? Improved response and error handling? Make configuration changes without having to recompile? and more… Now we have to refactor code and introduce new code and test cases, run it through QA, etc. etc. A More Configurable Solution! It is time to graduate Spring JmsTemplate and play with the big kids. We can easily do this with a Spring Integration flow. How it is done with Spring Integration Here we have a diagram illustrating the 3 simple components to Spring Integration replacing the JmsTemplate send. Create a Gateway interface – an interface defining method(s) that accept the type of data you wish to send and any optional header values. Define a Channel – the pipe connecting our endpoints Define an Outbound JMS Adapter – sends the message to your JMS provider (ActiveMQ, RabbitMQ, etc.) Simply inject this into our service classes and invoke the methods. Immediate Gains Add header & header values via the methods defined in the interface Simple invokation of Gateway methods from our service classes Multiple Gateway methods Configure method level or class level destinations Future Gains Change the JMS Adapter (one-way) to a JMS Gateway (two-way) to processes responses from JMS We can change the channel to a queue (buffered) channel We can wire in a transformer for message transformation We can wire in additional destinations, and wire in a “header (key), header value, or content based” router and add another adapter We can wire in other inbound adapters receiving data from another source, such as SMTP, FTP, File, etc. Wiretap the channel to send a copy of the message elsewhere Change the channel to a logging adapter channel which would provide us with logging of the messages coming through Add the “message-history” option to our SI configuration to track the message along its route and more… Optimal JMS Send Solution The Spring Integration Gateway Interface Gateway provides a one or two way communication with Spring Integration. If the method returns void, it is inherently one-way. The interface MyJmsGateway, has one Gateway method declared sendMyMessage(). When this method is invoked by your service class, the first argument will go into a message header field named “myHeaderKey”, the second argument goes into the payload. package com.gordondickens.sijms; import org.springframework.integration.annotation.Gateway;import org.springframework.integration.annotation.Header; public interface MyJmsGateway { @Gateway public void sendMyMessage(@Header("myHeaderKey") String s, Object o);} Spring Integration Configuration Because the interface is proxied at runtime, we need to configure in the Gateway via XML. Sending the Message package com.gordondickens.sijms; import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration("classpath:/com/gordondickens/sijms/JmsSenderTests-context.xml")@RunWith(SpringJUnit4ClassRunner.class)public class JmsSenderTests { @Autowired MyJmsGateway myJmsGateway; @Test public void testJmsSend() { myJmsGateway.sendMyMessage("myHeaderValue", "MY PayLoad"); } Summary Simple implementation Invoke a method to send a message to JMS – Very SOA eh? Flexible configuration Reconfigure & restart WITHOUT recompiling – SWEET!
April 21, 2011
by Gordon Dickens
· 84,939 Views
article thumbnail
Converting a Spring SimpleFormController into an @Controller
In my previous post, I showed how to convert a Spring web controller class to use the @Controller annotation. In this post, I aim to show how forms in a Spring MVC application can also be converted to using annotations. Forms in Spring are typically modelled by extending the org.springframework.web.servlet.mvc.SimpleFormController class, but using Spring annotations, they can also be simplified and defined by the @Controller annotation.Without annotations, a SimpleFormController would be defined as below as in both a Java class and as a bean in XML. import org.springframework.web.servlet.mvc.SimpleFormController public class PriceIncreaseFormController extends SimpleFormController { public ModelAndView onSubmit(Object command) { // Submit the form } protected Object formBackingObject(HttpServletRequest request) throws ServletException { // Initialize the form } } To convert the class to use annotations, we need to add an @Controller and @RequestMapping annotation. We can then define a simple POJO controller that does not need to extend Spring's classes. @Controller @RequestMapping("/priceincrease.htm") public class PriceIncreaseFormController { @Autowired private PriceIncreaseValidator priceIncreaseValidator; @RequestMapping(method=RequestMethod.POST) public String onSubmit(@ModelAttribute("priceIncrease")PriceIncrease priceIncrease, BindingResult result) { int increase = priceIncrease.getPercentage(); priceIncreaseValidator.validate(increase, result); if (result.hasErrors()) return "priceIncrease"; // Validator has succeeded. // Perform necessary actions and return to success page. return "redirect:home.htm"; } @RequestMapping(method=RequestMethod.GET) public String initializeForm(ModelMap model) { // Perform and Model / Form initialization Map priority = new LinkedHashMap(); priority.put(1, "Low"); priority.put(2, "Normal"); priority.put(3, "High"); model.addAttribute("priorityList", priority); return "priceincrease"; } // Other getters and setters an needed. } After defining the class like this, there is no need for the class to be defined within the Spring Context XML file. The two methods outlined above in this simple class show how the initializeForm() method is called when an HTTP GET request is made to the form and how the form is submitted in the onSubmit() method via a HTTP POST request. The method called on a GET request is used to initialize the form, whereas the method called on a POST request is called when the form is submitted. The final thing to notice from this class is that the validation has to be explicitly called within the onSubmit() method. In this example, the PriceValidator is injected into the class via the @Autowired annotation. From http://www.davidsalter.co.uk/1/post/2011/04/converting-a-spring-simpleformcontroller-into-an-controller.html
April 20, 2011
by David Salter
· 60,186 Views · 8 Likes
article thumbnail
HTML encoding/escaping with StringTemplate and Spring MVC
Last week my colleague T.C. and I had to work out how to HTML encode the values entered by the user when redisplaying those onto the page to prevent a cross site scripting attack on the website. I wrote a blog post a couple of years ago describing how to do this in ASP.NET MVC and the general idea is that we need to have a custom renderer which HTML encodes any strings that pass through it. In our case this means that we needed to write a custom renderer for String Template and hook that into Spring MVC. We already had a view class StringTemplateView so we needed to add to that class and add our custom renderer. The viewResolver was defined like so: @Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/templates/"); viewResolver.setViewClass(StringTemplateView.class); viewResolver.setSuffix(".st"); return viewResolver; } And after some guidance from Jim we changed StringTemplateView to look like this: public class StringTemplateView extends InternalResourceView { @Override protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { String templateRootDir = format("%s/WEB-INF/templates", getServletContext().getRealPath("/")); StringTemplateGroup group = new StringTemplateGroup("view", templateRootDir); StringTemplate template = group.getInstanceOf(getBeanName()); AttributeRenderer htmlEncodedRenderer = new HtmlEncodedRenderer(); template.registerRenderer(String.class, htmlEncodedRenderer); ... } private class HtmlEncodedRenderer implements AttributeRenderer { @Override public String toString(Object o) { return HtmlUtils.htmlEscape(o.toString()); } @Override public String toString(Object o, String formatName) { return HtmlUtils.htmlEscape(o.toString()); } } } At the moment we want to HTML encode everything that we render through StringTemplate but if that changes then we could make use of the formatName parameter which we’re currently ignoring. In retrospect this looks pretty simple to do but my Googling skills were pretty much failing me at the time so I thought it’d be good to document. From http://www.markhneedham.com/blog/2011/04/09/html-encodingescaping-with-stringtemplate-and-spring-mvc
April 19, 2011
by Mark Needham
· 24,266 Views · 15 Likes
article thumbnail
Hammurabi - A Scala Rule Engine
One of the most common reasons why software projects fail, or suffer unbearable delays, is the misunderstandings between the analysts who define the business rules of the domain for which the software is going to be written and the developers who have to code these rules. The latter write those rules in a language that is completely obscure for the first ones. In this way the business analysts don't have a chance to read, understand and validate what the programmers developed and then they can only empirically test the final software behavior, hardly covering all the possible corner cases and often recognizing mistakes only when it is too late. What Hammurabi is Hammurabi is a rule engine written in Scala that tries to leverage the features of this language making it particularly suitable to implement extremely readable internal Domain Specific Languages. Indeed, what actually makes Hammurabi different from all other rule engines is that it is possible to write and compile its rules directly in the host language. Anyway the Hammurabi's rules also have the important property of being readable even by non technical person. As usual a practical example worth more than a thousand words. The golfers problem This logical puzzle has been taken from the first chapter of the Jess in Action book written by Ernest Friedman-Hill and published by Manning. It is described there as it follows: A foursome of golfers is standing at a tee, in a line from left to right. Each golfer wears different colored pants; one is wearing red pants. The golfer to Fred’s immediate right is wearing blue pants. Joe is second in line. Bob is wearing plaid pants. Tom isn’t in position one or four, and he isn’t wearing the hideous orange pants. In what order will the four golfers tee off, and what color are each golfer’s pants?” The Jess solution Jess is written in Java and is one of the most popular rule engine on the market. The solution to the golfers problems presented in the book mentioned above is the following: first it is necessary to define the data structures representing the problem (deftemplate pants-color (slot of) (slot is)) (deftemplate position (slot of) (slot is)) A deftemplate is a bit like a class declaration in Java and in this case is used to write a first rule that in turns creates the facts representing each of the possible combinations of golfers, pants-color and positions: (defrule generate-possibilities => (foreach ?name (create$ Fred Joe Bob Tom) (foreach ?color (create$ red blue plaid orange) (assert (pants-color (of ?name)(is ?color))) ) (foreach ?position (create$ 1 2 3 4) (assert (position (of ?name)(is ?position))) ) ) ) After that it is possible to translate the sentences of the problem in the corresponding Jess rule: (defrule find-solution ;; There is a golfer named Fred, whose position is ?p1 ;; and pants color is ?c1 (position (of Fred) (is ?p1)) (pants-color (of Fred) (is ?c1)) ;; The golfer to immediate right of Fred ;; is wearing blue pants. (position (of ?n&~Fred)(is ?p&:(eq ?p (+ ?p1 1)))) (pants-color (of ?n&~Fred)(is blue&~?c1)) ;; Joe is in position #2 (position (of Joe) (is ?p2&2&~?p1)) (pants-color (of Joe) (is ?c2&~?c1)) ;; Bob is wearing the plaid pants (position (of Bob)(is ?p3&~?p1&~?p&~?p2)) (pants-color (of Bob&~?n)(is plaid&?c3&~?c1&~?c2)) ;; Tom is not in position 1 or 4 ;; and is not wearing orange (position (of Tom&~?n)(is ?p4&~1&~4&~?p1&~?p2&~?p3)) (pants-color (of Tom)(is ?c4&~orange&~blue&~?c1&~?c2&~?c3)) => (printout t Fred " " ?p1 " " ?c1 crlf) (printout t Joe " " ?p2 " " ?c2 crlf) (printout t Bob " " ?p3 " " ?c3 crlf) (printout t Tom " " ?p4 " " ?c4 crlf) ) where the rows starting with ;; are just comments. In this way if you enter the code for the problem into Jess and then run it, you get the answer directly: Fred 1 orange Joe 2 blue Bob 4 plaid Tom 3 red Note that the facts that the golfers are in different positions and wear pants of different colors is not expressed in an explicit rule but need to be spread and repeated in many statements. This solution is clearly difficult to be maintained and doesn't scale well as underlined by the last condition statement stating that the position ?p4 of Tom is ?p4&~1&~4&~?p1&~?p2&~?p3 where ~ means not in the Jess language. In other words it says that the Tom's position is not only different from the position 1 and 4 but it is also different from the positions of all the other golfers (named one by one) formerly defined. Actually the needs to describe a golfer's position also as the negation of the positions of all the other golfers implies something even worse: it is not possible to translate each sentence of the problem in a different rule, but they have to be combined together in a single big rule. After this huge if part, its then section (the one after the => symbol) prints out a table containing the set of variables ?p1…?p4 and ?c1…?c4 that solves the problem. The Hammurabi solution As done while presenting the Jess solution, also with Hammurabi the first thing to do is to define the domain of the problem. In order to do that, since the Hammurabi rules are valid Scala statements, it is sufficient to create a plain Scala Person class having as attributes the name, the position and the color of the pants of the golfer that it represents: class Person(n: String) { val name = n var pos: Int = _ var color: String = _ } Then we can model the fact that all the golfers must have different position and pants color by putting them in 2 different Set: var availablePos = (1 to 4).toSet var availableColors = Set("blue", "plaid", "red", "orange") and write two small methods that pull off them from the corresponding set once they have been assigned to a specific golfer: val assign = new { def color(color: String) = new { def to(person: Person) = { person.color = color availableColors = availableColors - color } } def position(pos: Int) = new { def to(person: Person) = { person.pos = pos availablePos = availablePos - pos } } } Those methods are written in a quite weird way just to make even more readable the DSL that will be used to define the rules and to stress the idea that it is possible to write the rules in a valid Scala that could be easily understood by a non-technical person. Of course it is easy to go even further by encapsulating other concepts in some convenient methods as it has been done above. Now everything is ready to write the set of rules describing the golfers problem: val ruleSet = Set( rule ("Unique positions") let { val p = any(kindOf[Person]) when { (availablePos.size equals 1) and (p.pos equals 0) } then { assign position availablePos.head to p } }, rule ("Unique colors") let { val p = any(kindOf[Person]) when { (availableColors.size equals 1) and (p.color == null) } then { assign color availableColors.head to p } }, rule ("Joe is in position 2") let { val p = any(kindOf[Person]) when { p.name equals "Joe" } then { assign position 2 to p } }, rule ("Person to Fred’s immediate right is wearing blue pants") let { val p1 = any(kindOf[Person]) val p2 = any(kindOf[Person]) when { (p1.name equals "Fred") and (p2.pos equals p1.pos + 1) } then { assign color "blue" to p2 } }, rule ("Fred isn't in position 4") let { val possibleFredPos = availablePos - 4 val p = any(kindOf[Person]) when { (p.name equals "Fred") and (possibleFredPos.size == 1) } then { assign position possibleFredPos.head to p } }, rule ("Tom isn't in position 1 or 4") let { val possibleTomPos = availablePos - 1 - 4 val p = any(kindOf[Person]) when { (p.name equals "Tom") and (possibleTomPos.size equals 1) } then { assign position possibleTomPos.head to p } }, rule ("Bob is wearing plaid pants") let { val p = any(kindOf[Person]) when { p.name equals "Bob" } then { assign color "plaid" to p } }, rule ("Tom isn't wearing orange pants") let { val possibleTomColors = availableColors - "orange" val p = any(kindOf[Person]) when { (p.name equals "Tom") and (possibleTomColors.size equals 1) } then { assign color possibleTomColors.head to p } } ) Here the first 2 rules explicitly leverage the uniqueness of positions and pants colors by assigning the last available of them to the only person who still doesn't have one. The other rules just match one by one the sentences of the problem as it has been defined. Now it is possible to make Hammurabi solve the problem by creating the four golfers: val tom = new Person("Tom") val joe = new Person("Joe") val fred = new Person("Fred") val bob = new Person("Bob") add them to a working memory (the set of objects against which the rule engine will evaluate and fire the rules): val workingMemory = WorkingMemory(tom, joe, fred, bob) and letting the rule engine, initialized with the formerly defined set of rules, to work on it: RuleEngine(ruleSet) execOn workingMemory Working with immutable data structures Immutability is probably not something that should be enforced at all costs in Hammurabi, for a very simple reason: the largest part of the execution time is spent by Hammurabi, like all other rule engines, looking for rules that can actually be executed (fired), i.e. the ones for which the when condition is true. During this phase data are only read and never written, so immutability doesn't matter at all, and all the rules that can be fired are put in an agenda. During the subsequent phase the rules in the agenda MUST be fired one by one, since the execution of one of them could make false the when condition of another one. It means that lack of immutability shouldn't prevent the rule engine to safely run in parallel during the discovery phase. That said, it is also possible to obtain the same result working with immutable data structures. For example having an immutable person: case class Person(name: String, pos: Int = 0, color: String = null) it's enough to rewrite the methods that assign the position and pants color to the golfers as it follows: val assign = new { def color(color: String) = new { def to(person: Person) = { remove(person) produce(person.copy(color = color)) availableColors = availableColors - color } } def position(pos: Int) = new { def to(person: Person) = { remove(person) produce(person.copy(pos = pos)) availablePos = availablePos - pos } } } leaving all the rules unchanged. In this way the old version of the Person is removed from the working memory and a brand new one, with its position or color set accordingly to the fired rule, is produced and then added to the working memory itself. The methods remove and produce can be indeed used respectively to remove objects from the working memory and produce new objects, that could be then used to evaluate and fire other rules. Hammurabi internals In Hammurabi all the rules are evaluated (but not fired) in parallel basically by assigning each rule to a different Scala actor. The replacement of this actor implementation with one based on the upcoming Scala parallel collections is currently under evaluation but I decided to wait until this technology will be stable. As anticipated, the evaluation of the rule in parallel is safe because is a read only process. While the actors discover set of variables that can fire the rules they are evaluating, they add them to the rule engine's agenda. At the end of this evaluation process the rules are fired sequentially one by one after a re-evaluation of their application condition, because the execution of one of them could change the result of that condition for a subsequent one. All the rules are fired in no particular order unless a different priority has been specified for some of them. Indeed since sometimes there could be the need to treat some rules as special cases they have an optional property called salience that acts as a priority setting for that rule in order to allow activated rules with the highest salience to always fire first, followed by rules of lower salience. By default all rules have salience 0 but you can alter it in the rule definition as it follows: rule ("Important rule") withSalience 10 let { ... } rule ("Negligible rule") withSalience -5 let { ... } Each actor also records the set of values on which the rule it is responsible for has been already executed, in order to don't fire again the same rule on the same values. The evaluation phase and the firing one are then executed again and again until either there is no rule that can be fired or one of the rule during its firing phase invokes one of the methods exitWith, making the rule engine gracefully finishing returning a value representing the result of the whole evaluation process or failWith that cause the rule engine to terminate by throwing an exception. Of course if the rule engine stops just because there are no longer rules that can be fired, the result of the evaluation is represented by the whole working set (as in the former example) and you can read from there the values you are interested in. Further implementations and improvements At the moment it is only possible to take from the working memory the object(s) against which a given rule will be evaluated only selecting them by type, as shown in the statement: val p = any(kindOf[Person]) Further mechanisms to categorize and select those objects in a more precise way are under evaluation, even if it is already possible to limit them with a Boolean function as in the following example: val p = kindOf[Person] having (_.name == "Joe") This is useful also under a performance point of view because it dramatically lowers the number of combination that the rule engine needs to check before to find a rule that can be fired. For example the "Person to Fred’s immediate right is wearing blue pants" rule could be rewritten as it follows bringing the number of combination that has to be tried from 16 to 4: rule ("Person to Fred’s immediate right is wearing blue pants") let { val p1 = kindOf[Person] having (_.name == "Fred") val p2 = any(kindOf[Person]) when { p2.pos equals p1.pos + 1 } then { assign color "blue" to p2 } } I am also evaluating of directly feeding the working memory with a NoSQL database. In other words, with this solution, the data present in the db could represent the working memory itself. At the moment I am experimenting with MongoDB since is the one I know best, but if somebody has some other good idea or even better wants to collaborate with this project I'd be very glad of it. The version 0.1 of the Hammurabi rule engine has been just released and it is available here.
April 18, 2011
by Mario Fusco
· 27,917 Views
article thumbnail
Converting a Spring Controller into a @Controller
In the Spring Web Framework, its typical to implement a Controller as a class that implements org.springframework.web.servlet.mvc.Controller, for example: public class InventoryController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handle the request here } } This class would then be defined within an application's Spring context XML file (typically appname-servlet.xml) ... Using Spring annotations however, its possible to remove the need to implement the org.springframework.web.servlet.mvc.controller and remove the bean definition within the XML file. To change the Controller class to use annotations, the class needs to be annotated with the @Controller and @RequestMapping annotations as shown below. The method that will handle the request also needs to be annotated with the @RequestMapping. Note that this method no longer needs to confirm to the same signature as defined in org.springframework.web.servlet.mvc.Controller and now simply returns a ModelAndView instance. @Controller @RequestMapping("/home.htm") public class InventoryController { @RequestMapping(method=RequestMethod.GET) public ModelAndView handleRequest() { // Handle the request here } } Now that we've redefined the Controller class, we can remove the bean definition from the application's context file. The final stage then to allow Spring to use the annotated Controller is to specify in the application's context file that we want to use annotations. This is achieved by adding the annotation into the application context file. ... From http://www.davidsalter.co.uk/1/post/2011/04/converting-a-spring-controller-into-a-controller.html
April 15, 2011
by David Salter
· 18,505 Views
article thumbnail
Clojure: State Management
Those unfamiliar with Clojure are often interested in how you manage changing state within your applications. If you've heard a few things about Clojure but haven't really looked at it, I wouldn't be surprised if you thought it was impossible to write a "real" application with Clojure since "everything is immutable". I've even heard a developer that I respect make the mistake of saying: we're not going to use Clojure because it doesn't handle state well. Clearly, state management in Clojure is greatly misunderstood. I actually had a hard time not calling this blog entry "Clojure, it's about state". I think state shapes Clojure more than any other influence; it's the core of the language (as far as I can tell). Rich Hickey has clearly spent a lot of time thinking about state - there's an essay at http://clojure.org/state which describes common problems with a traditional approach to state management and Clojure's solutions. Rich's essay does a good job of succinctly discussing his views on state; you should read it before you continue with this entry. The remainder of this entry will give examples of how you can manage state using Clojure's functions. At the end of Rich's essay he says: In the local case, since Clojure does not have mutable local variables, instead of building up values in a mutating loop, you can instead do it functionally with recur or reduce. Before we get to reduce, let's start with the simplest example. You have an array of ints and you want to double each integer. In a language with mutable state you can loop through the array and build a new array with each integer doubled. for (int i=0; i < nums.length; i++) { result.add(nums[i] * 2); } In Clojure you would build the new array by calling the map function with a function that doubles each value. (I'm using Clojure 1.2) user=> (map (fn [i] (* i 2)) [1 2 3]) (2 4 6) If you're new to Clojure there's a few things worth mentioning. "user=>" is a REPL prompt. You enter some text and hit enter and the text is evaluated. If you've completed the list (closed the parenthesis), the results of evaluating that list will be printed to the following line. I remember what I thought the first time I looked at a lisp, and I know the code might not look like readable code, so here's a version that breaks up a few of the concepts and might make it easier to digest the example. user=> (defn double-int [i] (* i 2)) #'user/double-int user=> (def the-array [1 2 3]) #'user/the-array user=> (map double-int the-array) (2 4 6) In the first Clojure example you call the fn function to create an anonymous function, that was then passed to the map function (to be applied to each element of the array). The map function is a high order function that can take an anonymous function (example 1) or a named function (double-int, example 2). In Clojure (def ...) is a special form that allows you to define a var and defn is a function that allows you to easily define a function and assign it to a var. The syntax for defn is pretty straightforward, the first argument is the name, the second argument is the argument list of the new function, and any additional forms are the body of the function you are defining. Once you get used to Clojure's syntax you can even have a bit of fun with your function naming that might result in concise and maintainable code. user=> (defn *2 [i] (* 2 i)) #'user/*2 user=> (map *2 [1 2 3]) (2 4 6) but, I digress. Similarly, you may want to sum the numbers from an array. for (int i = 0; i < nums.length; i++) { result += nums[i]; } You can achieve goal of reducing an array to a single value in Clojure using the reduce function. user=> (reduce + [1 2 3]) 6 Clojure has several functions that allow you to create new values from existing values, which should be enough to solve any problem where you would traditionally use local mutable variables. For non-local mutable state you generally have 3 options: atoms, refs, and agents. When I started programming in Clojure, atoms were my primary choice for mutable state. Atoms are very easy to use and only require that you know a few functions to interact with them. Let's assume we're building a trading application that needs to keep around the current price of Apple. Our application will call our apple-price-update function when a new price is received and we'll need to keep that price around for (possible) later usage. The example below shows how you can use an atom to track the current price of Apple. user=> (def apple-price (atom nil)) #'user/apple-price user=> (defn update-apple-price [new-price] (reset! apple-price new-price)) #'user/update-apple-price user=> @apple-price nil user=> (update-apple-price 300.00) 300.0 user=> @apple-price 300.0 user=> (update-apple-price 301.00) 301.0 user=> (update-apple-price 302.00) 302.0 user=> @apple-price 302.0 The above example demonstrates how you can create a new atom and reset its value with each price update. The reset! function sets the value of the atom synchronously and returns its new value. You can also query the price of apple at any time using @ (or deref). If you're coming from a Java background the example above should be the easiest to relate to. Each time we call the update-apple-price function our state is set to a new value. However, atoms provide much more value than simply being a variable that you can reset. You may remember the following example from Java Concurrency in Practice. @NotThreadSafe public class UnsafeSequence { private int value; /** * Returns a unique value. */ public int getNext() { return value++; } } The book explains why this could cause potential problems. The problem with UnsafeSequence is that with some unlucky timing, two threads could call getNext and receive the same value. The increment notation, nextValue++, may appear to be a single operation, but is in fact three separate operations: read the value, add one to it, and write out the new value. Since operations in multiple threads may be arbitrarily interleaved by the runtime, it is possible for two threads to read the value at the same time, both see the same value, and then both add one to it. The result is that the same sequence number is returned from multiple calls in different threads. We could write a get-next function using a Clojure atom and the same race condition would not be a concern. user=> (def uniq-id (atom 0)) #'user/uniq-id user=> (defn get-next [] (swap! uniq-id inc)) #'user/get-next user=> (get-next) 1 user=> (get-next) 2 The above code demonstrates the result of calling get-next multiple times (the inc function just adds one to the value passed in). Since we aren't in a multithreaded environment the example isn't exactly breathtaking; however, what's actually happening under the covers is described very well on clojure.org/atoms - [Y]ou change the value by applying a function to the old value. This is done in an atomic manner by swap! Internally, swap! reads the current value, applies the function to it, and attempts to compare-and-set it in. Since another thread may have changed the value in the intervening time, it may have to retry, and does so in a spin loop. The net effect is that the value will always be the result of the application of the supplied function to a current value, atomically. Also, remember that changes to atoms are synchronous, so our get-next function will never return the same value twice. (note: while Java already provides an AtomicInteger class for handling this issue - that's not the point. The point of the example is to show that an Atom is safe to use across threads.) If you're truly interested in verifying that an atom is safe across threads, The Joy of Clojure provides the following snippet of code (as well as a wonderful explanation of all things Clojure, including mutability). (import '(java.util.concurrent Executors)) (def *pool* (Executors/newFixedThreadPool (+ 2 (.availableProcessors (Runtime/getRuntime))))) (defn dothreads [f & {thread-count :threads exec-count :times :or {thread-count 1 exec-count 1}] (dotimes [t thread-count] (.submit *pool* #(dotimes [_ exec-count] (f))))) (def ticks (atom 0)) (defn tick [] (swap! ticks inc)) (dothreads tick :threads 1000 :times 100) @ticks ;=> 100000 There you have it, 1000 threads updated ticks 100 times without issue. Atoms work wonderfully when you want to insure atomic updates to an individual piece of state; however, it probably wont be long before you find yourself wanting to coordinate some type of state update. For example, if you're running an online store, when a customer cancels an order the order is either active or cancelled; however, the order should never be active and cancelled. If you were to keep a set of active orders and a set of cancelled orders, you would never want to have an order be in both sets at the same time. Clojure addresses this issue by using refs. Refs are similar to atoms, but they also participate in coordinated updates. The following example shows the cancel-order function moving an order-id from the active orders set into the cancelled orders set. user=> (def active-orders (ref #{2 3 4})) #'user/active-orders user=> (def cancelled-orders (ref #{1})) #'user/cancelled-orders user=> (defn cancel-order [id] (dosync (commute active-orders disj id) (commute cancelled-orders conj id))) #'user/cancel-order user=> (cancel-order 2) #{1 2} user=> @active-orders #{3 4} user=> @cancelled-orders #{1 2} As you can see from the example, we're moving an order id from active to cancelled. Again, our REPL session doesn't show the power of what's going on with a ref, but clojure.org/refs contains a good explanation - All changes made to Refs during a transaction (via ref-set, alter or commute) will appear to occur at a single point in the 'Ref world' timeline (its 'write point'). The above quote is actually only 1 item in a 10 point list that discusses what's actually going on. It's worth reviewing the list a few times until you feel comfortable with everything that's going on. But, you don't need to completely understand everything to get started. You can begin to experiment with refs anytime you know you need coordinated changes to more than one piece of state. When you first begin to look at refs you may wonder if you should use commute or alter. For most cases commute will provide more concurrency and is preferred; however, you may need to guarantee that the ref has not been updated during the life of the current transaction. This is generally the case where alter comes into play. The following example shows using commute to update two values. The example demonstrates that the pairs are always updated only once; however, it also shows that the function is simply applied to the current value, so the incrementing is not sequential and @uid can be dereferenced to the same value multiple times. user=> (def uid (ref 0)) #'user/uid user=> (def used-id (ref [])) #'user/used-id user=> (defn use-id [] (dosync (commute uid inc) (commute used-id conj @uid))) #'user/use-id user=> (dothreads use-id :threads 10 :times 10) nil user=> @used-id [1 2 3 4 5 6 7 8 9 10 ... 89 92 92 94 93 94 97 97 99 100] The above example shows that commute simply applies regardless of the underlying value. As a result, you may see duplicate values and gaps in your sequence (shown in the 90s in our output). If you wanted to ensure that the value didn't change during your transaction you could switch to alter. The following example shows the behavior of changing from commute to alter. user=> (def uid (ref 0)) #'user/uid user=> (def used-id (ref [])) #'user/used-id user=> (defn use-id [] (dosync (alter uid inc) (alter used-id conj @uid))) #'user/use-id user=> (dothreads use-id :threads 10 :times 10) nil user=> @used-id [1 2 3 4 5 6 7 8 9 10 ... 91 92 93 94 95 96 97 98 99 100] There are more advanced examples using refs in The Joy of Clojure for those of you looking to discuss corner case conditions. Last, but not least, agents are also available. From clojure.org/agents - Like Refs, Agents provide shared access to mutable state. Where Refs support coordinated, synchronous change of multiple locations, Agents provide independent, asynchronous change of individual locations. While I understand agents conceptually, I haven't used them much in practice. Some people love them, and the last team I was on switched to using agents heavily in one of our applications shortly after I left. But, I personally don't have enough experience to say exactly where I think they fit in. I'm sure that will be a topic for a future blog post. Between Rich's essay and the examples above I hope a few things have become clear: Clojure has plenty of support for managing state Rich's distinction between identity and value allows Clojure to benefit from immutable structures while also allowing identity reassignment. Clojure, it's about state. From http://blog.jayfields.com/2011/04/clojure-state-management.html
April 13, 2011
by Jay Fields
· 9,876 Views
article thumbnail
Introduction to Efficient Java Matrix Library (EJML)
Linear algebra is a commonly used area of mathematics with a wide range of applications in various engineering and scientific fields. Examples of applications include line fitting, Kalman filters, face recognition, financial software, and numerical optimization to name a few. Many computer libraries have been developed for linear algebra. One of the better known would be LAPACK, which was originally programmed in Fortran. Introducing Efficient Java Matrix Library The following article provides a brief introduction to one of the newer linear algebra libraries for Java, Efficient Java Matrix Library (EJML), a free open source library. EJML is a linear algebra library for dense real matrices. EJML's design goals are; 1) to be as computationally and memory efficient as possible for both small and large matrices, and 2) to be accessible to both novices and experts. These goals are accomplished by dynamically selecting the best algorithms to use at runtime and through a thoughtfully designed clean API. Providing good documentation, code examples, and constant benchmarking for speed, memory, and stability are also priorities. The following functionality is provided: Basic Operators (addition, multiplication, ... ) Matrix Manipulation (extract, insert, combine, ... ) Linear Solvers (linear, least squares, incremental, ... ) Decompositions (LU, QR, Cholesky, SVD, Eigenvalue, ...) Matrix Features (rank, symmetric, definitiveness, ... ) Random Matrices (covariance, orthogonal, symmetric, ... ) Different Internal Formats (row-major, block) Unit Testing EJML can be downloaded from its website at: http://ejml.org/ Application Programming Interface There are three primary ways to interact with EJML, 1) a simple to use object oriented interface, 2) procedural interface that provides greater control over memory and algorithms, 3) an expert interface that directly access specialized algorithms that is abstracted away using the first two. To see a practical comparison of these three interfaces take a look at the Kalman filter example provided at EJML's website. There each interface is used to code up a functionally identical Kalman filter: Here are three code sniplets showing the Kalman gain being computed: Simple: SimpleMatrix K = P.mult(H.transpose().mult(S.invert())); Procedural: if( !invert(S,S_inv) ) throw new RuntimeException("Invert failed"); multTransA(H,S_inv,d); mult(P,d,K); Specialized: if( !solver.setA(S) ) throw new RuntimeException("Invert failed"); solver.invert(S_inv); MatrixMatrixMult.multTransA_small(H,S_inv,d); MatrixMatrixMult.mult_small(P,d,K); The full examples are available at: http://ejml.org/wiki/index.php?title=Example_Kalman_Filter Going beyond the basics, there are easy to use yet powerful Java interfaces for solving linear systems and matrix decompositions. These provide much more control over the type of algorithm used, what it computes, how much memory is used, and remove as much of the drudgery as possible. DecompositionFactory and LinearSolverFactory are provided for creating these solvers and decompositions. By using the factory the best most update algorithm will be automatically selected. EJML offer many different decomposition algorithms, even within the same family. For instance, there are four QR decompositions provided, each of which is catered towards a different sized matrix. Different factories hide much of these detail from the end user. Who is using EJML? Even though EJML is a fairly new library it has already been picked up by several opensource projects: goGPS: http://code.google.com/p/gogps/ Set Visualiser: http://www-edc.eng.cam.ac.uk/tools/set_visualiser/ Universal Java Matrix Library (UJML): http://www.ujmp.org/ Scalalab: http://code.google.com/p/scalalab/ Java Content Based Image Retrieval (JCBIR): http://code.google.com/p/jcbir/ JquantLib (Will be added): http://www.jquantlib.org/ Performance and Benchmarks What about speed, stability, and correctness? Constant benchmarking for speed and stability is a core part of EJML's development. It has many internal benchmarks and also uses Java Matrix Benchmark (JMatBench)[1] (http://code.google.com/p/java-matrix-benchmark/) to compare its performance against other libraries. At the time of this writing there are a total of 551 unit tests that test basic correctness of almost all the functions in EJML. For runtime performance EJML is one of the fastest single threaded libraries. When compared against multi-threaded libraries on systems with several cores/CPU's it still competitive for many operations, despite its disadvantage of being single threaded. It has one of the lowest memory footprints [2]. A brief summary of EJML's performance relative to other libraries is shown below. Runtime performance is measured on a Core i7M620 system. (2 cores with 4 threads) Performance varies significantly by system. This processor was choosen because it is the most modern system benchmarked. Click here to get a explaination of the plots shown below. [1] Both EJML and JMatBench are developed by the same author. [2] Memory usage is highly dependent on the operation being used and the parameters passed to it. JMatBench only tests a few operations, but at least it shows attention is being paid to memory usage.
April 12, 2011
by Peter Abeles
· 7,082 Views
article thumbnail
Practical PHP Testing Patterns: Parameterized Test
Sometimes the mechanics of different tests are really the same, and the only thing that changes between them are input and expected output data. As an example, consider testing mathematical calculations functions, or any kind of stateless method: you invoke it always in the same way, and then check the returned value. Another case is that of triangulation in Test-Driven Development. When an implementation is not obvious, triangulating it leads to the creation of multiple tests with different data, but usually the exact same procedure. To eliminate the duplication between these tests, we can code a method which models the whole test, and that accepts input (and possible initial state) and expected output as parameters. This method will perform the arrange, act, assert, and even teardown phases if needed. It will eliminate the need for maintaining the same test code in different places, of course. An advantage of these refactorings that we already cited in Test Utility Method is that adding a new test becomes equivalent to adding one or two lines of code. This pattern is really a specialized, standalone Test Utility Method. Implementation A simple form of Parameterized Test is a private method which is delegated from in the various test*() ones, which are called by the testing framework. The advantage of this first approach is to present more clear names to the code reader, and to support possible additional work to perform after the method is executed (it may return something which we can make further assertions on.) A second way of implementing Parameterized Test is with PHPUnit's @dataProvider annotation. Is it completely automatic, and displays data used in the test instance in case of failure in order to recognize which iteration we are in. You can also prepare input and output for @dataProvider programmatically (read: with code), so with a process as flexible and complex as you want. Variations Some older versions of Parameterized Test exist. A Loop-Driven Test uses nested loops that verify every combination of inputs/outputs. For example, it may check pairs of x and y coordinates in an image. Often exhaustive testing is an overkill and contains logic for the generation of data which may contain bugs. In a Tabular Test, you have a table, represented as code or in some configuration file, where each row corresponds to one test run and contains the necessary input/output relation. One Test Method works on everything here. This mechanism is obsolete as PHPUnit with @dataProvider executes each instance of the method into a different Testcase Object. You won't observe tests influencing each other, no problem with localization of which row is causing a failure. Example The code sample shows you how to go from a strong duplication between tests to a single copy of the code that uses @dataProvider to be executed N times. It also shows, in the third Testcase Class, how easy is to produce data for the tests with PHP code. assertEquals(0, sqrt(0)); } public function testSquareRootIsCalculatedCorrectlyByPHPFor1() { $this->assertEquals(1, sqrt(1)); } public function testSquareRootIsCalculatedCorrectlyByPHPFor4() { $this->assertEquals(2, sqrt(4)); } public function testSquareRootIsCalculatedCorrectlyByPHPFor9() { $this->assertEquals(3, sqrt(9)); } public function testSquareRootIsCalculatedCorrectlyByPHPFor16() { $this->assertEquals(4, sqrt(16)); } public function testSquareRootIsCalculatedCorrectlyByPHPForMinusOne() { $this->assertEquals('i', sqrt(-1)); } } class ParameterizedTest extends PHPUnit_Framework_TestCase { /** * This should be a static method, returning an array of arrays. * Each row of this table-like array is a set of arguments * for the Test Method. */ public static function squaresAndRoots() { return array( array(0, 0), array(1, 1), array(4, 2), array(9, 3), array(16, 4), array(-1, 'i') ); } /** * The annotation requires as unique argument the name of a public method * in this Testcase Class. * @dataProvider squaresAndRoots */ public function testSquareRootIsCalculatedCorrectlyByPHP($square, $root) { $this->assertEquals($root, sqrt($square)); } } class ProgrammaticDataProviderTest extends PHPUnit_Framework_TestCase { private static $width = 5; private static $height = 10; /** * I don't know why these methods are required to be static. It makes * no difference however as we are never going to call it directly. */ public static function everyCoupleOfCoordinates() { $testParameters = array(); for ($x = 1; $x <= self::$width; $x++) { for ($y = 1; $y <= self::$height; $y++) { $testParameters[] = array($x, $y); } } return $testParameters; } /** * I don't advise you to test an image at every pixel, but in some cases * you may need an exhaustive search. The programmatic generation of data * keeps the test code really short, but don't forget that the generation * logic may hide bugs if it becomes too complex. * @dataProvider everyCoupleOfCoordinates */ public function testImageHasCorrectTransparencyValue($x, $y) { $this->fail("This test will be executed in isolation with the x=$x and y=$y values."); } }
April 11, 2011
by Giorgio Sironi
· 5,139 Views
article thumbnail
Solr + Hadoop = Big Data Love
Bixo Labs shows how to use Solr as a NoSQL solution for big data Many people use the Hadoop open source project to process large data sets because it’s a great solution for scalable, reliable data processing workflows. Hadoop is by far the most popular system for handling big data, with companies using massive clusters to store and process petabytes of data on thousands of servers. Since it emerged from the Nutch open source web crawler project in 2006, Hadoop has grown in every way imaginable – users, developers, associated projects (aka the “Hadoop ecosystem”). Starting at roughly the same time, the Solr open source project has become the most widely used search solution on planet Earth. Solr wraps the API-level indexing and search functionality of Lucene with a RESTful API, GUI, and lots of useful administrative and data integration functionality. The interesting thing about combining these two open source projects is that you can use Hadoop to crunch the data, and then serve it up in Solr. And we’re not talking about just free-text search; Solr can be used as a key-value store (i.e. a NoSQL database) via its support for range queries. Even on a single server, Solr can easily handle many millions of records (“documents” in Lucene lingo). Even better, Solr now supports sharding and replication via the new, cutting-edge SolrCloud functionality. Background I started using Hadoop & Solr about five years ago, as key pieces of the Krugle code search startup I co-founded in 2005. Back then, Hadoop was still part of the Nutch web crawler we used to extract information about open source projects. And Solr was fresh out of the oven, having just been released as open source by CNET. At Bixo Labs we use Hadoop, Solr, Cascading, Mahout, and many other open source technologies to create custom data processing workflows. The web is a common source of our input data, which we crawl using the Bixo open source project. The Problem During a web crawl, the state of the crawl is contained in something commonly called a “crawl DB”. For broad crawls, this has to be something that works with billions of records, since you need one entry for each known URL. Each “record” has the URL as the key, and contains important state information such as the time and result of the last request. For Hadoop-based crawlers such as Nutch and Bixo, the crawl DB is commonly kept in a set of flat files, where each file is a Hadoop “SequenceFile”. These are just a packed array of serialized key/value objects. Sometimes we need to poke at this data, and here’s where the simple flat-file structure creates a problem. There’s no easy way run queries against the data, but we can’t store it in a traditional database since billions of records + RDBMS == pain and suffering. Here is where scalable NoSQL solutions shine. For example, the Nutch project is currently re-factoring this crawl DB layer to allow plugging in HBase. Other options include Cassandra, MongoDB, CouchDB, etc. But for simple analytics and exploration on smaller datasets, a Solr-based solution works and is easier to configure. Plus you get useful and surprising fun functionality like facets, geospatial queries, range queries, free-form text search, and lots of other goodies for free. Architecture So what exactly would such a Hadoop + Solr system look like? As mentioned previously, in this example our input data comes from a Bixo web crawler’s CrawlDB, with one entry for each known URL. But the input data could just as easily be log files, or records from a traditional RDBMS, or the output of another data processing workflow. The key point is that we’re going to take a bunch of input data, (optionally) munge it into a more useful format, and then generate a Lucene index that we access via Solr. Hadoop For the uninitiated, Hadoop implements both a distributed file system (aka “HDFS”) and an execution layer that supports the map-reduce programming model. Typically data is loaded and transformed during the map phase, and then combined/saved during the reduce phase. In our example, the map phase reads in Hadoop compressed SequenceFiles that contain the state of our web crawl, and our reduce phase write out Lucene indexes. The focus of this article isn’t on how to write Hadoop map-reduce jobs, but I did want to show you the code that implements the guts of the job. Note that it’s not typical Hadoop key/value manipulation code, which is painful to write, debug, and maintain. Instead we use Cascading, which is an open source workflow planning and data processing API that creates Hadoop jobs from shorter, more representative code. The snippet below reads SequenceFiles from HDFS, and pipes those records into a sink (output) that stores them using a LuceneScheme, which in turn saves records as Lucene documents in an index. Tap source = new Hfs(new SequenceFile(CRAWLDB_FIELDS), inputDir); Pipe urlPipe = new Pipe("crawldb urls"); urlPipe = new Each(urlPipe, new ExtractDomain()); Tap sink = new Hfs(new LuceneScheme(SOLR_FIELDS, STORE_SETTINGS, INDEX_SETTINGS, StandardAnalyzer.class, MAX_FIELD_LENGTH), outputDir, true); FlowConnector fc = new FlowConnector(); fc.connect(source, sink, urlPipe).complete(); We defined CRAWLDB_FIELDS and SOLR_FIELDS to be the set of input and output data elements, using names like “url” and “status”. We take advantage of the Lucene Scheme that we’ve created for Cascading, which lets us easily map from Cascading’s view of the world (records with fields) to Lucene’s index (documents with fields). We don’t have a Cascading Scheme that directly supports Solr (wouldn’t that be handy?), but we can make-do for now since we can do simple analysis for this example. We indexed all of the fields so that we can perform queries against them. Only the status message contains normal English text, so that’s the only one we have to analyze (i.e., break the text up into terms using spaces and other token delimiters). In addition, the ExtractDomain operation pulls the domain from the URL field and builds a new Solr field containing just the domain. This will allow us to do queries against the domain of the URL as well as the complete URL. We could also have chosen to apply a custom analyzer to the URL to break it into several pieces (i.e., protocol, domain, port, path, query parameters) that could have been queried individually. Running the Hadoop Job For simplicity and pay-as-you-go, it’s hard to beat Amazon’s EC2 and Elastic Mapreduce offerings for running Hadoop jobs. You can easily spin up a cluster of 50 servers, run your job, save the results, and shut it down – all without needing to buy hardware or pay for IT support. There are many ways to create and configure a Hadoop cluster; for us, we’re very familiar with the (modified) EC2 Hadoop scripts that you can find in the Bixo distribution. Step-by-step instructions are available at http://openbixo.org/documentation/running-bixo-in-ec2/ The code for this article is available via GitHub, at http://github.com/bixolabs/hadoop2solr. The README displayed on that page contains step-by-step instructions for building and running the job. After the job is done, we’ll copy the resulting index out of the Hadoop distributed file system (HDFS) and onto the Hadoop cluster’s master server, then kill off the one slave we used. The Hadoop master is now ready to be configured as our Solr server. Solr On the Solr side of things, we need to create a schema that matches the index we’re generating. The key section of our schema.xml file is where we define the fields. These fields have a one-to-one correspondence with the SOLR_FIELDS we defined in our Hadoop workflow. They also need to use the same Lucene settings as what we defined in the static IndexWorkflow.java STORE_SETTINGS and INDEX_SETTINGS. Once we have this defined, all that’s left is to set up a server that we can use. To keep it simple, we’ll use the single EC2 instance in Amazon’s cloud (m1.large) that we used as our master for the Hadoop job, and run the simple Solr search server that relies on embedded Jetty to provide the webapp container. Similar to the Hadoop job, step-by-step instructions are in the README for the hadoop2solr project on GitHub. But in a nutshell, we’ll copy and unzip a Solr 1.4.1 setup on the EC2 server, do the same for our custom Solr configuration, create a symlink to the index, and then start it running with: Giving it a Try Now comes the interesting part. Since we opened up the default Jetty port used by Solr (8983) on this EC2 instance, we can directly access Solr’s handy admin console by pointing our browser at http://:8983/solr/admin % cd solr % java -Dsolr.solr.home=../solr-conf -Dsolr.data.dir=../solr-data -jar start.jar From here we can run queries against Solr: We can also use curl to talk to the server via HTTP requests: curl http://:8983/solr/select/?q=-status%3AFETCHED+and+-status%3AUNFETCHED The response is XML by default. Below is an example of the response from the above request, where we found 2,546 matches in 94ms. Now here’s what I find amazing. For an index of 82 million documents, running on a fairly wimpy box (EC2 m1.large = 2 virtual cores), the typical response time for a simple query like “status:FETCHED” is only 400 milliseconds, to find 9M documents. Even a complex query such as (status not FETCHED and not UNFETCHED) only takes six seconds. Scaling Obviously we could use beefier boxes. If we switched to something like m1.xlarge (15GB of memory, 4 virtual cores) then it’s likely we could handle upwards of 200M “records” in our Solr index and still get reasonable response times. If we wanted to scale beyond a single box, there are a number of solutions. Even out of the box Solr supports sharding, where your HTTP request can specify multiple servers to use in parallel. More recently, the Solr trunk has support for SolrCloud. This uses the ZooKeeper open source project to simplify coordination of multiple Solr servers. Finally, the Katta open source project supports Lucene-level distributed search, with many of the features needed for production quality distributed search that have not yet been added to SolrCloud. Summary The combination of Hadoop and Solr makes it easy to crunch lots of data and then quickly serve up the results via a fast, flexible search & query API. Because Solr supports query-style requests, it’s suitable as a NoSQL replacement for traditional databases in many situations, especially when the size of the data exceeds what is reasonable with a typical RDBMS. Solr has some limitations that you should be aware of, specifically: · Updating the index works best as a batch operation. Individual records can be updated, but each commit (index update) generates a new Lucene segment, which will impact performance. · Current support for replication, fail-over, and other attributes that you’d want in a production-grade solution aren’t yet there in SolrCloud. If this matters to you, consider Katta instead. · Many SQL queries can’t be easily mapped to Solr queries. The code for this article is available via GitHub, at http://github.com/bixolabs/hadoop2solr. The README displayed on that page contains additional technical details.
April 4, 2011
by Ken Krugler
· 119,670 Views
article thumbnail
Windows PowerShell & ColdFusion Setup
I recently found the Windows PowerShell and can't stop using it. I've setup a couple of helper functions to let me start CF from a simple command in the console. Before you can do anything you need to create a profile script. From within PowerShell you can run $profile to get the expected location for your profile. If you don't already have the file create it now. You will also need to tell PowerShell that it is ok to execute the new script by running Set-ExecutionPolicy Unrestricted You can, and should, read more about script execution. If you have the standard ColdFusion install you can try this script (note: you should change line 1 to point at your correct ColdFusion install, my example shows CF9): new-alias jrun "C:\ColdFusion9\runtime\bin\jrun.exe" function cf($server="coldfusion"){ jrun -start $server } Using MultiServer? Try adding this to your profile script: new-alias jrun "C:\JRun4\bin\jrun.exe" function cf($server="cfusion"){ jrun -start $server } Now, in the console, you can start your default CF servers by simply typing cf If you want to use something other than the default server, like when using multiserver, you can type cf myserver or cf -server myserver To stop the server just type Ctrl+C Happy PowerShell scripting!
March 31, 2011
by Steve Good
· 8,645 Views
  • Previous
  • ...
  • 867
  • 868
  • 869
  • 870
  • 871
  • 872
  • 873
  • 874
  • 875
  • 876
  • ...
  • 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
×