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>

 

sample htaccess file

Sample htaccess file

<Limit GET POST>
order allow,deny
SetEnvIf Remote_Addr ^10\.87\. ban
#allow from 10.87.63.0/8
allow from env=allow
deny from env=ban
</Limit>
#https://www.countryipblocks.net/block-specific-ips-from-your-allow-list-using-setenvif

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^test$ https://google.co.in
  #RewriteRule .* https://google.co.in
    #RewriteRule ^abc/([a-z]*)/([0-9]*)$ xyz.php?name=$1&id=$2 [NC,L,QSA]
    #RewriteCond %{HTTP_HOST} ^reporting.soc.saint-gobain.net [NC] 
    #RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://domain.com/$1 [R,L]
</IfModule>

 

 

php debug performance script

Php Script to check bugs and performance:
<?php

/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Asia/Kolkata');
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
date_default_timezone_set('Asia/Kolkata');

echo date('H:i:s') , " Program Started" , EOL;


// Echo memory peak usage
echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
// Echo done
echo date('H:i:s') , " Program End" , EOL;

?>

 

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)

How to run linux commands on windows

    1. Cygwin is a Unix-like environment and command-line interface for Microsoft Windows.
      Cygwin provides native integration of Windows-based applications, data, and other system resources with applications, software tools, and data of the Unix-like environment.
      Thus it is possible to launch Windows applications from the Cygwin environment, as well as to use Cygwin tools and applications within the Windows operating context.

      Official Site: https://www.cygwin.com/

       

    2. git bash is a shell where: the running process is sh.exe (packaged with msysgit, as share/WinGit/Git Bash.vbs)
      git is a known command$HOME is defined

      Official Site: https://git-scm.com/

  • How to install cygwin on Windows

How to enable ssh login to windows using cygwin

rsync on windows os

rsync: Failed to exec ssh: No such file or directory(2) on windows

nstalling cwrsync, you are likely to get this error  when you try to run this sample command from the command line.

rsync  -avz  -e  ssh ycsoftware@google.com:/home/ycsoftware /cygdrive/z/ycsoftware/

“rsync: Failed to exec ssh: No such file or directory(2)” cwrsync

The reason you are getting this is because for some reason rsync is not able to find the path to the ssh.exe file. You should change it to something like this:

C:/cygwin64/bin/rsync.exe -ar . /cygdrive/c/xampp/htdocs/test2/

Ref: http://ycsoftware.net/rsync-failed-to-exec-ssh-no-such-file-or-directory2-on-windows/