VOOZH about

URL: https://dzone.com/users/230813/sivaprasad.html

⇱ Siva Prasad Reddy Katamreddy - DZone Member


Siva Prasad Reddy Katamreddy

Software Architect at SivaLabs

Hyderabad, IN

Joined Jun 2007

https://sivalabs.in

About

I am Siva, a passionate software developer, blogger and book author. My current technical focus is on modern architectures including microservices, continuous integration and continuous delivery (CI/CD), and DevOps. My technical skills include Java 8, Kotlin, Groovy, Spring, SpringBoot, Spring Security, Spring Cloud, Hibernate/JPA, MySQL, ElasticSearch, Cassandra, Redis, MongoDB, Kafka, Jenkins, Ansible etc.

Stats

Reputation: 582
Pageviews: 2.7M
Articles: 20
Comments: 42

Articles

10 Steps to Become an Outstanding Java Developer
If you are a Java developer and passionate about technology, you can follow these ten steps which could make you an outstanding Java developer.
Updated May 3, 2022
· 318,219 Views · 59 Likes
How Spring Boot Auto-Configuration Works
A deep dive into the world of Spring Boot's @Conditional annotation with a worked example using Mongo and MySQL DB implementations.
Updated January 21, 2020
· 183,984 Views · 68 Likes
Microservices - Part 5: Spring Cloud Zuul Proxy as API Gateway
In this tutorial, we'll learn how to use Spring Cloud Zuul Proxy as an API gateway, an essential component of microservice architecture.
March 16, 2018
· 58,960 Views · 15 Likes
Microservices - Part 4: Spring Cloud Circuit Breaker Using Netflix Hystrix
This microservices tutorial continues by showing how to set up a circuit breaker to fix potential issues from microservice dependencies.
March 13, 2018
· 70,495 Views · 22 Likes
Microservices - Part 3: Spring Cloud Service Registry and Discovery
Learn about setting up service registry and discovery or your Spring Cloud and Spring Boot microservices development.
March 10, 2018
· 32,201 Views · 21 Likes
Microservices - Part 2: Configuration Management With Spring Cloud Config and Vault
Continue your microservices journey by learning about configuration with Spring Cloud Config Server and storing sensitive data with Vault.
March 9, 2018
· 22,011 Views · 20 Likes
Microservices Using Spring Boot and Spring Cloud — Part 1: Overview
In this series, we look at getting started on your microservices journey, leveraging Spring Boot and Spring Cloud. Here's an introduction to the various concepts needed.
March 4, 2018
· 86,143 Views · 75 Likes
Why Spring Boot?
This article gives an overview of various Spring configuration styles and helps you understand the complexity of configuring Spring applications.
May 20, 2016
· 353,941 Views · 179 Likes
Spring Boot: Working With MyBatis
MyBatis is a SQL framework for advanced mapping and stored procedures.
March 24, 2016
· 111,342 Views · 12 Likes
A Developer's Perspective on Spring vs. JavaEE
Hear the opinion of a Spring and JavaEE developer that wants to share his thoughts on this epic Spring vs JavaEE debate. Covers business and technical aspects.
June 18, 2015
· 69,860 Views · 38 Likes
AngularJS: Different Ways of Using Array Filters
In this article, we learn how to utilize AngularJS's array filter features in a variety of use cases. Read on to get started.
October 24, 2014
· 315,797 Views · 5 Likes
SpringBoot: Introducing SpringBoot
SpringBoot...there is a lot of buzz about SpringBoot nowadays. So what is SpringBoot? SpringBoot is a new spring portfolio project which takes opinionated view of building production-ready Spring applications by drastically reducing the amount of configuration required. Spring Boot is taking the convention over configuration style to the next level by registering the default configurations automatically based on the classpath libraries available at runtime. Well.. you might have already read this kind of introduction to SpringBoot on many blogs. So let me elaborate on what SpringBoot is and how it helps developing Spring applications more quickly. Spring framework was created by Rod Johnson when many of the Java developers are struggling with EJB 1.x/2.x for building enterprise applications. Spring framework makes developing the business components easy by using Dependency Injection and Aspect Oriented Programming concepts. Spring became very popular and many more Spring modules like SpringSecurity, Spring Batch, Spring Data etc become part of Spring portfolio. As more and more features added to Spring, configuring all the spring modules and their dependencies become a tedious task. Adding to that Spring provides atleast 3 ways of doing anything :-). Some people see it as flexibility and some others see it as confusing. Slowly, configuring all the Spring modules to work together became a big challenge. Spring team came up with many approaches to reduce the amount of configuration needed by introducing Spring XML DSLs, Annotations and JavaConfig. In the very beginning I remember configuring a big pile of jar version declarations in section and lot of declarations. Then I learned creating maven archetypes with basic structure and minimum required configurations. This reduced lot of repetitive work, but not eliminated completely. Whether you write the configuration by hand or generate by some automated ways, if there is code that you can see then you have to maintain it. So whether you use XML or Annotations or JavaConfig, you still need to configure(copy-paste) the same infrastructure setup one more time. On the other hand, J2EE (which is dead long time ago) emerged as JavaEE and since JavaEE6 it became easy (compared to J2EE and JavaEE5) to develop enterprise applications using JavaEE platform. Also JavaEE7 released with all the cool CDI, WebSockets, Batch, JSON support etc things became even more simple and powerful as well. With JavaEE you don't need so much XML configuration and your war file size will be in KBs (really??? for non-helloworld/non-stageshow apps also :-)). Naturally this "convention over configuration" and "you no need to glue APIs together appServer already did it" arguments became the main selling points for JavaEE over Spring. Then Spring team addresses this problem with SpringBoot :-). Now its time to JavaEE to show whats the SpringBoot's counterpart in JavaEE land :-) JBoss Forge?? I love this Spring vs JavaEE thing which leads to the birth of powerful tools which ultimately simplify the developers life :-). Many times we need similar kind of infrastructure setup using same libraries. For example, take a web application where you map DispatcherServlet url-pattern to "/", implement RESTFul webservices using Jackson JSON library with Spring Data JPA backend. Similarly there could be batch or spring integration applications which needs similar infrastructure configuration. SpringBoot to the rescue. SpringBoot look at the jar files available to the runtime classpath and register the beans for you with sensible defaults which can be overridden with explicit settings. Also SpringBoot configure those beans only when the jars files available and you haven't define any such type of bean. Altogether SpringBoot provides common infrastructure without requiring any explicit configuration but lets the developer overrides if needed. To make things more simpler, SpringBoot team provides many starter projects which are pre-configured with commonly used dependencies. For example Spring Data JPA starter project comes with JPA 2.x with Hibernate implementation along with Spring Data JPA infrastructure setup. Spring Web starter comes with Spring WebMVC, Embedded Tomcat, Jackson JSON, Logback setup. Aaah..enough theory..lets jump onto coding. I am using latest STS-3.5.1 IDE which provides many more starter project options like Facebbok, Twitter, Solr etc than its earlier version. Create a SpringBoot starter project by going to File -> New -> Spring Starter Project -> select Web and Actuator and provide the other required details and Finish. This will create a Spring Starter Web project with the following pom.xml and Application.java 4.0.0 com.sivalabs hello-springboot 1.0-SNAPSHOT jar hello-springboot Spring Boot Hello World org.springframework.boot spring-boot-starter-parent 1.1.3.RELEASE org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test UTF-8 com.sivalabs.springboot.Application 1.7 org.springframework.boot spring-boot-maven-plugin package com.sivalabs.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } Go ahead and run this class as a standalone Java class. It will start the embedded Tomcat server on 8080 port. But we haven't added any endpoints to access, lets go ahead and add a simple REST endpoint. @Configuration @ComponentScan @EnableAutoConfiguration @Controller public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @RequestMapping(value="/") @ResponseBody public String bootup() { return "SpringBoot is up and running"; } } Now point your browser to http://localhost:8080/ and you should see the response "SpringBoot is up and running". Remember while creating project we have added Actuator starter module also. With Actuator you can obtain many interesting facts about your application. Try accessing the following URLs and you can see lot of runtime environment configurations that are provided by SpringBoot. http://localhost:8080/beans http://localhost:8080/metrics http://localhost:8080/trace http://localhost:8080/env http://localhost:8080/mappings http://localhost:8080/autoconfig http://localhost:8080/dump SpringBoot actuator deserves a dedicated blog post to cover its vast number of features, I will cover it in my upcoming posts. I hope this article provides some basic introduction to SpringBoot and how it simplifies the Spring application development. More on SpringBoot in upcoming articles. - See more at: http://www.sivalabs.in/2014/07/springboot-introducing-springboot.html#sthash.7syCIt8V.dpuf
July 4, 2014
· 12,418 Views · 5 Likes
Exporting Spring Data JPA Repositories as REST Services using Spring Data REST
Spring Data modules provides various modules to work with various types of datasources like RDBMS, NOSQL stores etc in unified way. In my previous article SpringMVC4 + Spring Data JPA + SpringSecurity configuration using JavaConfig I have explained how to configure Spring Data JPA using JavaConfig. Now in this post let us see how we can use Spring Data JPA repositories and export JPA entities as REST endpoints using Spring Data REST. First let us configure spring-data-jpa and spring-data-rest-webmvc dependencies in our pom.xml. org.springframework.data spring-data-jpa 1.5.0.RELEASE org.springframework.data spring-data-rest-webmvc 2.0.0.RELEASE Make sure you have latest released versions configured correctly, otherwise you will encounter the following error: java.lang.ClassNotFoundException: org.springframework.data.mapping.SimplePropertyHandler Create JPA entities. @Entity @Table(name = "USERS") public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_id") private Integer id; @Column(name = "username", nullable = false, unique = true, length = 50) private String userName; @Column(name = "password", nullable = false, length = 50) private String password; @Column(name = "firstname", nullable = false, length = 50) private String firstName; @Column(name = "lastname", length = 50) private String lastName; @Column(name = "email", nullable = false, unique = true, length = 50) private String email; @Temporal(TemporalType.DATE) private Date dob; private boolean enabled=true; @OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL) @JoinColumn(name="user_id") private Set roles = new HashSet<>(); @OneToMany(mappedBy = "user") private List contacts = new ArrayList<>(); //setters and getters } @Entity @Table(name = "ROLES") public class Role implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "role_id") private Integer id; @Column(name="role_name",nullable=false) private String roleName; //setters and getters } @Entity @Table(name = "CONTACTS") public class Contact implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "contact_id") private Integer id; @Column(name = "firstname", nullable = false, length = 50) private String firstName; @Column(name = "lastname", length = 50) private String lastName; @Column(name = "email", nullable = false, unique = true, length = 50) private String email; @Temporal(TemporalType.DATE) private Date dob; @ManyToOne @JoinColumn(name = "user_id") private User user; //setters and getters } Configure DispatcherServlet using AbstractAnnotationConfigDispatcherServletInitializer. Observe that we have added RepositoryRestMvcConfiguration.class to getServletConfigClasses() method. RepositoryRestMvcConfiguration is the one which does the heavy lifting of looking for Spring Data Repositories and exporting them as REST endpoints. package com.sivalabs.springdatarest.web.config; import javax.servlet.Filter; import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import com.sivalabs.springdatarest.config.AppConfig; public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class[] getRootConfigClasses() { return new Class[] { AppConfig.class}; } @Override protected Class[] getServletConfigClasses() { return new Class[] { WebMvcConfig.class, RepositoryRestMvcConfiguration.class }; } @Override protected String[] getServletMappings() { return new String[] { "/rest/*" }; } @Override protected Filter[] getServletFilters() { return new Filter[]{ new OpenEntityManagerInViewFilter() }; } } Create Spring Data JPA repositories for JPA entities. public interface UserRepository extends JpaRepository { } public interface RoleRepository extends JpaRepository { } public interface ContactRepository extends JpaRepository { } That's it. Spring Data REST will take care of rest of the things. You can use spring Rest Shell https://github.com/spring-projects/rest-shell or Chrome's Postman Addon to test the exported REST services. D:\rest-shell-1.2.1.RELEASE\bin>rest-shell http://localhost:8080:> Now we can change the baseUri using baseUri command as follows: http://localhost:8080:>baseUri http://localhost:8080/spring-data-rest-demo/rest/ http://localhost:8080/spring-data-rest-demo/rest/> http://localhost:8080/spring-data-rest-demo/rest/>list rel href ====================================================================================== users http://localhost:8080/spring-data-rest-demo/rest/users{?page,size,sort} roles http://localhost:8080/spring-data-rest-demo/rest/roles{?page,size,sort} contacts http://localhost:8080/spring-data-rest-demo/rest/contacts{?page,size,sort} Note: It seems there is an issue with rest-shell when the DispatcherServlet url mapped to "/" and issue list command it responds with "No resources found". http://localhost:8080/spring-data-rest-demo/rest/>get users/ { "_links": { "self": { "href": "http://localhost:8080/spring-data-rest-demo/rest/users/{?page,size,sort}", "templated": true }, "search": { "href": "http://localhost:8080/spring-data-rest-demo/rest/users/search" } }, "_embedded": { "users": [ { "userName": "admin", "password": "admin", "firstName": "Administrator", "lastName": null, "email": "[email protected]", "dob": null, "enabled": true, "_links": { "self": { "href": "http://localhost:8080/spring-data-rest-demo/rest/users/1" }, "roles": { "href": "http://localhost:8080/spring-data-rest-demo/rest/users/1/roles" }, "contacts": { "href": "http://localhost:8080/spring-data-rest-demo/rest/users/1/contacts" } } }, { "userName": "siva", "password": "siva", "firstName": "Siva", "lastName": null, "email": "[email protected]", "dob": null, "enabled": true, "_links": { "self": { "href": "http://localhost:8080/spring-data-rest-demo/rest/users/2" }, "roles": { "href": "http://localhost:8080/spring-data-rest-demo/rest/users/2/roles" }, "contacts": { "href": "http://localhost:8080/spring-data-rest-demo/rest/users/2/contacts" } } } ] }, "page": { "size": 20, "totalElements": 2, "totalPages": 1, "number": 0 } } You can find the source code at https://github.com/sivaprasadreddy/sivalabs-blog-samples-code/tree/master/spring-data-rest-demo For more Info on Spring Rest Shell: https://github.com/spring-projects/rest-shell
March 7, 2014
· 29,998 Views
Clean Code: Don't Mix Different Levels of Abstractions
We spend more time on reading code than writing. So if the code is more readable then obviously it will increase the developer productivity. Many people associate readability of code with coding conventions like following standard naming conventions, closing file, DB resources etc etc. When it comes to code reviews most of the people focus on these trivial things only, like checking for naming convention violations, properly releasing resources in finally block or not. Do we need "Senior Resources" in team (I hate to call a human being as a Resource) to do these things?Tools like Findbugs, PMD, Checkstyle, Sonar can do that for you. I agree that following a standard naming convention by all the team members is a good thing. But that doesn't increase the readability of code. Let us take a simple example. I would like to implement Fund Transfer usecase and following are the rules to implement: Source and target accounts should be valid accounts Check whether source account has sufficient amount Check whether source account has provision for Overdraft and check whether this transaction exceeds the overdraft limit Check for duplicate transaction with last transaction. If source, target accounts and amount is same with last transaction consider it as a duplicate transaction If everything is fine then transfer amount to target account Assume we have the following implementation for the above usecase: public class UglyMoneyTransferService { public void transferFunds(Account source, Account target, BigDecimal amount, boolean allowDuplicateTxn) throws IllegalArgumentException, RuntimeException { Connection conn = null; try { conn = DBUtils.getConnection(); PreparedStatement pstmt = conn.prepareStatement("Select * from accounts where acno = ?"); pstmt.setString(1, source.getAcno()); ResultSet rs = pstmt.executeQuery(); Account sourceAccount = null; if(rs.next()) { sourceAccount = new Account(); //populate account properties from ResultSet } if(sourceAccount == null){ throw new IllegalArgumentException("Invalid Source ACNO"); } Account targetAccount = null; pstmt.setString(1, target.getAcno()); rs = pstmt.executeQuery(); if(rs.next()) { targetAccount = new Account(); //populate account properties from ResultSet } if(targetAccount == null){ throw new IllegalArgumentException("Invalid Target ACNO"); } if(!sourceAccount.isOverdraftAllowed()) { if((sourceAccount.getBalance() - amount) < 0) { throw new RuntimeException("Insufficient Balance"); } } else { if(((sourceAccount.getBalance()+sourceAccount.getOverdraftLimit()) - amount) < 0) { throw new RuntimeException("Insufficient Balance, Exceeding Overdraft Limit"); } } AccountTransaction lastTxn = .. ; //JDBC code to obtain last transaction of sourceAccount if(lastTxn != null) { if(lastTxn.getTargetAcno().equals(targetAccount.getAcno()) && lastTxn.getAmount() == amount && !allowDuplicateTxn) { throw new RuntimeException("Duplicate transaction exception");//ask for confirmation and proceed } } sourceAccount.debit(amount); targetAccount.credit(amount); TransactionService.saveTransaction(source, target, amount); } catch(Exception e){ logger.error("",e); } finally { try { conn.close(); } catch(Exception e){ //Not everything is in your control..sometimes we have to believe in GOD/JamesGosling and proceed } } } } The above code is readable..right??...because: 1. We have followed naming conventions like camel casing variable names 2. We have all the open braces ({) on the method definition line 3. We have closed DB Connection in finally block 4. we have logged exception instead of using System.err.println() and most important, it is working as expected. So is it readable and clean code?? In my opinion absolutely not. There are many issues in the above code from readability perspective. 1. Mixing DB interaction code with business logic 2. Throwing IllegalArgumentException, RuntimeException etc from business methods instead of Business specific exceptions 3. Most importantly, the code is mixed with different levels of abstractions. Let me explain what I mean by different levels of abstractions. Firstly, from business perspective fund transfer means validating source/target accounts, checking for sufficient balance, checking for overdraft limit, checking for duplicate transaction and making the fund transfer. From technical point of view there are various tasks like fetching Account details from DB, performing all the business related checks, throwing Exceptions if there are any violations, properly closing the resources etc. But in the above code everything is mixed together. While reading the code you start looking at JDBC code and your brain is working in Technical mode and after getting Account object from ResultSet you are checking for null and throwing Exception if it is null which is Business requirement. So immediately you need to switch your mind to Business mode and think "OK, if the account is invalid we want to abort the operation immediately". Though you managed to switch between Technical and Business modes, what about making an enhancement to one perticular subtask like "Fund transfer is considred duplicate only if it matches with the last transaction that happened with in an hour only". To make that enhancement you have to go through the entire method because you haven't modularised your sub-tasks and there is no separation of concerns. Let's rewrite the above code as follows: class FundTransferTxn { private Account sourceAccount; private Account targetAccount; private BigDecimal amount; private boolean allowDuplicateTxn; //setters & getters } public class CleanMoneyTransferService { public void transferFunds(FundTransferTxn txn) { Account sourceAccount = validateAndGetAccount(txn.getSourceAccount().getAcno()); Account targetAccount = validateAndGetAccount(txn.getTargetAccount().getAcno()); checkForOverdraft(sourceAccount, txn.getAmount()); checkForDuplicateTransaction(txn); makeTransfer(sourceAccount, targetAccount, txn.getAmount()); } private Account validateAndGetAccount(String acno){ Account account = AccountDAO.getAccount(acno); if(account == null){ throw new InvalidAccountException("Invalid ACNO :"+acno); } } private void checkForOverdraft(Account account, BigDecimal amount){ if(!account.isOverdraftAllowed()){ if((account.getBalance() - amount) < 0){ throw new InsufficientBalanceException("Insufficient Balance"); } } else{ if(((account.getBalance()+account.getOverdraftLimit()) - amount) < 0){ throw new ExceedingOverdraftLimitException("Insufficient Balance, Exceeding Overdraft Limit"); } } } private void checkForDuplicateTransaction(FundTransferTxn txn){ AccountTransaction lastTxn = TransactionDAO.getLastTransaction(txn.getSourceAccount().getAcno()); if(lastTxn != null){ if(lastTxn.getTargetAcno().equals(txn.getTargetAccount().getAcno()) && lastTxn.getAmount() == txn.getAmount() && !txn.isAllowDuplicateTxn()){ throw new DuplicateTransactionException("Duplicate transaction exception"); } } } private void makeTransfer(Account source, Account target, BigDecimal amount){ sourceAccount.debit(amount); targetAccount.credit(amount); TransactionService.saveTransaction(source, target, amount); } } The above improved method do exactly what the initial verson is doing but now it looks lot better than earlier version. We have divided the entire task into sub-tasks and implemented each sub-task in a separate method. We have delegated DB interactions to DAOs We are throwing Business specific Exceptions instead of Java language Exceptions All in all we have separated the levels of abstractions. At the first level we have highest level of abstraction in transferFunds(FundTransferTxn txn) method. By looking at this method we can understand what we are doing as part of Fund Transfer operation without worrying much about implementation or technical details. At the second level we have business logic implementation methods checkForOverdraft, checkForDuplicateTransaction etc which performs business logic, again without worrying much about technical details. At the lowest level we have technical implementation details in AccountDAO and TransactionDAO which contains DB interaction logic. So the reader(future developer/maintainer) of your code can easily understand what you are doing at the high level and can dig into method which he is interested in. As I said earlier, if we have to make the change to consider the transaction as a duplicate transaction only if it happened with in an hour, we can easily understand that checkForDuplicateTransaction() is the one we have to look into and make change. Happy coding!!
December 31, 2013
· 19,109 Views · 2 Likes
How to POST and GET JSON between EXTJS and SpringMVC3
After one month of evaluation of frameworks and tools, I choose ExtJS for UI and Spring/SpringMVC for the business layer for my pet project. By using ExtJS we can send data to server by form submits or as request parameters, or in JSON format through Ajax requests. ExtJS uses JSON format in many situations to hold data. So I thought using JSON as data exchange format between EXTJS and Spring would be consistent. The following code snippets explain how we can use ExtJS and SpringMVC3 to exchange data in JSON format. 1. Register MappingJacksonHttpMessageConverter in dispatcher-servlet.xml Add jackson-json jar(s) to WEB-INF/lib 2. Trigger the POST request from ExtJS script as follows: Ext.Ajax.request({ url : 'doSomething.htm', method: 'POST', headers: { 'Content-Type': 'application/json' }, params : { "test" : "testParam" }, jsonData: { "username" : "admin", "emailId" : "[email protected]" }, success: function (response) { var jsonResp = Ext.util.JSON.decode(response.responseText); Ext.Msg.alert("Info","UserName from Server : "+jsonResp.username); }, failure: function (response) { var jsonResp = Ext.util.JSON.decode(response.responseText); Ext.Msg.alert("Error",jsonResp.error); } }); 3. Write a Spring Controller to handle the "/doSomething.htm" reguest. @Controller public class DataController { @RequestMapping(value = "/doSomething", method = RequestMethod.POST) @ResponseBody public User handle(@RequestBody User user) throws IOException { System.out.println("Username From Client : "+user.getUsername()); System.out.println("EmailId from Client : "+user.getEmailId()); user.setUsername("SivaPrasadReddy"); user.setEmailId("[email protected]"); return user; } } Any other better approaches? From http://sivalabs.blogspot.com/2011/06/how-to-post-and-get-json-between-extjs.html
June 29, 2011
· 55,758 Views
How I Resolved SpringMVC+Hibernate Error: No Hibernate Session Bound to Thread
I used the SpringMVC @Controller annotation approach and configured the Web related Spring configuration in dispatcher-servlet.xml.
May 18, 2011
· 69,520 Views · 2 Likes
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
· 75,264 Views · 7 Likes
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
· 61,529 Views · 1 Like
The Next Level of the Don't Repeat Yourself(DRY) Principle
We have been building software applications using various languages for several years. Over this time new frameworks, new tools, new methodologies have appeared. Especially in the Java platform, where we have plenty of choices in each area following various design patterns and principles like MVC, FrontController etc. We have many development principles like KISS(Keep It Simple Stupid), DRY(Don't Repeat Yourself) which encourage developers to write better, more maintainable code. The DRY principle in particular, is a very good one which every developer should understand and follow. The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." So the DRY principle is saying that if you need to write same piece of code in many places, instead of copy-pasting it, make it as a seperate method and call that method whereever it is required. This is applying DRY at the code level. I really appreciate the Jakartha-Commons Utils authors for practically implementing DRY principle. Whenever I need a utility like some String operation, Date calculation, Regular expression, property loading etc I just open the Jakartha-Commons website and I am sure I can find what I need there. Even though each application has its own set of business requirements there are many things which are common to web/enterprise applications. Especially infrastructure code which may be similar to many applications. Now I think it is time to take DRY priciple to the next level, I mean to apply at functional level. Let us see where we can apply DRY at functional level. The following are some of the things where we can build reusable components/small projects which we can directly use with other projects. 1. An application multi-level menu bar: I have seen many applications having a horizontal menu bar at the top of the page with single/multi level sub-menus. The menu bar can be built using Javascript or custom tags. What I am suggesting is if we can build a CustomTag to generate a Menu bar from an xml configuration and a style sheet that the component can use in any project. For Example: We can create an xml structure for our menu as follows and create a custom tag to parse that xml and render a menu bar with a default stylesheet. If the user has provided a custom stylesheet, the custom tag will use that. 1 File 1 New 2 Save ..... ..... 2 Edit 1 Cut 2 Copy ..... ..... 2. Role-based authentication and authorisation system: I have been involved in many projects where the application users will have one or more roles and each role has one or more privileges. Each privilege is nothing but an action that a user will invoke in the appliation. Application events will driven by role based authorization. And also there could be a requirement to create user groups and assign privileges to user groups instead of individual users. I think this Role based Authorization System can also be built as a component which we can plug in to any project. 3. Job Scheduling: For many enterprises there could be several batch jobs that should be run on particular schedules. I think there is a need to build a job scheduling web application with the following features: a) A web based UI to create and schedule new jobs b) Provision to track the status of the running jobs c) Provision to run jobs in adhoc manner d) Provision to reschedule, terminate a job e) Informing the concerned groups about the status of jobs through emails f) Automatic email notifications on job failures We can build a web application with the above mentioned features and leaving business logic implementation in the jobs for the developers. 4.Sophisticated logging system: While developing the application logging plays a vital role in debugging the problems. We can use AOP for logging in a better way with cleaner approach. Many times the developer needs to check what parameters are being sent to methods and where it is throwing an exception. For this we can write MethodParamsDumperAspect using SpringAOP+AspectJ which will display the method parameter values using reflection/commons-beanutils. The only thing which a developer need configure is the base package name. 5. Configurable and customizable workflow engine: I have seen many intranet portals with HelpDesk applications with the following features. 1. A customer will raise a request. 2. The system will identify the workflow to process the request and the request will be routed to the concerned person. 3. The requester can view the status of his request as each step is in progress. Like this there are many WorkFlow based systems. We can build a generic workflow engine where in the administrator can setup the metadata like Request Types, Steps for each request, Request Status codes etc. So here my point is all these days we followed DRY in writing code. Let us take it to the next level in building components/sub-projects.If an architect or developer got a requirement to build a reusable component, it would be great if he/she can publish his/her approach (and code if possible) so that the other developers across the Java community can use the approach/code instead of reinventing the wheel. From : http://sivalabs.blogspot.com/2011/01/next-level-of-dont-repeat-yourselfdry.html
February 4, 2011
· 18,775 Views · 3 Likes
PrimeFaces Quick Start Tutorial - Part1
PrimeFaces is an open source component library for JSF 2.0 with more than 100 rich components. PrimeFaces is far better than many other JSF component libraries because of the following reasons: 1. Rich set of UI components (DataTable, AutoComplete, HtmlEditor, Charts etc). 2.No extra xml configuration is required and there is no required dependencies. 3. Built-in Ajax based on standard JSF 2.0 Ajax APIs. 4. Skinning Framework with 25+ built-in themes. 5. Awesome documentation with code examples. Let us build a sample application using PrimeFaces with the following features: 1. A Login screen which accepts username and password and authenticate the user. 2. Upon successful login user will be shown a User Search screen. Users can search for users by their name. The search results will be displayed in a DataTable with pagination, sorting and filtering support. 3. Upon clicking on a row the user details will be displayed in a form. First download JSF 2 jars from http://javaserverfaces.java.net/download.html Place the jsf-api-2.0.3.jar, jsf-impl-2.0.3.jar and jstl-1.0.2.jar jars in WEB-INF/lib folder. Download PrimeFaces from http://www.primefaces.org/downloads.html. Place primefaces-2.2.RC2.jar in WEB-INF/lib folder. Configure FacesServlet in web.xml index.jsp Faces Servlet javax.faces.webapp.FacesServlet 1 Faces Servlet *.jsf Create faces-config.xml in WEB-INF folder. Welcome page index.jsp just forwards to login screen. Create login.xhtml page. You can get the blusky theme from PrimeFaces bundle.Create home.xhtml which contains UserSearchForm, Results dataTable and UserDetails Panel. Create User.java domain class. package com.primefaces.sample;import java.util.Date;public class User{ private Integer userId; private String username; private String emailId; private String phone; private Date dob; private String gender; private String address; public User() {} public User(Integer userId, String username, String emailId, String phone, Date dob, String gender, String address) { this.userId = userId; this.username = username; this.emailId = emailId; this.phone = phone; this.dob = dob; this.gender = gender; this.address = address; } //setter and getters } Create UserService.java which acts as a mock database table. package com.primefaces.sample;import java.util.ArrayList;import java.util.Collection;import java.util.Date;import java.util.HashMap;import java.util.Map;import java.util.Set;public class UserService{ private static final Map USERS_TABLE = new HashMap(); static { USERS_TABLE.put(1, new User(1, "Administrator", "[email protected]", "9000510456", new Date(), "M", "Hyderabad")); USERS_TABLE.put(2, new User(2, "Guest", "[email protected]", "9247469543", new Date(), "M", "Hyderabad")); USERS_TABLE.put(3, new User(3, "John", "[email protected]", "9000510456", new Date(), "M", "Hyderabad")); USERS_TABLE.put(4, new User(4, "Paul", "[email protected]", "9247469543", new Date(), "M", "Hyderabad")); USERS_TABLE.put(5, new User(5, "raju", "[email protected]", "9000510456", new Date(), "M", "Hyderabad")); USERS_TABLE.put(6, new User(6, "raghav", "[email protected]", "9247469543", new Date(), "M", "Hyderabad")); USERS_TABLE.put(7, new User(7, "caren", "[email protected]", "9000510456", new Date(), "M", "Hyderabad")); USERS_TABLE.put(8, new User(8, "Mike", "[email protected]", "9247469543", new Date(), "M", "Hyderabad")); USERS_TABLE.put(9, new User(9, "Steve", "[email protected]", "9000510456", new Date(), "M", "Hyderabad")); USERS_TABLE.put(10, new User(10, "Polhman", "[email protected]", "9247469543", new Date(), "M", "Hyderabad")); USERS_TABLE.put(11, new User(11, "Rogermoor", "[email protected]", "9000510456", new Date(), "M", "Hyderabad")); USERS_TABLE.put(12, new User(12, "Robinhood", "[email protected]", "9247469543", new Date(), "M", "Hyderabad")); USERS_TABLE.put(13, new User(13, "Sean", "[email protected]", "9000510456", new Date(), "M", "Hyderabad")); USERS_TABLE.put(14, new User(14, "Gabriel", "[email protected]", "9247469543", new Date(), "M", "Hyderabad")); USERS_TABLE.put(15, new User(15, "raman", "[email protected]", "9000510456", new Date(), "M", "Hyderabad")); } public Integer create(User user) { if(user == null) { throw new RuntimeException("Unable to create User. User object is null."); } Integer userId = this.getMaxUserId(); user.setUserId(userId); USERS_TABLE.put(userId, user); return userId; } public void delete(User user) { if(user == null) { throw new RuntimeException("Unable to delete User. User object is null."); } USERS_TABLE.remove(user.getUserId()); } public Collection getAllUsers() { return USERS_TABLE.values(); } public User getUser(Integer userId) { return USERS_TABLE.get(userId); } public Collection searchUsers(String username) { String searchCriteria = (username == null)? "":username.toLowerCase().trim(); Collection users = USERS_TABLE.values(); Collection searchResults = new ArrayList(); for (User user : users) { if(user.getUsername() != null && user.getUsername().toLowerCase().trim().startsWith(searchCriteria)) { searchResults.add(user); } } return searchResults; } public void update(User user) { if(user == null || !USERS_TABLE.containsKey(user.getUserId())) { throw new RuntimeException("Unable to update User. User object is null or User Id ["+user.getUserId()+"] is invalid." ); } USERS_TABLE.put(user.getUserId(), user); } protected Integer getMaxUserId() { Set keys = USERS_TABLE.keySet(); Integer maxId = 1; for (Integer key : keys) { if(key > maxId) { maxId = key; } } return maxId; } Create UserManagedBean.java package com.primefaces.sample;import java.util.Collection;import javax.faces.application.FacesMessage;import javax.faces.bean.ApplicationScoped;import javax.faces.bean.ManagedBean;import javax.faces.context.FacesContext;import org.primefaces.event.SelectEvent;import org.primefaces.event.UnselectEvent;@ManagedBean@ApplicationScopedpublic class UserManagedBean{ UserService userService = new UserService(); private String username; private String password; private String searchUser; private Collection searchUsersResults; private User selectedUser; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public User getSelectedUser() { if(selectedUser == null){ selectedUser = new User(); } return selectedUser; } public void setSelectedUser(User selectedUser) { this.selectedUser = selectedUser; } public Collection getSearchUsersResults() { return searchUsersResults; } public void setSearchUsersResults(Collection searchUsersResults) { this.searchUsersResults = searchUsersResults; } public String getSearchUser() { return searchUser; } public void setSearchUser(String searchUser) { this.searchUser = searchUser; } public String login() { if("test".equalsIgnoreCase(getUsername()) && "test".equals(getPassword())) { return "home"; } else { FacesContext context = FacesContext.getCurrentInstance(); context.addMessage("username", new FacesMessage("Invalid UserName and Password")); return "login"; } } public String searchUser() { String username = (this.searchUser == null)? "":this.searchUser.trim(); this.searchUsersResults = userService.searchUsers(username); System.out.println(searchUsersResults); return "home"; } public String updateUser() { userService.update(this.selectedUser); return "home"; } public void onUserSelect(SelectEvent event) { } public void onUserUnselect(UnselectEvent event) { } That all we need to do. You can run the application and see the rich user interface with blusky theme. By default we don't get auto-complete for PrimeFaces tag in Eclipse. To enable AutoComplete, Go to Window-->Preferences-->General-->ContentTypes Select JSP and add .xhtml as file association. From http://sivalabs.blogspot.com/2011/02/primefaces-quickstart-tutorial-part1.html
February 2, 2011
· 191,483 Views · 4 Likes

Comments

Spring Boot: Working With MyBatis

Jul 04, 2018 · Dave Fecak

I still personally like it. But I would try JOOQ. I keep hearing a lot of good things about JOOQ.

Microservices - Part 5: Spring Cloud Zuul Proxy as API Gateway

May 04, 2018 · Thomas Jardinet

A better approach would be using OAuth based security so that all microservices can be secured individually.

Microservices - Part 2: Configuration Management With Spring Cloud Config and Vault

Mar 09, 2018 · Arran Glen

Here I am explaining how to use the Spring Cloud features to address concerns occur while building microservices. I am intentionally keeping business logic very low so that reader can focus on "How to use Spring Cloud features".

Why Spring Boot?

Nov 24, 2017 · Tim Spann

Here it is https://sivalabs.in/2016/03/how-springboot-autoconfiguration-magic/

5 Tips For Using Lombok In Production

Jun 07, 2017 · Alex Collins

Tip#3: Do you mean DTOs (Data Transfer Object)?

Unit Testing JPA... Stop Integration Testing!

Jun 29, 2016 · Michael Remijan

We can call whatever we want but IMO I don't think the testing technique proposed in this article give any benifit.

I prefer testing business logic using Unit Tests by abstracting how the data is loaded (DB/Mock etc). But I always prefer testing the integration code (DB/WebService etc) using real services.

Unit Testing JPA... Stop Integration Testing!

Jun 27, 2016 · Michael Remijan

Looking at all your Unit Test, it seems like you are testing (1) whether Java Annotation/Reflection API is working or not (2) Are developers adding annotations properly or not.

How do you know whether the developers are writing unit tests properly?

Sorry to say this, but it looks like over engineering.

Spring Boot: Working With MyBatis

Mar 25, 2016 · Dave Fecak

Seems like the author name of this article points to some other "Siva Prasad"!!

A Webapp Makeover with Spring 4 and Spring Boot

Dec 15, 2013 · James Sugrue

A good and simple way to start creating spring boot apps is http://start.spring.io/

How Changing Java Package Names Transformed my System Architecture

Jul 20, 2012 · James Sugrue

Hi Johannes Brodwall,

I like the idea of package by feature which greately reduces the time for moving across the packages while coding and all the related stuff will be at one place(package). But what about interactions between the services in different packages?

Suppose we are building a blog app and we are putting all user related operations(controllers/services/repositories) in com.mycompany.myblog.users package. And all blog post related operations(controllers/services/repositories) in com.mycompany.myblog.posts package.

Now I want to show User Profile along with all the posts that he posted. Should I call myblog.posts.PostsService.getPostsByUser(userId) from myblog.users.UserController.showUserProfile()?

What about coupling between packages?

Also wherever I read about package by feature, everyone says its a good practice. Then why many book authors and even frameworks encourage to group by layers? Just curious to know :-)

Thanks,

-Siva

How to POST and GET JSON between EXTJS and SpringMVC3

Jul 10, 2011 · Siva Prasad Reddy Katamreddy

Hi,

Having a filter to decode json as request parameters and making SpringMVC handle it as normal requests is a good idea. I will try this.

Thanks,

Siva

How to POST and GET JSON between EXTJS and SpringMVC3

Jul 10, 2011 · Siva Prasad Reddy Katamreddy

Hi,

Having a filter to decode json as request parameters and making SpringMVC handle it as normal requests is a good idea. I will try this.

Thanks,

Siva

How to POST and GET JSON between EXTJS and SpringMVC3

Jul 10, 2011 · Siva Prasad Reddy Katamreddy

Hi,

Having a filter to decode json as request parameters and making SpringMVC handle it as normal requests is a good idea. I will try this.

Thanks,

Siva

How to POST and GET JSON between EXTJS and SpringMVC3

Jun 29, 2011 · Siva Prasad Reddy Katamreddy

Hi,

I took the following criteria for choosing Javascript library:

1. DOM Manipulation: In this all frameworks ExtJS, JQuery, Dojo, YUI are providing very good utilities to do DOM manipulation.

2. Communicating to Server : In this regard also all the frameworks are more or less equal.

3. Widget Library: In this area ExtJS is better than rest of all.

YUI is also good in Widget support. But look and feel is poor.

Dojo doesn't have a Grid with Pagination support(may be new version might have this).

We need to add Jquery plugins to get this Pagination Grid support. It might be easy but it would be great if we have this in-built with the framework.

4. Look and Feel: In this also ExtJS are far better than others.

YUI's pagination bar , Collapsible Layouts doesn't look good (to me :-))

For ExtJS the main strong points are its Widget Library, look n feel and Server Communication.

Thanks,

Siva

How to POST and GET JSON between EXTJS and SpringMVC3

Jun 29, 2011 · Siva Prasad Reddy Katamreddy

Hi,

I took the following criteria for choosing Javascript library:

1. DOM Manipulation: In this all frameworks ExtJS, JQuery, Dojo, YUI are providing very good utilities to do DOM manipulation.

2. Communicating to Server : In this regard also all the frameworks are more or less equal.

3. Widget Library: In this area ExtJS is better than rest of all.

YUI is also good in Widget support. But look and feel is poor.

Dojo doesn't have a Grid with Pagination support(may be new version might have this).

We need to add Jquery plugins to get this Pagination Grid support. It might be easy but it would be great if we have this in-built with the framework.

4. Look and Feel: In this also ExtJS are far better than others.

YUI's pagination bar , Collapsible Layouts doesn't look good (to me :-))

For ExtJS the main strong points are its Widget Library, look n feel and Server Communication.

Thanks,

Siva

Spring and Hibernate Application with Zero XML

Feb 23, 2011 · Siva Prasad Reddy Katamreddy

I agree with you.

I missed to convey my main intention of going to use Annotation approach entirely instead of simple xml based approach.

Here it is:

I had a discussion with one of my friend about extending PropertyPlaceholderConfigurer and provide additional utility methods like JConfig's centralized Configuration manager.
All over the Annotation based Spring examples use xml based PropertyPlaceholderConfigurer configuration. So I thought of just telling there is a way to configure customized PropertyPlaceholderConfigurer through Annotations.

I am neither fan of Annotations nor XML. If you ask me to choose the approach, I will choose XML for non-frequently changing configuration and Annotations for Controller mappings and all.

Spring and Hibernate Application with Zero XML

Feb 23, 2011 · Siva Prasad Reddy Katamreddy

I agree with you.

I missed to convey my main intention of going to use Annotation approach entirely instead of simple xml based approach.

Here it is:

I had a discussion with one of my friend about extending PropertyPlaceholderConfigurer and provide additional utility methods like JConfig's centralized Configuration manager.
All over the Annotation based Spring examples use xml based PropertyPlaceholderConfigurer configuration. So I thought of just telling there is a way to configure customized PropertyPlaceholderConfigurer through Annotations.

I am neither fan of Annotations nor XML. If you ask me to choose the approach, I will choose XML for non-frequently changing configuration and Annotations for Controller mappings and all.

Spring and Hibernate Application with Zero XML

Feb 23, 2011 · Siva Prasad Reddy Katamreddy

I agree with you.

I missed to convey my main intention of going to use Annotation approach entirely instead of simple xml based approach.

Here it is:

I had a discussion with one of my friend about extending PropertyPlaceholderConfigurer and provide additional utility methods like JConfig's centralized Configuration manager.
All over the Annotation based Spring examples use xml based PropertyPlaceholderConfigurer configuration. So I thought of just telling there is a way to configure customized PropertyPlaceholderConfigurer through Annotations.

I am neither fan of Annotations nor XML. If you ask me to choose the approach, I will choose XML for non-frequently changing configuration and Annotations for Controller mappings and all.

Getting Started with iBatis (MyBatis): XML Configuration

Feb 21, 2011 · James Sugrue

Hi,

I worked with IBATIS two years back and it is simple superb.

If you are planning to immplement your persistence layer using your own hand written SQLs and take advantage of automatic population of sql results into Java Objects and passing Java Objects to Persistence engine to store in DB IBATIS is the way to go.

I haven't tried the brand new MyBATIS yet, but hoping its better than IBATIS.

Thank you so much Loiane Groner for this article. :-)

The Next Level of the Don't Repeat Yourself(DRY) Principle

Feb 14, 2011 · Siva Prasad Reddy Katamreddy

Hi,

All the stuff which you mentioned are standalone APIs for their respective tasks.

Take Quartz, using quartz we can write the job scheduling applications. I agree.

But my point is we should have a framework kind of semi completed job scheduling application which can be used by anyone by plugging-in their job implementations. And the framework should take care of rest of the activities that I mentioned in the above post.

Similarly for Logging, If we can write an Aspect to print the method parameters in details in such a way that anyone can use that aspect and be able to print method parameters in DEBUG mode by just passing their pointcut details.

Your thoughts??

The Next Level of the Don't Repeat Yourself(DRY) Principle

Feb 14, 2011 · Siva Prasad Reddy Katamreddy

Hi,

All the stuff which you mentioned are standalone APIs for their respective tasks.

Take Quartz, using quartz we can write the job scheduling applications. I agree.

But my point is we should have a framework kind of semi completed job scheduling application which can be used by anyone by plugging-in their job implementations. And the framework should take care of rest of the activities that I mentioned in the above post.

Similarly for Logging, If we can write an Aspect to print the method parameters in details in such a way that anyone can use that aspect and be able to print method parameters in DEBUG mode by just passing their pointcut details.

Your thoughts??

The Next Level of the Don't Repeat Yourself(DRY) Principle

Feb 14, 2011 · Siva Prasad Reddy Katamreddy

Hi,

All the stuff which you mentioned are standalone APIs for their respective tasks.

Take Quartz, using quartz we can write the job scheduling applications. I agree.

But my point is we should have a framework kind of semi completed job scheduling application which can be used by anyone by plugging-in their job implementations. And the framework should take care of rest of the activities that I mentioned in the above post.

Similarly for Logging, If we can write an Aspect to print the method parameters in details in such a way that anyone can use that aspect and be able to print method parameters in DEBUG mode by just passing their pointcut details.

Your thoughts??

Java Coding Best Practices: Better Search Implementation

Feb 10, 2011 · Siva Prasad Reddy Katamreddy

To get all the results we can call: searchResults.getResults();
If we want to get page wise results pass the page number as: searchResults.getResults(2);


This logic can be integrated with DisplayTag.

Java Coding Best Practices: Better Search Implementation

Feb 10, 2011 · Siva Prasad Reddy Katamreddy

To get all the results we can call: searchResults.getResults();
If we want to get page wise results pass the page number as: searchResults.getResults(2);


This logic can be integrated with DisplayTag.

Java Coding Best Practices: Better Search Implementation

Feb 10, 2011 · Siva Prasad Reddy Katamreddy

To get all the results we can call: searchResults.getResults();
If we want to get page wise results pass the page number as: searchResults.getResults(2);


This logic can be integrated with DisplayTag.

Java Coding Best Practices: Better Search Implementation

Feb 10, 2011 · Siva Prasad Reddy Katamreddy

To get all the results we can call: searchResults.getResults();
If we want to get page wise results pass the page number as: searchResults.getResults(2);


This logic can be integrated with DisplayTag.

Java Coding Best Practices: Better Search Implementation

Feb 09, 2011 · Siva Prasad Reddy Katamreddy

Hi,

Thanks that you like this article. This idea can be improved to be more generic and support others features also including pagination(client/server), filtering etc.

That Map is of type <String, Object> and the count is of Integer type. So I cast it to Integer.

Java Coding Best Practices: Better Search Implementation

Feb 09, 2011 · Siva Prasad Reddy Katamreddy

Hi,

Thanks that you like this article. This idea can be improved to be more generic and support others features also including pagination(client/server), filtering etc.

That Map is of type <String, Object> and the count is of Integer type. So I cast it to Integer.

Java Coding Best Practices: Better Search Implementation

Feb 09, 2011 · Siva Prasad Reddy Katamreddy

Hi,

Thanks that you like this article. This idea can be improved to be more generic and support others features also including pagination(client/server), filtering etc.

That Map is of type <String, Object> and the count is of Integer type. So I cast it to Integer.

PrimeFaces Quick Start Tutorial - Part1

Feb 04, 2011 · Siva Prasad Reddy Katamreddy

@Jonathan Fisher,

I haven't deep dive into JSF2 but i haven't found any major improvements in JSF2 except annotation support over JSF1.x as of now. Could you please tell me or point me to some url where i can see what are the things improved/added in JSF2.x.

Thanks,
Siva.

PrimeFaces Quick Start Tutorial - Part1

Feb 04, 2011 · Siva Prasad Reddy Katamreddy

@Jonathan Fisher,

I haven't deep dive into JSF2 but i haven't found any major improvements in JSF2 except annotation support over JSF1.x as of now. Could you please tell me or point me to some url where i can see what are the things improved/added in JSF2.x.

Thanks,
Siva.

PrimeFaces Quick Start Tutorial - Part1

Feb 04, 2011 · Siva Prasad Reddy Katamreddy

@Jonathan Fisher,

I haven't deep dive into JSF2 but i haven't found any major improvements in JSF2 except annotation support over JSF1.x as of now. Could you please tell me or point me to some url where i can see what are the things improved/added in JSF2.x.

Thanks,
Siva.

10 Steps to Become an Outstanding Java Developer

Jan 28, 2011 · Siva Prasad Reddy Katamreddy

Hi Jakob,

I read your article and its really good. And also there are several other pretty good posts on your blog and i like them very much. Keep blogging :-)

10 Steps to Become an Outstanding Java Developer

Jan 28, 2011 · Siva Prasad Reddy Katamreddy

Hi Jakob,

I read your article and its really good. And also there are several other pretty good posts on your blog and i like them very much. Keep blogging :-)

10 Steps to Become an Outstanding Java Developer

Jan 27, 2011 · Siva Prasad Reddy Katamreddy

For 11 item best practice is composition - strategy pattern, isn't it?

Ofcourse, you can use strategy pattern.

But here what I am trying to say is "Try to co-relate the real world things to java, you may get crazy but very innovative solutions"

10 Steps to Become an Outstanding Java Developer

Jan 27, 2011 · Siva Prasad Reddy Katamreddy

For 11 item best practice is composition - strategy pattern, isn't it?

Ofcourse, you can use strategy pattern.

But here what I am trying to say is "Try to co-relate the real world things to java, you may get crazy but very innovative solutions"

10 Steps to Become an Outstanding Java Developer

Jan 27, 2011 · Siva Prasad Reddy Katamreddy

For 11 item best practice is composition - strategy pattern, isn't it?

Ofcourse, you can use strategy pattern.

But here what I am trying to say is "Try to co-relate the real world things to java, you may get crazy but very innovative solutions"

10 Steps to Become an Outstanding Java Developer

Jan 27, 2011 · Siva Prasad Reddy Katamreddy

In my opinion, these certifications may make you good at understanding the language constructs and core APIs.

Suppose if you consider SCJP there won't be a question on the best way of modeling a problem, if you consider SCWCD most of the questions will be on testing your understanding on Servlet and JSP APIs.

Having an idea on core APIs is expected skills, to be an outstanding developer you should have something more than a normal developer.

10 Steps to Become an Outstanding Java Developer

Jan 27, 2011 · Siva Prasad Reddy Katamreddy

In my opinion, these certifications may make you good at understanding the language constructs and core APIs.

Suppose if you consider SCJP there won't be a question on the best way of modeling a problem, if you consider SCWCD most of the questions will be on testing your understanding on Servlet and JSP APIs.

Having an idea on core APIs is expected skills, to be an outstanding developer you should have something more than a normal developer.

10 Steps to Become an Outstanding Java Developer

Jan 26, 2011 · Siva Prasad Reddy Katamreddy

Ooooops....I missed it... Anyway i will include it in my full list at 0th position :-)

10 Steps to Become an Outstanding Java Developer

Jan 26, 2011 · Siva Prasad Reddy Katamreddy

Ooooops....I missed it... Anyway i will include it in my full list at 0th position :-)

10 Steps to Become an Outstanding Java Developer

Jan 26, 2011 · Siva Prasad Reddy Katamreddy

In addition to the above 10 steps, the bonus 11th step is "Think out of the box, try to co-relate the real world situations to technology". Then working on technology will become more fun and challenging.

For example, imagine you are the GOD and you have to implement the human behaviour using Java. Every human being will behave differently for different situations. But GOD can't implement the behaviour of all the mankind using a seperate method.

Suppose take the case of how a human being aswer a phone call.

The core implementation is just to pick the call and say hello. But if the caller is your girl friend you say Hi sweet heart, if the caller is customer care executive you might say Hello, I am busy call me later :-)

So GOD might have implemented the answerCall() method as :


public void answerCall(Call call)

{

System.out.println(call.getSalutation());//call.getSalutation() might be like"Hello Mr XYZ"

}

Then GOD might have used SpringAOP to change this behaviour based on caller type.

 @Before

public class PhoneCallSalutationAdvice()

{

Call call = ....;

if(call.isGirlFriend())

{

call.setSalutation("Hi Sweet heart...");

} else if if(call.isCustomerSupportGuys())

{

call.setSalutation("Hi , I am busy right now...call me later.");

return;

}else{

call.setSalutation("Hello "+call.getCallerName());

}

}

:-)

User has been successfully modified

Failed to modify user

Let's be friends: