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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

The Latest Coding Topics

article thumbnail
Practical PHP Testing Patterns: Test Spy
The concept of behavior verification consists in verifying not only the output of the System Under Test, but the calls to other components. These method calls are an output normally not visible to a caller like the test; unless he injects, instead of the real collaborator, a Test Double which can be accessed also by him. Today we will explore the first pattern for behavior verification: the Test Spy. It is a Test Double which records calls so that assertions can be made on them later in the test (after the exercise part). Spies gives us the ability to observe side-effects of the SUT, expressed as interactions with other objects. Usually behavior verification is taught with Mocks, which also verify the calls that are made on them but with specifications provided before the exercise phase. Use cases Why using a Spy instead a Mock? I bet you have heard already about Mocks at this point in the series. Here are some possible use cases on when to define Test Spies. When we cannot predict what the collaborator will be called with (if we can, we may use a Mock instead). When an assertion on calls is complex to define beforehand, or needs all (or more than one of) the calls to be completed before taking place. The matchers used for Mocks are not sufficient for verification. When a Mock that immediately threw an exception would only result in the SUT swallowing it. So a Spy is better in this case as it leaves verification for later. PHPUnit matchers in general do not always throw an exception or always wait for the end of test (it depends on the particular constraint.) The behavior involves more than one collaborator (it happens sometimes). In this case, you can make an assertion using the data recorded by more than one Spy. Implementation 1. Like with all Test Doubles, provide an alternate implementation or subclass. Probably the calls to the Spy won't return anything (or will return something canned to avoid the SUT's failure, like in a Stub). The methods implementations will just record all calls, or some property of the calls like the first parameter or their total number. 2. Inject the Test Double and exercise the SUT. 3. Make assertions on the Test Double data gathered by the Spy. Variations The variations of the pattern are mainly on how to retrieve the data from the Test Spy. Retrieval Interface: the Test Spy is a class with additional methods, or public properties (eek) that expose the recorded data. This variation cannot be coded with PHPUnit generation of Test Doubles, only by hand-rolling them. Self Shunt: the Test Spy and Test Case Object are a single object. This means we inject $this as the Test Double and we have the maximum freedom of defining new methods and access the recording. The caveat is that it can only be done with interfaces in PHPUnit, because Test Case Classes must extend PHPUnit_Framework_TestCase. That's a good reason to extract an interface, though. Inner Test Double: we inject a private class (not existent in PHP) or a closure which records everything. A closure for example can access $this public properties or methods, or some other local ArrayObject passed by handler (or variable passed by reference) where the data can be kept. Indirect Output Registry: same as Inner Test Double, but the target for recordings is a full-fledged object. Almost always an overkill. Examples The sample code shows you how to implement a Spy, in its different variations and in use cases where it actually make sense. Most of the times, Mock are used instead and the pattern is equivalent. Test Spies are a little more difficult to write, but they are invaluable in the case where your verification logic does not fit the framework of Mocks (predefined, single-object expectations). createUser(array('mail' => 'someone@example.com', 'nickname' => 'johndoe')); $this->assertEquals(array('executeQuery', 'mail'), $this->order); } private $order = array(); private $queries = array(); public function executeQuery($query, array $params) { $this->order[] = 'executeQuery'; $this->queries[] = $query; } private $mails = array(); public function mail($to, $subject, $object) { $this->order[] = 'mail'; $this->mails[] = array('to' => $to, 'subject' => $subject, 'object' => $object); } public function testInnerTestDoubleArrayObject() { $parts = new ArrayObject(); $receiver = $this->getMock('Receiver'); $receiver->expects($this->any()) ->method('definePart') ->will($this->returnCallback(function($amount) use ($parts) { $parts[] = $amount; })); $sut = new RandomDivider($receiver); $sut->divide(10); $this->assertEquals(10, array_sum($parts->getArrayCopy())); } public function testInnerTestDoubleArrayPassedByReference() { $parts = array(); // an array would not be passed by handler by default $receiver = $this->getMock('Receiver'); $receiver->expects($this->any()) ->method('definePart') ->will($this->returnCallback(function($amount) use (&$parts) { // but we can pass it by reference $parts[] = $amount; })); $sut = new RandomDivider($receiver); $sut->divide(10); $this->assertEquals(10, array_sum($parts)); } } interface Mailer { public function mail($to, $subject, $object); } interface Db { public function executeQuery($query, array $params); } class UserDao { private $db; private $mailer; public function __construct(DB $db, Mailer $mailer) { $this->db = $db; $this->mailer = $mailer; } public function createUser(array $userDetails) { // internally it would use PDO $this->db->executeQuery("INSERT INTO users ...", $userDetails); $this->mailer->mail($userDetails['mail'], 'You have been registered on example.com', '...'); } } interface Receiver { public function definePart($amount); } class RandomDivider { private $receiver; public function __construct(Receiver $receiver) { $this->receiver = $receiver; } public function divide($total) { $part = ceil(rand() * $total); $this->receiver->definePart($part); $this->receiver->definePart($total - $part); } }
March 9, 2011
by Giorgio Sironi
· 3,025 Views
article thumbnail
Upgrading to JSF 2
Last week, I spent a few hours upgrading AppFuse from JSF 1.2 to JSF 2.0. In reality, I upgraded from MyFaces 1.2.7 to 2.0.4, but all JSF implementations should be the same, right? All in all, it was a pretty easy upgrade with a few minor AppFuse-specific things. My goal in upgrading was to do the bare minimum to get things working and to leave integration of JSF 2 features for a later date. In addition to upgrading MyFaces, I had to upgrade Tomahawk by changing the dependency's artifactId to tomahawk20. I was also able to remove the following listener from my web.xml: org.apache.myfaces.webapp.StartupServletContextListener After that, I discovered that MyFaces uses a new URI (/javax.faces.resource/) for serving up some of its resource files. I kindly asked Spring Security to ignore these requests by adding the following to my security.xml file. Since JSF 2 includes Facelets by default, I tried removing Facelets as a dependency. After doing this, I received the following error: ERROR [308855416@qtp-120902214-7] ViewHandlerWrapper.fillChain(158) | Error instantiation parent Faces ViewHandler java.lang.ClassNotFoundException: com.sun.facelets.FaceletViewHandler at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:244) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:230) at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:401) at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:363) at org.ajax4jsf.framework.ViewHandlerWrapper.fillChain(ViewHandlerWrapper.java:144) at org.ajax4jsf.framework.ViewHandlerWrapper.calculateRenderKitId(ViewHandlerWrapper.java:68) at org.apache.myfaces.lifecycle.DefaultRestoreViewSupport.isPostback(DefaultRestoreViewSupport.java:179) at org.apache.myfaces.lifecycle.RestoreViewExecutor.execute(RestoreViewExecutor.java:113) at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:171) at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189) Figuring this was caused by the following element in my web.xml ... org.ajax4jsf.VIEW_HANDLERS com.sun.facelets.FaceletViewHandler ... I removed it and tried again. This time I received a NoClassDefFoundError: java.lang.NoClassDefFoundError: com/sun/facelets/tag/TagHandler at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632) at java.lang.ClassLoader.defineClass(ClassLoader.java:616) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) at java.net.URLClassLoader.defineClass(URLClassLoader.java:283) at java.net.URLClassLoader.access$000(URLClassLoader.java:58) at java.net.URLClassLoader$1.run(URLClassLoader.java:197) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:392) at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:363) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:247) at org.apache.myfaces.shared_impl.util.ClassUtils.classForName(ClassUtils.java:184) at org.apache.myfaces.view.facelets.util.ReflectionUtil.forName(ReflectionUtil.java:67) Since everything seemed to work with Facelets in the classpath, I decided to save this headache for a later date. I entered two issues in AppFuse's JIRA, one for removing Facelets and one for replacing Ajax4JSF with RichFaces. The next issue I encountered was redirecting from AppFuse's password hint page. The navigation-rule for this page is as follows: navigation-rule> /passwordHint.xhtml success /login With JSF 2.0, the rule changes the URL to /login.xhtml when redirecting (where it was left as /login with 1.2) and it was caught by the security setting in my web.xml that prevents users from viewing raw templates. Protect XHTML Templates *.xhtml To solve this issue, I had to make a couple of changes: Comment out the security-constraint in web.xml and move it to Spring Security's security.xml file. Add a rule to urlrewrite.xml that redirects back to login (since login.xhtml doesn't exist and I'm using extensionless URLs). ^/login.xhtml$ %{context-path}/login After getting the Password Hint feature passing in the browser, I tried running the integration tests (powered by Canoo WebTest). The Password Hint test kept failing with the following error: [ERROR] /Users/mraible/dev/appfuse/web/jsf/src/test/resources/web-tests.xml:51: JavaScript error loading page http://localhost:9876/appfuse-jsf-2.1.0-SNAPSHOT/passwordHint?username=admin: syntax error (http:// localhost:9876/appfuse-jsf-2.1.0-SNAPSHOT/javax.faces.resource/oamSubmit.js.jsf?ln=org.apache.myfaces#122) Figuring this was caused by my hack to submit the form when the page was loaded, I turned to Pretty Faces, which allows you to call a method directly from a URL. After adding the Pretty Faces dependencies to my pom.xml, I created a src/main/webapp/WEB-INF/pretty-config.xml file with the following XML: #{userForm.edit} #{passwordHint.execute} This allowed me to remove both editProfile.xhtml and passwordHint.xhtml, both of which simply auto-submitted forms. At this point, I figured I'd be good to go and ran my integration tests again. The first thing I discovered was that ".jsf" was being tacked onto my pretty URL, most likely by the UrlRewriteFilter. Adding the following to my PasswordHint.java class solved this. if (username.endsWith(".jsf")) { username = username.substring(0, username.indexOf(".jsf")); } The next thing was a cryptic error that took me a while to figure out. DEBUG [1152467051@qtp-144702232-0] PasswordHint.execute(38) | Processing Password Hint... 2011-03-05 05:48:52.471:WARN::/passwordHint/admin com.ocpsoft.pretty.PrettyException: Exception occurred while processing <:#{passwordHint.execute}> null at com.ocpsoft.pretty.faces.beans.ActionExecutor.executeActions(ActionExecutor.java:71) at com.ocpsoft.pretty.faces.event.PrettyPhaseListener.processEvent(PrettyPhaseListener.java:214) at com.ocpsoft.pretty.faces.event.PrettyPhaseListener.afterPhase(PrettyPhaseListener.java:108) at org.apache.myfaces.lifecycle.PhaseListenerManager.informPhaseListenersAfter(PhaseListenerManager.java:111) at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:185) at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189) Digging into the bowels of MyFaces, I discovered a class was looking for a viewId with an extension and no view-id was being set. Adding the following to the top of my execute() method solved this. getFacesContext().getViewRoot().setViewId("/passwordHint.xhtml"); After making this change, all AppFuse's integration tests are passing and the upgrade seems complete. The only other issues I encountered were logging-related. The first is an error about Tomahawk that doesn't seem to affect anything. Mar 5, 2011 6:44:01 AM com.sun.facelets.compiler.TagLibraryConfig loadImplicit SEVERE: Error Loading Library: jar:file:/Users/mraible/.m2/repository/org/apache/myfaces/tomahawk/tomahawk20/1.1.10/tomahawk20-1.1.10.jar!/META-INF/tomahawk.taglib.xml java.io.IOException: Error parsing [jar:file:/Users/mraible/.m2/repository/org/apache/myfaces/tomahawk/tomahawk20/1.1.10/tomahawk20-1.1.10.jar!/META-INF/tomahawk.taglib.xml]: at com.sun.facelets.compiler.TagLibraryConfig.create(TagLibraryConfig.java:410) at com.sun.facelets.compiler.TagLibraryConfig.loadImplicit(TagLibraryConfig.java:431) at com.sun.facelets.compiler.Compiler.initialize(Compiler.java:87) at com.sun.facelets.compiler.Compiler.compile(Compiler.java:104) The second is excessive logging from MyFaces. As far as I can tell, this is because MyFaces switched to java.util.logging instead of commons logging. With all the frameworks that AppFuse leverages, I think it has all the logging frameworks in its classpath now. I was hoping to fix this by posting a message to the mailing list, but haven't received a reply yet. [WARNING] [talledLocalContainer] Mar 5, 2011 6:50:25 AM org.apache.myfaces.config.annotation.TomcatAnnotationLifecycleProvider newInstance [WARNING] [talledLocalContainer] INFO: Creating instance of org.appfuse.webapp.action.BasePage [WARNING] [talledLocalContainer] Mar 5, 2011 6:50:25 AM org.apache.myfaces.config.annotation.TomcatAnnotationLifecycleProvider destroyInstance [WARNING] [talledLocalContainer] INFO: Destroy instance of org.appfuse.webapp.action.BasePage After successfully upgrading AppFuse, I turned to AppFuse Light, where things were much easier. Now that AppFuse uses JSF 2, I hope to start leveraging some of its new features. If you're yearning to get started with them today, I invite you to grab the source and start integrating them yourself. From http://raibledesigns.com/rd/entry/upgrading_to_jsf_2
March 8, 2011
by Matt Raible
· 19,843 Views · 1 Like
article thumbnail
Java 7: Do we really need <> in the diamond operator?
As you may know, one of new features of upcoming Java 7 will be the diamond operator. Purpose of the diamond operator is to simplify instantiation of generic classes. For example, instead of List p = new ArrayList(); with the diamond operator we can write only List p = new ArrayList<>(); and let compiler infer the value of type argument. Nice simplification. But do we really need to write <>? Isn't new ArrayList() enough? In this article, I will describe the arguments of the <> proponents and explain why I think that these arguments are not very strong. However, I also describe arguments why we need <>. In Java 1.4, we had raw types only: List p = new ArrayList(); Java 5 introduced generics: List p = new ArrayList(); Many types in Java API were generified and even though we can still use generic types as raw types, there is no reason for this in Java 5 or newer. When generics were introduced, raw types were allowed for backward compatibility so that we could gradually and smoothly adopt generics. For example, code in Java 1.4 can be combined with new generic code because raw and generic types are allowed together. This is also expressed in the JLS (4.8 Raw Types): "The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types." Now let's go back to the diamond operator and ask again: "Do we really need <>?". The proponents of the <> syntax say that we need <> to preserve backward compatibility. Let's look at an example from the coin-dev conference: class Foo { Foo(X x) { } Foo get(X x) { return this; } } class Test { void test() { Foo f1 = new Foo(1).get(""); //ok - can pass String where Object is expected Foo f2 = new Foo<>(1).get(""); //fail - cannot pass String where Integer is expected } } This shows the difference between new Foo(1) and new Foo<>(1). Clearly, these two are different and if we changed the semantics of new Foo(1), it would break backward compatibility. But wait. Backward compatibility with what? Isn't line Foo f1 = new Foo(1).get(""); a little suspicious? It uses generic type in the left part and raw type in the right part. Although it is legal, it is probably either omission or malpractice. And its legality is probably only a side effect of "a concession to compatibility of legacy code". Let's go further and look at another example from the coin-dev conference. It shows the difference between raw type and parameterized type with the diamond: public class X { public X(T t) { } public T get() { return null; } public static int f(String s) { return 1; } public static int f(Object o) { return 2; } public static void main(String[] args) { System.out.println(f(new X<>("").get())); System.out.println(f(new X("").get())); } } Let's play with the code a bit. Let's assume that there was a library with the X class: public class X { public X(Object o) { } public Object get() { return null; } } and some code that compiled against this library: public class Client { static int f(String s) { return 1; } static int f(Object o) { return 2; } public static void main(String[] args) { System.out.println(f(new X("").get())); } } Then, the library was generified: public class X { public X(T t) { } public T get() { return null; } } and we compiled the client project against the generified version. Now, if we changed the semantics of new X("") to new X("") (or new X<>("") with the diamond syntax), the code would behave differently. So, the answer to the title question is 'yes'. If we want to stay backward compatible, we need <> and we cannot put new X("") semantically equal to new X<>(""). Another questions are how long can Java evolve and remain compatible with concessions to compatibility and whether newcomers to Java will appreciate this. From http://tronicek.blogspot.com/2011/03/do-we-really-need-in-diamond-operator.html
March 7, 2011
by Zdenek Tronicek
· 58,772 Views · 3 Likes
article thumbnail
Persisting Entity Classes using XML in JPA
Preface This document explains the working of a JPA application purely based on XML configurations. This explains how to create entity classes without using any annotations in Java classes. Entire configuration is done using xml files. Introduction Persistence is one of the major challenges for enterprise applications. JPA is the persistence standard from Sun Microsystems. JPA supports two ways of configuring persistence information- through annotations and XML files. This article discusses the XML based approach towards embedding persistence information for the entity classes. Setting up the environment JPA is light-weight persistence model. It works for both JavaSE and JavaEE applications. All the required class files are present in the JavaEE.jar file which should be added to the classpath. Along with the JavaEE.jar file, we need to add the Persistence Provider jar file as well to the classpath. The provider can be Toplink/ Hibernate/ App server specific persistence provider. In this application, we’ve used Toplink as the persistence provider. So we need to add toplink-essentials.jar file as well in the class path. To summarize, the jar files required are: 1.JavaEE.jar 2.ToplinkEssentials.jar (Replace with the jar file for Persistence Provider, in case you want to use other persistence provider) 3.derbyClient.jar (For JavaDB (Derby) Database, replace this with the jar file of your database) Instead of adding the configuration details in the entity class in the form of annotations, we’ll add the configuration information in the orm.xml file. Before we look into the code, let us discuss the orm.xml file in detail. orm.xml orm.xml file contains all the configuration details required for mapping a class to a relational database table. These details include the primary key of the entity class and the various constraints/ rules to be applied for the primary key. Other details about the entity class include the various attributes of the entity class and columns to which the attributes should be mapped. We can also specify multiple constraints for the same attribute. Other configurable things include information about the various relationships the entity may have with other entities (one-to-one, many-to-one, many-to-many or one-to-many), embedded attributes, information about the version and transient attributes. One application can have multiple entities. The configuration details about all these entity classes, embeddable classes go inside the same orm.xml file. Name of this configuration file can be anything, not mandatorily orm.xml. It should be placed in META-INF subdirectory along with the persistence.xml file. Persistence.xml file should include the orm.xml file. Please find below sample orm.xml and persistence.xml file. The xml schema definitions are highlighted for both. Also, please note the entry required in persistence.xml for including the orm.xml file. PFB the entries made in a sample orm.xml, which’ll persist employee instances to the database. My First JPA XML Application entity Different properties in orm.xml file The various properties in the orm.xml in the order defined in xml schema definition are discussed below: Root tag is It contains the following four types of elements: The persistence-unit-metadata element contains metadata for the entire persistence unit. It is undefined if this element occurs in multiple mapping files within the same persistence unit. The package, schema, catalog and access elements apply to all the entity, mapped-superclass and embeddable elements defined in the same file in which they occur. The sequence-generator, table-generator, named-query, named-native-query and sql-result-set-mapping elements are global to the persistence unit. The entity, mapped-superclass and embeddable elements each define the mapping information for a managed persistent class. The mapping information contained in these elements may be complete or it may be partial. One line string information about the entity classes in the application. specifies the package of the classes listed within the sub elements and attributes of the same mapping file only. classAttribute defines the fully qualified class name of the entity class name: Attribute defines the name of the entity entity: tag can be repeated to embed mapping information for all the entity classes in the application. The Sub-Tags of entity tag are maps the database table to which the entity class shall be persisted overrides or creates a new id-class setting overrides or creates a new inheritance setting overrides or creates a new discriminator value setting, useful in Single_Table Inheritance strategy. overrides or creates a new discriminator column setting, used while configuring Super class in Single_Table inheritance strategy. A sequence-generator is unique by name A table-generator is unique by name used to define named-query for the entity class. Can be repeated to define multiple named queries for the entity class. used to define native named query for the entity class. creates or overrides a pre-persist setting i.e. the entity listener method to be invoked before persisting the entity instance. creates or overrides a post-persist setting i.e. the entity listener method to be invoked after persisting the entity instance. creates or overrides a pre-remove setting i.e. the entity listener method to be invoked before removing the entity instance. creates or overrides a post-remove setting i.e. the entity listener method to be invoked after removing the entity instance. creates or overrides a pre-update setting i.e. the entity listener method to be invoked before updating the entity instance. creates or overrides a post-update setting i.e. the entity listener method to be invoked before updating the entity instance. creates or overrides a post-load setting i.e. the entity listener method to be invoked after loading the entity instance state from database defines the attributes of the entity class which shall be persisted in the database table. The sub tags of the attributes are: :- this tag defines the id column of the entity class. Cannot be repeated for an entity. An entity class can have only one Id attribute. :-this is used to define the ID generation strategy to be used for the primary key column. :-this tag is used to map the entity columns to the columns in the database table. Should be repeated to provide configurations for all the attributes of the entity class. :- This tag is used to add the various column-level constraints on the entity attributes. E.g. unique, insertable, updatable, length, precision etc. :- maps the Version attribute of the entity class. Development Environment We’ve used NetBeans IDE 6.5.1 for creating this JavaSE application for persistence through XML files. NetBeans has persistence support for JPA as well as Hibernate. So, we can choose either Hibernate or Toplink Essentials as the Persistence Provider. Let’s name the application as “JPAEntity”. The name of the entity class is “Employee” and is placed in the package “entity”. “EmpClient.java” is the client class. The xml configuration files are put in META-INF sub directory. The directory structure of the application is as follows:- First JPA META-INF orm.xml persistence.xml entity Employee.java EmpClient.java Developing the Application Step1:Start the NetBeans IDE. Create a new Java Application Step 2:Add the jar files for the Persistence Provider (Toplink Essentials in our case), JavaEE.jar and the database driver(DerbyClient.jar in our case) to the classpath. Step 3: Add the entity class “Employee.java” and client class “EmpClient.java” in the package "jpaentity" This is the code of Employee.java package jpaentity; public class Employee { private int empId; private String empName; private double empSalary; public Employee() { } public Employee(int empId, String empName, double empSalary) { this.empId = empId; this.empName = empName; this.empSalary = empSalary; } public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public double getEmpSalary() { return empSalary; } public void setEmpSalary(double empSalary) { this.empSalary = empSalary; } @Override public String toString() { return "Employee Id:="+empId+ +" Employee Name:="+empName+" Employee Salary:="+empSalary; } }//End of Employee.java This is the code of EmpClient.java package jpaentity; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class EmpClient { private EntityManager em; private EntityManagerFactory emf; public void initEmfAndEm() { emf=Persistence.createEntityManagerFactory("JPAEntityPU"); em=emf.createEntityManager(); } public void cleanup() { em.close(); } public void insertAndRetrieve() { System.out.println("-------------------Creating the Objects---------------------"); Employee empObj1=new Employee(1, "Anu", 1000.0); Employee empObj2=new Employee(2, "Rahul", 1500.0); System.out.println("-------------------Starting the transaction---------------------"); em.getTransaction().begin(); em.persist(empObj1); em.persist(empObj2); System.out.println("-------------------Committing the transaction---------------------"); em.getTransaction().commit(); System.out.println("-------------------Objects saved successfully--------------------"); System.out.println("*******************************************************************"); System.out.println("------------------- Reading Objects--------------------"); List emps=em.createQuery("select p from Employee p").getResultList(); for (Employee current:emps) System.out.println(current); System.out.println("-------------------Finished Reading Objects--------------------"); } public static void main(String args[]) { EmpClient myClient=new EmpClient(); System.out.println("-------------------Starting the Client---------------------"); myClient.initEmfAndEm(); myClient.insertAndRetrieve(); myClient.cleanup(); System.out.println("---------------Shutting down the Client---------------------"); } }//End of EmpClient.java Step 4: Set up the database connection. Go to Services Tab in the NetBeans IDE and expand the Databases node. Right click on JavaDB node and select Create Database. Give the database name, username and password and click on OK. The database is created and ready to accept connections. Step 5: Add the persistence unit to the application. Also, add the orm.xml file. The name of the orm.xml file can be changed. We have named it mapping.xml. Following is the code of mapping.xml file My First JPA XML Application entity Add the following code to the persistence.xml file oracle.toplink.essentials.PersistenceProvider \META-INF\orm.xml jpaentity.Employee Steps for execution Compile the source files Build the project Start the Database Server Execute the “EmpClient” class. Connect to the database & verify the table has been created & data is also added in the table. Advantages and Disadvantages of Using XML for Configuration Advantages No coupling between the metadata and the source code Compatible with pre EJB3.0 development process Support from IDEs like NetBeans, Eclipse etc Easy to modify with the help of good editors. Disadvantages Complexity Difficulty in debugging in absence of editors Wrap Up This article helps in understanding entity configuration with XML files as an alternative to embedding annotations in Java code for configuring persistence details.
March 6, 2011
by Anu Bakshi
· 130,683 Views · 1 Like
article thumbnail
IBatis (MyBatis): Handling Joins: Advanced Result Mapping, Association, Collections, N+1 Select Problem
This tutorial will present examples using advanced result mappings, how to handle mappings with association, collections, the n+1 problem, and more.
March 2, 2011
by Loiane Groner
· 119,881 Views · 2 Likes
article thumbnail
How to Create a Statically Linked Version of git Binaries
Creating a statically linked version of a unix software saves you in all the circumstances where you can’t install the software as root, when you don’t have development tools on the target machine, when you cannot find a prepackaged version for the specific server, when the libraries available on a server are conflicting with the ones required by your software, etc. Examples: The unix server that hosts this blog, provides me a restricted shell to manage mysql and public web files with minimal access privileges. On this server I periodically update WordPress and other things, and I like to keep the changes under control and backed up with git. The problem is that on this server I haven’t git binaries, and I cannot install software and libraries required. Having the files of my WordPress installation under git version control saved me a lot of time in the past when somebody hacked into the server and changed the php files to do nasty stuff. I was able to easily check what was exactly changed since last legitimate update with “git status” command, and restore things as before. I own a little NAS (network attached storage) which runs a mini distribution of Linux which doesn’t have a prepackaged version of git to install, nor I cannot use any package management tool like apt rpm or yum etc. So I thought that I can compile by myself the git binaries and have them deployed on the target machine. It is possible, but there is an important note: when you build a software on a unix server, the resulting binaries are referencing the libraries installed there, so you cannot easily port the binaries between servers since they have dependencies. What you need is a “statically linked” version of the software, which fortunately it’s not so difficult to achieve. Binaries which are statically linked are usually bigger in size and will possibly require more memory to execute, but they won’t require the specific libraries to be present on the executing computer, since the libraries code is contained in the binaries themselves. Here is how I built a static version of git on an ubuntu virtual machine, that can be ported to other unix servers: # let's make sure we have all we need to proceed $ sudo apt-get install libexpat1-dev asciidoc libz-dev gettext curl # let's create the directory to host the built artifacts $ sudo mkdir /opt/git-1.7.4.1-static # we are ready to download and unpack latest version of git sources $ curl http://kernel.org/pub/software/scm/git/git-1.7.4.1.tar.bz2 | tar xvj $ cd git-1.7.4.1/ # then compile and install the files in the target directory we created $ ./configure --prefix=/opt/git-1.7.4.1-static CFLAGS="${CFLAGS} -static" NO_OPENSSL=1 NO_CURL=1 $ sudo make install $ sudo make install-doc On the above commands, the thing to notice is the CFLAGS=”${CFLAGS} -static” which is used to specify that the libraries must be statically linked with the binaries. The last thing to do is create a tarball of /opt/git-1.7.4.1-static folder and copy that on the target machine; adding the /opt/git-1.7.4.1-static/bin directory to the PATH variable and the /opt/git-1.7.4.1-static/share/man to the MANPATH variable. If possible, it’s a good idea to keep the same installation path on target machine (/opt/git-1.7.4.1-static) since this path gets hardcoded in some git scripts during the build process. But it shouldn’t give too many problems, anyway. From http://en.newinstance.it/2011/02/27/how-to-create-a-statically-linked-version-of-git-binaries/
February 28, 2011
by Luigi Viggiano
· 11,136 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,061 Views
article thumbnail
5 Key Events in the history of Cloud Computing
While we have been evaluating in our blog posts the various features available on popular Cloud Computing platforms today, I thought it might be a good idea to understand when and how all this started and look back at where this began and trace some of the key events in the progress of cloud computing. Amazon like all other Internet companies in the period of the dot com bubble were left with large amounts of underutilized computing infrastructure, reports suggest less than 10% of the server infrastructure of many companies were being used. Amazon may have use cloud computing as a way to provide this unused resources as utility computing service when they launched S3 as the first true cloud computing service in March 2006. 1. Launch of Amazon Web Services in July 2002 The initial version of AWS in 2002 was focused more on making information available from Amazon to partners through a web services model with programmatic and developer support and was very focused on Amazon as a retailer. While this set the stage for the next steps the launch of S3 was the true step towards building a cloud platform. Amazon Press Release 2. S3 Launches in March 2006 Here are some interesting articles on the launch of S3 in 2006. The real breakthrough however was the pricing model for S3 which defined the model of 'pay-per-use' which has now become the defacto standard for cloud pricing. Also the launch of S3 really defined the shift of Amazon from being just a retailer to a strong player in the technology space. Techcrunch Post on S3 on March 14th, 2006 Read Write Web Post on S3 and EC2 on Nov 3rd, 2006 Business Week Article on Jeff Bezos vision on cloud computing on Nov 13th, 2006 3. EC2 Launches in August 2006 EC2 had a much quieter launch in August 2006 but i would think had the bigger impact by making core computing infrastructure available. This completed the loop on enabling a more complete cloud infrastructure being available. In fact at that time analysts had some difficulty in understanding what the big deal is, and thought it looks similar to other hosting services available online only with a different pricing model. Some interesting articles from that time on the launch: Technologyevangelist Blog Virtualization Info 4. Launch of Google App Engine in April 2008 The launch of Google App Engine in 2008 was the entry of the first pure play technology company into the Cloud Computing market. Google a dominant Internet company entering into this market was clearly a major step towards wide spread adoption of cloud computing. As with all their other products they introduced radical pricing models with a free entry level plan and extremely low cost computing and storage services which are currently among the lowest in the market. Techcrunch post on App Engine Launch Google App Engine Launch Post 5. Windows Azure launches Beta in Nov 2009 The entry of Microsoft into Cloud Computing is a clear indication of the growth of the space. Microsoft for long has not accepted the Internet and the web as a significant market and has continued to focus on the desktop market for all these years. I think this is a realization that a clear shift is taking place. The launch of Azure is a key event in the history of cloud computing with the largest software company making a small but significant shift to the web. Launch of Azure Beta Azure General Availability - Feb 2010 You might also like: Cloud Computing, Google App Engine: How big is the market Really ? Comparing Google App Engine with Amazon EC2 Comparing Amazon EC2 and Microsoft Azure Languages Supported by Google App Engine Cloud Computing: What is it really ?
February 26, 2011
by Kaushik Raghupathi
· 46,936 Views
article thumbnail
How to Collect the Images and Meta Tags from a Webpage with PHP
Meta Tags and the Facebook Example You’ve definitely seen the “share a link” screen in Facebook. When you paste a link into the box (fig. 1) and press the “Attach” button you’ll get the prompted cite parsed with a title, description and possibly thumb (fig. 2). This functionality is well known in Facebook, but it appears to be well known also in various social services. In fact Linkedin, Reddit, ‘s bookmarklet use it. fig. 1 - Facebook Attach a Link Prompt Screen Fist thing to notice is that this information, prompted by Facebook, is the same as the meta tag information. However there is a slight difference. fig. 2 - Facebook Attached Link Screen Facebook prefers for the thumb the image set into the . In the case above this tag appears to be: And the image pointed in the SRC attribute is exactly the same as the one prompted by Facebook (fig. 3). fig. 3 - Vimeo Thumb First thing to note is that the real thumb is bigger than the thumb shown in Facebook, so Facebook resizes it and the second thing to note is that there are more meta tags of the og:… format. Meta Tags and The Open Graph Protocol By default meta tags contain various information about the web page. They are not visible in the webpage, but contain some info about it. The most common meta tags are the title, description and keywords tags. They of course contain the title of the page, not that this can be different from the
February 25, 2011
by Stoimen Popov
· 24,246 Views · 1 Like
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,070 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
· 74,974 Views · 7 Likes
article thumbnail
How to remove getters and setters
Getters and setters are one of the first abstraction step that is thought over public fields in object-oriented programming. However, the paradigm was never about encapsulating properties by providing a special reading/writing mechanism via methods, but about objects responding to messages. In other words, encapsulation is (not only, but also) about being capable of changing private fields. If you write getters and setters, you introduce a leaky abstraction over private fields, since the names and number of your public methods are influenced coupled to them. They aren't really private anymore: for example in service classes I pass dependencies for private methods in the constructor, and the client code is never affected when these dependencies change. With getters and setters, a field addition, removal or renaming affects the contract of the class. In this article, we're going to take this User Entity class and explore the many ways we have for removing getters and setters. The choice between them depends mainly on what you need them for: it's the client code that should decide what contracts wants from these classes. nickname = $nickname; } public function getNickname() { return $nickname; } public function setPassword($password) { $this->password = $password; } public function getPassword() { return $this->password; } // ... you get the picture: other 8 getters or setters } The various techniques are ordered by complexity. As always, I express use cases for the User class via a test case. All the code is on Github. Constructor First, we can pass some fields in the constructor. If we do not expose the field then, the value will be immutable and the client code will never even know that this value exists. For example, our User has an immutable nickname, which serves also as a primary key: public function testPassWriteOnlyDataInTheConstructor() { $user = new User('giorgiosironi'); // should not explode //removed the setter as it cannot be changed } class User { public function __construct($nickname, $activationKey = '') { $this->nickname = $nickname; $this->activationKey = $activationKey; } } Information Expert Next, we have the Information Expert pattern: assign an operation to the object with the greatest knowledge for accomplishing it. If you do so, you won't need to expose private fields via getters and setters, since you will model some behavior as code in that class, which can see private fields. For example, when we register an User we want to activate it via email verification, so we send an activation key via mail. But to check it, we don't need to extract the value from the User object. // Information Expert /** * @expectedException InvalidArgumentException */ public function testAnUserIsActivated() { $user = new User('giorgiosironi', 'ABC'); $user->activate('AB'); } class User { public function activate($key) { if ($this->activationKey === $key) { $this->active = true; return; } throw new InvalidArgumentException('Key for activation is incorrect.'); } } This style is an example of the Tell, Don't Ask principle: we tell our User to do something instead of asking it for information and doing it ourselves. Double Dispatch Putting behavior inside an Entity class is nice, but sometimes the operation needs some external dependency to work, like a login mechanism needing a storage for the identity of the user (usually the session). We have two types of coupling to solve here: static: the User class should not depend on any other infrastructure class, which in turn refers the database or the session storage. runtime: the User class cannot hold a reference to an infrastructure object, for instance because we want to serialize it or to create it simply with a new operator, or our ORM does not support injection of collaborators. The first issues is solved by introducing an interface implemented by the infrastructure class; the second by passing in the dependency via Double Dispatch instead of via the constructor like we do with service classes. public function testUsersLogin() { $user = new User('giorgiosironi'); $user->setPassword('gs'); // will be removed in next tests // in reality, we would use a SessionLoginAdapter or something like that $loginAdapterMock = $this->getMock('LoginAdapter'); $loginAdapterMock->expects($this->once()) ->method('storeIdentity') ->with('giorgiosironi'); $user->login('gs', $loginAdapterMock); } class User { public function login($password, LoginAdapter $loginAdapter) { if ($this->password == $password) { $loginAdapter->storeIdentity($this->nickname); return true; } else { return false; } } } Still an example of Tell, Don't Ask, but more real world now. Command and changesets You really have to put data inside this object: the user has just compiled a form and you have to get thos input values in. So how do we define that operation? As an atomic method call, by passing in what I call a Changeset but it's a specialization of a Command (not Command pattern but CommandQueryResponsibilitySegregation). In the simplest cases, it's just a Value Object or a Data Transfer Object with no behavior. public function testCommandForChangingPassword() { $user = new User('giorgiosironi'); $passwordChange = new ChangeUserPassword('', 'gs'); $user->handle($passwordChange); $this->assertEquals('gs', $user->getPassword()); //deprecated, will be removed in next tests } class User { public function handle($command) { if ($command instanceof ChangeUserPassword) { $this->handleChangeUserPassword($command); } if ($command instanceof SetUserDetails) { $this->handleSetUserDetails($command); } // support other commands here... } private function handleChangeUserPassword(ChangeUserPassword $command) { if ($command->getOldPassword() == $this->password) { $this->password = $command->getNewPassword(); } else { throw new Exception('The old password is not correct.'); } } } Think about it: you will have to put these getters and setters somewhere; it's best to put them on an object which is a data structure than that on your Entity. This way: you will be coupled to the current fields only on this particular operation and not when you pass an User around. you will make it clear that you support only a full update operation, and it's not ok to call an isolate setter. Actually in PHP you could just use an array as a Changeset, but a class provides a stricter contract. Also public fields are not viable for a contract as no error will be raised by PHP if you assign a non-existent field on a Changeset object. Rendering on a canvas In the Growing Object-Oriented Software mailing list, there has been recently a discussion on how to emulate getters via callbacks. This solution is the specular of our Changeset argument used for extracting data instead of updating it. public function testCanvasForRenderingAnObject() { $user = new User('giorgiosironi'); $detailsSet = new SetUserDetails('Italy', 'Pizza'); //THIS may have set/get $user->handle($detailsSet); // canvas can also be a form, or xml, or json... $canvas = new HtmlCanvas('{{location}{{favoriteFood}'); $user->render($canvas); $this->assertEquals('ItalyPizza', (string) $canvas); } class User { public function render(Canvas $canvas) { $canvas->nickname = $this->nickname; $canvas->location = $this->location; $canvas->favoriteFood = $this->favoriteFood; } } Again, the canvas is hidden behind an interface and can be anything: an HTML view, a form, a JSON or RSS feed generator... CQRS In Command-Query Responsibility Segregation, you use the ORM for mapping your objects in the database, and fill your report screens by querying it directly, or even by querying another store which is continuously rebuilt from your master database. I don't know of any implementations of CQRS in PHP, but this mechanism promises to at least eliminate getters, as your domain objects will be write-only. Conclusion The full code is in this Github repository, as always. You have no excuses now: go and ditch one of your getters and setters immediately. Your code will breath a bit of fresh air.
February 22, 2011
by Giorgio Sironi
· 21,737 Views
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
· 65,481 Views · 2 Likes
article thumbnail
Getting Started with iBatis (MyBatis): Annotations
This tutorial will walk you through how to setup iBatis (MyBatis) in a simple Java project and will present examples using simple insert, update, select and delete statements using annotations. This is the third tutorial of the iBatis/MyBatis series, you can read the first 2 tutorials on the following links: Introduction to iBatis (MyBatis), An alternative to Hibernate and JDBC Getting Started with iBatis (MyBatis): XML Configuration iBatis/ MyBatis 3 offers a new feature: annotations. But it lacks examples and documentation about annotations. I started to explore and read the MyBatis mailing list archive to write this tutorial. Another thing you will notice is the limitation related to annotations. I am going to demonstrate some examples that you can do with annotations in this tutorial. All the power of iBatis is in its XMl configuration. So let’s play a little bit with annotations. It is much simpler and you can use it for simple queries in small projects. As I already mentioned, if you want something more complex, you will have to use XML configuration. One more thing before we get started: this tutorial is the same as the previous one, but instead of XML, we are going to use annotations. Pre-Requisites For this tutorial I am using: IDE: Eclipse (you can use your favorite one) DataBase: MySQL Libs/jars: Mybatis, MySQL conector and JUnit (for testing) This is how your project should look like: Sample Database Please run this script into your database before getting started with the project implementation: I will not post the sample database here again. You can get it from the previous post about iBatis or download this sample project. The files are the same. 1 – Contact POJO We will create a POJO class first to respresent a contact with id, name, phone number and email address – same as previous post. 2 – ContactMapper In this file, we are going to set up all the queries using annotations. It is the MyBatis-Interface for the SQLSessionFactory. A mapper class is simply an interface with method definitions that match up against the SqlSession methods. Mapper interfaces do not need to implement any interface or extend any class. As long as the method signature can be used to uniquely identify a corresponding mapped statement. Mapper interfaces can extend other interfaces. Be sure that you have the statements in the appropriate namespace when using XML binding to Mapper interfaces. Also, the only limitation is that you cannot have the same method signature in two interfaces in a hierarchy (a bad idea anyway). A mapperclass is simply an interface with method definitions that match up against the SqlSession methods. You can create some strings with the SQL code. Remember it has to be the same code as in XML Configuration. package com.loiane.data; import java.util.List; import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Options;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.Result;import org.apache.ibatis.annotations.Results;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update; import com.loiane.model.Contact; public interface ContactMapper { final String SELECT_ALL = "SELECT * FROM CONTACT"; final String SELECT_BY_ID = "SELECT * FROM CONTACT WHERE CONTACT_ID = #{id}"; final String UPDATE = "UPDATE CONTACT SET CONTACT_EMAIL = #{email}, CONTACT_NAME = #{name}, CONTACT_PHONE = #{phone} WHERE CONTACT_ID = #{id}"; final String UPDATE_NAME = "UPDATE CONTACT SET CONTACT_NAME = #{name} WHERE CONTACT_ID = #{id}"; final String DELETE = "DELETE FROM CONTACT WHERE CONTACT_ID = #{id}"; final String INSERT = "INSERT INTO CONTACT (CONTACT_EMAIL, CONTACT_NAME, CONTACT_PHONE) VALUES (#{name}, #{phone}, #{email})"; /** * Returns the list of all Contact instances from the database. * @return the list of all Contact instances from the database. */ @Select(SELECT_ALL) @Results(value = { @Result(property="id", column="CONTACT_ID"), @Result(property="name", column="CONTACT_NAME"), @Result(property="phone", column="CONTACT_PHONE"), @Result(property="email", column="CONTACT_EMAIL") }) List selectAll(); /** * Returns a Contact instance from the database. * @param id primary key value used for lookup. * @return A Contact instance with a primary key value equals to pk. null if there is no matching row. */ @Select(SELECT_BY_ID) @Results(value = { @Result(property="id"), @Result(property="name", column="CONTACT_NAME"), @Result(property="phone", column="CONTACT_PHONE"), @Result(property="email", column="CONTACT_EMAIL") }) Contact selectById(int id); /** * Updates an instance of Contact in the database. * @param contact the instance to be updated. */ @Update(UPDATE) void update(Contact contact); /** * Updates an instance of Contact in the database. * @param name name value to be updated. * @param id primary key value used for lookup. */ void updateName(@Param("name") String name, @Param("id") int id); /** * Delete an instance of Contact from the database. * @param id primary key value of the instance to be deleted. */ @Delete(DELETE) void delete(int id); /** * Insert an instance of Contact into the database. * @param contact the instance to be persisted. */ @Insert(INSERT) @Options(useGeneratedKeys = true, keyProperty = "id") void insert(Contact contact);} @Select The @Select annotation is very simple. Let’s take a look at the first select statment of this class: selectAll. Note that you don’t need to use the mapping if your database table columns mach the name of the class atributes. I used different names to use the @Result annotation. If table columns match with atribute names, you don’t need to use the @Result annotation. Not let’s take a look on the second method: selectById. Notice that we have a parameter. It is a simple parameter – easy to use when you have a single parameter. @Update Let’s say you want to update all the columns. You can pass the object as parameter and iBatis will do all the magic for you. Remember to mach the parameter name with the atribute name, otherwise iBatis can get confused, Now let’s say you want to use 2 or 3 paramaters, and they don’t belong to an object. If you take a look at iBatis XML configuration you will see you have to set the option parameterType (remember?) and specify you parameter type in it, in another words, you can use only one parameter. If you are using annotation, you can use more than one parameter using the @Param annotation. @Delete The @Delete annotation is also very simple. It follows the previous rules related to parameters. @Insert The @Insert annotation also follows the rules related to parameters. You can use an object or use the @Param annotation to specify more than one parameter. What about the generation key? Well, if your database supports auto generation key, you can set it up using annotations with the @Options annotation. You will need to specify the option useGeneratedKeys and keyProperty. If your database does not support auto generation key, sorry, but I still did not figure out how to do it (in last case, use can do it manually and then pass as parameter to your insert query). 3 – MyBatisConnectionFactory Every MyBatis application centers around an instance of SqlSessionFactory. A SqlSessionFactory instance can be acquired by using the SqlSessionFactoryBuilder. SqlSessionFactoryBuilder can build a SqlSessionFactory instance from an XML configuration file, of from a custom prepared instance of the Configuration class. An observation about this file: on the previous example, we set the mappers on the iBatis Configuration XML file. Using annotations, we will set the mapper manually. In a future example, I’ll show you how to work with XML and Annotations together. package com.loiane.dao; import java.io.FileNotFoundException;import java.io.IOException;import java.io.Reader; import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.loiane.data.ContactMapper; public class MyBatisConnectionFactory { private static SqlSessionFactory sqlSessionFactory; static { try { String resource = "SqlMapConfig.xml"; Reader reader = Resources.getResourceAsReader(resource); if (sqlSessionFactory == null) { sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); sqlSessionFactory.getConfiguration().addMapper(ContactMapper.class); } } catch (FileNotFoundException fileNotFoundException) { fileNotFoundException.printStackTrace(); } catch (IOException iOException) { iOException.printStackTrace(); } } public static SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } } 4 – ContactDAO Now that we set up everything needed, let’s create our DAO. To call the sql statments, we need to do one more configuration, that is to set and get the mapper from the SqlSessionFactory. Then we just need to call the mapper method. It is a little bit different, but it does the same thing. package com.loiane.dao; import java.util.List; import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory; import com.loiane.data.ContactMapper;import com.loiane.model.Contact; public class ContactDAO { private SqlSessionFactory sqlSessionFactory; public ContactDAO(){ sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory(); } /** * Returns the list of all Contact instances from the database. * @return the list of all Contact instances from the database. */ public List selectAll(){ SqlSession session = sqlSessionFactory.openSession(); try { ContactMapper mapper = session.getMapper(ContactMapper.class); List list = mapper.selectAll(); return list; } finally { session.close(); } } /** * Returns a Contact instance from the database. * @param id primary key value used for lookup. * @return A Contact instance with a primary key value equals to pk. null if there is no matching row. */ public Contact selectById(int id){ SqlSession session = sqlSessionFactory.openSession(); try { ContactMapper mapper = session.getMapper(ContactMapper.class); Contact list = mapper.selectById(id); return list; } finally { session.close(); } } /** * Updates an instance of Contact in the database. * @param contact the instance to be updated. */ public void update(Contact contact){ SqlSession session = sqlSessionFactory.openSession(); try { ContactMapper mapper = session.getMapper(ContactMapper.class); mapper.update(contact); session.commit(); } finally { session.close(); } } /** * Updates an instance of Contact in the database. * @param name name value to be updated. * @param id primary key value used for lookup. */ public void updateName(String name, int id){ SqlSession session = sqlSessionFactory.openSession(); try { ContactMapper mapper = session.getMapper(ContactMapper.class); mapper.updateName(name, id); session.commit(); } finally { session.close(); } } /** * Insert an instance of Contact into the database. * @param contact the instance to be persisted. */ public void insert(Contact contact){ SqlSession session = sqlSessionFactory.openSession(); try { ContactMapper mapper = session.getMapper(ContactMapper.class); mapper.insert(contact); session.commit(); } finally { session.close(); } } /** * Delete an instance of Contact from the database. * @param id primary key value of the instance to be deleted. */ public void delete(int id){ SqlSession session = sqlSessionFactory.openSession(); try { ContactMapper mapper = session.getMapper(ContactMapper.class); mapper.delete(id); session.commit(); } finally { session.close(); } } 5 – Mapper Configuration File The MyBatis XML configuration file contains settings and properties that have a dramatic effect on how MyBatis behaves. This time, we do not need to configure alias or xml config files. We did all the magic with annotations, so we have a simple config file with only the information about the database we want to connect with. Download I suggest you to take a look at the org.apache.ibatis.annotations package and try to find out what each annotation can do. Unfortunatelly, you won’t find much documentation or examples on MyBatis website. I also created a TestCase class. If you want to download the complete sample project, you can get it from my GitHub account: https://github.com/loiane/ibatis-annotations-helloworld If you want to download the zip file of the project, just click on download: There are more articles about iBatis to come. Stay tooned! In next articles, I’m going to demonstrate how to implement the feature using XML and then Annotations (when it is possible). Happy Coding! From http://loianegroner.com/2011/02/getting-started-with-ibatis-mybatis-annotations/
February 22, 2011
by Loiane Groner
· 71,688 Views
article thumbnail
Getting Started with iBatis (MyBatis): XML Configuration
This tutorial will walk you through how to setup iBatis (MyBatis) in a simple Java project and will present examples using simple insert, update, select and delete statements.
February 18, 2011
by Loiane Groner
· 111,777 Views
article thumbnail
Practical PHP Testing Patterns: Garbage-Collected Teardown
In order to perform tests, you create fixtures such as the System Under Test and input or output data. Usually this fixtures are just objects. Garbage collection, a mechanism present in many languages, deletes objects and variables (and thus fixtures) when there are no references for them anymore in the available scopes. The logic behind garbage collection is that objects which are not reachable anymore by any other object in the local or global scope are as good as garbage. Their code can't possibly be executed as you cannot call a method on them without a reference. Basically, if you do not put your fixtures in strange places, they will be automatically deleted with the test case. While a setUp() method is very common, a tearDown() method is usually not necessary. Implementation References like local variables or fields on $this (at the Testcase Object level) are deleted with the test case object. Currently, the PHPUnit manual say that the gabage collection of Testcase Objects is not predictable, so you may have to perform an unset() over $this->field to have the object removed. Static references are special: they are always reachable, as they are kept on classes (the current or other ones) instead of objects, and won't be deleted. Even if an object is pointed by another object in a static reference, it won't be garbage-collected for transitivity. Also singletons are a big problem (which derives from the static fields where their instances are kept): if you put something in Zend_Registry or in a singleton, it won't be deleted after a test. That's one reason singletons are dangerous: it's not only a matter of performance, but of them being capable of bringing objects from one test to another, spoiling our pursue of test isolation. PHP garbage collection Up to PHP 5.2, objects with mutual references won't usually be collected, even if neither of them was reachable from the other scopes. This is not a problem for a script that produces a web page and exits, but it can be for a test suite which runs for some minutes when at full capacity. In fact, an example of problematic behavior is the ezComponents test suite, which is cited on php.net. The suite would require several gigabytes of memory to run, due to the leaks of the long-running PHP process. From PHP 5.3, if zend.enable_gc is enabled (by default, it is) cycles will be collected when the table of roots is full. So this particular issue (circular references) won't worry you anymore. In case you encounter erratic behavior, see if you can change the php.ini directive memory_limit to detect the problem, and use the native function memory_get_usage() to gather statistics. Examples In this code sample, I show you tests that create fixtures which are automatically collected. How do we prove that these objects are really deleted? With a simple __destruct() method. Keep in mind that explicit teardown is usually not necessary: you should adopt it only if you have an heavy fixture, which you want to be gargabe-collected before the end of the PHP process. Running this test case: deletedFixture = new SomeFixture(1); $this->abandonedFixture = new SomeFixture(2); } public function testFirst() { } public function testSecond() { } public function tearDown() { // this fixture will be garbage-collected at the end of each test unset($this->deletedFixture); // since we do not touch $this->abandonedFixture, its collection // is not predictable. It can happen at any time after the tests execution. } } class SomeFixture { private $number; public function __construct($number) { $this->number = $number; } public function __destruct() { echo "Cleaning up fixture $this->number.\n"; } } gives this output: [13:11:15][giorgio@Desmond:~]$ phpunit code/practical-php-testing-patterns/GarbageCollectedTeardownTest.php PHPUnit 3.5.5 by Sebastian Bergmann. Cleaning up fixture 1. .Cleaning up fixture 1. . Time: 0 seconds, Memory: 4.75Mb OK (2 tests, 0 assertions) Cleaning up fixture 2. Cleaning up fixture 2.
February 15, 2011
by Giorgio Sironi
· 2,574 Views
article thumbnail
Table sorting & pagination with jQuery and Razor in ASP.NET MVC
Introduction jQuery enjoys living inside pages which are built on top of ASP.NET MVC Framework. The ASP.NET MVC is a place where things are organized very well and it is quite hard to make them dirty, especially because the pattern enforces you on purity (you can still make it dirty if you want so ;) ). We all know how easy is to build a HTML table with a header row, footer row and table rows showing some data. With ASP.NET MVC we can do this pretty easy, but, the result will be pure HTML table which only shows data, but does not includes sorting, pagination or some other advanced features that we were used to have in the ASP.NET WebForms GridView. Ok, there is the WebGrid MVC Helper, but what if we want to make something from pure table in our own clean style? In one of my recent projects, I’ve been using the jQuery tablesorter and tablesorter.pager plugins that go along. You don’t need to know jQuery to make this work… You need to know little CSS to create nice design for your table, but of course you can use mine from the demo… So, what you will see in this blog is how to attach this plugin to your pure html table and a div for pagination and make your table with advanced sorting and pagination features. Demo Project Resources The resources I’m using for this demo project are shown in the following solution explorer window print screen: Content/images – folder that contains all the up/down arrow images, pagination buttons etc. You can freely replace them with your own, but keep the names the same if you don’t want to change anything in the CSS we will built later. Content/Site.css – The main css theme, where we will add the theme for our table too Controllers/HomeController.cs – The controller I’m using for this project Models/Person.cs – For this demo, I’m using Person.cs class Scripts – jquery-1.4.4.min.js, jquery.tablesorter.js, jquery.tablesorter.pager.js – required script to make the magic happens Views/Home/Index.cshtml – Index view (razor view engine) the other items are not important for the demo. ASP.NET MVC 1. Model In this demo I use only one Person class which defines Person entity with several properties. You can use your own model, maybe one which will access data from database or any other resource. Person.cs public class Person { public string Name { get; set; } public string Surname { get; set; } public string Email { get; set; } public int? Phone { get; set; } public DateTime? DateAdded { get; set; } public int? Age { get; set; } public Person(string name, string surname, string email, int? phone, DateTime? dateadded, int? age) { Name = name; Surname = surname; Email = email; Phone = phone; DateAdded = dateadded; Age = age; } } 2. View In our example, we have only one Index.chtml page where Razor View engine is used. Razor view engine is my favorite for ASP.NET MVC because it’s very intuitive, fluid and keeps your code clean. 3. Controller Since this is simple example with one page, we use one HomeController.cs where we have two methods, one of ActionResult type (Index) and another GetPeople() used to create and return list of people. HomeController.cs public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { ViewBag.People = GetPeople(); return View(); } public List GetPeople() { List listPeople = new List(); listPeople.Add(new Person("Hajan", "Selmani", "hajan@hajan.com", 070070070,DateTime.Now, 25)); listPeople.Add(new Person("Straight", "Dean", "email@address.com", 123456789, DateTime.Now.AddDays(-5), 35)); listPeople.Add(new Person("Karsen", "Livia", "karsen@livia.com", 46874651, DateTime.Now.AddDays(-2), 31)); listPeople.Add(new Person("Ringer", "Anne", "anne@ringer.org", null, DateTime.Now, null)); listPeople.Add(new Person("O'Leary", "Michael", "23sssa@asssa.org", 32424344, DateTime.Now, 44)); listPeople.Add(new Person("Gringlesby", "Anne", "email@yahoo.org", null, DateTime.Now.AddDays(-9), 18)); listPeople.Add(new Person("Locksley", "Stearns", "my@email.org", 2135345, DateTime.Now, null)); listPeople.Add(new Person("DeFrance", "Michel", "email@address.com", 235325352, DateTime.Now.AddDays(-18), null)); listPeople.Add(new Person("White", "Johnson", null, null, DateTime.Now.AddDays(-22), 55)); listPeople.Add(new Person("Panteley", "Sylvia", null, 23233223, DateTime.Now.AddDays(-1), 32)); listPeople.Add(new Person("Blotchet-Halls", "Reginald", null, 323243423, DateTime.Now, 26)); listPeople.Add(new Person("Merr", "South", "merr@hotmail.com", 3232442, DateTime.Now.AddDays(-5), 85)); listPeople.Add(new Person("MacFeather", "Stearns", "mcstearns@live.com", null, DateTime.Now, null)); return listPeople; } } TABLE CSS/HTML DESIGN Now, lets start with the implementation. First of all, lets create the table structure and the main CSS. 1. HTML Structure @{ Layout = null; } value value value So, this is the main structure you need to create for each of your tables where you want to apply the functionality we will create. Of course the scripts are referenced once ;). As you see, our table has class tablesorter and also we have a div with id pager. In the next steps we will use both these to create the needed functionalities. The complete Index.cshtml coded to get the data from controller and display in the page is: NameSurnameEmailPhoneDate Added @{ foreach (var p in ViewBag.People) { @p.Name@p.Surname@p.Email@p.Phone@p.DateAdded } } NameSurnameEmailPhoneDate Added 510203040 So, mainly the structure is the same. I have added @Razor code to create table with data retrieved from the ViewBag.People which has been filled with data in the home controller. 2. CSS Design The CSS code I’ve created is: /* DEMO TABLE */ body { font-size: 75%; font-family: Verdana, Tahoma, Arial, "Helvetica Neue", Helvetica, Sans-Serif; color: #232323; background-color: #fff; } table { border-spacing:0; border:1px solid gray;} table.tablesorter thead tr .header { background-image: url(images/bg.png); background-repeat: no-repeat; background-position: center right; cursor: pointer; } table.tablesorter tbody td { color: #3D3D3D; padding: 4px; background-color: #FFF; vertical-align: top; } table.tablesorter tbody tr.odd td { background-color:#F0F0F6; } table.tablesorter thead tr .headerSortUp { background-image: url(images/asc.png); } table.tablesorter thead tr .headerSortDown { background-image: url(images/desc.png); } table th { width:150px; border:1px outset gray; background-color:#3C78B5; color:White; cursor:pointer; } table thead th:hover { background-color:Yellow; color:Black;} table td { width:150px; border:1px solid gray;} PAGINATION AND SORTING Now, when everything is ready and we have the data, lets make pagination and sorting functionalities 1. jQuery Scripts referencing 2. jQuery Sorting and Pagination script So, with only two lines of code, I’m using both tablesorter and tablesorterPager plugins, giving some options to both these. Options added: tablesorter - widthFixed: true – gives fixed width of the columns tablesorter - sortList[[0,0]] – An array of instructions for per-column sorting and direction in the format: [[columnIndex, sortDirection], ... ] where columnIndex is a zero-based index for your columns left-to-right and sortDirection is 0 for Ascending and 1 for Descending. A valid argument that sorts ascending first by column 1 and then column 2 looks like: [[0,0],[1,0]] (source: http://tablesorter.com/docs/) tablesorterPager – container: $(“#pager”) – tells the pager container, the div with id pager in our case. tablesorterPager – size: the default size of each page, where I get the default value selected, so if you put selected to any other of the options in your select list, you will have this number of rows as default per page for the table too. END RESULTS 1. Table once the page is loaded (default results per page is 5 and is automatically sorted by 1st column as sortList is specified) 2. Sorted by Phone Descending 3. Changed pagination to 10 items per page 4. Sorted by Phone and Name (use SHIFT to sort on multiple columns) 5. Sorted by Date Added 6. Page 3, 5 items per page ADDITIONAL ENHANCEMENTS We can do additional enhancements to the table. We can make search for each column. I will cover this in one of my next blogs. Stay tuned. DEMO PROJECT You can download demo project source code from HERE. CONCLUSION Once you finish with the demo, run your page and open the source code. You will be amazed of the purity of your code. Working with pagination in client side can be very useful. One of the benefits is performance, but if you have thousands of rows in your tables, you will get opposite result when talking about performance. Hence, sometimes it is nice idea to make pagination on back-end. So, the compromise between both approaches would be best to combine both of them. I use at most up to 500 rows on client-side and once the user reach the last page, we can trigger ajax postback which can get the next 500 rows using server-side pagination of the same data. I would like to recommend the following blog post http://weblogs.asp.net/gunnarpeipman/archive/2010/09/14/returning-paged-results-from-repositories-using-pagedresult-lt-t-gt.aspx, which will help you understand how to return page results from repository. I hope this was helpful post for you. Wait for my next posts ;). Please do let me know your feedback. Best Regards, Hajan
February 14, 2011
by Hajan Selmani
· 76,901 Views
article thumbnail
Java Coding Best Practices: Better Search Implementation
In web applications searching for information based on the selected criteria and displaying the results is a very common requirement. Suppose we need to search users based on their name. The end user will enter the username in the textbox and hit the search button and the user results will be fetched from database and display in a grid. At first this looks simple and we can start to implement it as follows: public class UserSearchAction extends Action { public ActionForward execute(...) { SearchForm sf = (SearchForm)form; String searchName = sf.getSearchName(); UserService userService = new UserService(); List searchResults = userService.search(searchName); //put search results in request and dsplay in JSP } } public class UserService { public List search(String username) { // query the DB and get the results by applying filter on USERNAME column List users = UserDAO.search(username); } } The above implementation works fine for the current requirement. Later client wants to display only 10 rows per page and display a message like "Displaying 1-10 of 35 Users". Now the code need to be changed for the change request. public class UserSearchAction extends Action { public ActionForward execute(...) { SearchForm sf = (SearchForm)form; String searchName = sf.getSearchName(); UserService userService = new UserService(); Map searchResultsMap = userService.search(searchName, start, pageSize); List users = (List)searchResultsMap.get("DATA"); Integer count = (Integer)searchResultsMap.get("COUNT"); //put search results in request and dsplay in JSP } } public class UserService { public Map search(String username, int start, int pageSize) { //Get the total number of results for this criteria int count = UserDAO.searchResultsCount(username); List users = UserDAO.search(username, start, pageSize); // query the DB and get the start to start+pageSize results by applying filter on USERNAME column Map RESULTS_MAP = new HashMap(); RESULTS_MAP.put("DATA",users); RESULTS_MAP.put("COUNT",count); return RESULTS_MAP; } } Later the client wants to give an option to the end user to choose the search type either by UserID or by Username and show the paginated results. Now again the code needs to be changed for the change request. public class UserSearchAction extends Action { public ActionForward execute(...) { SearchForm sf = (SearchForm)form; String searchName = sf.getSearchName(); String searchId = sf.getSearchId(); UserService userService = new UserService(); Map searchCriteriaMap = new HashMap(); //searchCriteriaMap.put("SEARCH_BY","NAME"); searchCriteriaMap.put("SEARCH_BY","ID"); searchCriteriaMap.put("ID",searchId); searchCriteriaMap.put("START",start); searchCriteriaMap.put("PAGESIZE",pageSize); Map searchResultsMap = userService.search(searchCriteriaMap); List users = (List)searchResultsMap.get("DATA"); Integer count = (Integer)searchResultsMap.get("COUNT"); //put search results in request and dsplay in JSP } } public class UserService { public Map search(Map searchCriteriaMap) { return UserDAO.search(searchCriteriaMap); } } public class UserDAO { public Map search(Map searchCriteriaMap) { String SEARCH_BY = (String)searchCriteriaMap.get("SEARCH_BY"); int start = (Integer)searchCriteriaMap.get("START"); int pageSize = (Integer)searchCriteriaMap.get("PAGESIZE"); if("ID".equals(SEARCH_BY)) { int id = (Integer)searchCriteriaMap.get("ID"); //Get the total number of results for this criteria int count = UserDAO.searchResultsCount(id); // query the DB and get the start to start+pageSize results by applying filter on USER_ID column List users = search(id, start, pageSize); } else { String username = (String)searchCriteriaMap.get("USERNAME"); //Get the total number of results for this criteria int count = UserDAO.searchResultsCount(username); // query the DB and get the start to start+pageSize results by applying filter on USERNAME column List users = search(username, start, pageSize); } Map RESULTS_MAP = new HashMap(); RESULTS_MAP.put("DATA",users); RESULTS_MAP.put("COUNT",count); return RESULTS_MAP; } } Finally the code becomes a big mess and completely violates object oriented principles. There are lot of problems with the above code. 1. For each change request the method signatures are changing 2. Code needs to be changed for each enhancement such as adding more search criteria We can design a better object model for this kind of search functionality which is Object Oriented and scalable as follows. A generic SearchCriteria which holds common search criteria like pagination, sorting details. package com.sivalabs.javabp; public abstract class SearchCriteria { private boolean pagination = false; private int pageSize = 25; private String sortOrder = "ASC"; public boolean isPagination() { return pagination; } public void setPagination(boolean pagination) { this.pagination = pagination; } public String getSortOrder() { return sortOrder; } public void setSortOrder(String sortOrder) { this.sortOrder = sortOrder; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } } A generic SearchResults object which holds the actual results and other detials like total available results count, page wise results provider etc. package com.sivalabs.javabp; import java.util.ArrayList; import java.util.List; public abstract class SearchResults { private int totalResults = 0; private int pageSize = 25; private List results = null; public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalResults() { return totalResults; } private void setTotalResults(int totalResults) { this.totalResults = totalResults; } public List getResults() { return results; } public List getResults(int page) { if(page <= 0 || page > this.getNumberOfPages()) { throw new RuntimeException("Page number is zero or there are no that many page results."); } List subList = new ArrayList(); int start = (page -1)*this.getPageSize(); int end = start + this.getPageSize(); if(end > this.results.size()) { end = this.results.size(); } for (int i = start; i < end; i++) { subList.add(this.results.get(i)); } return subList; } public int getNumberOfPages() { if(this.results == null || this.results.size() == 0) { return 0; } return (this.totalResults/this.pageSize)+(this.totalResults%this.pageSize > 0 ? 1: 0); } public void setResults(List aRresults) { if(aRresults == null) { aRresults = new ArrayList(); } this.results = aRresults; this.setTotalResults(this.results.size()); } } A SearchCriteria class specific to User Search. package com.sivalabs.javabp; public class UserSearchCriteria extends SearchCriteria { public enum UserSearchType { BY_ID, BY_NAME }; private UserSearchType searchType = UserSearchType.BY_NAME; private int id; private String username; public UserSearchType getSearchType() { return searchType; } public void setSearchType(UserSearchType searchType) { this.searchType = searchType; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } A SearchResults class specific to User Search. package com.sivalabs.javabp; import java.text.MessageFormat; public class UserSearchResults extends SearchResults { public static String getDataGridMessage(int start, int end, int total) { return MessageFormat.format("Displaying {0} to {1} Users of {2}", start, end, total); } } UserService takes the SearchCriteria, invokes the DAO and get the results, prepares the UserSearchResults and return it back. package com.sivalabs.javabp; import java.util.ArrayList; import java.util.List; import com.sivalabs.javabp.UserSearchCriteria.UserSearchType; public class UserService { public SearchResults search(UserSearchCriteria searchCriteria) { UserSearchType searchType = searchCriteria.getSearchType(); String sortOrder = searchCriteria.getSortOrder(); System.out.println(searchType+":"+sortOrder); List results = null; if(searchType == UserSearchType.BY_NAME) { //Use hibernate Criteria API to get and sort results based on USERNAME field in sortOrder results = userDAO.searchUsers(...); } else if(searchType == UserSearchType.BY_ID) { //Use hibernate Criteria API to get and sort results based on USER_ID field in sortOrder results = userDAO.searchUsers(...); } UserSearchResults searchResults = new UserSearchResults(); searchResults.setPageSize(searchCriteria.getPageSize()); searchResults.setResults(results); return searchResults; } } package com.sivalabs.javabp; import com.sivalabs.javabp.UserSearchCriteria.UserSearchType; public class TestClient { public static void main(String[] args) { UserSearchCriteria criteria = new UserSearchCriteria(); criteria.setPageSize(3); //criteria.setSearchType(UserSearchType.BY_ID); //criteria.setId(2); criteria.setSearchType(UserSearchType.BY_NAME); criteria.setUsername("s"); UserService userService = new UserService(); SearchResults searchResults = userService.search(criteria); System.out.println(searchResults.getTotalResults()); System.out.println(searchResults.getResults().size()+":"+searchResults.getResults()); System.out.println(searchResults.getResults(1).size()+":"+searchResults.getResults(1)); } } With this approach if we want to add a new criteria like search by EMAIL we can do it as follows: 1. Add BY_EMAIL criteria type to UserSearchType enum 2. Add new property "email" to UserSearchCriteria 3. criteria.setSearchType(UserSearchType.BY_EMAIL); criteria.setEmail("gmail"); 4. In UserService prepare the HibernateCriteria with email filter. Thats it :-) From : http://sivalabs.blogspot.com/2011/02/java-coding-best-practices-better.html
February 9, 2011
by Siva Prasad Reddy Katamreddy
· 61,115 Views · 1 Like
article thumbnail
Introduction to iBatis (MyBatis), An alternative to Hibernate and JDBC
i started to write a new article series about ibatis / mybatis . this is the first article and it will walk you through what is ibatis / mybatis and why you should use it. for those who does not know ibatis / mybatis yet, it is a persistence framework – an alternative to jdbc and hibernate , available for java and .net platforms. i’ve been working with it for almost two years, and i am enjoying it! the first thing you may notice in this and following articles about ibatis/mybatis is that i am using both ibatis and mybatis terms. why? until june 2010, ibatis was under apache license and since then, the framework founders decided to move it to google code and they renamed it to mybatis. the framework is still the same though, it just has a different name now. i gathered some resources, so i am just going to quote them: what is mybatis/ibatis? the mybatis data mapper framework makes it easier to use a relational database with object-oriented applications. mybatis couples objects with stored procedures or sql statements using a xml descriptor. simplicity is the biggest advantage of the mybatis data mapper over object relational mapping tools.to use the mybatis data mapper, you rely on your own objects, xml, and sql. there is little to learn that you don’t already know. with the mybatis data mapper, you have the full power of both sql and stored procedures at your fingertips. ( www.mybatis.org ) ibatis is based on the idea that there is value in relational databases and sql, and that it is a good idea to embrace the industrywide investment in sql. we have experiences whereby the database and even the sql itself have outlived the application source code, and even multiple versions of the source code. in some cases we have seen that an application was rewritten in a different language, but the sql and database remained largely unchanged. it is for such reasons that ibatis does not attempt to hide sql or avoid sql. it is a persistence layer framework that instead embraces sql by making it easier to work with and easier to integrate into modern object-oriented software. these days, there are rumors that databases and sql threaten our object models, but that does not have to be the case. ibatis can help to ensure that it is not. ( ibatis in action book) so… what is ibatis ? a jdbc framework developers write sql, ibatis executes it using jdbc. no more try/catch/finally/try/catch. an sql mapper automatically maps object properties to prepared statement parameters. automatically maps result sets to objects. support for getting rid of n+1 queries. a transaction manager ibatis will provide transaction management for database operations if no other transaction manager is available. ibatis will use external transaction management (spring, ejb cmt, etc.) if available. great integration with spring, but can also be used without spring (the spring folks were early supporters of ibatis). what isn’t ibatis ? an orm does not generate sql does not have a proprietary query language does not know about object identity does not transparently persist objects does not build an object cache essentially, ibatis is a very lightweight persistence solution that gives you most of the semantics of an o/r mapping toolkit, without all the drama. in other words ,ibatis strives to ease the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level orm capabilities (automated and configurable mapping of objects to sql calls, data type conversion management, support for static queries as well as dynamic queries based upon an object’s state, mapping of complex joins to complex object graphs, etc.). ibatis simply maps javabeans to sql statements using a very simple xml descriptor. simplicity is the key advantage of ibatis over other frameworks and object relational mapping tools.( http://www.developersbook.com ) who is using ibatis/mybatis? see the list in this link: http://www.apachebookstore.com/confluence/oss/pages/viewpage.action?pageid=25 i think the biggest case is myspace , with millions of users. very nice! this was just an introduction, so in next articles i will show how to create an application using ibatis/mybatis – step-by-step. enjoy! from http://loianegroner.com/2011/02/introduction-to-ibatis-mybatis-an-alternative-to-hibernate-and-jdbc/
February 9, 2011
by Loiane Groner
· 41,865 Views · 5 Likes
article thumbnail
Sending Beans as XML with JmsTemplate
We often want to send XML via web services. We may already have the schema or annotated JAXB2 classes configured in our application. What if we want to send the same format via JMS? By default Spring JMS is configured to send & receive objects serialized. How can we switch to using JAXB2 (or any other OXM marshaling strategy)? The following example assumes we are going from annotations first instead of from XML Schema. Quick Overview Annotate Bean with JAXB2 Configure OXM Converter Integration Test Visualize Results Logging Configuration Maven Configuration 1. Annotate Bean with JAXB2 Use JAXB2 annotations for our bean package com.gordondickens.jmswithoxm; import java.math.BigDecimal; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "account") @XmlAccessorType(XmlAccessType.FIELD) public class Account { @XmlElement(required = true) private String name; @XmlElement private String description; @XmlElement private BigDecimal balance; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } @Override public String toString() { return "Account [name=" + name + ", description=" + description + ", balance=" + balance + "]"; } } 2. Configure OXM Converter Define our Marshalers – We see defines JAXB2 as our marshaller for the Account class Register our MarshallingMessageConverter – We register the MarshallingMessageConverter to use the JAXB2 marshaller for both inbound and outbound data Register our Converter – In the JmsTemplate, we register our oxmMessageConverter as the messageConverter. This replaces the default SimpleMessageConverter which will relies on Serialization Notice the ActiveMQ namespace? 3. Integration Test Populate the Account bean Calls convertAndSend on the JmsTemplate to marshal & send the Account Includes a postProcessor callback to log the XML data Calls receiveAndConvert on the JmsTemplate to get & unmarshal the Account Asserts end state ? package com.gordondickens.jmswithoxm; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.math.BigDecimal; import javax.jms.BytesMessage; import javax.jms.JMSException; import javax.jms.Message; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessagePostProcessor; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class JmsWithOxmTest { private static final Logger logger = LoggerFactory .getLogger(JunitWithOxmTest.class); private static final String TEST_DEST = "oxmTestQueue"; @Autowired JmsTemplate jmsTemplate; @Test public void testSendingMessage() { Account account = generateTestMessage(); jmsTemplate.convertAndSend(TEST_DEST, account, new MessagePostProcessor() { @Override public Message postProcessMessage(Message message) throws JMSException { if (message instanceof BytesMessage) { BytesMessage messageBody = (BytesMessage) message; // message is in write mode, close & reset to start // of byte stream messageBody.reset(); Long length = messageBody.getBodyLength(); logger.debug("***** MESSAGE LENGTH is {} bytes", length); byte[] byteMyMessage = new byte[length.intValue()]; int red = messageBody.readBytes(byteMyMessage); logger.debug( "***** SENDING MESSAGE - \n\n{}\n", new String(byteMyMessage)); } return message; } }); Account account2 = (Account) jmsTemplate.receiveAndConvert(TEST_DEST); assertNotNull("Account MUST return from JMS", account2); assertEquals("Name MUST match", account.getName(), account2.getName()); assertEquals("Description MUST match", account.getDescription(), account2.getDescription()); assertEquals("Balance MUST match", account.getBalance(), account2.getBalance()); } private Account generateTestMessage() { Account account = new Account(); account.setBalance(new BigDecimal(12345.67)); account.setDescription("A no account varmint"); account.setName("Waskally Wabbit"); logger.debug("Generated Test Message: " + account.toString()); return account; } } 4. Visualizing Results Run: mvn clean test See Account XML between the block & Output has been Formatted for clarity ------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.gordondickens.jmswithoxm.JmsWithOxmTest INFO o.s.o.j.Jaxb2Marshaller - Creating JAXBContext with classes to be bound [class com.gordondickens.jmswithoxm.Account] DEBUG c.g.j.JmsWithOxmTest - Generated Test Message: Account [name=Waskally Wabbit, description=A no account varmint, balance=12345.670000000000072759576141834259033203125] DEBUG o.s.j.c.JmsTemplate - Executing callback on JMS Session: ActiveMQSession {id=ID:Technophiliac-61135-1296856347600-2:1:1,started=false} DEBUG c.g.j.JmsWithOxmTest - ***** MESSAGE LENGTH is 213 bytes DEBUG c.g.j.JmsWithOxmTest - ***** SENDING MESSAGE - Waskally Wabbit A no account varmint 12345.670000000000072759576141834259033203125 DEBUG o.s.j.c.JmsTemplate - Sending created message: ActiveMQBytesMessage {commandId = 0, responseRequired = false, messageId = null, originalDestination = null, originalTransactionId = null, producerId = null, destination = null, transactionId = null, expiration = 0, timestamp = 0, arrival = 0, brokerInTime = 0, brokerOutTime = 0, correlationId = null, replyTo = null, persistent = false, type = null, priority = 0, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = org.apache.activemq.util.ByteSequence@b364dcb, marshalledProperties = null, dataStructure = null, redeliveryCounter = 0, size = 0, properties = null, readOnlyProperties = false, readOnlyBody = true, droppable = false} ActiveMQBytesMessage{ bytesOut = null, dataOut = null, dataIn = java.io.DataInputStream@1a2d502d } DEBUG o.s.j.c.JmsTemplate - Executing callback on JMS Session: ActiveMQSession {id=ID:Technophiliac-61135-1296856347600-2:2:1,started=true} Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.276 sec 5. Logging Configuration Logback is very similar to Log4J Logback patterns use Log4J characters also See: Logback Pattern Layout Documentation %-5level %logger{5} - %msg%n 6. Maven Configuration Using Logback to support Log4J, SLF4J, Apache (JCL) & Java Util Logging Included IDE builders for STS/Eclipse & IntelliJ IDEA 4.0.0 com.gordondickens.jmswithoxm spring-jms-oxm 1.0.0.CI-SNAPSHOT jar JMS to OXM Spring http://gordondickens.com Sample JMS with OXM Message Conversion gordon.dickens Gordon Dickens gordondickens@gmail.com Author http://www.gordondickens.com 3.0.5.RELEASE 4.8.1 1.1.1 1.6.1 5.4.2 0.9.27 1.2.16 UTF-8 false quick true junit junit ${junit.version} test log4j log4j ${log4j.version} org.slf4j slf4j-api ${slf4j.version} org.slf4j jcl-over-slf4j ${slf4j.version} org.slf4j jul-to-slf4j ${slf4j.version} ch.qos.logback logback-classic ${logback.version} ch.qos.logback logback-core ${logback.version} ch.qos.logback logback-access ${logback.version} org.springframework spring-core ${spring.version} commons-logging commons-logging org.springframework spring-test ${spring.version} test commons-logging commons-logging org.apache.activemq activemq-core ${activemq.version} org.springframework spring-context commons-logging commons-logging commons-logging commons-logging-api org.apache.xbean xbean-spring 3.7 commons-logging commons-logging org.springframework spring-context ${spring.version} org.springframework spring-jms ${spring.version} org.springframework spring-oxm ${spring.version} javax.xml.bind jaxb-api 2.2.2 org.apache.geronimo.specs geronimo-jms_1.1_spec ${jms.version} org.apache.maven.plugins maven-surefire-plugin 2.7.1 org.apache.maven.plugins maven-eclipse-plugin 2.8 true true 2.0 org.springframework.ide.eclipse.core.springbuilder org.springframework.ide.eclipse.core.springnature org.apache.maven.plugins maven-compiler-plugin 2.3.2 1.6 1.6 org.apache.maven.plugins maven-idea-plugin 2.2 true true true 6. Getting the code Code is in my Git Repo: https://github.com/gordonad/core-spring-demos/tree/master/demos/JmsOxmDemo Further Reading Spring Reference for JMS – Section 21.3.1 Using Message Converters Core Spring Training – Where I teach JMS with Spring Enterprise Integration with Spring Training – Where I teach JMS with Spring From http://gordondickens.com/wordpress/2011/02/07/sending-beans-as-xml-with-jmstemplate/
February 8, 2011
by Gordon Dickens
· 17,500 Views
  • Previous
  • ...
  • 816
  • 817
  • 818
  • 819
  • 820
  • 821
  • 822
  • 823
  • 824
  • 825
  • ...
  • Next

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: