Spring Boot

CalcController.java

package com.javatest.demo;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

class MyCalc {
    private int num1;
    private int num2;

    public int getNum1() {
        return num1;
    }
    public void setNum1(int num1) {
        this.num1 = num1;
    }
    public int getNum2() {
        return num2;
    }
    public void setNum2(int num2) {
        this.num2 = num2;
    }
    
    @Override
    public String toString() {
        return "MyCalc [num1=" + num1 + ", num2=" + num2 + "]";
    }
}

@RestController
public class CalcController {


    @RequestMapping("test")
    public String test() {
        return "Testing....";
    }

    /** Read query params */
    @RequestMapping("mycalc")
    @GetMapping
    public String getMet(@RequestParam("num1") int x, @RequestParam int y) {
        return String.format("%s + %s = %s", x, y, x+y);
    }

    /** Read raw json data */
    @PostMapping("mycalc")
    public String postMet(@RequestBody MyCalc obj) {
        int x = obj.getNum1();
        int y = obj.getNum2();

        return String.format("%s - %s = %s", x, y, x - y);
    }

    /** Read form data */
    @PutMapping("mycalc")
    public String putMet(
        @RequestParam("num1") int x,
        @RequestParam("num2") int y) {
        return String.format("%s * %s = %s", x, y, x * y);
    }

    /** Read from raw json */
    @DeleteMapping("mycalc")
    public String deleteMet(@RequestBody MyCalc obj) {
        int x = obj.getNum1();
        int y = obj.getNum2();
        return String.format("%s / %s = %s", x, y, x / y);
    }

}

src/main/resources/application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/<databasename>
spring.datasource.username=<username>
spring.datasource.password=<password>
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver

User.java (POJO/DAO/JPA)

package com.javatest.demo;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name="users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String age;
    private String city;
    private int quota;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public int getQuota() {
        return quota;
    }
    public void setQuota(int quota) {
        this.quota = quota;
    }


    
    // getters and setters

    
}

UserController.java

package com.javatest.demo;


import java.util.List;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.jpa.repository.JpaRepository;

interface UserRepository extends JpaRepository<User, Long> {
    // Custom queries can be defined here
}

@RestController
@RequestMapping("users")
public class UserController {
    
    private final UserRepository userRepository;
    
    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @RequestMapping("")
    public String index() {
        return "I am from index";
    }

    @RequestMapping("listing")
    public List<User> listing() {
        // List<User> users = new ArrayList<>();
        return userRepository.findAll();
    }

    @DeleteMapping("delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        // Check if the user with the specified ID exists
        if (userRepository.existsById(id)) {
            userRepository.deleteById(id);
            return String.format("User %s is deleted successfully", id);
        } else {
            // Handle the case when the user does not exist (e.g., return an error response)
            // You can throw an exception or return an appropriate response based on your application's requirements.
        }
        return "";
    }

    @PostMapping("create")
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }


    @GetMapping("get-single/{id}")
    public User getUserById(@PathVariable Long id) {
        // Use the UserRepository to fetch the user by ID
        return userRepository.findById(id).orElse(null);
    }

    @PutMapping("/update/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
        // Check if the user with the specified ID exists
        userRepository.findById(id).orElse(null);

        // Set the ID of the updated user to the specified ID
        updatedUser.setId(id);

        // Save the updated user to the database
        return userRepository.save(updatedUser);
    }

}

DemoApplication.java (Run this file to serve spring boot application)

package com.javatest.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}

File Structure

.
├── HELP.md
├── mvnw
├── mvnw.cmd
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── javatest
│   │   │           └── demo
│   │   │               ├── CalcController.java
│   │   │               ├── DemoApplication.java
│   │   │               ├── User.java
│   │   │               └── UserController.java
│   │   └── resources
│   │       ├── application.properties
│   │       ├── static
│   │       └── templates
│   └── test
│       └── java
│           └── com
│               └── javatest
│                   └── demo
│                       └── DemoApplicationTests.java
└── target
    ├── classes
    │   ├── application.properties
    │   └── com
    │       └── javatest
    │           └── demo
    │               ├── CalcController.class
    │               ├── DemoApplication.class
    │               ├── MyCalc.class
    │               ├── User.class
    │               ├── UserController.class
    │               └── UserRepository.class
    └── test-classes
        └── com
            └── javatest
                └── demo
                    └── DemoApplicationTests.class

23 directories, 18 files

POC

VSCode Extesnsions

Java Cheat Sheet

Softwares to Install

JDK 11
https://www.oracle.com/in/java/technologies/javase-jdk11-downloads.html

Apache Tomcat Server (version 9)
https://tomcat.apache.org/download-90.cgi

Eclipse EE (2021)
https://www.eclipse.org/downloads/packages/release/neon/3/eclipse-ide-java-ee-developers

Xampp for MySQL (latest version)
https://www.apachefriends.org/download.html

Postman for REST API
https://www.postman.com/downloads/

Addition of Two Numbers

class Main {
	
	public static void main(String args[]) {
		System.out.println(args[0]);
		System.out.println(args[1]);
		
		int num1 = Integer.parseInt(args[0]);
		int num2 = Integer.parseInt(args[1]);

		int add = num1 + num2;
		
		System.out.println(String.format("%s + %s = %s", num1, num2, add));
	}
	
}

Inheritance

class Bank {
	
	protected int balance;
	
	public Bank(int bal) {
		this.balance = bal;
		System.out.println(String.format("Account opened with Balance: %s", this.balance));
	}
	
	public void deposit(int amt) {
		System.out.println(String.format("Deposit Amount: %s", amt));
		this.balance += amt;
	}
	
	public void withdraw(int amt) {
		System.out.println(String.format("Withdraw Amount: %s", amt));
		this.balance -= amt;
	}
	
	public void showBalance() {
		System.out.println(String.format("Available Balance: %s", this.balance));
	}
	
}

class HDFC extends Bank {
	public HDFC(int bal) {
		super(bal);
	}
}

class SBI extends Bank {
	public SBI(int bal) {
		super(bal);
	}
	
	public void withdraw(int amt) {
		super.withdraw(amt);
		super.balance -= 20;
	}
	
}

class Main {
	public static void main(String args[]) {
		Bank bobj = new Bank(1000);
		bobj.showBalance();
		bobj.deposit(500);
		bobj.showBalance();
		bobj.withdraw(300);
		bobj.showBalance();
		
		System.out.println("====================");
		
		HDFC hobj = new HDFC(2000);
		hobj.showBalance();
		hobj.deposit(500);
		hobj.showBalance();
		hobj.withdraw(300);
		hobj.showBalance();
		
		System.out.println("====================");
		
		SBI sobj = new SBI(3000);
		sobj.showBalance();
		sobj.deposit(500);
		sobj.showBalance();
		sobj.withdraw(300);
		sobj.showBalance();
	}
}

Exception Handling

class Main {
	public static void main(String args[]) {
		try {
			
			int num1 = Integer.parseInt(args[0]);
			int num2 = Integer.parseInt(args[1]);
			
			try {
				int div = num1 / num2;
				System.out.println(String.format("Division of %s and %s is %s", num1, num2, div));
			} catch (Exception e) {
				System.out.println(e);
			}
			
			
		} catch (ArrayIndexOutOfBoundsException aie) {
			System.out.println(aie);
			
		} catch (Exception e) {
			System.out.println(e);
		}
		
	}
}

Servlet Demo

Servlet Life Cycle

  1. form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Addition of 2 numbers</title>
<link
	href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css"
	rel="stylesheet"
	integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x"
	crossorigin="anonymous">
</head>
<body class="container">
	<form action="CalcServlet" class="m-5">
		<div class="row">
			<div class="col">Number 1</div>
			<div class="col">
				<input type="text" name="num1" placeholder="Enter number" autofocus>
			</div>
		</div>
		<div class="row">
			<div class="col">Number 1</div>
			<div class="col">
				<input type="text" name="num2" placeholder="Enter number">
			</div>
		</div>
		<div class="row">
			<div class="col">
				<input class="btn btn-primary" type="submit" value="Calculate" />
			</div>
		</div>
	</form>
</body>
</html>

2. CalcServlet

import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * Servlet implementation class AddServlet
 */
@WebServlet("/CalcServlet")
public class CalcServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CalcServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		int num1 = Integer.parseInt(request.getParameter("num1"));
		int num2 = Integer.parseInt(request.getParameter("num2"));
		
		response.getWriter().write(String.format("%s + %s = %s", num1, num2, num1+num2));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		int num1 = Integer.parseInt(request.getParameter("num1"));
		int num2 = Integer.parseInt(request.getParameter("num2"));
		
		response.getWriter().write(String.format("%s * %s = %s", num1, num2, num1*num2));
	}
	
	protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		int num1 = Integer.parseInt(request.getParameter("num1"));
		int num2 = Integer.parseInt(request.getParameter("num2"));
		
		response.getWriter().write(String.format("%s - %s = %s", num1, num2, num1-num2));
	}

	protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		int num1 = Integer.parseInt(request.getParameter("num1"));
		int num2 = Integer.parseInt(request.getParameter("num2"));
		
		response.getWriter().write(String.format("%s / %s = %s", num1, num2, num1/num2));
	}

	protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		int num1 = Integer.parseInt(request.getParameter("num1"));
		int num2 = Integer.parseInt(request.getParameter("num2"));
		
		response.getWriter().write(String.format("%s %% %s = %s", num1, num2, num1%num2));
	}

}

DATABASE SQL

CREATE DATABASE

CREATE DATABASE company;

CREATE TABLE

CREATE TABLE users(
    id INT,
    NAME VARCHAR(100) NOT NULL,
    age TINYINT NOT NULL,
    city VARCHAR(200) NOT NULL
);

ALTER TABLE

ALTER TABLE
    users MODIFY id INT PRIMARY KEY AUTO_INCREMENT;

MySQL JDBC

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class CRUDLDemo {
	public static void main(String args[]) {
		String conn_str = "jdbc:mysql://localhost:3306/company";
		String dbusername = "root";
		String dbpassword = "";

		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			Connection conn = DriverManager.getConnection(conn_str, dbusername, dbpassword);

			String select_sql = "SELECT * FROM users";
			Statement stmt = conn.createStatement();

			ResultSet rs = stmt.executeQuery(select_sql);

			while (rs.next()) {
				System.out.println(rs.getInt("id"));
				System.out.println(rs.getString("name"));
				System.out.println(rs.getInt("age"));
				System.out.println(rs.getString("city"));
			}

//			String insert_sql = "INSERT INTO users VALUES (NULL, 'Priyanka', 30, 'Mumbai', NOW(), NOW())";
//			Statement stmt = conn.createStatement();
//			int result = stmt.executeUpdate(insert_sql);
//			System.out.println(result);

//			String delete_sql = "DELETE FROM users WHERE id = 3";
//			Statement stmt = conn.createStatement();
//			int result = stmt.executeUpdate(delete_sql);
//			System.out.println(result);

//			String update_sql = "UPDATE users SET city = 'Panvel' WHERE id = 2";
//			Statement stmt = conn.createStatement();
//			int result = stmt.executeUpdate(update_sql);
//			System.out.println(result);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

select.jsp

<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<% 

String conn_string = "jdbc:mysql://localhost:3306/company";
String db_username = "root";
String db_password = "";

Connection conn = null;

try{
	Class.forName("com.mysql.cj.jdbc.Driver");
	conn = DriverManager.getConnection(conn_string, db_username, db_password);
} catch(Exception e) {
	out.println(e);
}

String select_sql = "SELECT * FROM users";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(select_sql);

while(rs.next()) {
	out.println(String.format("Id: %s | Name: %s | Age: %s | City: %s<br>", rs.getInt("id"), rs.getString("name"), rs.getInt("age"), rs.getString("city")));
}

%>

insert.jsp

<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%
String conn_string = "jdbc:mysql://localhost:3306/company";
String db_username = "root";
String db_password = "";

Connection conn = null;

try{
	Class.forName("com.mysql.cj.jdbc.Driver");
	conn = DriverManager.getConnection(conn_string, db_username, db_password);
} catch(Exception e) {
	out.println(e);
}

String insert_sql = "INSERT INTO users VALUES (NULL, 'Priyanka', 30, 'Mumbai', NOW(), NOW())";
Statement stmt = conn.createStatement();
int result = stmt.executeUpdate(insert_sql);

if(result == 1) {
	out.println("Record inserted successfully...");
} else {
	out.println("Something went wrong...");
}
%>

update.jsp

<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%
String conn_string = "jdbc:mysql://localhost:3306/company";
String db_username = "root";
String db_password = "";

Connection conn = null;

try{
	Class.forName("com.mysql.cj.jdbc.Driver");
	conn = DriverManager.getConnection(conn_string, db_username, db_password);
} catch(Exception e) {
	out.println(e);
}

String update_sql = "UPDATE users SET name = 'Palkar' WHERE id = 4";
Statement stmt = conn.createStatement();
int result = stmt.executeUpdate(update_sql);

if(result == 1) {
	out.println("Record updated successfully...");
} else {
	out.println("Something went wrong...");
}
%>

delete.jsp

<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%
String conn_string = "jdbc:mysql://localhost:3306/company";
String db_username = "root";
String db_password = "";

Connection conn = null;

try{
	Class.forName("com.mysql.cj.jdbc.Driver");
	conn = DriverManager.getConnection(conn_string, db_username, db_password);
} catch(Exception e) {
	out.println(e);
}

String delete_sql = "DELETE FROM users WHERE id = 4";
Statement stmt = conn.createStatement();
int result = stmt.executeUpdate(delete_sql);

if(result == 1) {
	out.println("Record deleted successfully...");
} else {
	out.println("Something went wrong...");
}
%>

functions.jsp

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>

<%!
public Connection getConnection() {

		String conn_string = "jdbc:mysql://localhost:3306/company";
		String db_username = "root";
		String db_password = "";

		Connection conn = null;

		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			conn = DriverManager.getConnection(conn_string, db_username, db_password);
		} catch (Exception e) {
			System.out.println(e);
		}

		return conn;
}

public void authorize(HttpSession session, HttpServletResponse response) {
	
	if(session.getAttribute("username") == null) {
		try {				
			response.sendRedirect("login_form.jsp?msg=Please login to access this page");
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

%>

include functions and header

<%@include file="functions.jsp" %>
<jsp:include page="header.jsp" />

Hibernate 5.4 Configuration

 

Core Hibernate 5.4 Configuration

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>HibernateProj</groupId>
  <artifactId>HibernateProj</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.4.10.Final</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.15</version>
    </dependency>
  </dependencies>
</project>
<?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.current_session_context_class">thread</property> -->
    	<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
    </session-factory>
</hibernate-configuration>
package com;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

public class MainClass {
  @SuppressWarnings("deprecation")
  public static void main(String[] args) {

    try{  
      Class.forName("com.mysql.cj.jdbc.Driver");  
      Connection con=DriverManager.getConnection(  
          "jdbc:mysql://localhost:3306/test","root","");  
      //here sonoo is database name, root is username and password  
      Statement stmt=con.createStatement();
//			stmt.executeUpdate("insert into emp VALUES (null, 'shailesh', 31, 'Nagpur')");
      ResultSet rs=stmt.executeQuery("select * from emp");  
      while(rs.next())
        System.out.println(rs.getString(1)+"  "+rs.getString(2)+"  "+rs.getString(3)+"  "+rs.getString(4));  
      con.close();  
    } catch(Exception e){ System.out.println(e);}  

    System.out.println("Hibernate connection established successfully...");

    Session session = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory().openSession();
    Query query = session.createNativeQuery("select * from emp");
    List<Student[]> list = query.list();
    System.out.println(list);

    for(Object[] obj : list) {
      Student std = new Student((Integer)obj[0], (String)obj[1], (Integer)obj[2], (String)obj[3]);
      System.out.println(std);
    }		
    ////////////////////////////////////////////////
    Query query2 = session.createNativeQuery("Select id, name, age, city from emp");
    query2.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
    List<Student> students = query2.list();
    System.out.println(students);
    session.close();
    //==============================//
    Session session2 = new Configuration().configure("database.cfg.xml").buildSessionFactory().openSession();
    List list2 = session2.createNativeQuery("select * from testdmarc").list();
    System.out.println(list2);
  }
}

 

Reference:

https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#sql

https://tools.jboss.org/downloads/jbosstools/2019-09/4.13.0.Final.html#update_site

https://www.tutorialspoint.com/hibernate/hibernate_examples.htm

Hibernate Native SQL Query Example

Servlet File Upload

Ref:
https://www.codejava.net/java-ee/servlet/java-file-upload-example-with-servlet-30-api

https://www.baeldung.com/upload-file-servlet

Servlet 3 File Upload – @MultipartConfig, Part

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

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;

/**
 * Servlet implementation class MultiPartServlet
 */
@WebServlet("/multiPartServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*10, 	// 10 MB 
maxFileSize=1024*1024*50,      	// 50 MB
maxRequestSize=1024*1024*100)   	// 100 MB
public class MultiPartServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MultiPartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
    
    PrintWriter out = response.getWriter();
  }

  private static final String SAVE_DIR = "uploadFiles";
  
  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    // gets absolute path of the web application
        String appPath = request.getServletContext().getRealPath("");
        // constructs path of the directory to save uploaded file
        String savePath = appPath + File.separator + SAVE_DIR;
         
        // creates the save directory if it does not exists
        File fileSaveDir = new File(savePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdir();
        }
    
    
    for (Part part : request.getParts()) {
        String fileName = extractFileName(part);
//		    part.write(fileName);
        response.getWriter().println("/home/shailesh/eclipse-workspace/TestProject/WebContent/images/" + fileName);
        part.write("/home/shailesh/eclipse-workspace/TestProject/WebContent/images/" + fileName);
    }
    response.getWriter().println("Uploaded...");
    doGet(request, response);
  }
  
  private String extractFileName(Part part) {
      String contentDisp = part.getHeader("content-disposition");
      String[] items = contentDisp.split(";");
      for (String s : items) {
          if (s.trim().startsWith("filename")) {
              return s.substring(s.indexOf("=") + 2, s.length()-1);
          }
      }
      return "";
  }

}

 

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>TestProject</groupId>
  <artifactId>TestProject</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.3</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  	<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
  <dependency>
    	<groupId>org.springframework</groupId>
   	 	<artifactId>spring-webmvc</artifactId>
    	<version>5.2.1.RELEASE</version>
  </dependency>
  
  <!-- Apache Commons FileUpload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.2</version>
    </dependency>

    <!-- Apache Commons IO -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.5</version>
    </dependency>
  
  </dependencies>
</project>
<form method="post" action="multiPartServlet" enctype="multipart/form-data">
  Choose a file: <input type="file" name="multiPartServlet" />
    <input type="submit" value="Upload" />
</form>

 

Core Java Assignment

Classes and Objects
1. Create class Rectangle
a) data members
– length
– breadth
b) methods
– setDimensions
– area
– perimeter

2. Create class Cube
a) data members
– length
– breadth
– height
b) methods
– setDimensions
– volume

3. Create class Worker
a) data members
– wages
– wdays
b) methods
– setData
– payment

Method Overloading

1. Create class Box
a) data members
– length
– breadth
– height
b) methods
– setDimensions(3 args)
– setDimensions(1 arg)
– volume

Method Returning Value
1. WAP to find total payment of two employeesCreate
Create class Worker
a) data members
– wages
– wdays
b) methods
– setData
– int payment

Constructors
1. Create class Circle and initialize radius using a default constructor
2. Create class Circle and initialize radius using parameterized constructor
3. Create class Circle and define two constructor default and parameterized (Constructor overloading)

Static data members and member functions
1. Create a class Circle and find its area
a) data members
– int radius
– static double pi
b) methods
– area

2. Create a class Bank Account and find interest
a) data members
– int account_number
– int balance
– static double interest_rate
b) methods
– interest (balance * interest_rate * no_of_period / 100.0)
– changeRate (change interest_rate)

OOPS

  1. Design a class Rectangle
    data members
    length
    breadth
    member functions/methods
    setDimension()
    area()
    perimeter()

  2. Design a class Worker
    data members
    wages
    wdays
    member function / method
    setData()
    payment()

  3. Design a class Box
    data members
    length
    breadth
    height
    member functions / methods
    setDimension()
    volume()

  4. Design a class Rectangle (only for Java / C++)
    data members
    length
    breadth
    member functions / methods
    setDimension()
    area()
    perimeter()
    It must overload setDimension() method twice:
    1. by passing 1 argument
    2. by passing 2 arguments

  5. Design a class Box (only for Java / C++)
    data members
    length
    breadth
    height
    member functions / methods
    volume()
    It must contain 3 constructors
    1. 1 parameter
    2. 2 parameter
    3. 3 paramter
  6. Design a class Account
    data members
    balance
    member functions / methods
    deposit(amt)
    withdraw(amt)
    showBalance()

  7. Design a class Set
    data members
    3 numbers
    member functions / methods
    SUM()
    MEAN()
    MAX()
    MIN()

  8. Design a class Student
    data members
    roll_number
    name
    member functions / methods
    setData()
    getData()

  9. Design a class Account
    data members
    balance
    interest_rate
    interest_rate must be shared by all objects (static modifier) and its default value 10.25
    interest(no_of_years)

  10. Design a class Student
    data members
    roll_number
    name
    member functions / methods
    setData()
    getData()

  11. Design a class Account
    account_number
    balance
    interest_rate
    member functions / methods
    interest(no_of_years)

  12. Design a class Student
    data members
    roll_number
    name
    member function / methods
    getData()
    roll_number must be automatically generated.It also keep track of total number of Students.

  13. Design a package MyCircle and MyRectangle (Only for Java)
    radius
    length
    breadth
    member functions / methods:
    area()
    circumference()
    perimeter()

  14. Design a class Student
    data members
    roll_number
    name
    member functions / methods
    getData()
    showData()
    Create 5 objects of Student using Array

  15. Design a class Student and List ClassRoom
    add list of Students in ClassRoom
    display List

  16. Design a class Account and List Bank
    add list of Account in Bank
    display List

  17. Create array of Student Objects
    data members
    roll_no
    name
    college
    member functions / methods
    readData()
    showData()

  18. Create a class RBI (Only for Java)
    data members
    balance
    member functions
    RBI()
    deposit(int amt)
    withdraw(int amt)
    showBalance()

Array to CSV in Java

 

package com.demo;

import java.io.IOException;
import com.csvreader.CsvWriter;

public class ArrayToCSVDemo {

  public static void main(String[] args) {
    
    String array[] = {"Suryanagar, Vikhroli", "Java", "SQL", "13"};
    
    try {
      
      CsvWriter writer = new CsvWriter("awesomefile.csv");
      
      writer.writeRecord(array);
      
      writer.close();
      
    } catch (IOException e) {

      e.printStackTrace();
    }
    
  }

}

Reference Link: http://www.journaldev.com/12014/opencsv-csvreader-csvwriter-example

Jar File: http://www.java2s.com/Code/Jar/j/Downloadjavacsvjar.htm

Using FileWriter class

import java.io.FileWriter;

public class TestFileWriter {

  public static String implodeString(String[] split) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < split.length; i++) {			
        sb.append(split[i]);
        if (i != split.length - 1) {
            sb.append("\",\"");
        }
    }
    return "\"" . concat(sb.toString()) .concat("\"");
  }
  
  public static void main(String[] args) {
    
    String array[] = {"Suryanagar, Vikhroli", "Java", "SQL", "13"};
    
    try {
      
      FileWriter fw = new FileWriter("testout.csv");
      //fw.write("\"Suryanagar, Vikhroli\", Java, SQL, 13");
      fw.write(implodeString(array));
      fw.close();
    } catch (Exception e) {
      System.out.println(e);
    }

    System.out.println("Success...");

  }

}

 

 

Apache POI (Poor Obfuscation Implementation File System)

Prerequisite
Download all poi jar files
https://poi.apache.org/download.html


  1.  Terms
    • Workbook – The file contains number of sheets
    • Sheet – Matrix contains rows and cell
    • Row – Record of an entity in one row
    • Cell – A single cell which hold value
  2. JFileChooser fileChooser = new JFileChooser();
            int returnValue = fileChooser.showDialog(null, "Select File");
            
            if(returnValue == JFileChooser.APPROVE_OPTION) {
                Workbook workbook = new HSSFWorkbook(new FileInputStream(fileChooser.getSelectedFile()));
                
                Sheet sheet = workbook.getSheetAt(0);
                
                for(Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();){
                    for(Iterator<Cell> cit = rit.next().cellIterator(); cit.hasNext();){
                        System.out.println(cit.next());
                    }
                    System.out.println("");
                }
            } else {
                System.out.println("Invalid output");
            }
  3. JFileChooser fileChooser = new JFileChooser();
            int returnValue = fileChooser.showDialog(null, "Select File");
            
            if(returnValue == JFileChooser.APPROVE_OPTION) {
                FileInputStream excelFile = new FileInputStream(fileChooser.getSelectedFile());
                Workbook workbook = new XSSFWorkbook(excelFile);
                
                Sheet sheet = workbook.getSheetAt(0);
                
                for(Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();) {
                    for(Iterator<Cell> cit = rit.next().cellIterator(); cit.hasNext();) {
                        System.out.print(cit.next() + "\t" + cit.next());
                    }
                    System.out.println("");
                }
            }
  4.  Workbook workbook = new HSSFWorkbook();
            
            Sheet sheet1 = workbook.createSheet("movies");
    //        Sheet sheet2 = workbook.createSheet("Test Cases");
    //        Sheet sheet3 = workbook.createSheet(WorkbookUtil.createSafeSheetName("$*(^&?"));
            
            Row row = sheet1.createRow(0);
            
    //        Cell cell = row.createCell(4);
    //        cell.setCellValue("Hello World");
    //        Cell cell2 = row.createCell(3);
    //        cell2.setCellValue("terminator");
    //        System.out.println(cell.getRichStringCellValue().toString());
    //        System.out.println(cell2.getRichStringCellValue().toString());
    
            Cell cell1 = row.createCell(0);
            Cell cell2 = row.createCell(1);
            Cell cell3 = row.createCell(2);
            Cell cell4 = row.createCell(3);
            Cell cell5 = row.createCell(4);
            
            cell1.setCellValue(5);
            cell2.setCellValue("+");
            cell3.setCellValue(6);
            cell4.setCellValue("=");
            cell5.setCellFormula("A1+C1");
            
            try {
                FileOutputStream outputStream = new FileOutputStream("test1.xlsx");
                workbook.write(outputStream);
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
  5.  Complete Program
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Iterator;
    import javax.swing.JFileChooser;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.util.WorkbookUtil;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    /**
     *
     * @author Shailesh Sonare
     */
    public class ApachePOIDemo {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] shailesh) throws IOException {
            
            /*
            
            Workbook workbook = new HSSFWorkbook();
            
            Sheet sheet1 = workbook.createSheet("movies");
    //        Sheet sheet2 = workbook.createSheet("Test Cases");
    //        Sheet sheet3 = workbook.createSheet(WorkbookUtil.createSafeSheetName("$*(^&?"));
            
            Row row = sheet1.createRow(0);
            
    //        Cell cell = row.createCell(4);
    //        cell.setCellValue("Hello World");
    //        Cell cell2 = row.createCell(3);
    //        cell2.setCellValue("terminator");
    //        System.out.println(cell.getRichStringCellValue().toString());
    //        System.out.println(cell2.getRichStringCellValue().toString());
    
            Cell cell1 = row.createCell(0);
            Cell cell2 = row.createCell(1);
            Cell cell3 = row.createCell(2);
            Cell cell4 = row.createCell(3);
            Cell cell5 = row.createCell(4);
            
            cell1.setCellValue(5);
            cell2.setCellValue("+");
            cell3.setCellValue(6);
            cell4.setCellValue("=");
            cell5.setCellFormula("A1+C1");
            
            try {
                FileOutputStream outputStream = new FileOutputStream("test1.xlsx");
                workbook.write(outputStream);
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            */
            /*
            JFileChooser fileChooser = new JFileChooser();
            int returnValue = fileChooser.showDialog(null, "Select File");
            
            if(returnValue == JFileChooser.APPROVE_OPTION) {
                Workbook workbook = new HSSFWorkbook(new FileInputStream(fileChooser.getSelectedFile()));
                
                Sheet sheet = workbook.getSheetAt(0);
                
                for(Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();){
                    for(Iterator<Cell> cit = rit.next().cellIterator(); cit.hasNext();){
                        System.out.println(cit.next());
                    }
                    System.out.println("");
                }
            } else {
                System.out.println("Invalid output");
            }
            */
            
            JFileChooser fileChooser = new JFileChooser();
            int returnValue = fileChooser.showDialog(null, "Select File");
            
            if(returnValue == JFileChooser.APPROVE_OPTION) {
                FileInputStream excelFile = new FileInputStream(fileChooser.getSelectedFile());
                Workbook workbook = new XSSFWorkbook(excelFile);
                
                Sheet sheet = workbook.getSheetAt(0);
                
                for(Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();) {
                    for(Iterator<Cell> cit = rit.next().cellIterator(); cit.hasNext();) {
                        System.out.print(cit.next() + "\t" + cit.next());
                    }
                    System.out.println("");
                }
            }
            
        }    
    }