About Me

B.E.(Computer Science), Android/Java Developer, CCNA, CCNA SECURITY (IINS), CCNP (R&S), 4011 Recognized(NSA & CNSS)U.S.A. , MCSA, MCTS, REDHAT CERTIFIED NETWORK SECURITY ADMINISTRATOR(RH253), AFCEH.

Friday, March 21, 2014

FileWatcher implementation in Java 7

       

 /**
  * This method handles the Watcher as the File is Modified .......... By Kumar Vivek Mitra
  * @param folderToBeWatched
  */
 public void fileModificationWatcher(final String folderToBeWatched){
  
  new Thread(new Runnable(){

   @Override
   public void run() {
    
    try {
       Path faxFolder = Paths.get(folderToBeWatched);
       watchServiceCreate = FileSystems.getDefault().newWatchService();
       faxFolder.register(watchServiceCreate, StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_CREATE);
      
       boolean valid = true;
       do {
        watchKeyCreate = watchServiceCreate.take();

         for (WatchEvent event : watchKeyCreate.pollEvents()) {
           WatchEvent.Kind kind = event.kind();
           if (StandardWatchEventKinds.ENTRY_MODIFY.equals(event.kind()) || StandardWatchEventKinds.ENTRY_DELETE.equals(event.kind()) || StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
             String fileName = event.context().toString();
             makeChangesToHashFile(folderToBeWatched);
             System.out.println("File Modified:" + fileName);
           }else{
            System.out.println("Still not");
           }
           
         }
         
         valid = watchKeyCreate.reset();
         
                        
       }while(valid);
       
    } catch (Exception e) { e.printStackTrace(); }
    
   }
   
  }).start();
 }
 
 

      
 

C# code to calculate the Checksum using MD5

       



/**
 * Coded by Kumar Vivek Mitra 16_1_2014, for comparing the checksum of files.
 *
 */



using System.Security.Cryptography;
using System.IO;
using System;

class CheckSumTest
 {
   static void Main()
    {

      CheckSumTest instance  = new CheckSumTest();
      

      System.Console.WriteLine("Generating Checksum.................." );
      System.Console.WriteLine();
      string FileOneCheckSum = instance.GetCheckSum("D:\\VIVEK_1_1_2014\\csharpworkspace\\ABCD Bezubaan 320Kbps.mp3");
      string FileTwoCheckSum = instance.GetCheckSum("D:\\VIVEK_1_1_2014\\csharpworkspace\\test_cbr.mp3");
      System.Console.WriteLine("File One CheckSum :"+ FileOneCheckSum);
      System.Console.WriteLine("File Two CheckSum :"+ FileTwoCheckSum );
      System.Console.WriteLine("================ Comparing ============");
      

      int Differ = instance.CheckKaro(FileOneCheckSum ,FileTwoCheckSum);

      if(Differ == 0)
        {

           System.Console.WriteLine("Both files are exactly same");
        }
      else
        {

           System.Console.WriteLine("Both files are different");
        }
    }




   // Method to check checksum of files

   public int CheckKaro(string strOne, string strTwo)
    {

      return string.Compare(strOne,strTwo);

    }




   // Method to obtain the checksum of file

   public string GetCheckSum(string file)
    {
      

      using (var md5 = MD5.Create())
      {
        using (var stream = File.OpenRead(file))

         {

           return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-","").ToLower();
         }

      }
      

    }



 }



      
 

Monday, March 10, 2014

Find the External Storage on Any Android Device of Any Manufacturer

       


/**
 * This class is implemented by Kumar Vivek Mitra on 10_1_2014
 * to find the exact external storage onto the android device,
 * as external storage keep changing according to the manufactures.
 * THIS CLASS CAN ALSO BE USED TO FIND ALL THE STORAGES ON THE ANDROID DEVICES
 */



package com.promact.model.syncserver;

import java.io.InputStream;
import java.util.HashSet;
import java.util.Locale;

public class ExternalStorageFinderClass {
 
 
 ///// ----------------------------------- Java Instance Variables
 
 private static ExternalStorageFinderClass externalStorageUniquesInstance = new ExternalStorageFinderClass();
 
 ///// ----------------------------------- Java Instance Variables
 
 
 ///// ----------------------------------- Android Instance Variables
 
 
 
 ///// ----------------------------------- Android Instance Variables
 
 
 
 /**
  * Private Constructor to prevent creation of an instance of this class
  * from outside.
  */
 private ExternalStorageFinderClass(){}  
 
 
 
 
 /**
  * Method to get the Unique instance of this class
  */
 public static ExternalStorageFinderClass getInstance(){
  
  return externalStorageUniquesInstance;
 }
 
 

 /**
  * Method to get the external storages
  */
 public static HashSet getExternalStorages() {
     final HashSet out = new HashSet();
     String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
     String s = "";
     try {
         final Process process = new ProcessBuilder().command("mount").redirectErrorStream(true).start();
         process.waitFor();
         final InputStream is = process.getInputStream();
         final byte[] buffer  = new byte[1024];
         
         while (is.read(buffer) != -1) {
             s = s + new String(buffer);
         }
         
         is.close();
     } catch (final Exception e) {e.printStackTrace();}

     // filter/process output
     final String[] lines = s.split("\n");
     for (String line : lines) {
         if (!line.toLowerCase(Locale.US).contains("asec")) {
             if (line.matches(reg)) {
                 String[] parts = line.split(" ");
                 for (String part : parts) {
                     if (part.startsWith("/"))
                         if (!part.toLowerCase(Locale.US).contains("vold"))
                             out.add(part);
                 }
             }
         }
     }
     return out;
 }
 
 /** 
  * To get the first entry of the
  * HashSet returned from ExternalStorageFinderClass
  * by invoking its getExternalStorage() method, by Kumar Vivek Mitra 1_10_2014
  */
 public String getExtPath(){
 
   String extPath = "";
   
  // Edited for making it compatible with Nexus 5 by Kumar Vivek Mitra 18_6_2014
  if(getExternalStorages().toArray().length == 0){
   
         extPath = Environment.getExternalStorageDirectory().toString();
  }
  else{
         extPath = getExternalStorages().toArray()[0].toString();
  }
  
  return extPath;
 }
}







      
 

Sunday, December 1, 2013

Conversion of String to Integer in C#

       


class ConvertIt
 {
   static void Main()
    {

        string stringToNumber = "1000";
        int numberParse = 0;
        int numberConvertTo = 0;
        int numberTryParse = 0;
        bool isTryParse = false;

        // Using .Parse() will result in throwing ArgumentNullException in case of string being null.
        numberParse     = int.Parse(stringToNumber); 
        
        // Using Convert.ToInt32() will result in 0 in the case of string being null.
        numberConvertTo = System.Convert.ToInt32(stringToNumber);

        // Better than .Parse() as we get to know whether the string got converted or not Without throwing ArgumentNullException
        isTryParse      = int.TryParse(stringToNumber, out numberTryParse);

        if(isTryParse == true)
           {

             System.Console.WriteLine("Conversion to integer successful");

           }
      
        else
           {
             System.Console.WriteLine("Conversion to integer failed");

           }
         
         System.Console.WriteLine("numberParse: "+numberParse);
         System.Console.WriteLine("numberConvertTo: "+numberConvertTo);
         System.Console.WriteLine("numberTryParse: "+numberTryParse);
    }

 }

      
 

Tuesday, October 1, 2013

Story of Compilation and Execution of a C# program:

       


class Car
{
 static void Main()
  {
   System.Console.WriteLine("Wroom wroom.........");
  }
}

Compilation:
===========

csc.exe Car.cs

--> Successful compilation of the above program result in an Assembly, which consists of CIL (Common Intermediate Language).
    But Processor is unable to interpret this CIL directly.

Execution:
=========

Car.exe

--> VES (Virutal Execution System) or more commonly known as runtime converts this CIL into Native Machine Level Code during Runtime. This process
    is known as Just In Time Compilation or Jitting.
 
 
 
      
 

Thursday, September 26, 2013

Compilation and Execution of program with Different File and Class name in Java and C#:

       




      
          Java     
          ----                         
              
-> File_Name: Test.java 

  class Hello{
  
      public static void main(String[] args){

           System.out.println("Hello");

      }
  }  
           



Compile:
-------  
         javac Test.java

Run:
---      java Hello      // Using the Class name which contains the main() method.


   

           C#
          ----

-> File_Name: Test.cs


  class Hello                                
  {
   static void Main()
   {
     System.Console.WriteLine("Hello");
   }
  }




Compile:
-------  csc.exe Test.cs
  
Run:
---      Test.exe     // Using the File name itself for compile as well as running it.



      
 

Tuesday, September 24, 2013

Convert character to String:

       


public class ConvertCharToString {

 public String doTheConversion(char c) {

  String str = Character.toString(c);

  return str;

 }

 public static void main(String[] args) {

  String s = new ConvertCharToString().doTheConversion('n');

  System.out.println(s);

 }

}