Multithreaded File Downloader in java

               Multiple small chunks of a large file are downloaded here. this program explores the concurrency, file input output operations and how it transferred.

Let us explore the steps.

Steps:

  • First, initialize the URL.
  • The content length is retrieved.
  • Split the download task.
  • By the use of Fixed Thread Pool, the parallel downloads are done.
  •  Finally, the chunks are written.

Built-in Packages used for this process:

ExecutorService ,HttpURLConnection and RandomAccessFile.

Program implementation:

import java.io.*;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class MThreadedDownloader {

    private static final int T_COUNT = 3;

    private final String fURL;

    private final String opFile;

    public MThreadedDownloader(String fURL, String opFile) {

        this.fURL = fURL;

        this.opFile = opFile;

    }

    public void downloadIt() throws Exception {

        URL url1 = new URL(fURL);

 

        HttpURLConnection con1 = (HttpURLConnection) url1.openConnection();

        int cLength = con1.getContentLength();

        con1.disconnect();

        int chunk_Size = cLength / T_COUNT;

        ExecutorService exe1 = Executors.newFixedThreadPool(T_COUNT);

        for (int i = 0; i < T_COUNT; i++) {

            int start_Byte = i * chunk_Size;

            int end_Byte = (i == T_COUNT - 1) ? cLength - 1 : (start_Byte + chunk_Size - 1);

            exe1.execute(new DThread(fURL, opFile, start_Byte, end_Byte, i));

        }

        exe1.shutdown();

        while (!exe1.isTerminated()) {

            Thread.sleep(100);

        }

        System.out.println("Download complete.");

    }

    private static class DThread implements Runnable {

        private final String fURL;

        private final String opFile;

        private final int start_Byte;

        private final int end_Byte;

        private final int thread_Id;

        public DThread(String fURL, String opFile, int start_Byte, int end_Byte, int thread_Id) {

            this.fURL = fURL;

            this.opFile = opFile;

            this.start_Byte = start_Byte;

            this.end_Byte = end_Byte;

            this.thread_Id = thread_Id;

        }

        @Override

        public void run() {

            try {

                HttpURLConnection con1 = (HttpURLConnection) new URL(fURL).openConnection();

                String bRange = "bytes=" + start_Byte + "-" + end_Byte;

                con1.setRequestProperty("Range", bRange);

                con1.connect();

                try (InputStream in1 = con1.getInputStream();

                     RandomAccessFile raf1 = new RandomAccessFile(opFile, "rw")) {

                    raf1.seek(start_Byte);

                    byte[] buffer1 = new byte[4096];

                    int bytes_Read;

                    while ((bytes_Read = in1.read(buffer1)) != -1) {

                        raf1.write(buffer1, 0, bytes_Read);

                    }

                }

                System.out.printf("Thread is %d completed downloading bytes %d to %d%n", thread_Id, start_Byte, end_Byte);

            } catch (IOException e) {

                System.err.printf("Thread is %d encountered an error: %s%n", thread_Id, e.getMessage());

            }

        }

    }

    public static void main(String[] args) throws Exception {

        String url1 = "C:\\raji\\blog\\keywords.zip";

        String output1 = "largefile.zip";

        new MThreadedDownloader(url1, output1).downloadIt();

    }

}

This is the sample implementation of Multithreaded File Downloader. Hope, this code is useful to you.

ORM(Object Relational Mapping) implementation in java

               A programming technique that interacts the relational database for developers. That is called ORM(Object Relational Mapping).

Actually, it is like a bridge between front end and back end code. Here, front end is your code. Back end is your relational database.

 Let us create a Customer database for this project.

Java implementation:

Part1: Customer Class creation

public class Customer {

    private int c_id;

    private String c_name;

    private String c_email;

    // let us code the constructor

    public Customer() {}

    public Customer(int c_id, String c_name, String c_email) {

        this.c_id = c_id;

        this.c_name = c_name;

        this.c_email = c_email;

    }

    // code for input

    public int getId() { return c_id; }

    public void setId(int c_id) { this.c_id = c_id; }

    public String getName() { return c_name; }

    public void setName(String c_name) { this.c_name = c_name; }

    public String getEmail() { return c_email; }

    public void setEmail(String c_email) { this.c_email = c_email; }

    @Override

    public String toString() {

        return "Customer{c_id=" + c_id + ", c_name=" + c_name + ", c_email=" + c_email + "}";

    }

}

Part 2: CustomerDao class code is written here

import java.sql.*;

public class CustomerDao {

    private Connection connection1;

    public CustomerDao(Connection connection1) {

        this.connection1 = connection1;

    }

    public void add(Customer cust) throws SQLException {

        String query = "INSERT INTO Customer (c_id, c_name, c_email) VALUES (?, ?, ?)";

        try (PreparedStatement st1 = connection1.prepareStatement(query)) {

            st1.setInt(1, cust.getId());

            st1.setString(2, cust.getName());

            st1.setString(3, cust.getEmail());

            st1.executeUpdate();

        }

    }

    public Customer findById(int c_id) throws SQLException {

        String query = "SELECT * FROM Customer WHERE c_id = ?";

        try (PreparedStatement st1 = connection1.prepareStatement(query)) {

            st1.setInt(1, c_id);

            ResultSet rs = st1.executeQuery();

            if (rs.next()) {

                return new Customer(

                    rs.getInt("c_id"),

                    rs.getString("c_name"),

                    rs.getString("c_email")

                );

            }

        }

        return null;

    }

Part 3: ORMain class

import java.sql.*;

public class ORMain {

    public static void main(String[] args) {

        try {

            // Step 1: Let us Connect to database (using SQLite)

            Connection con1 = DriverManager.getConnection("jdbc:sqlite:sampledb.db");

            // Step 2: if the table doesn’t exist, it creates it.

            try (Statement st1 = con1.createStatement()) {

                String sql = "CREATE TABLE IF NOT EXISTS users (c_id INTEGER PRIMARY KEY, c_name TEXT, c_email TEXT)";

                st1.execute(sql);

            }

            // Step 3: insert a data and retrieve it

            CustomerDao da1 = new CustomerDao(con1);

            Customer cust = new Customer(4, "Rajeeva", "raje_va@abc.com");

            da1.add(cust);

            Customer retr1 = da1.findById(3);

            System.out.println("The data is Retrieved here: " + retr1);

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

}

That’s all. this is the mini ORM code in java.  Hope ,it will  give you the information. Keep coding!!!