Sunday 2 March 2014

Android Notification example



final NotificationManager mgr =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification note = new Notification(R.drawable.phone,"Vacant Class Notification..!", System.currentTimeMillis());
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

// This pending intent will open after notification click
PendingIntent i = PendingIntent.getActivity(this, 0,new Intent(this, NotificationReceiver.class), 0);
note.setLatestEventInfo(getApplicationContext(), "Vacant Class Notification..!",message, i);
note.sound = soundUri;

mgr.notify(0, note);

Sunday 16 February 2014

Android Dynamic Check-box Example

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Attendance extends Activity {
CheckBox checkBox;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.stud_attendence);
LinearLayout my_layout = (LinearLayout) findViewById(R.id.my_layout);
LinkedHashMap<String, String> alphabet = new LinkedHashMap<String, String>();
// int Array_Count = 0;
String[] Str_Array = new String[] { "12111447:Arun Kumar",
"12111448:Aneesh", "12111449:Binoy shyam" };


for (int i = 0; i < Str_Array.length; i++) {
String[] std= Str_Array[i].split(":");
alphabet.put(std[0],std[1]);

}

Set<?> set = alphabet.entrySet();

Iterator<?> i = set.iterator();
while (i.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry me = (Map.Entry) i.next();
checkBox = new CheckBox(this);
checkBox.setId(Integer.parseInt(me.getKey().toString()));
checkBox.setText(me.getKey().toString()+" : "+me.getValue().toString());
checkBox.setOnClickListener(getOnClickDoSomething(checkBox));
my_layout.addView(checkBox);
}

}

View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(
getApplicationContext(),
"Id:" + button.getId() + " and text: "
+ button.getText().toString(), 2000).show();

}
};
}

}

Output:





Wednesday 12 February 2014

Android Reading Inbox SMS

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;

public class SMSRead extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      TextView view = new TextView(this);
      Uri uriSMSURI = Uri.parse("content://sms/inbox");
      Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
      String sms = "";
      while (cur.moveToNext()) {
          sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";         
      }
      view.setText(sms);
      setContentView(view);
  }
}
Add below permission to AndroidManifest.xml
   
<uses-permission android:name="android.permission.READ_SMS" />
  

Monday 10 February 2014

DES Algorithm source code in JAVA


import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;

public class DES {

    static Cipher ce;
    static Cipher cd;

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

     

        SecretKey skey;
        skey = KeyGenerator.getInstance("DES").generateKey();

        byte[] initializationVector = new byte[]{0x10, 0x10, 0x01, 0x04, 0x01, 0x01, 0x01, 0x02};

        AlgorithmParameterSpec algParameters = new IvParameterSpec(initializationVector);

        ce = Cipher.getInstance("DES/CBC/PKCS5Padding");

        cd = Cipher.getInstance("DES/CBC/PKCS5Padding");

        ce.init(Cipher.ENCRYPT_MODE, skey, algParameters);

        cd.init(Cipher.DECRYPT_MODE, skey, algParameters);

        FileInputStream is = new FileInputStream("F:/sem1report/test.txt");

        FileOutputStream os = new FileOutputStream("F:/sem1report/encry.txt");

        int dataSize = is.available();

        byte[] inbytes = new byte[dataSize];

        is.read(inbytes);

//        String str2 = new String(inbytes);
//
//        System.out.println("Input file contentn" + str2 + "n");

        write_encode(inbytes, os);

        os.flush();

        is.close();

        os.close();

        System.out.println("Ecrypted Content to output.txt");

        FileInputStream is1 = new FileInputStream("F:/sem1report/encry.txt");
        int endataSize = is1.available();

        byte[] decBytes = new byte[endataSize];

        read_decode(decBytes, is1);

        is.close();
        FileOutputStream os1 = new FileOutputStream("F:/sem1report/decry.txt");

        os1.write(decBytes);
        os1.flush();
//        String str = new String(decBytes);
//
//        System.out.println("Decrypted file contents:n" + str);

    }

    public static void write_encode(byte[] bytes, OutputStream output) throws Exception {

        CipherOutputStream cOutputStream = new CipherOutputStream(output, ce);

        cOutputStream.write(bytes, 0, bytes.length);

        cOutputStream.close();
    }

    public static void read_decode(byte[] bytes, InputStream input) throws Exception {

        CipherInputStream cInputStream = new CipherInputStream(input, cd);

        int position = 0, i;

        while ((i = cInputStream.read()) != -1) {

            bytes[position] = (byte) i;

            position++;

        }
    }
}

Sunday 9 February 2014

Decimal to Hexadecimal Converter in Java

CONVERT DECIMAL INTEGER TO HEXADECIMAL 

NUMBER EXAMPLE


import java.io.*;
import java.lang.*;

public class DecimalToHexadecimal{
  public static void main(String[] args) throws IOException{  
  BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter the decimal value:");
  String hex = bf.readLine();
  int i = Integer.parseInt(hex);
  String hex1 = Integer.toHexString(i);
  System.out.println("Hexa decimal: " + hex1);
  }
}


run:
Enter the decimal value:
16
Hexa decimal: 10

How to Convert from binary to hex in java

SIMPLE ONE LINE CODE TO CONVERT STRING CONTAINING A BINARY VALUE TO HEX


String bin = Integer.toHexString(Integer.parseInt(binOutput, 2));
//when integer size exceeds use Long instead of Integer

String bin = Long .toHexString(Long .parseLong(binOutput, 2));

FULL CODE FOR CONVERSION


import java.io.*;
import java.lang.*;



public class  BinaryToHexadecimal{
  public static void main(String[] args)throws IOException{
  BufferedReader bf= new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter the Binary number:");
  String hex = bf.readLine();
  long num = Long.parseLong(hex);
  long rem;
  while(num > 0){
  rem = num % 10;
  num = num / 10;
  if(rem != 0 && rem != 1){
  System.out.println("This is not a binary number.");
  System.out.println("Please try once again.");
  System.exit(0);
  }
  }
  int i= Integer.parseInt(hex,2);
  String hexString = Integer.toHexString(i);
  System.out.println("Hexa decimal: " + hexString);
  }
}

run:
Enter the Binary number:
101010
Hexa decimal: 2a

----------------------------------------------

Saturday 8 February 2014

Android Code for Turn On GPS programmatically

private void turnGPSOn()
{
   String provider = Settings.Secure.getString(getContentResolver(),        Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

   if(!provider.contains("gps")){ //if gps is disabled
       final Intent poke = new Intent();
             poke.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
       poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
       poke.setData(Uri.parse("3"));
       sendBroadcast(poke);
   }
}

Windows Commands

1) process list------tasklist
2)To open a pdf file------start "" /max "c:\nameofpdf.pdf"
3)to shutdown---------shutdown /s
4)to restart---------shutdown /r
5)for playing vlc-----

String path= "C:\\Users\\name\\Desktop\\as.mp4";

String command1 = "cmd.exe /c cd C:/Program Files/VideoLAN/VLC &cmd.exe  /k \"vlc \""+path+"\"  --video-filter=scene --start-time=0 --stop-time=89 vlc://quit\"";          
          Process p = RunTime.getRunTime.exec(command1);


6)to open all types of files and folders remotely


 public void open_files(String abspath) {
        try {
            Runtime r = Runtime.getRuntime();
            String path = "cmd.exe /c start \"\" /max \"" + abspath + "\"";

            System.out.println("path = " + path);

            Process p = r.exec(path);

        } catch (Exception e) {
        }
    }

Java code for Unzipping

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnZip
{
    List<String> fileList;
    private static final String INPUT_ZIP_FILE = "/home/javaa/Desktop/file.zip";
    private static final String OUTPUT_FOLDER = "/home/javaa/Desktop/file";

    public static void main( String[] args )
    {
    UnZip unZip = new UnZip();
    unZip.unZipIt(INPUT_ZIP_FILE,OUTPUT_FOLDER);
    }

    /**
     * Unzip it
     * @param zipFile input zip file
     * @param output zip file output folder
     */
    public void unZipIt(String zipFile, String outputFolder){

     byte[] buffer = new byte[1024];

     try{

    //create output directory is not exists
    File folder = new File(OUTPUT_FOLDER);
    if(!folder.exists()){
    folder.mkdir();
    }

    //get the zip file content
    ZipInputStream zis =
    new ZipInputStream(new FileInputStream(zipFile));
    //get the zipped file list entry
    ZipEntry ze = zis.getNextEntry();

    while(ze!=null){

      String fileName = ze.getName();
           File newFile = new File(outputFolder + File.separator + fileName);

           System.out.println("file unzip : "+ newFile.getAbsoluteFile());

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(buffer)) > 0) {
        fos.write(buffer, 0, len);
            }

            fos.close();
            ze = zis.getNextEntry();
    }

        zis.closeEntry();
    zis.close();

    System.out.println("Done");

    }catch(IOException ex){
       ex.printStackTrace();
    }
   }
}

JAVA Source code for Sending email with attachment


import com.sun.xml.internal.ws.util.ByteArrayDataSource;
import java.io.File;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;


public class SendMailWithAttachments {

    public static String subject;
    public static String body;
    public static String recipients;
    public static String send = "";
    public static String passwd = "";

    public static synchronized void sendMail(String subject, String body, String recipients, String sender, String password, String fileAttachment)
            throws Exception {
        send = sender;
        passwd = password;
        System.out.println("Sender name>>>>>>>>"+send);
        System.out.println("Password>>>>>>>>>>>"+passwd);
        if (subject.equals("") || body.equals("") || recipients.equals("")) {
            System.out.println("Error in sending mail");
        } else {
            String mailhost = "smtp.gmail.com";
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.host", mailhost);
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smwd);tp.quitwait", "false");

            Session session = Session.getDefaultInstance(props,
                    new javax.mail.Authenticator() {

                        @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(send, passwd);

                        }
                    });


            MimeMessage message = new MimeMessage(session);
            DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));

            message.setSender(new InternetAddress(send));
            message.setSubject(subject);

            message.setDataHandler(handler);

            if (!fileAttachment.equals("")) {
                DataSource source = new FileDataSource(fileAttachment);
                message.setDataHandler(new DataHandler(source));
                message.setFileName(new File(fileAttachment).getName());
            }
            if (recipients.indexOf(',') > 0) {
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
            } else {
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
            }

            Transport.send(message);
     
        }
    }


    }
}

NB: for proper working of this code include mail.jar in library and make sure that the antivirus and firewall of your system is off..Otherwise an Exception named SSLHandShakeException will arise.

JAVA Source Code for sending an email


import com.sun.istack.internal.ByteArrayDataSource;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;

public class SimpleMail {

    public synchronized void sendMail(String subject, String body, String sender, String recipients)
            throws Exception {

        String mailhost = "smtp.gmail.com";
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", mailhost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smwd);tp.quitwait", "false");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {

                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("from mail id", "password of from emailid");

                    }
                });

        MimeMessage message = new MimeMessage(session);
        message.setSender(new InternetAddress(sender));
        message.setSubject(subject);
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
        message.setDataHandler(handler);
        if (recipients.indexOf(',') > 0) {
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
        } else {
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
        }


        Transport.send(message);

    }

}

NB: for proper working of this code include mail.jar in library and make sure that the antivirus and firewall of your system is off..Otherwise an Exception named SSLHandShakeException will arise.




Random Number Generation


import java.util.Random;

public class Randomnumber {

    public static void main(String[] args) {
       long r = generateRandom(12);
        System.out.println("r = " + r);
    }

    public static long generateRandom(int length) {
        Random random = new Random();
        char[] digits = new char[length];
        digits[0] = (char) (random.nextInt(9) + '1');
        for (int i = 1; i < length; i++) {
            digits[i] = (char) (random.nextInt(10) + '0');
        }
        return Long.parseLong(new String(digits));
    }
}

java code for open any file programmatically



import java.io.File;

public class OpenAnyFile {

    public static void main(String[] args) {
        File ff = new File("C:\\Users\\Desktop\\sylabus.docx");
        open_files(ff.getAbsolutePath());
    }

    public static void open_files(String abspath) {
        try {
            Runtime r = Runtime.getRuntime();
            String path = "cmd.exe /c start \"\" /max \"" + abspath + "\"";

            System.out.println("path = " + path);

            Process p = r.exec(path);

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

Image Resizing in java


import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

public class ImageResize{

    /**
    * Resize an image
    * @param sourceImg  The source of the image to resize.
    * @param destImg    The destination of the resized image.
    * @param Width      The maximum width you want the new image to be, use 0 for source width.
    * @param Height     The maximum height you want the new image to be, use 0 for source height.
    * @return           true if successful and false if unsuccessful.
    */
    public static Boolean resizeImage(String sourceImg, String destImg, Integer Width, Integer Height) {
        BufferedImage origImage;
        try {

            origImage = ImageIO.read(new File(sourceImg));
            int type = origImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : origImage.getType();

            //*Special* if the width or height is 0 use image src dimensions
            if (Width == 0) {
                Width = origImage.getWidth();
            }
            if (Height == 0) {
                Height = origImage.getHeight();
            }

            int fHeight = Height;
            int fWidth = Width;

            //Work out the resized width/height
            if (origImage.getHeight() > Height || origImage.getWidth() > Width) {
                fHeight = Height;
                int wid = Width;
                float sum = (float)origImage.getWidth() / (float)origImage.getHeight();
                fWidth = Math.round(fHeight * sum);

                if (fWidth > wid) {
                    //rezise again for the width this time
                    fHeight = Math.round(wid/sum);
                    fWidth = wid;
                }
            }

            BufferedImage resizedImage = new BufferedImage(fWidth, fHeight, type);
            Graphics2D g = resizedImage.createGraphics();
            g.setComposite(AlphaComposite.Src);

            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            g.drawImage(origImage, 0, 0, fWidth, fHeight, null);
            g.dispose();

            ImageIO.write(resizedImage, "png", new File(destImg));

        } catch (IOException ex) {
         
            return false;
        }

        return true;
    }
}

JAVA SOURCE CODE FOR PIXEL WISE COMPARISON OF TWO IMAGES AND SHOWING PERCENTAGE SIMILARITY.


import java.io.*;
import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
class spe
{
  public static void main(String args[]) throws IOException{
long start = System.currentTimeMillis();
    File file= new File("p1.png");
    BufferedImage image = ImageIO.read(file);
 int width = image.getWidth(null);
    int height = image.getHeight(null);
int[][] clr=  new int[width][height];
File files= new File("p2.png");
    BufferedImage images = ImageIO.read(files);
 int widthe = images.getWidth(null);
    int heighte = images.getHeight(null);
int[][] clre=  new int[widthe][heighte];
int smw=0;
int smh=0;
int p=0;
//CALUCLATING THE SMALLEST VALUE AMONG WIDTH AND HEIGHT
if(width>widthe){ smw =widthe;}
else {smw=width;}
if(height>heighte){smh=heighte;}
else {smh=height;}
//CHECKING NUMBER OF PIXELS SIMILARITY
for(int a=0;a<smw;a++){
for(int b=0;b<smh;b++){
clre[a][b]=images.getRGB(a,b);
clr[a][b]=image.getRGB(a,b);
if(clr[a][b]==clre[a][b]) {p=p+1;}
}}

float w,h=0;
if(width>widthe) {w=width;}
else {w=widthe;}
if(height>heighte){ h = height;}
else{h = heighte;}
float s = (smw*smh);
//CALUCLATING PERCENTAGE
float x =(100*p)/s;

System.out.println("THE PERCENTAGE SIMILARITY IS APPROXIMATELY ="+x+"%");
long stop = System.currentTimeMillis();
System.out.println("TIME TAKEN IS ="+(stop-start));
  }
}



Java code for Folder Zipping


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FolderZiper {
  public static void main(String[] a) throws Exception {
    zipFolder("/home/java/Desktop/VirtLab", "/home/java/Desktop/zzz.zip");
  }

  static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
    ZipOutputStream zip = null;
    FileOutputStream fileWriter = null;

    fileWriter = new FileOutputStream(destZipFile);
    zip = new ZipOutputStream(fileWriter);

    addFolderToZip("", srcFolder, zip);
    zip.flush();
    zip.close();
  }

  static private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
      throws Exception {

    File folder = new File(srcFile);
    if (folder.isDirectory()) {
      addFolderToZip(path, srcFile, zip);
    } else {
      byte[] buf = new byte[1024];
      int len;
      FileInputStream in = new FileInputStream(srcFile);
      zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
      while ((len = in.read(buf)) > 0) {
        zip.write(buf, 0, len);
      }
    }
  }

  static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
      throws Exception {
    File folder = new File(srcFolder);

    for (String fileName : folder.list()) {
      if (path.equals("")) {
        addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
      } else {
        addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
      }
    }
  }
}

Java code for File Zipping


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class Filezip {

    public static void Zip(String source, String target) {
        try {
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target)));
            byte[] data = new byte[1000];
            int count;
            out.putNextEntry(new ZipEntry(target));
            BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(source));
            while ((count = buffer.read(data, 0, 1000)) != -1) {
                out.write(data, 0, count);
            }
             buffer.close();

            out.flush();
             out.close();
            System.out.println("file Zipped...");


        } catch (Exception e) {
            System.out.println("file not zipped...");
            e.printStackTrace();
        }

    }

}

embeding google map in html

  <iframe width="500" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=Central+Park,+New+York,+NY,+USA&amp;aq=0&amp;sll=14.093957,1.318359&amp;sspn=69.699334,135.263672&amp;vpsrc=6&amp;ie=UTF8&amp;hq=Central+Park,+New+York,+NY,+USA&amp;ll=40.778265,-73.96988&amp;spn=0.033797,0.06403&amp;t=m&amp;output=embed">
</iframe>

javascript Email validation using regular Expression

 
<script>
var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
var email=document.getElementById("email").value;
    if(email.search(emailRegex)==-1) {
                    alert("You have entered an invalid email.");
                    return false;
                }

</script>

Difference b/w two dates


import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDifferentExample {

    public static void main(String[] args) {

        String dateStart = "10/10/2013";
        String dateStop = "02/10/2014";

        //HH converts hour in 24 hours format (0-23), day calculation
        SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");

        Date d1 = null;
        Date d2 = null;

        try {
            d1 = format.parse(dateStart);
            d2 = format.parse(dateStop);
            //in milliseconds
            long diff = d2.getTime() - d1.getTime();
            long diffSeconds = diff / 1000 % 60;
            long diffMinutes = diff / (60 * 1000) % 60;
            long diffHours = diff / (60 * 60 * 1000) % 24;
            long diffDays = diff / (24 * 60 * 60 * 1000);
            System.out.print(diffDays + " days, "+diffHours + " hours, "+diffMinutes + " minutes, "+diffSeconds + " seconds ");
       
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Add Days To Current Date


import java.util.Calendar;

public class AddDaysToCurrentDate {

    public static void main(String[] args) {
        Calendar now = Calendar.getInstance();

        System.out.println("Current date : " + now.get(Calendar.DATE)
                + "-"
                + (now.get(Calendar.MONTH)+1)
                + "-"
                + now.get(Calendar.YEAR));

        //add days to current date using Calendar.add method
        now.add(Calendar.DATE, 5);

       System.out.println("Day after one day : " + now.get(Calendar.DATE)
                + "-"
                + (now.get(Calendar.MONTH)+1)
                + "-"
                + now.get(Calendar.YEAR));

        //substract days from current date using Calendar.add method
        now = Calendar.getInstance();
        now.add(Calendar.DATE, -10);


          System.out.println("date before 10 days :" + now.get(Calendar.DATE)
                + "-"
                + (now.get(Calendar.MONTH)+1)
                + "-"
                + now.get(Calendar.YEAR));
    }
}

Getting the Day from a given Date

import java.util.*;
import java.text.*;

class CheckDay {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter date(1-31):");
        int dd = input.nextInt();
        System.out.println("Enter month(1-12): ");
        int month = input.nextInt() - 1;
        System.out.println("Enter year: ");
        int year = input.nextInt();
        Date date = (new GregorianCalendar(year, month, dd)).getTime();
        SimpleDateFormat f = new SimpleDateFormat("EEEE");
        String day = f.format(date);
        System.out.println(day);
    }
}

Windows Command for incoming IP blocking--Java Code

//blocking.... 

Runtime r = Runtime.getRuntime();
Process p = r.exec("netsh advfirewall firewall add rule name=abc action=block remoteip=any dir=in");


//unblocking...

 Runtime r = Runtime.getRuntime();
 Process p = r.exec("netsh advfirewall firewall delete rule name=abc remoteip=any");

//to turn on windows firewall

 Runtime r = Runtime.getRuntime();
 Process p = r.exec("netsh firewall set opmode enable");


//to turn off windows firewall

 Runtime r = Runtime.getRuntime();
 Process p = r.exec("netsh firewall set opmode disable");