Friday, 30 March 2018

how to create Spring Rest Application using Spring boot and spring data jpa

step 1:create the database studentdb
CREATE SCHEMA `studentdb` ;

step 2: create the following table.
CREATE  TABLE `studentdb`.`student` (
  `student_id` BIGINT NOT NULL AUTO_INCREMENT ,
  `student_name` VARCHAR(45) NULL ,
  `student_age` INT NULL ,
  `gender` VARCHAR(6) NULL ,
  PRIMARY KEY (`student_id`) );

Note: for creating table you have to follow the camelCase.
more about you can read from here
http://stackoverflow.com/questions/23456197/spring-data-jpa-repository-underscore-on-entity-column-name and store some data into this tables

INSERT INTO `studentdb`.`student` (`student_name`, `student_age`, `gender`) VALUES ('ishwar', '26', 'Male');
INSERT INTO `studentdb`.`student` (`student_name`, `student_age`, `gender`) VALUES ('Yogesh', '24', 'Male');
INSERT INTO `studentdb`.`student` (`student_mame`, `student_age`, `gender`) VALUES ('Mayur', '26', 'Male');
INSERT INTO `studentdb`.`student` (`student_name`, `student_age`, `gender`) VALUES ('Jaydip', '24', 'Male');
INSERT INTO `studentdb`.`student` (`student_name`, `student_age`, `gender`) VALUES ('Kirte', '22', 'Male');


step 3: create maven project and gave project name student and give group name students.

step 4:create the com.poolofjava.entities package and create student entities like following.

package com.poolofjava.entities;

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="student")
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Long studentId;
@Column(name="student_name")
String studentName;
@Column(name="student_age")
int  studentAge;
@Column(name="gender")
String gender;
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student(){
}
/*
* this consturctor is use for the finding student base on the id
* so the id assign using this constructor
*/
public Student(Long studentId){
this.studentId=studentId;
}

}


step 5: now create the repository inside the com.poolofjava.repository package...create class StudentRepository

package com.poolofjava.repository;

import java.util.List;
import org.springframework.data.repository.CrudRepository;

import com.poolofjava.entities.Student;

public interface StudentRepository extends CrudRepository<Student,Long> {
public List<Student> findBystudentId(Long studentId);


}

step 6 :now create the rest controller in the package com.poolofjava.controller

package com.poolofjava.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.poolofjava.entities.Student;
import com.poolofjava.repository.StudentRepository;

@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
StudentRepository student;
@RequestMapping(method = { RequestMethod.GET },value = "/studentid/{studentid}",produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public List<Student> getStudentDeails(@PathVariable("studentid") Long id){
System.out.println("the id is"+id);
return student.findBystudentId(id);
}

}

step 7: now create main application class inside the package com.poolofjava.

package com.poolofjava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan
@EnableWebMvc
@EnableSpringDataWebSupport
@EnableTransactionManagement
@EnableJpaRepositories(basePackages={"com.poolofjava.repository"})
@EntityScan(basePackages={"com.poolofjava.entities"})
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) throws Throwable {
       new SpringApplication(Application.class).run(args);
   }

}

step 8: now create the  application.properties file inside the resource folder.

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/studentdb
spring.datasource.username=snefouser
spring.datasource.password=snefouser
spring.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=create-drop

step 9:now modify the pom.xml file

<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>students</groupId>
  <artifactId>student</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>student</name>
  
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <start-class>com.poolofjava.Application</start-class>
    <java.version>1.7</java.version>
    <logback.version>1.1.2</logback.version>
    <querydsl.version>3.4.0</querydsl.version>
  </properties>
  
  
  <!-- ths library for the spring data jpa -->
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

<dependency>
        <groupId>com.mysema.querydsl</groupId>
        <artifactId>querydsl-core</artifactId>
        <version>${querydsl.version}</version> 
    </dependency>
    <!-- for executing spring boot suing embeded tomcat -->
     <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-tomcat</artifactId>
   <scope>provided</scope>
</dependency>
<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.30</version>
    </dependency>
    
</dependencies>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version><!--$NO-MVN-MAN-VER$-->
            <configuration>
                <debug>true</debug>
            </configuration>
        </plugin>
    </plugins>
  </build>  
  
</project>

The project structure look will be:





Now run the project using following steps
1)compile the maven project
C:\my_work\student>mvn clean install
2)run the spring boot project using following command or you can run the main application also.
C:\my_work\student>mvn spring-boot:run

now try to search student data using id from browser.

http://localhost:8080/student/studentid/2
output
{"studentId":2,"studentName":"Yogesh","studentAge":24,"gender":"Male"}]




Wednesday, 16 July 2014

No 'Access-Control-Allow-Origin' header is present on the requested resource

if you are getting this types of exception and you are using Apache tomcat 7.42 or  latest version then you 
need to  modify the web.xml file which is store in side the apache-tomcat-7.0.52\conf\web.xml

This error will comes when you are try to access resources from the other server for e.g
you are loading templates from the tomcat 6 and you are sending the request to Apache tomcat 7 for getting data then this types of error will comes..for the security reason the Apache tomcat want be allow to load templates from one server and get the data from other server. so for solution of this, you have to include the filter in Apache tomcat 7 like bellow.
you need to paste this bellow contain.
     <filter>
       <filter-name>CorsFilter</filter-name>
       <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
 </init-param>
     </filter>
     <filter-mapping>
       <filter-name>CorsFilter</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>

then  it will work. for more information you can visit this link

Friday, 13 September 2013

how to Concate the JSON Arary in java

This example is use for the concate or merge the more than one json Aray into signle json Array and for this example we need to download the json-lib-2.4-jdk15 library.

 import net.sf.json.JSONArray;  
 import net.sf.json.JSONException;  
 public class JsonConcateDemo {  
       public static JSONArray concatArray(JSONArray... arrs)throws JSONException   
       {  
         JSONArray result = new JSONArray();  
         for (JSONArray arr : arrs) {  
           for (int i = 0; i < arr.size(); i++) {  
             result.add(arr.get(i));  
           }  
         }  
         return result;  
       }  
       public static void main(String args[])  
       {  
            JSONArray jsonArray1=new JSONArray();  
            jsonArray1.add(0,"one");  
            jsonArray1.add(1,"two");  
            JSONArray jsonArray2=new JSONArray();  
            jsonArray2.add(0,"three");  
            jsonArray2.add(1,"four");  
            System.out.println("the JSONARRAY1:"+jsonArray1.toString());  
            System.out.println("the JSONARRAY2:"+jsonArray2.toString());  
            System.out.println("New concate array JSONArray1 and JSONArray2"+concatArray(jsonArray1,jsonArray2));  
       }  
 }  

The Output
 the JSONARRAY1:["one","two"]  
 the JSONARRAY2:["three","four"]  
 now new concate array JSONArray1 and JSONArray2["one","two","three","four"]  

Saturday, 10 August 2013

How to bind datasource with InitialContext programatically in java class

This following way data source binding with the InitialContext is used for when you are implementing Junit testing in the project because when you run Junit testing the project is not deploy so if you initialized data source in tomee.xml and web.xml is not initialize.so for this reason you have to invoked one method for the initialize the data source problematically like following way.

Here i am showing example with java and MySQL if you are using any other database then you just need to
change 'url'  properties and 'driverClassName' properties.

Here i created two methods
1)initialdsn()
    This method binding the data source with InitialContext so in future we can get using jndi lookup.
2)checkdsn()
    This method is showing that how you will access data source.

NOTE:Don't forget to include jar file into the classpath.

 import java.sql.Connection;  
 import java.sql.ResultSet;  
 import java.sql.Statement;  
 import java.util.Properties;  
 import javax.naming.Context;  
 import javax.naming.InitialContext;  
 import javax.sql.DataSource;  
 import org.apache.commons.dbcp.BasicDataSourceFactory;  
 public class DSNDEMO {  
      public static void initialdsn()throws Exception  
      {  
                System.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.apache.naming.java.javaURLContextFactory");  
                System.setProperty(Context.URL_PKG_PREFIXES,"org.apache.naming");   
                Properties properties = new Properties ();  
                properties.setProperty("url", "jdbc:mysql://localhost:3306/ops");  
                properties.setProperty("driverClassName","com.mysql.jdbc.Driver");  
                properties.setProperty("maxActive", "10");  
                properties.setProperty("maxIdle", "8");  
                properties.setProperty("minIdle", "10");  
                properties.setProperty("maxWait", "10");  
                properties.setProperty("testOnBorrow", "true");  
                properties.setProperty("username", "root");  
                properties.setProperty("password", "");  
                properties.setProperty("validationQuery", "SELECT 1");  
                properties.setProperty("removeAbandoned", "true");  
                properties.setProperty("removeAbandonedTimeout", "1");  
                properties.setProperty("logAbandoned", "true");  
                DataSource ds = BasicDataSourceFactory.createDataSource(properties);  
                InitialContext ic = new InitialContext();  
                ic.createSubcontext("java:");  
                ic.createSubcontext("java:/comp");  
                  ic.createSubcontext("java:/comp/env");  
                ic.createSubcontext("java:/comp/env/jdbc");  
                 ic.bind("java:/comp/env/jdbc/mydb", ds);  
      }  
      public static void checkdsn()throws Exception  
      {  
           Context initContext = new InitialContext();  
            Context webContext = (Context)initContext.lookup("java:/comp/env");  
          DataSource ds = (DataSource) webContext.lookup("jdbc/mydb");  
          Connection con=ds.getConnection();  
          Statement stmt=con.createStatement();  
          ResultSet rs=stmt.executeQuery("select *from student_master");  
          while(rs.next())  
          {  
               System.out.println(rs.getString(1));  
          }  
      }  
 public static void main(String args[])throws Exception  
 {  
           DSNDEMO.initialdsn();  
           DSNDEMO.checkdsn();  
      }  
 }  

For this you have to download this  naming-common-4.1.31.jar and you need to include in your classpath or you can download from here

So for the above program you need to include following jar file into classpath.

1)naming-common-4.1.31.jar  (This contains class org.apache.naming.java.javaURLContextFactory)
2)commons-pool-1.5.7.jar
3)commons-dbcp-1.4.jar
4)mysql-connector-java-3.0.17-ga-bin

for Junit you create one method and include the initialdsn() source code in that method.

if you are getting any exception then free for comment here.

Friday, 9 August 2013

How to encrypt password in java

This is one of the method for encrypt the password using MD5 and using this method you can encrypt but you can not decrypt the password .

 import java.security.MessageDigest;  
 public class PasswordEncryptDemo {  
      public static String Password(String plainText) throws Exception  
      {  
           MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5");  
           mdAlgorithm.update(plainText.getBytes());  
           byte[] digest = mdAlgorithm.digest();  
           StringBuffer hexString = new StringBuffer();  
           for (int i = 0; i < digest.length; i++)  
           {  
             plainText = Integer.toHexString(0xFF & digest[i]);  
             if (plainText.length() < 2)   
             {  
               plainText = "0" + plainText;  
             }  
             hexString.append(plainText);  
           }  
           return hexString.toString();  
      }  
      public static void main(String args[])throws Exception  
      {  
           String planinText="poolof123";  
           System.out.println("The plain text is:"+planinText);  
           System.out.println("The encrypted text is:"+PasswordEncryptDemo.Password(planinText));  
      }  
 }  

output:
 The plain text is:poolof123  
 The encrypted text is:15e3c36a6a68803819c5d25a053b5535  

Saturday, 25 May 2013

How to import our own java class file in jsp page.

This example is showing  how to create class file and how to use that class file in jsp page.
here I am showing example without using eclipse or any IDE.
When we are developing any project, we need to create one separate class file for connecting with database so here I am creating one class file which is java class file and  I will use whenever i need to connect with database.

First you  need to create class.
DatabaseConnection.java

package myCon;
import java.sql.*;
public class DatabaseConnection
{

    private static Connection connection;

    static
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost/cosociety", "root", "");
        } catch (Exception e)
        {
            System.out.println(e.toString());
        }
    }

    public static Connection getConnection()
    {
        return connection;
    }
  
}
The above java file which i created is to get connection with the database.
When you are creating class, you have to create package for that.If you are not creating package, then at run time jvm always search class file in default package and the class file will not found so jvm will throw errors.so for that we need to create package and our class file we need to store in package.
Now for compilation:
This following compilation is doing using the cmd.
C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\slvsc\inc>javac -
d .  DatabaseConnection.java
after executing the above command, your  class file will be available inside the package, "myConn".
Now you have to create structure for your project.
You have to put myConn package inside the
WEB-INF->classes
you have to create folder like above and put your package inside classes  folder.
Now structure is
WEB-INF->classes-> myCon->DatabaseConnection.class
Then you can call it using the following way.

The following example is used for retrieving data from employee table.
<%@ page import="myCon.DatabaseConnection"%> //this line used for import class in jsp page
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*" %>


<%!
    Connection connection;
    String sql="";
    Statement stmt;
    ResultSet rs,rsn;
%>
<%
   
  try
   {      
    connection=DatabaseConnection.getConnection();
    stmt=connection.createStatement();
    sql="select *from employee";
    rs=stmt.executeQuery(sql);
    while(rs.next())
    {
        out.println(rs.getString("EMP_Name"));
    }
   
   }
    catch(SQLException sa)
   {
        out.println("Error loading driver:" + sa.getMessage());   
   }

%>



How to give validation for email id and mobile number using pattern matching in java script

This is html file which checks for proper email id and mobile number using pattern matching in java script.

 <html>  
 <head>  
 <style>  
 .message  
 {  
 border:0px solid black;  
 background-color:orange;  
 height:20px;  
 width:180px;  
 text-align:center;  
 display:none;  
 }  
 .header11  
 {  
 border:0px solid black;  
 background-color:orange;  
 height:20px;  
 width:180px;  
 text-align:center;  
 display:none;  
 }  
 </style>  
 <script>  
 function validation()  
 {  
   var name=document.getElementById("name").value;  
   var email=document.getElementById("email").value;  
   var mono=document.getElementById("mono").value;  
   var add=document.getElementById("add").value;  
   var loc=document.getElementById("loc").value;  
   if(name=="" && email=="" && mono=="" && add=="" && loc=="")  
   {  
           document.getElementById("name").focus();  
     alert("please Fill the information!");  
     return false;  
   }  
      else if(name=="")  
   {  
             document.getElementById("name").value="";  
             document.getElementById("name").focus();  
       alert("please enter name");  
       return false;  
   }  
   else if(!email.match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/) || email=="")  
   {  
     alert("please enter Email id");  
           document.getElementById("email").value="";  
     document.getElementById("email").focus();  
     return false;  
   }  
   else if(!mono.match (/^(\+91-|\+91|0|9)?\d{10}$/) || mono=="")  
   {  
     alert("please enter Mobile Number");  
     document.getElementById("mono").value="";  
     document.getElementById("mono").focus();  
     return false;  
   }  
   else if(add.trim()=="")  
   {  
     alert("please enter Address");  
     document.getElementById("add").value="";  
     document.getElementById("add").focus();  
     return false;  
   }  
   else if (!loc.match(/^[a-zA-Z]+$/) || loc=="")  
   {  
     alert("please enter Location");  
     document.getElementById("loc").value="";  
     document.getElementById("loc").focus();  
     return false;  
   }  
   else  
        return true;  
 }  
 </script>  
 </head>  
 <body>  
 <div class="header">  
 <div class="header11" id="demo">All Fields manadatory</div>  
 <form action="connect.jsp" onsubmit="return validation()">  
 <div>Name<input type="text" id="name"></div></div>  
 <div>Email<input type="text" id="email" ></div>  
 <div>Mobile No<input type="text" id="mono"></div>  
 <div>Address<textarea rows="5" cols="20" id="add"></textarea></div>  
 <div>Location<input type="text" id="loc"></div>  
 <input type="submit" value="submit">  
 </form>  
 </div>  
 </body>  
 </html>  

Here we use meta-characters (can have special meanings in patterns--do not match themselves)
 meta-characters are:     \ | ( ) [ ] { } ^ $ * + ? .

 A meta-character is treated as a normal character if it is back-slashed.
 period is a special meta-character which matches any character except newline

In some places we use [],that means we can specify a sequence of characters ex..[abcd]. this exactly matches the specified text.we also specify the range or spans of characters by giving dashes.
ex:[a-z] this matches a character with small letter a to z .
 A caret at the left end of a class definition means the opposite.

    Character class abbreviations

   Abbr.       Equiv. Pattern          Matches

   \d               [0-9]                    a digit
   \D              [^0-9]                  not a digit
   \w           [A-Za-z_0-9]           a word character
   \W          [^A-Za-z_0-9]         not a word character
   \s             [ \r\t\n\f]         a whitespace character
   \S             [^ \r\t\n\f]       not a whitespace character


   Quantifiers

    {n} exactly n repetitions
    {m, n} at least m but not more than n
repetitions


Other quantifiers (just abbreviations for the most commonly used quantifiers)
      * means zero or more repetitions
          e.g., \d* means zero or more digits

      + means one or more repetitions
          e.g.,  \d+ means one or more digits

     ? Means zero or one
          e.g., \d? means zero or one digit

    Anchors

 The pattern can be forced to match only at the
      left end with ^; at the end with $

     e.g.1 (mobile number):
(/^(\+91-|\+91|0|9)?\d{10}$/)
in this example we are checking for the proper mobile number.
we gave the expression inside the / / symbol.So that expression will be compared to check the valid        contact number.
here we have given \ symbol.so that the literal meaning(plus) will be retained.
^ symbol is to check at the starting of the expression.

so here we are checking for +91 at the starting of the expression. The meaning of | symbol is 'or' meaning, if the previous condition doesn't match,it checks with the second pattern.so  /^(\+91-|\+91|0|9) is to check +91 'or' +90. and ? symbol is to check 1 or more occurrence of the previous pattern.and finally \d{10}$/  is for checking 10 digits at the end of the expression.


      e.g.2  (email):
    if(!email.match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/) || email=="")

     here we have given caret symbol inside /  /  that means it should check at the starting of the expression.
and also we specified the range..
so ^[_a-z0-9-]+  is to find one or more occurrence of small letter a to z and digits from 0 to 9 at the starting of the expression.

   (\.[_a-z0-9-]+)*  is to literally match the " . "  symbol since its literal meaning is obtained by giving \ symbol and one or more occurrence of alphabets and numeric.  * symbol is to check zero or more occurrence of the pattern.

(\.[a-z]{2,3})$/) and $ at the end of the expression means it checks the pattern at the end of the expression.
here a character should be there at least 2 times but not more than 3 times.