Wednesday, 6 June 2012

write a sample code for Date And Time in java?



Description:java provides the Date class available in java.util package, this class encapsulates the current date and time.

The Date class supports two constructors. The first constructor initializes the object with the current date and time.

Date( )

The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, january 1 1990

Date(long millisec)

Once you have a Date object available, you can call any of the following support methods to play with dates:

Boolean after(Date date)
Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false.
    boolean before(Date date)
Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false.
    Object clone( )
Duplicates the invoking Date object.
    int compareTo(Date date)
Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date.
    int compareTo(Object obj)
Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException.
    boolean equals(Object date)
Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false.
    long getTime( )
Returns the number of milliseconds that have elapsed since January 1, 1970.
    int hashCode( )
Returns a hash code for the invoking object.
    void setTime(long time)
Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970
    String toString( )
Converts the invoking Date object into a string and returns the result.

import java.util.Date;
 
class DateDemo {
   public static void main(String args[]) {
       // Instantiate a Date object
       Date date = new Date();
      
       // display time and date using toString()
       System.out.println(date.toString());
   }
}

out put:

Thur june 07 09:51:52 CDT 2012


Tuesday, 5 June 2012

write a code for Java - Sending Email

To send an email using your Java Application is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine.

Send a Simple Email:

Here is an example to send a simple email from your machine. Here it is assumed that your localhost is connected to the internet and capable enough to send an email.

// File Name SendEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail
{
   public static void main(String [] args)
   {
     
      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compile and run this program to send a simple email:

$ java SendEmail
Sent message successfully....

Monday, 4 June 2012

java developer Eclipse Shortcuts


Editors are an integral part of a programmer’s life. If you have good proficiency in using an editor thats a great advantage. It comes very handy to debug. Traditional notepad and SOPs (System.out.println) are the way we start learning a language but that is not sufficient, so beginners start using an IDE and most importantly know the shortcuts.

For java developers there is a huge list and some popular areEclipse, Netbeans, IntelliJ Idea. I use Eclipse as my IDE and vim as a light weight editor.


File Navigation – Eclipse Shortcuts

    CTRL SHIFT R – Open a resource. You need not know the path and just part of the file name is enough.
    CTRL E – Open a file (editor) from within the list of all open files.
    CTRL PAGE UP or PAGE DOWN – Navigate to previous or next file from within the list of all open files.
    ALT <- or ALT -> – Go to previous or next edit positions from editor history list.

Java Editing – Eclipse Shortcuts

    CTRL SPACE – Type assist
    CTRL SHIFT F – Format code.
    CTRL O – List all methods of the class and again CTRL O lists including inherited methods.
    CTRL SHIFT O – Organize imports.
    CTRL SHIFT U – Find reference in file.
    CTRL / – Comment a line.
    F3 – Go to the declaration of the variable.
    F4 – Show type hierarchy of on a class.
    CTRL T – Show inheritance tree of current token.
    SHIFT F2 – Show Javadoc for current element.
    ALT SHIFT Z – Enclose block in try-catch.

General Editing – Eclipse Shortcuts

    F12 – Focus on current editor.
    CTRL L – Go to line number.
    CTRL D – Delete a line.
    CTRL <- or -> – Move one element left or right.
    CTRL M – Maximize editor.
    CTRL SHIFT P – Go to the matching parenthesis.

Debug, Run – Eclipse Shortcuts

    CTRL . or , – Navigate to next or previous error.
    F5 – Step into.
    F6 – Step over.
    F8 – Resume
    CTRL Q – Inspect.
    CTRL F11 – Run last run program.
    CTRL 1 – Quick fix code.

Search – Eclipse Shortcuts

    CTRL SHIFT G – Search for current cursor positioned word reference in workspace
    CTRL H – Java search in workspace.

Sunday, 3 June 2012

java List and Queue Interface

List Interface :

The List interface extends the Collection interface to define an ordered collection. It is also known as the sequence collection which permits duplicates element to accommodate in  the set but does not map a key value to an object. It permits one or more elements to be null.

This interface adds position-oriented operations such as insert an element, get an element as well as remove or change an element based on their numerical position in the list. It also performs search operation to allow searching a specified object in the list and returns its numerical position.

In addition to methods of  the Set interface, it provides following three methods shown in the table below:

get( ) Returns the element at the specified index position in this collection

listIterator( ) Returns a List Iterator object for the collection which may then be used to retrieve an object

Queue Interface:

A Queue interface extends the Collection interface to define an ordered collection for holding elements  in a FIFO (first-in-first-out) manner to process them i.e. in a FIFO queue the element that is inserted firstly will also get removed  first.

Besides basic collection operations, queues also provide additional operations such as insertion, removal, and inspection .
The Methods of this interface are as follows.

peek( ) Returns an element but if queue is empty then it returns null

 poll( )  Removes an element but returns null if the queue is empty.


implementation-classes:

ArrayList
LinkedList
RunArrayList


import java.util.*;

public class ListQueueDemo {
  public static void main(String args[]) {
  int numbers[]={34, 22,10,60,30};
 List <Integer>list = new ArrayList<Integer>();
  try{
  for(int i=0; i<5; i++){
  list.add(numbers[i]);
  }
  System.out.println("the List is: ");
  System.out.println(list);
  LinkedList <Integer>queue = new LinkedList<Integer>();
  for(int i=0; i<5; i++){
  queue.addFirst(numbers[i]);
  }
  System.out.println("The Oueue is: ");
 System.out.println(queue);
  queue.removeLast();
  System.out.println("After removing last element the queue is: "+ queue);
 
  }
  catch(Exception e){}
  }
}

Friday, 1 June 2012

How to Parse JSON in Java

Use json-lib, a library which adds JSON support to any Java program. json-lib can take a String and turn it into a JSONObject which can then be used to retrieve specific attributes.

1. Add this dependency to your project:

<dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.3</version>
      <scope>compile</scope>
    </dependency>





What does this mean? See How to Add a Dependency to a Java Project

2. Put the following JSON sample in your classpath:

{'foo':'bar',
 'coolness':2.0,
 'altitude':39000,
 'pilot':{'firstName':'Buzz',
          'lastName':'Aldrin'},
 'mission':'apollo 11'}



3. Load the resource from the classpath and parse this JSON as follows:

package com.discursive.answers;

import java.io.InputStream;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.apache.commons.io.IOUtils;

public class JsonParsing {

    public static void main(String[] args) throws Exception {
        InputStream is =
                JsonParsing.class.getResourceAsStream( "sample-json.txt");
        String jsonTxt = IOUtils.toString( is );
       
        JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );       
        double coolness = json.getDouble( "coolness" );
        int altitude = json.getInt( "altitude" );
        JSONObject pilot = json.getJSONObject("pilot");
        String firstName = pilot.getString("firstName");
        String lastName = pilot.getString("lastName");
       
        System.out.println( "Coolness: " + coolness );
        System.out.println( "Altitude: " + altitude );
        System.out.println( "Pilot: " + lastName );
    }
}



Note that JSONSerializer returns a JSON object. This is a general object which could be a JSONObject or a JSONArray depending on the JSON you are trying to parse. In this example, since I know that the JSON is a JSONObject, I can cast the result directly to a JSONObject. If you are dealing with JSON that could return a JSONArray, you'll likely want to check the type of the object that is returned by toJSON.

Thursday, 31 May 2012

JAVA TOOLS :


Lack of imagination is one of our worst sins as software developers. We do the same things over and over again, but we rarely modify our ways - me at least. After some years, these are the tools that made it into my tricks box for everyday tasks. Tiresome operations are not my thing.

Chances are you are already using at least some of these, but here we go anyways:

StringUtils


The bread and butter of the commons-lang library, this utility class includes some methods that should seriously have been included in String long time ago.


StringUtils.isEmpty(null) && StringUtils.isEmpty(""); // true
StringUtils.isBlank("   \n\t");                       // true
StringUtils.substringAfterLast("foo.bar.baz", ".");   // "baz"
StringUtils.substringBeforeLast("foo.bar.baz", ".");  // "foo.bar"
StringUtils.split("foo.bar.baz", '.');                // { "foo", "bar", "baz" }
StringUtils.split("foo,  bar,baz", ", ");             // { "foo", "bar", "baz" }
StringUtils.leftPad("1", 3, '0');                     // "001"



IOUtils and FileUtils


A must-have for the rare occasions where you need to manipulate files by hand. Both are pretty much alike (FileUtils for File, IOUtils for InputStream and Reader classes) and come bundled in commons-io.


File file1;
File file2;
InputStream inputStream;
OutputStream outputStream;

// copy one file into another
FileUtils.copyFile(file1, file2);
IOUtils.copy(inputStream, outputStream);

// read a file into a String
String s1 = FileUtils.readFileToString(file1);
String s2 = IOUtils.toString(inputStream);

// read a file into a list of Strings, one item per line
List<String> l1 = FileUtils.readLines(file1);
List<String> l2 = IOUtils.readLines(inputStream);

// put this in your finally() clause after manipulating streams
IOUtils.closeQuietly(inputStream);

// return the list of xml and text files in the specified folder and any subfolders
Collection<File> c1 = FileUtils.listFiles(file1, { "xml", "txt" }, true);

// copy one folder and its contents into another
FileUtils.copyDirectoryToDirectory(file1, file2);

// delete one folder and its contents
FileUtils.deleteDirectory(file1);



Google collections


This is the best implementation of a collections extension that I know of. Some of these are shouting to be included in the JDK:


// create an ArrayList with three arguments
List<String> list = Lists.newArrayList("foo", "bar", "baz");

// notice that there is no generics or class cast,
// and still this line does not generate a warning.
Set<String> s = Sets.newConcurrentHashSet();

// intersect and union are basic features of a Set, if you ask me
Set<String> s = Sets.intersect(s1, s2);

// Example  of multiple values in a Map
ListMultimap<String, Validator> validators = new ArrayListMultimap<String, Validator>();
validators.put("save", new RequiredValidator());
validators.put("save", new StringValidator());
validators.put("delete", new NumberValidator());

validators.get("save"); // { RequiredValidator, StringValidator }
validators.get("foo");  // empty List (not null)
validators.values();    // { RequiredValidator, StringValidator, NumberValidator }



java.util.concurrent


Not everybody needs the heavy lifting of java.util.concurrent, but the concurrent collections are handy:


// a map that may be modified (by the same or different thread) while being iterated
Map<String, Something> repository = new ConcurrentHashMap<String, Something>();

// same with lists. This one is only available with Java 6
List<Something> list = new CopyOnWriteArrayList<Something>();



Hardly a large toolbox, is it? If your favourite library is missing, feel free to add it :)

Wednesday, 30 May 2012

ANDROID MOBLIE Taking Photos Simply

Suppose you are implementing a crowd-sourced weather service that makes a global weather map by blending together pictures of the sky taken by devices running your client app. Integrating photos is only a small part of your application. You want to take photos with minimal fuss, not reinvent the camera. Happily, most Android-powered devices already have at least one camera application installed. In this lesson, you learn how to make it take a picture for you.
If an essential function of your application is taking pictures, then restrict its visibility on Google Play to devices that have a camera. To advertise that your application depends on having a camera, put a <uses-feature> tag in your manifest file:

<manifest ... >
    <uses-feature android:name="android.hardware.camera" />
    ...
</manifest ... >

If your application uses, but does not require a camera in order to function, add android:required="false" to the tag. In doing so, Google Play will allow devices without a camera to download your application. It's then your responsibility to check for the availability of the camera at runtime by calling hasSystemFeature(PackageManager.FEATURE_CAMERA). If a camera is not available, you should then disable your camera features.
Take a Photo with the Camera App

The Android way of delegating actions to other applications is to invoke an Intent that describes what you want done. This process involves three pieces: The Intent itself, a call to start the external Activity, and some code to handle the image data when focus returns to your activity.

Here's a function that invokes an intent to capture a photo.

private void dispatchTakePictureIntent(int actionCode) {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(takePictureIntent, actionCode);
}

Congratulations: with this code, your application has gained the ability to make another camera application do its bidding! Of course, if no compatible application is ready to catch the intent, then your app will fall down like a botched stage dive. Here is a function to check whether an app can handle your intent:

public static boolean isIntentAvailable(Context context, String action) {
    final PackageManager packageManager = context.getPackageManager();
    final Intent intent = new Intent(action);
    List<ResolveInfo> list =
            packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}


View the Photo

If the simple feat of taking a photo is not the culmination of your app's ambition, then you probably want to get the image back from the camera application and do something with it.

The Android Camera application encodes the photo in the return Intent delivered to onActivityResult() as a small Bitmap in the extras, under the key "data". The following code retrieves this image and displays it in an ImageView.

private void handleSmallCameraPhoto(Intent intent) {
    Bundle extras = intent.getExtras();
    mImageBitmap = (Bitmap) extras.get("data");
    mImageView.setImageBitmap(mImageBitmap);
}

Note: This thumbnail image from "data" might be good for an icon, but not a lot more. Dealing with a full-sized image takes a bit more work.
Save the Photo

The Android Camera application saves a full-size photo if you give it a file to save into. You must provide a path that includes the storage volume, folder, and file name.

There is an easy way to get the path for photos, but it works only on Android 2.2 (API level 8) and later:


storageDir = new File(
    Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES
    ),
    getAlbumName()
);             

For earlier API levels, you have to provide the name of the photo directory yourself.


storageDir = new File (
    Environment.getExternalStorageDirectory()
        + PICTURES_DIR
        + getAlbumName()
);

Note: The path component PICTURES_DIR is just Pictures/, the standard location for shared photos on the external/shared storage.