Monday 29 August 2016

Spring Using Jdbc

Step 1:


Employee.java

package com.jeni.Spring;
public class Employee {
private int id;
private String Name;
private String salary;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
}


Step 2:

EmployeeDao.java

package com.jeni.Spring;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
   this.jdbcTemplate = jdbcTemplate;
}

public int saveEmployee(Employee e){
   String query="insert into register values('"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')";
   return jdbcTemplate.update(query);
}

public Employee newEmp() {
Employee emp = new Employee();
emp.setId(1001);
emp.setName("deepan");
emp.setSalary("7000");
return emp;
}

public int updateEmployee(Employee e){
   String query="update register set name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";
   return jdbcTemplate.update(query);
}
public int deleteEmployee(Employee e){
   String query="delete from register where id='"+e.getId()+"' ";
   return jdbcTemplate.update(query);
}  }


Step 3:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jeni</groupId>
<artifactId>Spring</artifactId>
<name>jdbcSpring</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>

<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>

<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>

<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>

<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Step 4:application.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3307/employee" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
 
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
 
<bean id="edao" class="com.jeni.Spring.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>


Step 5:Test.java

package com.jeni.Spring;

import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Test {

public static void main(String[] args) {
FileSystemXmlApplicationContext ctx;
     try{
     ctx=new FileSystemXmlApplicationContext("applicationcontext.xml");
   EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");  
   
   int saveEmployee = dao.saveEmployee(dao.newEmp());
   System.out.println("success"+saveEmployee);
     }
     catch(Exception ee)
     {
     System.out.println(ee);
     }
}
}








Saturday 27 August 2016

Servlets in Struts 2

To configure URL patterns to servlet and Struts2 



Struts.xml

<constant name="struts.action.excludePattern" value="/Register"/>

Monday 22 August 2016

CONSUME ONLINE WEB SERVICES USING JAVA

Step 1: Online webservice

http://www.webservicex.net/geoipservice.asmx?wsdl


Step 2:  In your command prompt


              >mkdir sei
              >cd sei/

              set your jdk bin path
                       > set path=" "
                       > wsimport  http://www.webservicex.net/geoipservice.asmx?wsdl

Step 3:  After that the package created in sei folder.it contains all class files.

Step 4: Then Convert class file to java file using the below commands

              sei> wsimport -keep -s src http://www.webservicex.net/geoipservice.asmx?wsdl

Step 5: After that import all the java files in our project.



                         

Step 6: Create a class file

IPFinder.java

package net.webservicex;
import java.util.*;
public class IPfinder {
public static void main(String arg[])
{
// if(arg.length!=1)
// {
// System.out.println("welcome");
// }
// else
// {

        System.out.println("Enter the ip address");
Scanner sc=new Scanner(System.in);

String ipAddress=sc.next();
GeoIPService ipservice=new GeoIPService();
GeoIPServiceSoap geoipservicesoap=ipservice.getGeoIPServiceSoap();
GeoIP geoip=geoipservicesoap.getGeoIP(ipAddress);
System.out.println(geoip.getCountryName());
}
}

             
         

Tuesday 16 August 2016

Distinct Keyword in Hibernate

Home.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="org.hibernate.*,org.hibernate.cfg.*,java.util.*" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        Standard <select name="std" >
            <%
                Session ses = null;

                try {
                    Configuration cfg = new Configuration();
                    cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file
                    SessionFactory factory = cfg.buildSessionFactory();
                    ses = factory.openSession();
                    Transaction t = ses.beginTransaction();
                    String s = "select distinct s.std from add_std s";
                    ListIterator<Object[]> ObjectsIterator = ses.createSQLQuery(s).list().listIterator();
                    while (ObjectsIterator.hasNext()) {
                        Object object = (Object) ObjectsIterator.next();
                        String name = (String) object;
                        System.out.println(name);
            %>
            <option><%=name%></option>
            <%
                    }
                    t.commit();
                    ses.close();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            %>
        </select>
    </body>
</html>

hibernate.cfg.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/student?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <mapping resource="my/AddStd.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

addstd.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Aug 16, 2016 2:31:08 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="my.add_std" table="add_std" catalog="student" optimistic-lock="version">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="std" type="string">
            <column name="std" length="30" not-null="true" />
        </property>
        <property name="sec" type="string">
            <column name="sec" length="30" not-null="true" />
        </property>
    </class>
</hibernate-mapping>


Tuesday 2 August 2016

UPLOAD VIDEO USING SERVLET&JSP

Step 1: To create database and table

Step 2: Create home page

home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Video Upload to Database Demo</title>
</head>
<body>
    <center>
        <h1>Video Upload to Database Demo</h1>
        <form method="post" action="uploadServlet" enctype="multipart/form-data">
            <table border="0">
             
                <tr>
                    <td>Upload Video: </td>
                    <td><input type="file" name="video" size="50"/></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="Save">
                    </td>
                </tr>
            </table>
        </form>
    </center>
</body>
</html>


uploadServlet.java


import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/uploadServlet")
@MultipartConfig(maxFileSize = 1024*1024*14)    // upload file's size up to 16MB
public class uploadServlet extends HttpServlet {
   
    // database connection settings
    private String dbURL = "jdbc:mysql://localhost:3306/db name";
    private String dbUser = "username";
    private String dbPass = "password";
   
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
     
        InputStream inputStream = null; // input stream of the upload file
       
        // obtains the upload file part in this multipart request
        Part filePart = request.getPart("video");
        if (filePart != null) {
            // prints out some information for debugging
            System.out.println(filePart.getName());
            System.out.println(filePart.getSize());
            System.out.println(filePart.getContentType());
           
            // obtains input stream of the upload file
            inputStream = filePart.getInputStream();
        }
       
        Connection conn = null; // connection to the database
        String message = null;  // message will be sent back to client
       
        try {
            // connects to the database
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            conn = DriverManager.getConnection(dbURL, dbUser, dbPass);

            // constructs SQL statement
            String sql = "INSERT INTO upload_image values (?)";
            PreparedStatement statement = conn.prepareStatement(sql);
         
           
            if (inputStream != null) {
                // fetches input stream of the upload file for the blob column
                statement.setBlob(1, inputStream);
            }

            // sends the statement to the database server
            int row = statement.executeUpdate();
            if (row > 0) {
                message = "File uploaded and saved into database";
            }
        } catch (SQLException ex) {
            message = "ERROR: " + ex.getMessage();
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                // closes the database connection
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
         
        }
    }
}


Step 3: Set maximum Allowed packet in mydql server.

            To Execute below query

       SET GLOBAL max_allowed_packet = 1024 * 1024 * 14



         

DEPLOY WAR FILE IN APACHE TOMCAT

Step 1: Create war file 

            i) In netbeans right click the project and select build.Automatically the war file created the                       project folder.

Step 2:   go to tomcat->bin folder start tomcat by clicking startup.bat  

               (or)

               goto command prompt-->services.msc--->select apache tomcat---Right click--->to start

Step 3:  Copy the .war file (E.g.:ImageUpload.war) to Tomcat 8.0\webapps. before copy the war file 
              have to stop the server

Step 4:    Now restart or start the server

Step 5:   goto browser and give localhost:8080(server port must be same as server.xml(conf folder                   in apache tomcat) file connector port no)


                 (eg)localhost:8080/ImageUpload/

Monday 1 August 2016

JASPER REPORT IN JAVA USING NETBEANS


Step 1  : Download iReport plugin here


Step 2  : To Install iReport plugin in Netbeans IDE

               Tools-->Plugin-->Downloaded--->Select ireport Plugin-->Install

Step 3  :   Create Jasper report

                 Newproject----->create Empty report(Student.jrxml)

Step 4 a: Connect Database in Netbeans



 4 b) Create new database and select the jdbc connection






















4 c) 





















4 d) Click the image as shown in below



4 e) Write the query here



4 f) Generate the field here when we write the query in query tab.as shown above



4 g)Drag and Drop the Field in Detail column



Step 5: Create java class

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.sf.jasperreports.engine.*;
import com.lowagie.text.Document; 
import com.lowagie.text.Paragraph; 
import com.lowagie.text.pdf.PdfWriter; 
import net.sf.jasperreports.engine.export.JRXlsAbstractExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.view.JasperViewer;

public class Demo {
    public static void main(String[] args) throws IOException
    {
          try
        {
      
//Specify Your Report Path
JasperReport jasperReport=JasperCompileManager.compileReport("path of your .jrxml file");
        
            Class.forName("com.mysql.jdbc.Driver");

            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db name" , "uname", "password");
Statement stmt = null;
ResultSet rset = null;
String queryString = "query here";
stmt = conn.createStatement();
rset = stmt.executeQuery(queryString);
 JRResultSetDataSource jasperReports = new JRResultSetDataSource(rset);

            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,null, jasperReports);
//Report saved in specified path
            JasperExportManager.exportReportToPdfFile(jasperPrint,"file download path.pdf");
//Report open in Runtime
          Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " +"file download path.pdf");
JRXlsExporter exporterXLS = new JRXlsExporter();
OutputStream output = new FileOutputStream(new File("file download path.xls"));
 exporterXLS.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);
 exporterXLS.setParameter(JRExporterParameter.OUTPUT_STREAM, output);
 exporterXLS.setParameter(JRXlsAbstractExporterParameter.IS_COLLAPSE_ROW_SPAN, Boolean.TRUE);
 exporterXLS.setParameter(JRXlsAbstractExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS, Boolean.TRUE);
 exporterXLS.setParameter(JRXlsAbstractExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
 exporterXLS.setParameter(JRXlsAbstractExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
 exporterXLS.setParameter(JRXlsAbstractExporterParameter.IS_DETECT_CELL_TYPE, Boolean.FALSE);
 exporterXLS.setParameter(JRXlsAbstractExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
 exporterXLS.setParameter(JRXlsAbstractExporterParameter.IS_IGNORE_GRAPHICS, Boolean.TRUE);
 exporterXLS.exportReport();
            //JasperViewer.viewReport(jasperPrint);

        }
 catch (JRException e)
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException ex)
        {
            ex.printStackTrace();
        }
        catch (SQLException ex)

        {
            ex.printStackTrace();
        }
    }
}


Step 6 : Required Jar Files