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

article thumbnail
CDI 1.0 vs. Spring 3.1 Feature Comparsion
This blog article provides a comparison matrix between Spring IoC 3.1 and CDI implementation JBoss Weld 1.1.
July 6, 2011
by Niklas Schlimm
· 32,277 Views
article thumbnail
Validating JSF EL Expressions in JSF Pages with static-jsfexpression-validator
update: version 0.9.3 with new group/artifactid released on 7/25 including native support for jsf 1.2 (reflected below in the pom snippet). update: version 0.9.4 with function tolerance for jsf 1.2 released on 7/28 (it doesn't check functions are ok but checks their parameters etc.) static-jsfexpression-validator is utility for verifying that el expressions in jsf pages, such as #{bean.property}, are correct, that means that they don’t reference undefined managed beans and nonexistent getters or action methods. the purpose is to make jsf-based web applications safer to refactor as the change of a method name will lead to the detection of an invalid expression without need for extensive manual ui tests. it can be run statically, for example from a test. currently it builds on the jsf implementation v. 1.1 but can be in few hours (or days) modified to support newer version of jsf. how does it work? defined managed beans (name + type) are extracted from faces-config files and/or spring application context files jsp pages are parsed by jasper , tomcat’s jsp parser for each jsf tag: if it defines local variables, they are recorded (such as var in h:datatable ) all jsf el expressions in the tag’s attributes are validated by a real el resolver using two magic classes, namely custom variableresolver and propertyresolver, that – instead of looking up managed bean instances and invoking their getters – fabricate “fake values” of the expected types so that the “resolution” of an expression can proceed. the effect is that the existence of the referenced properties and action methods is verified against the target classes. sometimes it is not possible to determine the type of a jsf variable or property (e.g. when it’s a collection element), in which case it is necessary to declare it beforehand. you can also manually declare extra variables (managed beans) and override the detected type of properties. minimal setup add this dependency to your maven/ivy/…: net.jakubholy.jeeutils.jsfelcheck static-jsfexpression-validator-jsf11 0.9.3 test alternatively, you can fetch static-jsfexpression-validator-jsf11-0.9.3.jar (or -jsf12- or -jsf20-) and its dependencies yourself, see the appendix a. run it: java -cp static-jsfexpression-validator-jsf11-0.9.3.jar:... net.jakubholy.jeeutils.jsfelcheck.jsfstaticanalyzer --jsproot /path/to/jsp/files/dir alternatively, run it from a java class to be able to configure everything: public class jsfelvaliditytest { @test public void should_have_only_defined_beans_and_valid_properties_in_jsf_el_expressions() throws exception { jsfstaticanalyzer jsfstaticanalyzer = new jsfstaticanalyzer(); jsfstaticanalyzer.setfacesconfigfiles(collections.singleton(new file("web/web-inf/faces-config.xml"))); map> none = collections.emptymap(); collectedvalidationresults results = jsfstaticanalyzer.validateelexpressions("web", none, none, none); assertequals("there shall be no invalid jsf el expressions; check system.err/.out for details. failure " + results.failures() , 0, results.failures().size()); } } run it and check the standard error and output for results, which should ideally look something like this: info: >>> started for '/somefile.jsp ############################################# ... >>> local variables that you must declare type for [0] ######################################### >>> failed jsf el expressions [0] ######################################### (set logging to fine for class net.jakubholy.jeeutils.jsfelcheck.validator.validatingjsfelresolver to se failure details and stacktraces) >>> total excluded expresions: 0 by filters: [] >>> total expressions checked: 5872 (failed: 0, ignored expressions: 0) in 0min 25s standard usage normally you will need to configure the validator because you will have cases where property type etc. cannot be derived automatically. declaring local variable types, extra variables, property type overrides local variables – h:datatable etc. if your jsp includes a jsf tag that declares a new local variable (typically h:datatable), like vegetable in the example below: ... where favouritevegetable is a collection of vegetables then you must tell the validator what type of objects the collection contains: map> localvariabletypes = new hashtable>(); localvariabletypes.put("vegetarion.favouritevegetable", vegetable.class); jsfstaticanalyzer.validateelexpressions("web", localvariabletypes, extravariables, propertytypeoverrides); the failure to do so would be indicated by a number of failed expression validations and a suggestion to register type for this variable: >>> local variables that you must declare type for [6] ######################################### declare component type of 'vegetarion.favouritevegetable' assigned to the variable vegetable (file /favourites.jsp, tag line 109) >>> failed jsf el expressions [38] ######################################### (set logging to fine for class net.jakubholy.jeeutils.jsfelcheck.validator.validatingjsfelresolver to se failure details and stacktraces) failedvalidationresult [failure=invalidexpressionexception [invalid el expression '#{vegetable.name}': propertynotfoundexception - property 'name' not found on class net.jakubholy.jeeutils.jsfelcheck.expressionfinder.impl.jasper.variables.contextvariableregistry$error_youmustdelcaretypeforthisvariable$$enhancerbymockitowithcglib$$3c8d0e8f]; expression=#{vegetable.name}, file=/favourites.jsp, tagline=118] defining variables not in faces-config variable: the first element of an el expression. if you happen to be using a variable that is not a managed bean defined in faces-config (or spring config file), for example because you create it manually, you need to declare it and its type: map> extravariables = new hashtable>(); localvariabletypes.put("mymessages", map.class); jsfstaticanalyzer.validateelexpressions("web", localvariabletypes, extravariables, propertytypeoverrides); expressions like #{mymessages['whatever.key']} would be now ok. overriding the detected type of properties, especially for collection elements property: any but the first segment of an el expression (#{variable.propert1.property2['property3]….}). sometimes you need to explicitely tell the validator the type of a property. this is necessary if the poperty is an object taken from a collection, where the type is unknown at the runtime, but it may be useful also at other times. if you had: then you’d need to declare the type like this: map> propertytypeoverrides = new hashtable>(); propertytypeoverrides.put("vegetablemap.*", vegetable.class); //or just for 1 key: propertytypeoverrides.put("vegetablemap.carrot", vegetable.class); jsfstaticanalyzer.validateelexpressions("web", localvariabletypes, extravariables, propertytypeoverrides); using the .* syntax you indicate that all elements contained in the collection/map are of the given type. you can also override the type of a single property, whether it is contained in a collection or not, as shown on the third line. excluding/including selected expressions for validation you may supply the validator with filters that determine which expressions should be checked or ignored. this may be useful mainly if you it is not possible to check them, for example because a variable iterates over a collection with incompatible objects. the ignored expressions are added to a separate report and the number of ignored expressions together with the filters responsible for them is printed. example: ignore all expressions for the variable evilcollection: jsfstaticanalyzer.addelexpressionfilter(new elexpressionfilter(){ @override public boolean accept(parsedelexpression expression) { if (expression.size() == 1 && expression.iterator().next().equals("evilcollection")) { return false; } return true; } @override public string tostring() { return "excludeevilcollectionwithincompatibleobjects"; } }); (i admit that the interface should be simplified.) other configuration in jsfstaticanalyzer: setfacesconfigfiles(collection): faces-config files where to look for defined managed beans; null/empty not to read any setspringconfigfiles(collection) spring applicationcontext files where to look for defined managed beans; null/empty not to read any setsuppressoutput(boolean) – do not print to system.err/.out – used if you want to process the produced collectedvalidationresults on your own setjspstoincludecommaseparated(string) – normally all jsps under the jspdir are processed, you can force processing only the ones you want by supplying thier names here (jspc setting) setprintcorrectexpressions(boolean) – set to true to print all the correctly validated jsf el expressions understanding the results jsfstaticanalyzer.validateelexpressions prints the results into the standard output and error and also returnes them in a collectedvalidationresults with the following content: resultsiterable failures() – expressions whose validation wasn’t successful resultsiterable goodresults() – expressions validated successfully resultsiterable excluded() – expressions ignored due to a filter collection – local variables (h:datatable’s var) for which you need to declare their type the resultsiterable have size() and the individual *result classes contain enough information to describe the problem (the expression, exception, location, …). now we will look how the results appear in the output. unknown managed bean (variable) failedvalidationresult [failure=invalidexpressionexception [invalid el expression '#{messages['message.res.ok']}': variablenotfoundexception - no variable 'messages' among the predefined ones.]; expression=#{messages['message.res.ok']}, file=/sample_failures.jsp, tagline=20] solution : fix it or add the variable to the extravariables map parameter. invalid property (no corresponding getter found on the variable/previous property) a) invalid property on a correct target object class this kind of failures is the raison d’être of this tool. failedvalidationresult [failure=invalidexpressionexception [invalid el expression '#{segment.departuredatexxx}': propertynotfoundexception - property 'departuredatexxx' not found on class example.segment$$enhancerbymockitowithcglib$$5eeba04]; expression=#{segment.departuredatexxx}, file=/sample_failures.jsp, tagline=92] solution : fix it, i.e. correct the expression to reference an existing property of the class. if the validator is using different class then it should then you might need to define a propertytypeoverride. b) invalid property on an unknown target object class – mockobjectofunknowntype failedvalidationresult [failure=invalidexpressionexception [invalid el expression '#{carlist[1].price}': propertynotfoundexception - property 'price' not found on class net.jakubholy.jeeutils.jsfelcheck.validator.mockobjectofunknowntype$$enhancerbymockitowithcglib$$9fa876d1]; expression=#{carlist[1].price}, file=/cars.jsp, tagline=46] solution : carlist is clearly a list whose element type cannot be determined and you must therefore declare it via the propertytypeoverrides map property. local variable without defined type failedvalidationresult [failure=invalidexpressionexception [invalid el expression ' #{traveler.name}': propertynotfoundexception - property 'name' not found on class net.jakubholy.jeeutils.jsfelcheck.expressionfinder.impl.jasper.variables.contextvariableregistry$error_youmustdelcaretypeforthisvariable$$enhancerbymockitowithcglib$$b8a846b2]; expression= #{traveler.name}, file=/worldtravels.jsp, tagline=118] solution : declare the type via the localvariabletypes map parameter. more documentation check the javadoc, especially in jsfstaticanalyzer . limitations currently only local variables defined by h:datatable ‘s var are recognized. to add support for others you’d need create and register a class similar to datatablevariableresolver handling of included files isn’t perfect, the don’t know about local variables defined in the including file. but we have all info needed to implement this. static includes are handled by the jasper parser (though it likely parses the included files also as top-level files, if they are on its search path). future it depends on my project’s needs, your feedback and your contributions . where to get it from the project’s github or from the project’s maven central repository, snapshots also may appear in the sonatype snapshots repo . appendices a. dependencies of v.0.9.0 (also mostly similar for later versions): (note: spring is not really needed if you haven’t spring-managed jsf beans.) aopalliance:aopalliance:jar:1.0:compile commons-beanutils:commons-beanutils:jar:1.6:compile commons-collections:commons-collections:jar:2.1:compile commons-digester:commons-digester:jar:1.5:compile commons-io:commons-io:jar:1.4:compile commons-logging:commons-logging:jar:1.0:compile javax.faces:jsf-api:jar:1.1_02:compile javax.faces:jsf-impl:jar:1.1_02:compile org.apache.tomcat:annotations-api:jar:6.0.29:compile org.apache.tomcat:catalina:jar:6.0.29:compile org.apache.tomcat:el-api:jar:6.0.29:compile org.apache.tomcat:jasper:jar:6.0.29:compile org.apache.tomcat:jasper-el:jar:6.0.29:compile org.apache.tomcat:jasper-jdt:jar:6.0.29:compile org.apache.tomcat:jsp-api:jar:6.0.29:compile org.apache.tomcat:juli:jar:6.0.29:compile org.apache.tomcat:servlet-api:jar:6.0.29:compile org.mockito:mockito-all:jar:1.8.5:compile org.springframework:spring-beans:jar:2.5.6:compile org.springframework:spring-context:jar:2.5.6:compile org.springframework:spring-core:jar:2.5.6:compile xml-apis:xml-apis:jar:1.0.b2:compile from http://theholyjava.wordpress.com/2011/06/22/validating-jsf-el-expressions-in-jsf-pages-with-static-jsfexpression-validator/
June 23, 2011
by Jakub Holý
· 12,801 Views
article thumbnail
Reading GPS Latitude and Longitude from Image and Video Files
The State of GPS Data from Mobile Devices Most of the mobile devices today support GPS geo tagging. In fact most of them come bundled with navigation software that uses GPS and therefore all the pictures and (maybe) videos can be geo tagged. But as expected different vendors come with different support and formats. iPhone OS comes with geotagging both on video and image files, while the latest Android and Symbian (the Nokia main OS for smartphones) can geo tag only images. Even more – until recently Symbian didn’t support any geotagging before the installation of an additional software – such as Location Tagger . So generally the things are quite simple: iPhone OS geotags both video and image files; Android geotags only images; Symbian geotags only images – and on some devices this is possible only after installing a software; This is in breve the state of mobile device geotagging! Why Use GPS Data? Perhaps one of the main reasons why not support geotagging especially on video files can be the usage of those geo tags. First of all what a geotag means? You may know that even Android doesn’t “geotag” videos this is not quite true. Because after using you gallery you can see where those videos are shot. This is fantastic, but actually the real information about where the video has been taken is not into the video file, but it’s in an additional log file that keeps it. Thus actually the video files doesn’t know the geo coordinates. Here comes the problem with video format, because you cannot be sure that every format supports tags that can keep geo coordinates. Actually quicktime’s MOV can store them, while Symbian’s 3GP cannot. In fact Symbian cannot store any geo information about video files! So now we’ve at least three different formats for each of those three vendors. quicktime for iPhone mpeg-4 with Android 3gp with Symbian For now I can only say that iPhone can keep the geotag into his video files. But let me return to the question – why we need this geo tags? Until the video file is on the mobile device – there’s no problem. But once you try to download it – whether on Flickr, YouTube, Picasa, etc. you’ll lose any geo information if it’s not into the file tags. And of course if the above sites can’t read it! The general reason to store this data into the file is to move it along with the file. Once you move this file from your mobile device to a web platform you’ll see where the file has been created. EXIF, Exiftool and PHP’s exif_read_data There are several tools to read geotags. For images, and here we talk only for JPEGs, this is the EXIF information. You can download the exif command line program and try to reed data with it:
June 22, 2011
by Stoimen Popov
· 15,656 Views
article thumbnail
Eclipse Indigo Release Train Now Available: 46 Million Lines of Code Across 62 Projects
For the eight successive year, the latest iteration of the Eclipse release train, Indigo, is now available for developers everywhere. And once again, the Eclipse community have shown that it is possible to coordinate software to be released on time. The scale of Indigo is huge - it contains 62 projects, 46 million lines of code contributed by 408 committers. “We are very proud to celebrate another on-time annual release train from the Eclipse community,” states Mike Milinkovich, executive director of the Eclipse Foundation. “This release has a long list of new features, especially for Java developers. Features such as Git support, Maven and Hudson integration, a great GUI builder in WindowBuilder, and our new Jubula testing tool will, I am sure, motivate developers to try Indigo.” Yesterday I listed some of the excellent tooling additions that are available in Indigo. Once again, the latest Eclipse release provides something for everyone. Download it now and find out for yourself. For Java Developers EGit 1.0 provides first-class support support for Java developers using Git for source code management WindowBuilder, a world-class Eclipse-based GUI builder, is now available as an Eclipse open source project Automated functional GUI testing for Java and HTML applications is included via Jubula m2eclipse brings tight integration with Maven and the Eclipse workspace, enabling developers to work with Maven projects directly from Eclipse Mylyn 3.6 supports Hudson build monitoring directly from the Eclipse workspace Eclipse Marketplace Client now supports drag and drop installation of Eclipse-based solutions directly into Eclipse making it significantly easier to install new solutions. New Innovation in Eclipse Modeling Xtext 2.0 has added significant new features for domain-specific languages (DSLs): 1) the ability to create DSLs with embedded Java-like expressions; 2) Xtend, a new template language that allows tightly integrated code generation into the Eclipse tooling environment; and 3) a new refactoring framework for DSLs. Acceleo 3.1 integrates code generation into Ant and Maven build chains, and includes improved generator editing facilities. CDO Model Repository 4.0 integrates with several NoSQL databases such as Objectivity/DB, MongoDB, and DB4O. Cache optimizations and many other enhancements allow for models of several gigabytes. EMF 2.7 makes it easy to replicate changes across distributed systems in an optimal way: a client can send back to the server a minimal description of what's been changed rather than sending back the whole, arbitrarily-large, new instance. Eclipse Extended Editing Framework (EEF) 1.0 generates advanced and good-looking EMF editors in one click. EMF Compare 1.2 brings dedicated UML support and is more fully integrated with the SCM. EMF Facet, a new project, allows extension of an existing Ecore metamodel without modification. EclipseRT Advancements EclipseLink 2.3 supports multi-tenant JPA Entities, making it possible to incorporate JPA persistency into SaaS-style applications. Equinox 3.7 now implements the OSGi 4.3 specification, including use of generic signatures, generic capabilities, and requirements for bundles. Eclipse Communication Framework (ECF) implements OSGi 4.2 Remote Service and Remote Service Admin standards.
June 22, 2011
by James Sugrue
· 13,746 Views
article thumbnail
Eclipse Indigo Highlights: Five Reasons to Check Out ECF
The Eclipse Communication Framework has been a steady participant in the Eclipse release trains, continuously adding to its impressive list of features. This year’s inclusion of ECF 3.5 in the Indigo release train is no exception. In this article, I'll take a look at five key features of the release: OSGi 4.2 Remote Services/RSA Standards Support ECF Indigo implements two recently-completed OSGi standards: OSGi remote services and OSGi Remote Service Admin (RSA). The OSGi Remote Services spec provides a simple, standardized way to expose OSGi services for network discovery and remote access. ECF Indigo also implements the Enterprise specification for remote services management known as Remote Services Admin (RSA). The RSA specification defines a management agent to allow for enterprise-application control of the discovery and distribution of remote services via a standardized API. Also included in the RSA specification is a standardized format for communicating meta-data about remote services, advanced handling of security, discovery and distribution event notification, and advanced handling of remote service versioning. ECF has run its implementation of RS/RSA through the OSGi Test Compatability Kit to ensure that it is compliant with the OSGi specification. Extensibility through Provider Architecture ECF has a provider architecture, that allows major components of the OSGi remote services/RSA implementation to be extended, enhanced, or replaced as needed. For example, for interoperability with existing services and applications, it’s frequently desirable to be able to substitute the wire protocol/transport to one that is already being used. With the ECF provider architecture, it’s possible to substitute the underlying protocol...and use other frameworks based upon REST, SOAP, JMS, XML-RPC, XMPP, and/or others. If you wish, you can even define and use a proprietary provider and use it to expose your remote services. Or you can use one provider for remote services development and testing, and another for deployment. Asynchronous Proxies ECF has support for remote service access via asynchronous proxies. This allows client consumers of remote services to avoid the reliability problems that are frequent when synchronous proxies are used over a relatively slow and unreliable network. The choice of whether to use synchronous or asynchronous proxies is up to the programmer, and can be made at runtime. Here is more information about this feature of ECF’s remote services implementation. XML-RPC provider ECF Indigo has an XML-RPC-based provider, which implements the remote services API. Remote Service invocation through a proxy and/or async proxy is supported too. In addition to being usable for interoperability with existing XML-RPC-based services, it can also be used as an example of how to easily use an existing framework to create a remote service provider. Google wave provider Although discontinued by Google, Wave is an open protocol with an open source implementation of the Wave server available. This means you can still build applications that take advantage of the real time shared editing functionality from within your Eclipse environment using this provider. Already, ECF provides real time shared editing using cola. This is limited to two users on a a document at a time - using the Wave provider, you could have multiple authors collaborating on the same document. Mustafa and Sebastian created a multiplayer Android phone game for EclipseCon this year, using the Wave protocol for concurrency control. Take a look at the results in the video below. ECF on Other OSGi Frameworks You're not limited to running ECF on Equinox anymore: ECF4Felix allows ECF to run on the Felix OSGi framework. So far testing has only been done on Felix. But if you are willing to help with testing ECF Remote Services/RSA on another framework, please send an email to the ecf-dev mailing list. ECF Documentation Project ECF recently started the ECF Documentation Project. This project is an approach to improve the amount and quality of the ECF documentation with the help of the committer, contributor, and consumer communities. It also aims to use of ECF for new and existing consumers. Currently this includes a Users Guide and an Integrators Guide. As a user of ECF, the documentation effort is a huge help in getting ECF to work right within your application. Great credit is due to the ECF team for this, and all other features listed here. ECF wiki: http://wiki.eclipse.org/ECF Remote services section of ECF wiki: http://wiki.eclipse.org/ECF#OSGi_Remote_Services OSGi compendium specification (Chap 13 is Remote Services): http://www.osgi.org/download/r4v42/r4.cmpn.pdf OSGi Enterprise Specification (Chap 122 is RSA): http://www.osgi.org/download/r4v42/r4.enterprise.pdf RSA wiki pages: http://wiki.eclipse.org/Remote_Services_Admin Getting Started with Remote Services: http://wiki.eclipse.org/EIG:Getting_Started_with_OSGi_Remote_Services Asynchronous Proxies (examples): http://wiki.eclipse.org/Asynchronous_Proxies_for_Remote_Services ECF Builder: https://build.ecf-project.org/jenkins/ ECF Github site (other providers, examples, Wave, and Newsreader) : https://github.com/ECF ECF4Felix: https://github.com/ECF/ECF4Felix
June 22, 2011
by James Sugrue
· 15,505 Views
article thumbnail
When to Use Apache Camel?
When to use Apache Camel, a popular JVM/Java environment, and when to use other alternatives.
June 5, 2011
by Kai Wähner DZone Core CORE
· 153,195 Views · 12 Likes
article thumbnail
CDI AOP Tutorial: Java Standard Method Interception Tutorial - Java EE
This article discusses CDI based AOP in a tutorial format. CDI is the Java standard for dependency injection (DI) and interception (AOP). It is evident from the popularity of DI and AOP that Java needs to address DI and AOP so that it can build other standards on top of it. DI and AOP are already the foundation of many Java frameworks. CDI is a foundational aspect of Java EE 6. It is or will be shortly supported by Caucho's Resin Java Application Server, Java EE WebProfile certified, IBM's WebSphere, Oracle's Glassfish, Red Hat's JBoss and many more application servers. CDI is similar to core Spring and Guice frameworks. Like JPA did for ORM, CDI simplifies and sanitizes the API for DI and AOP. If you have worked with Spring or Guice, you will find CDI easy to use and easy to learn. If you are new to AOP, then CDI is an easy on ramp for picking up AOP quickly, as it uses a small subset of what AOP provides. CDI based AOP is simpler to use and learn. One can argue that CDI only implements a small part of AOP—method interception. While this is a small part of what AOP has to offer, it is also the part that most developers use. CDI can be used standalone and can be embedded into any application. Here is the source code for this tutorial, and instructions for use. It is no accident that this tutorial follows many of the same examples in the written three years ago. It will be interesting to compare and contrast the examples in this tutorial with the one written three years ago for Spring based AOP. Design goals of this tutorial This tutorial is meant to be a description and explanation of AOP in CDI without the clutter of EJB 3.1 or JSF. There are already plenty of tutorials that cover EJB 3.1 and JSF (and CDI). We believe that CDI has merit on its own outside of the EJB and JSF space. This tutorial only covers CDI. Repeat there is no JSF 2 or EJB 3.1 in this tutorial. There are plenty of articles and tutorials that cover using CDI as part of a larger JEE 6 application. This tutorial is not that. This tutorial series is CDI and only CDI. This tutorial only has full, complete code examples with source code you can download and try out on your own. There are no code snippets where you can't figure out where in the code you are suppose to be. So far these tutorials have been well recieved and we got a lot of feedback. There appears to be a lot of interest in the CDI standard. Thanks for reading and thanks for your comments and participation so far. AOP Basics For some, AOP seems like voodoo magic. For others, AOP seems like a cure-all. For now, let's just say that AOP is a tool that you want in your developer toolbox. It can make seemingly impossible things easy. Aagin, when we talk about AOP in CDI, we are really talking about interception which is a small but very useful part of AOP. For brevity, I am going to refer to interception as AOP. The first time that I used AOP was with Spring's transaction management support. I did not realize I was using AOP. I just knew Spring could apply EJB-style declarative transaction management to POJOs. It was probably three to six months before I realized that I was using was Spring's AOP support. The Spring framework truly brought AOP out of the esoteric closet into the main stream light of day. CDI brings these concepts into the JSR standards where other Java standards can build on top of CDI. You can think of AOP as a way to apply services (called cross-cutting concerns) to objects. AOP encompasses more than this, but this is where it gets used mostly in the main stream. I've using AOP to apply caching services, transaction management, resource management, etc. to any number of objects in an application. I am currently working with a team of folks on the CDI implementation for the revived JSR-107 JCache. AOP is not a panacea, but it certainly fits a lot of otherwise difficult use cases. You can think of AOP as a dynamic decorator design pattern. The decorator pattern allows additional behavior to be added to an existing class by wrapping the original class and duplicating its interface and then delegating to the original. See this article decorator pattern for more detail about the decorator design pattern. (Notice in addition to supporting AOP style interception CDI also supports actual decorators, which are not covered in this article.) Sample application revisited For this introduction to AOP, let's take a simple example, let's apply security services to our Automated Teller Machine example from the first the first in this series. Let's say when a user logs into a system that a SecurityToken is created that carries the user's credentials and before methods on objects get invoked, we want to check to see if the user has credentials to invoke these methods. For review, let's look at the AutomatedTellerMachine interface. Code Listing: AutomatedTellerMachine interface package org.cdi.advocacy; import java.math.BigDecimal; public interface AutomatedTellerMachine { public abstract void deposit(BigDecimal bd); public abstract void withdraw(BigDecimal bd); } In a web application, you could write a ServletFilter, that stored this SecurityToken in HttpSession and then on every request retrieved the token from Session and put it into a ThreadLocal variable where it could be accessed from a SecurityService that you could implement. Perhaps the objects that needed the SecurityService could access it as follows: Code Listing: AutomatedTellerMachineImpl implementing security without AOP public void deposit(BigDecimal bd) { /* If the user is not logged in, don't let them use this method */ if(!securityManager.isLoggedIn()){ throw new SecurityViolationException(); } /* Only proceed if the current user is allowed. */ if (!securityManager.isAllowed("AutomatedTellerMachine", operationName)){ throw new SecurityViolationException(); } ... transport.communicateWithBank(...); } In our ATM example, the above might work out well, but imagine a system with thousands of classes that needed security. Now imagine, the way we check to see if a user is "logged in" changed. If we put this code into every method that needed security, then we could possibly have to change this a thousand times if we changed the way we checked to see if a user was logged in. What we want to do instead is to use CDI to create a decorated version of the AutomateTellerMachineImpl bean. The decorated version would add the additional behavior to the AutomateTellerMachineImpl object without changing the actual implementation of the AutomateTellerMachineImpl. In AOP speak, this concept is called a cross-cutting concern. A cross-cutting concern is a concern that crosses the boundry of many objects. CDI does this by creating what is called an AOP proxy. An AOP proxy is like a dynamic decorator. Underneath the covers CDI can generate a class at runtime (the AOP proxy) that has the same interface as our AutomatedTellerMachine. The AOP proxy wraps our existing atm object and provides additional behavior by delegating to a list of method interceptors. The method interceptors provide the additional behavior and are similar to ServletFilters but for methods instead of requests. Diagrams of CDI AOP support Thus before we added CDI AOP, our atm example was like Figure 1. Figure 1: Before AOP advice After we added AOP support, we now get an AOP proxy that applies the securityAdvice to the atm as show in figure 2. Figure 2: After AOP advice You can see that the AOP proxy implements the AutomatedTellerMachine interface. When the client object looks up the atm and starts invoking methods instead of executing the methods directly, it executes the method on the proxy, which then delegates the call to a series of method interceptor called advice, which eventually invoke the actual atm instance (now called atmTarget). Let's actually look at the code for this example. For this example, we will use a simplified SecurityToken that gets stored into a ThreadLocal variable, but one could imagine one that was populated with data from a database or an LDAP server or some other source of authentication and authorization. Here is the SecurityToken, which gets stored into a ThreadLocal variable, for this example: SecurityToken.java Gets stored in ThreadLocal package org.cdi.advocacy.security; /** * @author Richard Hightower * */ public class SecurityToken { private boolean allowed; private String userName; public SecurityToken() { } public SecurityToken(boolean allowed, String userName) { super(); this.allowed = allowed; this.userName = userName; } public boolean isAllowed(String object, String methodName) { return allowed; } /** * @return Returns the allowed. */ public boolean isAllowed() { return allowed; } /** * @param allowed The allowed to set. */ public void setAllowed(boolean allowed) { this.allowed = allowed; } /** * @return Returns the userName. */ public String getUserName() { return userName; } /** * @param userName The userName to set. */ public void setUserName(String userName) { this.userName = userName; } } The SecurityService stores the SecurityToken into the ThreadLocal variable, and then delegates to it to see if the current user has access to perform the current operation on the current object as follows: SecurityService.java Service package org.cdi.advocacy.security; public class SecurityService { private static ThreadLocal currentToken = new ThreadLocal(); public static void placeSecurityToken(SecurityToken token){ currentToken.set(token); } public static void clearSecuirtyToken(){ currentToken.set(null); } public boolean isLoggedIn(){ SecurityToken token = currentToken.get(); return token!=null; } public boolean isAllowed(String object, String method){ SecurityToken token = currentToken.get(); return token.isAllowed(); } public String getCurrentUserName(){ SecurityToken token = currentToken.get(); if (token!=null){ return token.getUserName(); }else { return "Unknown"; } } } The SecurityService will throw a SecurityViolationException if a user is not allowed to access a resource. SecurityViolationException is just a simple exception for this example. SecurityViolationException.java Exception package com.arcmind.springquickstart.security; /** * @author Richard Hightower * */ public class SecurityViolationException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; } To remove the security code out of the AutomatedTellerMachineImpl class and any other class that needs security, we will write an Aspect in CDI to intercept calls and perform security checks before the method call. To do this we will create a method interceptor (known is AOP speak as an advice) and intercept method calls on the atm object. Here is the SecurityAdvice class which will intercept calls on the AutomatedTellerMachineImpl class. SecurityAdvice package org.cdi.advocacy.security; import javax.inject.Inject; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; /** * @author Richard Hightower */ @Secure @Interceptor public class SecurityAdvice { @Inject private SecurityService securityManager; @AroundInvoke public Object checkSecurity(InvocationContext joinPoint) throws Exception { System.out.println("In SecurityAdvice"); /* If the user is not logged in, don't let them use this method */ if(!securityManager.isLoggedIn()){ throw new SecurityViolationException(); } /* Get the name of the method being invoked. */ String operationName = joinPoint.getMethod().getName(); /* Get the name of the object being invoked. */ String objectName = joinPoint.getTarget().getClass().getName(); /* * Invoke the method or next Interceptor in the list, * if the current user is allowed. */ if (!securityManager.isAllowed(objectName, operationName)){ throw new SecurityViolationException(); } return joinPoint.proceed(); } } Notice that we annotate the SecuirtyAdvice class with an @Secure annotation. The @Secure annotation is an @InterceptorBinding. We use it to denote both the interceptor and the classes it intercepts. More on this later. Notice that we use @Inject to inject the securityManager. Also we mark the method that implements that around advice with and @AroundInvoke annotation. This essentially says this is the method that does the dynamic decoration. Thus, the checkSecurity method of SecurityAdvice is the method that implements the advice. You can think of advice as the decoration that we want to apply to other objects. The objects getting the decoration are called advised objects. Notice that the SecurityService gets injected into the SecurityAdvice and the checkSecurity method uses the SecurityService* to see if the user is logged in and the user has the rights to execute the method. An instance of InvocationContext, namely joinPoint, is passed as an argument to checkSecurity. The InvocationContext has information about the method that is being called and provides control that determines if the method on the advised object's methods gets invoked (e.g., AutomatedTellerMachineImpl.withdraw and AutomatedTellerMachineImpl.deposit). If *`joinPoint.proceed()`* is not called then the wrapped method of the advised object (withdraw or deposit) is not called. (The proceed method causes the actual decorated method to be invoked or the next interceptor in the chain to get invoked.) In Spring, to apply an Advice like SecurityAdvice to an advised object, you need a pointcut. A pointcut is like a filter that picks the objects and methods that get decorated. In CDI, you just mark the class or methods of the class that you want decorated with an interceptor binding annotation. There is no complex pointcut language. You could implement one as a CDI extention, but it does not come with CDI by default. CDI uses the most common way developer apply interceptors, i.e., with annotations. CDI scans each class in each jar (and other classpath locations) that has a META-INF/beans.xml. The SecurityAdvice get installed in the CDI beans.xml. META-INF/beans.xml org.cdi.advocacy.security.SecurityAdvice You can install interceptors in the order you want them called. In order to associate a interceptor with the classes and methods it decorates, you have to define an InterceptorBinding annotation. An example of such a binding is defined below in the @Secure annotation. Secure.java annotation package org.cdi.advocacy.security; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; import javax.interceptor.InterceptorBinding; @InterceptorBinding @Retention(RUNTIME) @Target({TYPE, METHOD}) public @interface Secure { } Notice that we annotated the @Secure annotation with the @InterceptorBinding annotation. InterceptorBindings follow a lot of the same rules as Qualifiers as discussed in the first two articles in this series. InterceptorBindings are like qaulifiers for injection in that they can have members which can further qualify the injection. You can also disable InterceptorBinding annotation members from qualifying an interception by using the @NonBinding just like you can in Qualifiers. To finish our example, we need to annotate our AutomatedTellerMachine with the same @Secure annotation; thus, associating the AutomatedTellerMachine with our SecurityAdvice. AutomatedTellerMachine class using @Secure package org.cdi.advocacy; ... import javax.inject.Inject; import org.cdi.advocacy.security.Secure; @Secure public class AutomatedTellerMachineImpl implements AutomatedTellerMachine { @Inject @Json private ATMTransport transport; public void deposit(BigDecimal bd) { System.out.println("deposit called"); transport.communicateWithBank(null); } public void withdraw(BigDecimal bd) { System.out.println("withdraw called"); transport.communicateWithBank(null); } } You have the option of use @Secure on the methods or at the class level. In this example, we annotated the class itself, which then applies the interceptor to every method. Let's complete our example by reviewing the AtmMain main method that looks up the atm out of CDI's beanContainer. Let's review AtmMain as follows: AtmMain.java package org.cdi.advocacy; import java.math.BigDecimal; import org.cdi.advocacy.security.SecurityToken; import org.cdiadvocate.beancontainer.BeanContainer; import org.cdiadvocate.beancontainer.BeanContainerManager; import org.cdi.advocacy.security.SecurityService; public class AtmMain { public static void simulateLogin() { SecurityService.placeSecurityToken(new SecurityToken(true, "Rick Hightower")); } public static void simulateNoAccess() { SecurityService.placeSecurityToken(new SecurityToken(false, "Tricky Lowtower")); } public static BeanContainer beanContainer = BeanContainerManager .getInstance(); static { beanContainer.start(); } public static void main(String[] args) throws Exception { simulateLogin(); //simulateNoAccess(); AutomatedTellerMachine atm = beanContainer .getBeanByType(AutomatedTellerMachine.class); atm.deposit(new BigDecimal("1.00")); } } Continue reading... Click on the navigation links below the author bio to read the other pages of this article. Be sure to check out part I of this series as well! Although not a fan of EJB 3, Rick is a big fan of the potential of CDI and thinks that EJB 3.1 has come a lot closer to the mark. CDI Implementations - Resin Candi - Seam Weld - Apache OpenWebBeans Before we added AOP support when we looked up the atm, we looked up the object directly as shown in figure 1, now that we applied AOP when we look up the object we get what is in figure 2. When we look up the atm in the application context, we get the AOP proxy that applies the decoration (advice, method interceptor) to the atm target by wrapping the target and delegating to it after it invokes the series of method interceptors. Victroy lap The last code listing works just like you think. If you use simulateLogin, atm.deposit does not throw a SecurityException. If you use simulateNoAccess, it does throw a SecurityException. Now let's weave in a few more "Aspects" to the mix to drive some points home and to show how interception works with multiple interceptors. I will go quicker this time. LoggingInterceptor package org.cdi.advocacy; import java.util.Arrays; import java.util.logging.Logger; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; @Logable @Interceptor public class LoggingInterceptor { @AroundInvoke public Object log(InvocationContext ctx) throws Exception { System.out.println("In LoggingInterceptor"); Logger logger = Logger.getLogger(ctx.getTarget().getClass().getName()); logger.info("before call to " + ctx.getMethod() + " with args " + Arrays.toString(ctx.getParameters())); Object returnMe = ctx.proceed(); logger.info("after call to " + ctx.getMethod() + " returned " + returnMe); return returnMe; } } Now we need to define the Logable interceptor binding annotation as follows: package org.cdi.advocacy; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; import javax.interceptor.InterceptorBinding; @InterceptorBinding @Retention(RUNTIME) @Target({TYPE, METHOD}) public @interface Logable { } Now to use it we just mark the methods where we want this logging. AutomatedTellerMachineImpl.java using Logable package org.cdi.advocacy; ... @Secure public class AutomatedTellerMachineImpl implements AutomatedTellerMachine { ... @Logable public void deposit(BigDecimal bd) { System.out.println("deposit called"); transport.communicateWithBank(null); } public void withdraw(BigDecimal bd) { System.out.println("withdraw called"); transport.communicateWithBank(null); } } Notice that we use the @Secure at the class level which will applies the security interceptor to every mehtod in the AutomatedTellerMachineImpl. But, we use @Logable only on the deposit method which applies it, you guessed it, only on the deposit method. Now you have to add this interceptor to the beans.xml: META-INF/beans.xml org.cdi.advocacy.LoggingInterceptor org.cdi.advocacy.security.SecurityAdvice When we run this again, we get something like this in our console output: May 15, 2011 6:46:22 PM org.cdi.advocacy.LoggingInterceptor log INFO: before call to public void org.cdi.advocacy.AutomatedTellerMachineImpl.deposit(java.math.BigDecimal) with args [1.00] May 15, 2011 6:46:22 PM org.cdi.advocacy.LoggingInterceptor log INFO: after call to public void org.cdi.advocacy.AutomatedTellerMachineImpl.deposit(java.math.BigDecimal) returned null Notice that the order of interceptors in the beans.xml file determines the order of execution in the code. (I added a println to each interceptor just to show the ordering.) When we run this, we get the following output. Output: In LoggingInterceptor In SecurityAdvice If we switch the order in the beans.xml file, we will get a different order in the console output. META-INF/beans.xml org.cdi.advocacy.security.SecurityAdvice org.cdi.advocacy.LoggingInterceptor In SecurityAdvice In LoggingInterceptor This is important as many interceptors can be applied. You have one place to set the order. Conclusion AOP is neither a cure all or voodoo magic, but a powerful tool that needs to be in your bag of tricks. The Spring framework has brought AOP to the main stream masses and Spring 2.5/3.x has simplified using AOP. CDI brings AOP and DI into the standard's bodies where it can get further mainstreamed, refined and become part of future Java standards like JCache, Java EE 6 and Java EE 7. You can use Spring CDI to apply services (called cross-cutting concerns) to objects using AOP's interception model. AOP need not seem like a foreign concept as it is merely a more flexible version of the decorator design pattern. With AOP you can add additional behavior to an existing class without writing a lot of wrapper code. This can be a real time saver when you have a use case where you need to apply a cross cutting concern to a slew of classes. To reiterate... CDI is the Java standard for dependency injection and interception (AOP). It is evident from the popularity of DI and AOP that Java needs to address DI and AOP so that it can build other standards on top of it. DI and AOP are the foundation of many Java frameworks. I hope you share my excitement of CDI as a basis for other JSRs, Java frameworks and standards. CDI is a foundational aspect of Java EE 6. It is or will be shortly supported by Caucho's Resin, IBM's WebSphere, Oracle's Glassfish, Red Hat's JBoss and many more application servers. CDI is similar to core Spring and Guice frameworks. However CDI is a general purpose framework that can be used outside of JEE 6. CDI simplifies and sanitizes the API for DI and AOP. I find that working with CDI based AOP is easier and covers the most common use cases. CDI is a rethink on how to do dependency injection and AOP (interception really). It simplifies it. It reduces it. It gets rid of legacy, outdated ideas. CDI is to Spring and Guice what JPA is to Hibernate, and Toplink. CDI will co-exist with Spring and Guice. There are plugins to make them interoperate nicely (more on these shortly). This is just a brief taste. There is more to come. Resources CDI Source CDI advocacy group CDI advocacy blog CDI advocacy google code project Google group for CDI advocacy Manisfesto version 1 Weld reference documentation CDI JSR299 Resin fast and light CDI and Java EE 6 Web Profile implementation CDI & JSF Part 1 Intro by Andy Gibson CDI & JSF Part 2 Intro by Andy Gibson CDI & JSF Part 3 Intro by Andy Gibson About the Author This article was written with CDI advocacy in mind by Rick Hightower with some collaboration from others. Rick Hightower has worked as a CTO, Director of Development and a Developer for the last 20 years. He has been involved with J2EE since its inception. He worked at an EJB container company in 1999. He has been working with Java since 1996, and writing code professionally since 1990. Rick was an early Spring enthusiast. Rick enjoys bouncing back and forth between C, Python, Groovy and Java development. Although not a fan of EJB 3, Rick is a big fan of the potential of CDI and thinks that EJB 3.1 has come a lot closer to the mark. Rick Hightower is CTO of Mammatus and is an expert on Java and Cloud Computing. There are 18 code listings in this article
May 25, 2011
by Rick Hightower
· 83,654 Views · 10 Likes
article thumbnail
How I Resolved SpringMVC+Hibernate Error: No Hibernate Session Bound to Thread
I used the SpringMVC @Controller annotation approach and configured the Web related Spring configuration in dispatcher-servlet.xml.
May 18, 2011
by Siva Prasad Reddy Katamreddy
· 69,499 Views · 2 Likes
article thumbnail
Spring Expression Language (SpEL) Predefined Variables
Spring 3.0 introduced Spring Expression Language (SpEL). There are two variables that you have available “systemProperties” and “systemEnvironment“. SpEL allows us to access information from our beans and system beans information at runtime (late binding). These can be applied to bean fields as defaults using the JSR-303 @Value annotation on a field or in XML with the options. systemProperties – a java.util.Properties object retrieving properties from the runtime environment systemEnvironment – a java.util.Properties object retrieving environment specific properties from the runtime environment We can access specific elements from the Properties object with the syntax: systemProperties['property.name'] systemEnvironment['property.name'] public class MyEnvironment { @Value("#{ systemProperties['user.language'] }") private String varOne; @Value("#{ systemProperties }") private java.util.Properties systemProperties; @Value("#{ systemEnvironment }") private java.util.Properties systemEnvironment; @Override public String toString() { return "\n\n********************** MyEnvironment: [\n\tvarOne=" + varOne + ", \n\tsystemProperties=" + systemProperties + ", \n\tsystemEnvironment=" + systemEnvironment + "]"; } } Register the “MyEnvironment” bean in your Spring context and create a JUnit test to display the variables. From http://gordondickens.com/wordpress/2011/05/12/spring-expression-language-spel-predefined-variables/
May 16, 2011
by Gordon Dickens
· 24,200 Views
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,156 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,510 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,390 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,844 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,873 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,123 Views · 8 Likes
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,436 Views
article thumbnail
Creating a Copy of JavaBeans
In this post, we shall see how to make a copy of an object in Java. In our applications, JavaBeans play a very important role. However sometimes we simply need to make a copy of our JavaBeans so as to make changes to the copy and keep the original object intact. There are two ways in which this can be achieved in Java, depending upon the level of access you have to your beans. Using Object.clone() Using BeanUtils Copying using Object.clone() This method can be used when you have access to the source code of your bean classes. This method requires your JavaBeans to implement the cloneable interface. The Cloneable interface is a marker interface that indicates that the object allows itself to be cloned. We can call the Object.clone() method on only on objects whose classes implement the Cloneable interface. If we attempt to invoke the clone() method on an object of a class that does not implement the Cloneable interface, we get a CloneNotSupportedException. Also note that the clone() method is a protected method, so you will most likely need to create a public method on your bean class named clone() to mimic the functionality. We are going to demonstrate both the above methods using a simple Employee class. This class will contain an instance of another javabean 'Address'. We shall see in the below example, how we can obtain a deep copy of our beans. The following code demonstrates the usage of Object.clone() Address.java class Address { private int houseNo; public int getHouseNo() { return houseNo; } public void setHouseNo(int houseNo) { this.houseNo = houseNo; } @Override public String toString() { return "houseNo : " + houseNo; } } Employee.java class Employee implements Cloneable { private String name = null; private Address address=null; @Override public String toString() { return "name " + this.getName()+ " address : "+ address; } public Employee clone() { Employee emp = null; try { emp = (Employee) super.clone(); } catch (CloneNotSupportedException e) { System.out.println(e); } return emp; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } } Note that in the above classes, the Employee class and the Address class is declared with a visibility of default. We did not have to make them public, although we could have. Also note the way the clone() method has been written in the Employee class. I explicitly declared it as as a public method and called the superclass implementation of the clone method. Then, I downcasted it to am Employee object before returning. Lets see the code in action. public static void main(String[] args) { Employee emp1 = new Employee(); Address add1= new Address(); add1.setHouseNo(100); emp1.setName("ryan"); emp1.setAddress(add1); Employee emp2 = emp1.clone(); emp2.setName("ryan2"); print("emp1 : " + emp1); print("emp2 : " + emp2); print("emp1==emp2 "+(emp1==emp2)); } If you execute the following code, you will get the below output emp1 : name ryan address : houseNo : 100 emp2 : name ryan2 address : houseNo : 100 emp1==emp2 false You can replace the print statement with your logger statement to run the code. Note that the == operator indicates that both the objects are created independently on the heap. Moreover, the fields of the Address bean have also been copied. One crucial thing to be noted here is that you only needed to implement the Cloneable interface in the Employee class. The Address class does not need to implement Cloneable, although there wont be any serious repercussions if you do so! Now lets see the second method Using the BeanUtils.cloneBean() class This method makes use of the BeanUtils class provided by the apache foundation. In order to use this class, you need to have at least the following jar files in your classpath commons-beanutils-1.7.0.jar commons-collections-3.1.jar commons-logging-1.0.4.jar The version numbers may differ, but you can get the details from the here if the dependencies change. The BeanUtils class provides us a method called cloneBean that clones all the accessible properties of your beans. Here is the code in Action. Employee2.class public class Employee2{ private String name = null; private Address address=null; @Override public String toString() { return "name " + this.getName()+ " address : "+ address; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } } Note the declaration of the Employee2 class. We did not implement the Cloneable interface. Moreover, we made the class "public". Making the class public is required for the BeanUtils class to extract the data from the Bean. Also note that we did not have to write a clone() function in this class. We can reuse the existing Address class from the previous example, as no changes need to be done to it. You need to import the following line in your main class import org.apache.commons.beanutils.BeanUtils; Now lets take a look at the main function. public static void main(String[] args) throws Exception{ BeanUtils bu = new BeanUtils(); Employee2 emp1 = new Employee2(); Address add1= new Address(); add1.setHouseNo(100); emp1.setName("ryan"); emp1.setAddress(add1); Employee2 emp2 = (Employee2)bu.cloneBean(emp1); emp2.setName("??"); print(emp1); print(emp2); print("emp1==emp2 : "+(emp1==emp2)); } As you see above, we did not have to do much but simply call the cloneBean method on the BeanUtils object and downcast it to our Employee2 bean. As was expected, a deep copy of the object was created. If you run the code, you get the following output name ryan address : houseNo : 100 name ?? address : houseNo : 100 emp1==emp2 : false As expected, both the objects are considered to be different objects on the heap. They just have the same values for their properties. In the methods discussed above, you can see that the BeanUtils method can be used in a much wider scope because most of your JavaBeans will be public, but you may not always have access to the code of your JavaBeans to write a clone method. Thats all for now folks! Happy Programming :) From http://mycodefixes.blogspot.com/2011/02/creating-deep-copy-of-javabeans.html
February 28, 2011
by Ryan Sukale
· 25,434 Views
article thumbnail
Implementing Ajax Authentication using jQuery, Spring Security and HTTPS
I've always had a keen interest in implementing security in webapps. I implemented container-managed authentication (CMA) in AppFuse in 2002, watched Tomcat improve it's implementation in 2003 and implemented Remember Me with CMA in 2004. In 2005, I switched from CMA to Acegi Security (now Spring Security) and never looked back. I've been very happy with Spring Security over the years, but also hope to learn more about Apache Shiro and implementing OAuth to protect JavaScript APIs in the near future. I was recently re-inspired to learn more about security when working on a new feature at Overstock.com. The feature hasn't been released yet, but basically boils down to allowing users to login without leaving a page. For example, if they want to leave a review on a product, they would click a link, be prompted to login, enter their credentials, then continue to leave their review. The login prompt and subsequent review would likely be implemented using a lightbox. While lightboxes are often seen in webapps these days because they look good, it's also possible Lightbox UIs provide a poor user experience. User experience aside, I think it's interesting to see what's required to implement such a feature. To demonstrate how we did it, I whipped up an example using AppFuse Light, jQuery and Spring Security. The source is available in my ajax-login project on GitHub. To begin, I wanted to accomplish a number of things to replicate the Overstock environment: Force HTTPS for authentication. Allow testing HTTPS without installing a certificate locally. Implement a RESTful LoginService that allows users to login. Implement login with Ajax, with the request coming from an insecure page. Forcing HTTPS with Spring Security The first feature was fairly easy to implement thanks to Spring Security. Its configuration supports a requires-channel attribute that can be used for this. I used this to force HTTPS on the "users" page and it subsequently causes the login to be secure. Testing HTTPS without adding a certificate locally After making the above change in security.xml, I had to modify my jWebUnit test to work with SSL. In reality, I didn't have to modify the test, I just had to modify the configuration that ran the test. In my last post, I wrote about adding my 'untrusted' cert to my JVM keystore. For some reason, this works for HttpClient, but not for jWebUnit/HtmlUnit. The good news is I figured out an easier solution - adding the trustStore and trustStore password as system properties to the maven-failsafe-plugin configuration. maven-failsafe-plugin 2.7.2 **/*WebTest.java ${project.build.directory}/ssl.keystore appfuse The disadvantage to doing things this way is you'll have to pass these in as arguments when running unit tests in your IDE. Implementing a LoginService Next, I set about implementing a LoginService as a Spring MVC Controller that returns JSON thanks to the @ResponseBody annotation and Jackson. package org.appfuse.examples.web; import org.appfuse.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/api/login.json") public class LoginService { @Autowired @Qualifier("authenticationManager") AuthenticationManager authenticationManager; @RequestMapping(method = RequestMethod.GET) @ResponseBody public LoginStatus getStatus() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null && !auth.getName().equals("anonymousUser") && auth.isAuthenticated()) { return new LoginStatus(true, auth.getName()); } else { return new LoginStatus(false, null); } } @RequestMapping(method = RequestMethod.POST) @ResponseBody public LoginStatus login(@RequestParam("j_username") String username, @RequestParam("j_password") String password) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); User details = new User(username); token.setDetails(details); try { Authentication auth = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(auth); return new LoginStatus(auth.isAuthenticated(), auth.getName()); } catch (BadCredentialsException e) { return new LoginStatus(false, null); } } public class LoginStatus { private final boolean loggedIn; private final String username; public LoginStatus(boolean loggedIn, String username) { this.loggedIn = loggedIn; this.username = username; } public boolean isLoggedIn() { return loggedIn; } public String getUsername() { return username; } } } To verify this class worked as expected, I wrote a unit test using JUnit and Mockito. I used Mockito because Overstock is transitioning to it from EasyMock and I've found it very simple to use. package org.appfuse.examples.web; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextImpl; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class LoginServiceTest { LoginService loginService; AuthenticationManager authenticationManager; @Before public void before() { loginService = new LoginService(); authenticationManager = mock(AuthenticationManager.class); loginService.authenticationManager = authenticationManager; } @After public void after() { SecurityContextHolder.clearContext(); } @Test public void testLoginStatusSuccess() { Authentication auth = new TestingAuthenticationToken("foo", "bar"); auth.setAuthenticated(true); SecurityContext context = new SecurityContextImpl(); context.setAuthentication(auth); SecurityContextHolder.setContext(context); LoginService.LoginStatus status = loginService.getStatus(); assertTrue(status.isLoggedIn()); } @Test public void testLoginStatusFailure() { LoginService.LoginStatus status = loginService.getStatus(); assertFalse(status.isLoggedIn()); } @Test public void testGoodLogin() { Authentication auth = new TestingAuthenticationToken("foo", "bar"); auth.setAuthenticated(true); when(authenticationManager.authenticate(Matchers.anyObject())).thenReturn(auth); LoginService.LoginStatus status = loginService.login("foo", "bar"); assertTrue(status.isLoggedIn()); assertEquals("foo", status.getUsername()); } @Test public void testBadLogin() { Authentication auth = new TestingAuthenticationToken("foo", "bar"); auth.setAuthenticated(false); when(authenticationManager.authenticate(Matchers.anyObject())) .thenThrow(new BadCredentialsException("Bad Credentials")); LoginService.LoginStatus status = loginService.login("foo", "bar"); assertFalse(status.isLoggedIn()); assertEquals(null, status.getUsername()); } } Implement login with Ajax The last feature was the hardest to implement and still isn't fully working as I'd hoped. I used jQuery and jQuery UI to implement a dialog that opens the login page on the same page rather than redirecting to the login page. The "#demo" locator refers to a button in the page. Passing in the "ajax=true" parameter disables SiteMesh decoration on the login page, something that's described in my Ajaxified Body article. var dialog = $(''); $(document).ready(function() { $.get('/login?ajax=true', function(data) { dialog.html(data); dialog.dialog({ autoOpen: false, title: 'Authentication Required' }); }); $('#demo').click(function() { dialog.dialog('open'); // prevent the default action, e.g., following a link return false; }); }); Instead of adding a click handler to a specific id, it's probably better to use a CSS class that indicates authentication is required for a link, or -- even better -- use Ajax to see if the link is secured. The login page then has the following JavaScript to add a click handler to the "login" button that submits the request securely to the LoginService. var getHost = function() { var port = (window.location.port == "8080") ? ":8443" : ""; return ((secure) ? 'https://' : 'http://') + window.location.hostname + port; }; var loginFailed = function(data, status) { $(".error").remove(); $('#username-label').before('Login failed, please try again.'); }; $("#login").live('click', function(e) { e.preventDefault(); $.ajax({url: getHost() + "/api/login.json", type: "POST", data: $("#loginForm").serialize(), success: function(data, status) { if (data.loggedIn) { // success dialog.dialog('close'); location.href= getHost() + '/users'; } else { loginFailed(data); } }, error: loginFailed }); }); The biggest secret to making this all work (the HTTP -> HTTPS communication, which is considered cross-domain), is the window.name Transport and the jQuery plugin that implements it. To make this plugin work with Firefox 3.6, I had to implement a Filter that adds Access-Control headers. A question on Stackoverflow helped me figure this out. public class OptionsHeadersFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST"); response.setHeader("Access-Control-Max-Age", "360"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) { } public void destroy() { } } Issues I encountered a number of issues when implementing this in the ajax-login project. If you try to run this with ports (e.g. 8080 and 8443) in your URLs, you'll get a 501 (Not Implemented) response. Removing the ports by fronting with Apache and mod_proxy solves this problem. If you haven't accepted the certificate in your browser, the Ajax request will fail. In the example, I solved this by clicking on the "Users" tab to make a secure request, then going back to the homepage to try and login. The jQuery window.name version 0.9.1 doesn't work with jQuery 1.5.0. The error is "$.httpSuccess function not found." Finally, even though I was able to authenticate successfully, I was unable to make the authentication persist. I tried adding the following to persist the updated SecurityContext to the session, but it doesn't work. I expect the solution is to create a secure JSESSIONID cookie somehow. @Autowired SecurityContextRepository repository; @RequestMapping(method = RequestMethod.POST) @ResponseBody public LoginStatus login(@RequestParam("j_username") String username, @RequestParam("j_password") String password, HttpServletRequest request, HttpServletResponse response) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); ... try { Authentication auth = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(auth); // save the updated context to the session repository.saveContext(SecurityContextHolder.getContext(), request, response); return new LoginStatus(auth.isAuthenticated(), auth.getName()); } catch (BadCredentialsException e) { return new LoginStatus(false, null); } } Conclusion This article has shown you how to force HTTPS for login, how to do integration testing with a self-generated certificate, how to implement a LoginService with Spring MVC and Spring Security, as well as how to use jQuery to talk to a service cross-domain with the window.name Transport. While I don't have everything working as much as I'd like, I hope this helps you implement a similar feature in your applications. One thing to be aware of is with lightbox/dialog logins and HTTP -> HTTPS is that users won't see a secure icon in their address bar. If your app has sensitive data, you might want to force https for your entire app. OWASP's Secure Login Pages has a lot of good tips in this area. Update: I've posted a demo of the ajax-login webapp. Thanks to Contegix for hosting the demo and helping obtain/install an SSL certificate so quickly. Update March 24, 2011: Rob Winch figured out how to make this work and sent me a patch. From his comment: The first issue is that Access-Control-Allow-Credentials header must be set to true. This is so that the browser knows it can send and accept cookies. The second issue is that XMLHttpRequest.withCredentials should be set to true. The last change was that in order to allow credentials to work across domains, the Access-Control-Allow-Origin must be a specific value (i.e. it won't work if you use a wildcard). For more information, you can read about it on mozilla's site. I've updated the demo with these changes. Works great now - thanks Rob! From http://raibledesigns.com/rd/entry/implementing_ajax_authentication_using_jquery
February 24, 2011
by Matt Raible
· 89,449 Views
article thumbnail
Spring and Hibernate Application with Zero XML
The Spring framework came up with annotation support since 2.5 version which eases development. Whether the annotation based approach, or XML approach is better, is depends on the project and your personal preference. Let us see how we can write a Simple Application using Spring and Hibernate using annotations, no xml at all. The configuration for JDBC datasource and Hibernate properties: application.properties ################### JDBC Configuration ########################## jdbc.driverClassName=org.hsqldb.jdbcDriver jdbc.url=jdbc:hsqldb:file:db/SivaLabsDB;shutdown=true jdbc.username=sa jdbc.password= ################### Hibernate Configuration ########################## hibernate.dialect=org.hibernate.dialect.HSQLDialect hibernate.show_sql=true hibernate.hbm2ddl.auto=update hibernate.generate_statistics=true We can instantiate ApplicationContext from a Java file using the @Configuration annotation. AppConfig.java package com.sivalabs.springmvc.config; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.io.ClassPathResource; /** * @author SivaLabs * */ @Import({RepositoryConfig.class}) @Configuration public class AppConfig { // @Bean public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer() { PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setLocation(new ClassPathResource("application.properties")); ppc.setIgnoreUnresolvablePlaceholders(true); return ppc; } } Here @Import({RepositoryConfig.class}) is the same as the xml version: package com.sivalabs.springmvc.config; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.sql.DataSource; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.HibernateTransactionManager; import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean; import org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener; import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; import org.springframework.transaction.interceptor.TransactionAttributeSource; import org.springframework.transaction.interceptor.TransactionInterceptor; /** * @author SivaLabs * */ @Configuration public class RepositoryConfig { //${jdbc.driverClassName} @Value("${jdbc.driverClassName}") private String driverClassName; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Value("${hibernate.dialect}") private String hibernateDialect; @Value("${hibernate.show_sql}") private String hibernateShowSql; @Value("${hibernate.hbm2ddl.auto}") private String hibernateHbm2ddlAuto; @Bean() public DataSource getDataSource() { DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName(driverClassName); ds.setUrl(url); ds.setUsername(username); ds.setPassword(password); return ds; } @Bean @Autowired public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) { HibernateTransactionManager htm = new HibernateTransactionManager(); htm.setSessionFactory(sessionFactory); return htm; } @Bean @Autowired public HibernateTemplate getHibernateTemplate(SessionFactory sessionFactory) { HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory); return hibernateTemplate; } @Bean public AnnotationSessionFactoryBean getSessionFactory() { AnnotationSessionFactoryBean asfb = new AnnotationSessionFactoryBean(); asfb.setDataSource(getDataSource()); asfb.setHibernateProperties(getHibernateProperties()); asfb.setPackagesToScan(new String[]{"com.sivalabs"}); return asfb; } @Bean public Properties getHibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.dialect", hibernateDialect); properties.put("hibernate.show_sql", hibernateShowSql); properties.put("hibernate.hbm2ddl.auto", hibernateHbm2ddlAuto); return properties; } } Create an Entity User as follows: package com.sivalabs.springmvc.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * @author SivaLabs * */ @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String name; private String address; public User() { } public User(Integer id, String name, String address) { this.id = id; this.name = name; this.address = address; } @Override public String toString() { return "User [address=" + address + ", id=" + id + ", name=" + name+ "]"; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } Create UserRepository to perform DB operations using Hibernate. package com.sivalabs.springmvc.repositories; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.sivalabs.springmvc.entities.User; /** * @author SivaLabs * */ @Transactional @Repository public class UserRepository { @Autowired private HibernateTemplate hibernateTemplate; public List getAllUsers() { return this.hibernateTemplate.loadAll(User.class); } public Integer createUser(User user) { User mergeUser = this.hibernateTemplate.merge(user); return mergeUser.getId(); } } Create a UserService class which is responsible for performing User operations. package com.sivalabs.springmvc.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sivalabs.springmvc.entities.User; import com.sivalabs.springmvc.repositories.UserRepository; /** * @author SivaLabs * */ @Service public class UserService { @Autowired private UserRepository userRepository; public List getAllUsers() { return this.userRepository.getAllUsers(); } public Integer createUser(User user) { return this.userRepository.createUser(user); } } Now let us create ApplicationContext from AppConfig.java and test the functionality. package com.sivalabs.test; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.sivalabs.springmvc.entities.User; import com.sivalabs.springmvc.services.UserService; public class ContainerTest { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.scan("com.sivalabs");//This will load the configured components UserService, UserRepository, ctx.refresh(); System.out.println(ctx); UserService userService = ctx.getBean("userService", UserService.class); List allUser = userService.getAllUsers(); for (User u : allUser) { System.out.println(u); } User user = new User(null, "K.siva reddy", "hyderabad"); Integer id = userService.createUser(user); System.out.println("Newly created User Id="+id); allUser = userService.getAllUsers(); for (User u : allUser) { System.out.println(u); } } } See how application development is much more easier now with Annotations. From : http://sivalabs.blogspot.com/2011/02/springhibernate-application-with-zero.html
February 23, 2011
by Siva Prasad Reddy Katamreddy
· 75,250 Views · 7 Likes
article thumbnail
The Easiest Ways to Navigate Methods in a Class using Eclipse Keyboard Shortcuts
java classes can get big and hairy, making it difficult to find the method you’re looking for when browsing or editing a class. there is no specific order to where methods can be in a class and different developers have different preferences about where to put them. you could use the mouse wheel and scroll ferociously until you eventually find the method or you could even use page down/page up on your keyboard. but these methods can be time-consuming and haphazard, especially when the class has lots of methods or they’re scattered in an arbitrary order. luckily, eclipse has a number of fast and easy ways to help you navigate methods in a class, especially using the keyboard. i’ll discuss some of those keyboard shortcuts and also which ones to use when. quick outline the quick outline is basically a scaled-down popup version of the outline view. the main advantage over the outline view is that it has a search box that allows you to search for a method. here’s how to use the quick outline: press ctrl+o from anywhere within the class. type a search term in the search box and eclipse will just show all methods that match the search term. by default eclipse does an exact match search, but you can use wildcards. once you see the method you’re interested in, press down to select the method (if it’s not selected already). press enter once the method is selected. eclipse will take you directly to the method’s declaration. this is an example of the popup for java’s arraylist . searching for *rem will search for all method names that contain the word rem . here’s an example: notes: sort the view using the the down arrow menu in the top right corner. it makes it easier to find methods by scanning. resize the quick outline popup to see more methods. eclipse remembers the size of the popup for the next time you open it. next member & previous member another way to move between methods is to use two features called go to next member and go to previous member. when you press ctrl+shift+down , eclipse moves the cursor to the next method in the class. pressing ctrl+shift+up moves to the previous method. here’s a video to give you a quick example of how these shortcuts work: this shortcut works best if you’re already positioned in a method or if the class has few fields. that’s because to eclipse a member can either be a method or a field. if you’re at the top of the class, you have to move through all the fields before you actually start moving through the methods themselves, a time-consuming process especially for bigger classes with lots of fields. it helps to generate getters and setters at the bottom of the class because you don’t have to navigate through them to get to the useful methods. open declaration if you’ve got lots of private methods in your class then open declaration might be the best way to navigate between them. when you’re positioned on a method call and press f3 , eclipse takes you directly to the definition of that method. for example, if you’re busy in the method process() and your cursor’s positioned on initprocessing() , pressing f3 will take you directly to the declaration for that method further down the class. public void process() { //do things... initprocessing(); //... } ... private void initprocessing() { //init something... } this feature works very well with alt+left (backward history). see the section below for more details about the backward history. navigating back to a previously viewed method while browsing code, you’ll often want to return to the previous method you were viewing once you’re done viewing the method it calls. to do this, use alt+left (backward history) to move back to the last navigation point. this feature isn’t specific to just methods, but also works for navigating between previously visited editors. but it works great if you’ve just been browsing methods within a class. quick mentions eclipse’s outline view also allows easy navigation but mostly with the mouse. you could navigate to the view using alt+shift+q, o , and you can move to methods by typing their first letter, but i’ve found the quick outline to be more keyboard friendly. also, the outline view doesn’t support wildcard searches. you can also use eclipse’s call hierarchy ( ctrl+alt+h ) especially if you’re trying to understand the flow of methods in a class and move between them easily. knowing how to navigate between views and editors with the keyboard helps a lot since you’ll be moving between the call hierarchy view and editors a lot. what should i use when? use next/previous member shortcut if the class is small or you have a good idea of where other methods are in relation to the current method (eg. are they above/below the current method). use the quick outline if you don’t know the class too well or there are lots of methods in the class. use open declaration if you’re moving between many private methods of the class. it’s normally the fastest way to move to another private method in the class, but only if you’re already positioned in a method that calls it. from http://eclipseone.wordpress.com/2011/02/21/the-easiest-ways-to-navigate-methods-in-a-class-using-eclipse-keyboard-shortcuts/
February 22, 2011
by Byron M
· 66,667 Views · 2 Likes
  • Previous
  • ...
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • ...
  • 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
×