File download using HTTP Socket

// Socket Programming
// File download using Http Socket

import java.io.*;
import java.net.*;

public class Filedownload
{
     private final static int BUF_SIZE = 4096;
    
     public static void downloadFile(String fileURL, String targetDir) throws IOException
     {
          URL url = new URL(fileURL);
    
          // Establish connection to remote URL
          HttpURLConnection conc = (HttpURLConnection) url.openConnection();
         
          // Check response code for connection status.
          // Use static variable (HttpURLConnection.HTTP_OK) or its code (200).
          int responseCode = conc.getResponseCode();
          // if (responseCode == HttpURLConnection.HTTP_OK)
          if (responseCode == 200)         
          {
              // Get information about the file and its content
              String fileName = "";
              String content = conc.getHeaderField("Content-Disposition");
              String contentType = conc.getContentType();
              int contentLength = conc.getContentLength();





              if (content != null)
              {
                   // Extract file name from header field
                   int index = content.indexOf("filename=");
                   if (index > 0)
                   {
                        fileName = content.substring(index + 10,content.length() - 1);
                   }
              }
              else
              {
                   // Extract file name from URL
                   fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
              }

System.out.println("Content-Type = " + contentType);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);

// Open input stream from the HTTP connection
InputStream in = conc.getInputStream();
String filepath = targetDir + File.separator + fileName;

// Open output stream to save content to file
FileOutputStream out = new FileOutputStream(filepath);
                            
int data = -1;
byte[] buf = new byte[BUF_SIZE];
              while ((data = in.read(buf)) != -1)
              {
                   out.write(buf, 0, data);
              }

out.close();
in.close();

System.out.println("File downloaded");
}



else
{
System.out.println("No file to download. ");
System.out.println("Server replied HTTP code: " + responseCode);
}
conc.disconnect();
     }
         
public static void main(String[] args)
{
String fileURL = "http://drranurekha.com/wp-content/uploads/2018/02/3-Segmentation.pdf";
         
String targetDir = "D:/cnlab/Http_socket";
       
try
{
     downloadFile(fileURL, targetDir);
}
catch (IOException E)
{
     E.printStackTrace();
}
}
}




/*
Note 1: Specify the URL for file to download clearly
Example:
     Open a pdf file in BROWSER.
     Check the address bar and copy the link in url=""
     Paste it in string fileURL
*/

/*
Note 2:
response code retrieves the status of the http connection.
Example:
     HTTP_OK - HTTP Status-Code 200: OK.
     HTTP_ACCEPTED - HTTP Status-Code 202: Accepted.
     HTTP_NO_CONTENT - HTTP Status-Code 204: No Content.
     HTTP_FORBIDDEN - HTTP Status-Code 403: Forbidden.
     HTTP_CLIENT_TIMEOUT - HTTP Status-Code 408: Request Time-Out.
     HTTP_BAD_GATEWAY - HTTP Status-Code 502: Bad Gateway.
*/

/*
Note 3:
The MIME Content-disposition header provides presentation information for the body-part. It is often added to attachments specifying whether the attachment body part should be displayed (inline) or presented as a file name to be copied (attachment)
*/

Sample Output:

> javac Filedownload.java
> java Filedownload
Content-Type = application/pdf
Content-Length = 211589
fileName = 3-Segmentation.pdf
File downloaded
> 

Remote Method Invocation

REMOTE METHOD INVOCATION


// Display a string using Remote Method Invocation.


Steps to implement RMI:
1.    Start the program.
2.    Create and compile the following four source files
                     i.The interface file defines the remote interface that is provided by the server.
                   ii.The implementation file implements the remote interface
                  iii.The server file contains the main program for the server machine to update the RMI registry on that machine
                  iv.The client file implements client side of the distributed application by importing package.
3.    Generate a stub using RMI compiler as
rmic < implementation filename >
4.    Start the rmiregistry on the server machine as
start rmiregistry
5.    Execute the server program.
6.    Pass the necessary parameters and execute the client program.
7.    Verify the output.
8.    Stop the program.



PROGRAM:


// INTERFACE PROGRAM
// DispServerIntf.java

import java.rmi.*;

public interface DispServerIntf extends Remote
{
     String Display(String S) throws RemoteException;
}


// IMPLEMENTATION PROGRAM
// DispServerImpl.java

import java.rmi.*;
import java.rmi.server.*;

public class DispServerImpl extends UnicastRemoteObject implements DispServerIntf
{
     public DispServerImpl() throws RemoteException
     {
     }

     public String Display(String S) throws RemoteException
     {
          return ("WELCOME "+S+" ! ");
     }
}


// SERVER PROGRAM
// DispServer.java

import java.net.*;
import java.rmi.*;

public class DispServer
{
     public static void main(String args[])
     {
          try
          {
              DispServerImpl DispServerImpl = new DispServerImpl();
              Naming.rebind("DispServer", DispServerImpl);
          }
          catch(Exception e)
          {
              System.out.println("Exception: " + e);
          }
     }
}


// CLIENT PROGRAM
// DispClient.java

import java.rmi.*;

public class DispClient
{
     public static void main(String args[])
     {
          try
          {
              String DS_URL = "rmi://" + args[0] + "/DispServer";
              DispServerIntf DSIntf=(DispServerIntf)Naming.lookup(DS_URL);

              System.out.println("\n\n"+DSIntf.Display(args[1])+"\n");
          }

          catch(Exception e)
          {
              System.out.println("Exception: " + e);
          }
     }
}



OUTPUT:


SERVER WINDOW

> javac DispServerIntf.java
> javac DispServerImpl.java
> javac DispServer.java
> rmic DispServerImpl
> start rmiregistry
> java DispServer


RMIREGISTRY





CLIENT WINDOW

> javac DispClient.java
> java DispClient localhost "to Java"

WELCOME to Java !

>















Client Server Communication - Datagram Sockets



// Socket Programing – Datagram Sockets
// Client Server Communication

// Server Program

import java.io.*;
import java.net.*;

public class UDPServer
{
     public static void main(String as[]) throws IOException
     {
          DatagramSocket ds;
          DatagramPacket dp;
         
          final int buf_size = 512;
          final int port = 1500;
         
          byte msg_rec[] = new byte[buf_size];
         
          try
          {
              ds = new DatagramSocket(port);
             
              dp = new DatagramPacket(msg_rec, Buf_size);
              ds.receive(dp);
                  
              String Msg = "Welcome " + (new String(dp.getData())).trim();
              System.out.println(Msg);
          }
          catch(Exception e)
          {
              System.out.println("Exception " + e);
          }
     }
}
             
             
             
             



// Socket Programing – Datagram Sockets
// Client Server Communication

// Client Program

import java.io.*;
import java.net.*;
import java.util.*;

public class UDPClient
{
     public static void main(String as[]) throws IOException
     {
          DatagramSocket ds;
          DatagramPacket dp;
         
          final int port = 1500;
          final int buf_size = 512;
         
          Scanner s = new Scanner(System.in);
         
          byte[] msg_send = new byte[buf_size];    
         
          try
          {
              ds = new DatagramSocket();
              System.out.print("Enter data to send : ");
              String data = s.nextLine();
             
              msg_send = data.getBytes();
              InetAddress DA = InetAddress.getByName("localhost");
             
              dp = new DatagramPacket(msg_send, msg_send.length, DA, port);
              ds.send(dp);
          }
          catch(Exception e)
          {
              System.out.println("Exception " + e);
          }
     }
}
             
             
             
             
             
             
             
             
                           
             
             
             
             

Traceroute Command


// Traceroute Command
// traceroutecmd.java

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class traceroutecmd
{
     public static void runSystemCommand(String command)
     {
          try
          {
              Process p = Runtime.getRuntime().exec(command);
              BufferedReader inputStream = new BufferedReader(
                        new InputStreamReader(p.getInputStream()));

              String s = "";
              while ((s = inputStream.readLine()) != null)
                   System.out.println(s);
          }
          catch (Exception e)
          {
          }
     }

     public static void main(String[] args)
     {  
          // String ip = "www.google.co.in";
          // String ip = "127.0.0.1";
          String ip = "www.drranurekha.com";
          runSystemCommand("tracert " + ip);
     }
}




OUTPUT:

>javac traceroutecmd.java

>java traceroutecmd

Tracing route to drranurekha.com [160.153.137.167] over a maximum of 30 hops:

  1    <1 ms    <1 ms    <1 ms  10.0.15.1
  2    <1 ms    <1 ms    <1 ms  10.0.0.15
  3     1 ms     1 ms     1 ms  210.212.247.209
  4     2 ms     1 ms     1 ms  172.24.75.102
  5     *        *       21 ms  218.248.235.217
  6     *        *       12 ms  218.248.235.218
  7    21 ms    21 ms    21 ms  121.244.37.253.static.chennai.vsnl.net.in [121.244.37.253]
  8     *        *        *     Request timed out.
  9    49 ms    49 ms    49 ms  172.25.81.134
 10    50 ms    50 ms    70 ms  ix-ae-0-4.tcore1.mlv-mumbai.as6453.net [180.87.38.5]
 11   165 ms   165 ms   165 ms  if-ae-9-5.tcore1.wyn-marseille.as6453.net [80.231.217.17]
 12   172 ms   171 ms   171 ms  if-ae-8-1600.tcore1.pye-paris.as6453.net [80.231.217.6]
 13   171 ms   171 ms   171 ms  if-ae-15-2.tcore1.av2-amsterdam.as6453.net [195.219.194.145]
 14   175 ms   175 ms   175 ms  195.219.194.2
 15   171 ms   170 ms   170 ms  po72.bbsa0201-01.bbn.mgmt.ams1.gdg [188.121.33.74]
 16   170 ms   169 ms   169 ms  10.241.131.203
 17   175 ms   175 ms   175 ms  10.253.1.1
 18   166 ms   166 ms   166 ms  10.253.130.9
 19   173 ms   173 ms   173 ms  10.253.130.3
 20   169 ms   169 ms   169 ms  10.253.130.5
 21   169 ms   169 ms   169 ms  ip-160-153-137-167.ip.secureserver.net [160.153.137.167]

Trace complete.

                    >