Skip to main content

Posts

Showing posts from February, 2015

How to do Versioning Controllers in Grails Example

Points To Remember Versioning  of Controllers can be done in grails with the help of UrlMappings and Namespaces. We can have two or more controllers with the same name as long as they are in different packages and different namespaces . You can map these controllers in UrlMappings  like  /$namespace/$controller/$action Versioning of Grails Controllers  The easiest way of versioning the grails controllers is to do it with the help of namespaces. So in this example we will try to do versioning of the controllers on the basis of namespaces. Test.groovy package com.ekiras.versioning.v1 class TestController { static namespace = "v1" def index() { render "Hi, This is version 1" } } Test.groovy package com.ekiras.versioning.v2 class TestController { static namespace = "v2" def index() { render "Hi, This is version 2" } } UrlMappings class UrlMappings { static mappings = { "/$namespace/$controller/$a

What is NoClassDefFoundException in Java

Points To Remember NoClassDefFoundException is an Exception that occurs when a class is not found at runtime but was available at compile time. This exception is different from ClassNotFoundException. See the differences here . Example : Creating a NoClassDefFoundException Suppose we have two classes A and Test. We just make an object of class A in Test class. A.java class A{ public A(){ System.out.println("This is class A"); } } Test.java class Test{ public static void main(String args[]){ System.out.println("This is Test Class"); A obj = new A(); } } The output of the program will be as follows This is Test Class This is class A Now Suppose if you delete the class A.class from the current path and run the Test class you will get the following output This is Test Class Exception in thread "main" java.lang.NoClassDefFoundError: A at Test.main(Test.java:12) Caused by: java.lang.ClassNotFoundException: A at java.net.URLClassLoade

How to create Nested Custom Exceptions in Java

Points To Rememeber When you have to create a nested or a group of similar Exceptions in your application then  First create a ParentException class and this class should either extend Exception  class or RuntimeException class.  All the nested Exceptions will extend the ParentException and thus will lie in a hierarchy. Scenario There may be times when you want to have your own hierarchy of Custom Exception so that you can manage your application in a better way. Suppose we have a Quiz application where we want to show questions based on a Topic and display questions Creating Nested Custom Exceptions  So we have created three exception classes here. QuixException InvalidQuestionIdException InvalidAnswerException Here Quiz Exception is the Parent of all the other Exceptions. QuizException can catch all the nested Exceptions so that we do not have to catch each of them separately.   class QuizException extends Exception { public QuizException(String message) { super(message); } }

How to create a Custom Exception in Java

Points To Remember All the custom Exceptions must implement the Exception class or any of its subclass . There are four types of Constructors that you can use while defining your Custom Exception. Ex 1 : Basic Custom Exception In this case we will just created a Custom Exception where we define a Custom Exception and throw it with a message. This message is visible in the stacktrace. class CustomException extends Exception { public CustomException(String message) { super(message); } } public class Test { public static void main(String args[]) { try { throw new CustomException("Throwing Custom Exception"); } catch (CustomException e) { e.printStackTrace(); } try { throw new CustomException(" ThrowingAnother Custom Exception"); } catch (CustomException e) { e.printStackTrace(); } } } The output of the above example is CustomException: Throwing Custom Exception at Test.main(Test.java:12) CustomException: ThrowingAnother Custom Exceptio

Youtube Data Api v3 : Authenticate User

Points To Remember You must have a project created in Developers console to use Youtube data api and other api's. You should save the youtube refresh token in a database or file where you can save it for a long time and use it. Youtube refresh token is generated only once , so if you want to regenerate it go to google accounts page  and revoke access to your project and then re authenticate. To revoke access, go to Connected Apps and Sites  in the above mentioned url and click on your project and then click revoke access to revoke access to the app. Steps to Use Youtube Data Api v3 You need to create a new Project in your at  Developers Console . After creating a project you need to go to  Project -> Api & auth -> Credentials  , and then create a new  Client ID . Go to  Project -> Api & auth ->APIs  and enable  Youtube Analytics API  and  YouTube Data API v3 . This will enable your project to use consume these api's. For using these api's in your applic

How to use Enums in Hibernate Persistence

Points To Remember Enums are special java classes that are used to declare constants and methods. Enums have all the variables declared as public static final. Enums variables can be compared using ==  operator. End of a enum can be declared by a semi colon, but this is optional. There are two ways to use Enums  ORDINAL (saves the enum values in integer format starting from 0.) STRING (saves the enum value in String, takes the value of the field itself. ) Use Enums in Hibernate In this example we will be using Enums to save a value in database using hibernate. Suppose we have a Enum named Level  and we want to save it in database using hibernate persistence.Then we can map this in the following way. Level.java This is an Enum that defines the level of difficulty of a question. package com.ekiras.enums; public enum Level { LEVEL_ONE, LEVEL_TWO, LEVEL_THREE, LEVEL_FOUR, LEVEL_FIVE; } Qusetion.java This class contains the enum as a field that will be saved to the database. package co

Maven Spring MVC Hibernate Sitemesh Project Setup

Points To Remember You need to add the following dependencies to pom.xml spring-core spring-context spring-web spring-webmvc spring-tx spring-orm mysql-connector-java jstl hibernate  Create  Maven Spring Hibernate Sitemesh Annotation based Hello World project pom.xml pom.xml should contain the following dependencies <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework.samples.service.service</groupId> <artifactId>ekiras</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <java.version>1.7</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncodi

Hibernate Many to Many relational Mapping

Points To Remember Suppose we have two domains/ entities  User  and  Role  and we want to create a many to many relationship between them them, then we can do it like following in hibernate. Many to Many relationship between two Entities. User.java Create a User class as following package com.ekiras.domain; import java.util.ArrayList; import java.util.Collection; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id") private Long id; @Column(name="email") private String email; @Column(name="password") private String password; @Column(name="enabled") private boolean enabled; @ManyToM

How to create a database dump in Mysql

Points To Remember You can take dump of Mysql using mysqldump  in windows, linux or ubuntu operating systems. You should reach to the location of mysql/bin in a windows platform to use mysqldump, you can use from any location in ubuntu and linux. Taking dump of whole database When you want to take the dump of the whole file, you can simply do it with the following command mysqldump -u db_username -p database_name > path/dump.sql Here the database_name  is your database name and path is absolute path where you want to create dump. Taking dump of a table When you want to take the dump of a single table you can do this by the following command. mysqldump -u db_username -p database_name tablename > path/dump.sql Taking dump of a remote database When you want to take a dump of a remote user you can do this by the following command. mysqldump -u <db_username> -h <db_host> -p database_name > path/dump.sql Taking dump of a remote database table When you want to take the du

Many To Many Mapping in Hibernate Annotation

Points To Remember There are two ways to create hibernate many to many relational mappings in Hibernate. We will discuss both of them in detail here. First one is to use default hibernate mapping to create and manage these relations. By creating a new domain that will manage these relations for us. Suppose we want to have a simple User and Role mapping where a user can have multiple roles and a role can be assigned to multiple users. Then we can create and manage these relations in the following ways. Strategy 1 : Default Hibernate Mappings You can use this strategy as applied like shown in this article . This will make the hibernate to deal with all the mappings and operations like save , update, fetch etc. Advantage : This will make hibernate responsible for the mapping and operations like save, fetch, update etc. Disadvantage : You will not have control over the mapped relation. You will not be able to query the table it will create for mapping. Strategy 2 : Using Domain to Handle

Custom 404 Error Page in Spring MVC

Points To Remember You need to first add the errors in the web.xml  and redirect them to a url. Then you need to map these url to controller to handle them and take necessary actions.  You can either handle exceptions in your controllers as explained in the link. Custom Error Pages Here in this example we are going to create custom error pages in our spring mvc application. So will first of all configure the error codes in web.xml like the following. web.xml <error-page> <error-code>400</error-code> <location>/400</location> </error-page> <error-page> <error-code>404</error-code> <location>/404</location> </error-page> <error-page> <error-code>500</error-code> <location>/500.jsp</location> </error-page> Now when we have configured the error codes and mapped then with the respective url's, we will now create a Controller that will map these error code url

How to create Custom 404 page in Web Application

Points To Remember You can define your custom error pages in web.xml.  This is the best way to define custom 404 and other error pages. Configure Custom error pages Many times we want to create custom error pages in our web applications like for a 404 error, resource not found, 500 internal server error and other errors that we see commonly. So we may want to redirect such errors to a better looking custom error page. If you want to redirect to custom error pages in a web application you can add these custom error pages in web.xml like following. web.xml <error-page> <error-code>400</error-code> <location>/error/400.html</location> </error-page> <error-page> <error-code>404</error-code> <location>/error/404.html</location> </error-page> <error-page> <error-code>500</error-code> <location>/error/500.html</location> </error-page> <error-page> <error

How to create a Composite Key in Hibernate

Points To Remember You need to create an Embedded Object to create a composite key in Hibernate. You can create use an Embeddable Object as an EmbeddedId in class to make it a composite key. Create a Composite Key in Hibernate Suppose we have three classes User, Role and UserRole . In class UserRole we want to have a composite id that will include userId and roleId . Then we will first create an embedded object and then using this we will create a composite key. Let us first create an Embeddable object and User.java package com.ekiras.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id") private Long id; @Column(name="email") private String email; @Column(name="pass