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.

Sunday, 27 May 2012

WEB SERVICES IN JAVA

SOA and net Services

What is Service-Oriented Architecture?

Service Oriented design or SOA for brief may be a new design for the event of loosely coupled distributed applications. in reality service-oriented design is assortment of the many services within the network. These services communicate with one another and also the communications involves knowledge exchange & even service coordination. Earlier SOA was primarily based on the DCOM or Object Request Brokers (ORBs). these days SOA relies on the online Services.

Broadly SOA is classified into 2 terms: Services and Connections.



Services:

A service may be a operate or some processing logic or business processing that's well-defined, self-contained, and doesn't rely upon the context or state of different services. Example of Services are Loan Processing Services, which might be self-contained unit for method the Loan  Applications. different example could also be Weather Services, which might be used to urge the weather data. Any application on the network will use the service of the Weather Service to urge the weather data.

Connections:

Connections suggests that the link connecting these self-contained distributed services with one another, it enable shopper to Services communications. In case of net services SOAP over HTTP is employed to speak the between services.

The following figure may be a typical example of the service-oriented design. It shows how a service shopper sends a service request to a service supplier. once accepting the request, service supplier send a message to the service shopper. during this case a service supplier may be a service shopper.
Different Technologies Used:

SOA is far totally different from point-to-point architectures. SOA comprise loosely coupled, highly interoperable application services. These services is developed in several development technologies (such as Java, .NET, C++, PERL, PHP), the software elements become terribly reusable i.e. identical C# (C Sharp) service could also be employed by a Java application and / or the other programming language. WSDL defines an commonplace, that encapsulates / hides the seller / language specific implementation from the calling shopper / service.


Why SOA?

SOA design allows seamless Enterprise data Integration. Here are a number of the advantages of the Service Oriented Architecture:

 thanks to its platform independence, it permits firms to use the software and hardware of their alternative .
 there's no threat of vendor lock-in
    SOA allows incremental development, deployment, and maintenance.
 firms will use the prevailing software (investments) and use SOA to make applications while not replacing existing applications
    The coaching prices are low, therefore the obtainable labor pool is used for running the applications

Saturday, 26 May 2012

common Errors happen in java

Mistyping the name of a method when overriding

Overriding allows programmers to replace a method's implementation with new code. Overriding is a handy feature, and most OO programmers make heavy use of it. If you use the AWT 1.1 event handling model, you'll often override listener implementations to provide custom functionality. One easy trap to fall into with overriding, is to mistype the method name. If you mistype the name, you're no longer overriding a method - you're creating an entirely new method, but with the same parameter and return type.

public class MyWindowListener extends WindowAdapter {
    // This should be WindowClosed
    public void WindowClose(WindowEvent e) {
        // Exit when user closes window
        System.exit(0);
    }
});

Compilers won't pick up on this one, and the problem can be quite frustrating to detect. In the past, I've looked at a method, believed that it was being called, and taken ages to spot the problem. The symptom of this error will be that your code isn't being called, or you think the method has skipped over its code. The only way to ever be certain is to add a println statement, to record a message in a log file, or to use good trace debugger (like Visual J++ or Borland JBuilder) and step through line by line. If your method still isn't being called, then it's likely you've mistyped the name.



 Comparison assignment (  = rather than == )

This is an easy error to make. If you're used other languages before, such as Pascal, you'll realize just how poor a choice this was by the language's designers. In Pascal, for example, we use the := operator for assignment, and leave = for comparison. This looks like a throwback to C/C++, from which Java draws its roots.

Fortunately, even if you don't spot this one by looking at code on the screen, your compiler will. Most commonly, it will report an error message like this : "Can't convert xxx to boolean", where xxx is a Java type that you're assigning instead of comparing.



 Comparing two objects ( == instead of .equals)

When we use the == operator, we are actually comparing two object references, to see if they point to the same object. We cannot compare, for example, two strings for equality, using the == operator. We must instead use the .equals method, which is a method inherited by all classes from java.lang.Object.

Here's the correct way to compare two strings.

String abc = "abc"; String def = "def";

// Bad way
if ( (abc + def) == "abcdef" )
{
    ......
}

// Good way
if ( (abc + def).equals("abcdef") )
{
   .....
}

Thursday, 24 May 2012

Preventing concurrent access to shared variables by threads


When writing multi-threaded applications, many programmers (myself included) often cut corners, and leave their applications and applets vulnerable to thread conflicts. When two or more threads access the same data concurrently, there exists the possibility (and Murphy's law holding, the probability) that two threads will access or modify the same data at the same time. Don't be fooled into thinking that such problems won't occur on single-threaded processors. While accessing some data (performing a read), your thread may be suspended, and another thread scheduled. It writes its data, which is then overwritten when the first thread makes its changes.

Such problems are not just limited to multi-threaded applications or applets. If you write Java APIs, or JavaBeans, then your code may not be thread-safe. Even if you never write a single application that uses threads, people that use your code WILL. For the sanity of others, if not yourself, you should always take precautions to prevent concurrent access to shared data.

How can this problem be solved? The simplest method is to make your variables private (but you do that already,  right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner. Take the following accessor methods, which provide a safe way to change the value of a counter.

public class MyCounter
{
private int count = 0; // count starts at zero

public synchronized void setCount(int amount)
count = amount;
}
public synchronized int getCount()
{
return count;
}
}



Capitalization errors

This is one of the most frequent errors that we all make. It's so simple to do, and sometimes one can look at an uncapitalized variable or method and still not spot the problem. I myself have often been puzzled by these errors, because I recognize that the method or variable does exist, but don't spot the lack of capitalization.

While there's no silver bullet for detecting this error, you can easily train yourself to make less of them. There's a very simple trick you can learn :-

    all methods and member variables in the Java API begin with lowercase letters
    all methods and member variables use capitalization where a new word begins e.g - getDoubleValue()

If you use this pattern for all of your member variables and classes, and then make a conscious effort to get it right, you can gradually reduce the number of mistakes you'll make. It may take a while, but it can save some serious head scratching in the future.

Wednesday, 23 May 2012

Java Enumeration and Iterators


Defenitions:
Set: an unordered array of elements or objects
Collection: an ordered set
1.Vectors already implement the Collection interface, but you can define your own Collection.
2.ArrayLists and Vectors, both support Iterators

Enumeration
An enumeration is an object that generates elements one at a time, used for passing through a collection, usually of unknown size.
The traversing of elements can only be done once per creation.

Enumeration’s have two options:
nextElement() which returns the next object in the collection
hasMoreElements() which returns true, until the last object has been returned by nextElement()

Code Example:
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
dayNames.add(“Sun”);
dayNames.add(“Mon”);
dayNames.add(“Tues”);
dayNames.add(“Wednes”);
dayNames.add(“Thurs”);
dayNames.add(“Fri”);
dayNames.add(“Satur”};
days = dayNames.elements();
while (days.hasMoreElements())
System.out.println(days.nextElement()); } }




Enumerations do not allow for the modification of the collection, which is being traversed, thus the Iterators are used if this is required.

Iterators have 3 options:
hasNext() returns true if there is another element in the collection
next() which returns the next object
remove() which removes the last object taken using next()

Tuesday, 22 May 2012

Most Common Bugs in Java

1. Null pointers

Null pointers are one of the most common errors that Java programmers make. Compilers can't check this one for you - it will only surface at runtime, and if you don't discover it, your users certainly will.

When an attempt to access an object is made, and the reference to that object is null, a NullPointerException will be thrown. The cause of null pointers can be varied, but generally it means that either you haven't initialized an object, or you haven't checked the return value of a function.

Many functions return null to indicate an error condition - but unless you check your return values, you'll never know what's happening. Since the cause is an error condition, normal testing may not pick it up - which means that your users will end up discovering the problem for you. If the API function indicates that null may be returned, be sure to check this before using the object reference!

Another cause is where your initialization has been sloppy, or where it is conditional. For example, examine the following code, and see if you can spot the problem.

public static void main(String args[])
{
    // Accept up to 3 parameters act in arguments we mentioned the number'3'


    String[] list = new String[3];

    int index = 0;

    while ( (index < args.length) && ( index < 3 ) )
    {
        list[index++] = args[index];
    }

    // Check all the parameters
    for (int i = 0; i < list.length; i++)
    {
        if (list[i].equals "-help")
        {
            // *.........*/
        }
        else
        if (list[i].equals "-cp")
        {
            // *.........*/
        }
        // *.........*/ else .....
    }   
}

This code (while a contrived example), shows a common mistake. Under some circumstances, where the user enters three or more parameters, the code will run fine. If no parameters are entered, you'll get a NullPointerException at runtime. Sometimes your variables (the array of strings) will be initialized, and other times they won't. One easy solution is to check BEFORE you attempt to access a variable in an array that it is not equal to null.

Monday, 21 May 2012

What are Servlets?

Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server.

Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.

Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.

    Performance is significantly better.

    Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request.

    Servlets are platform-independent because they are written in Java.

    Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted.

    The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.

Servlets Architecture:



Servlets Tasks:

Servlets perform the following major tasks:

    Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program.

    Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.

    Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly.

    Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.

    Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.

Servlets Packages:

Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification.

Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of the Java's enterprise edition, an expanded version of the Java class library that supports large-scale development projects.

These classes implement the Java Servlet and JSP specifications. At the time of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.

Java servlets have been created and compiled just like any other Java class. After you install the servlet packages and add them to your computer's Classpath, you can compile servlets with the JDK's Java compiler or any other current compiler.

Java - Streams, Files and I/O

The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters etc.

A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Java does provide strong, flexible support for I/O as it relates to files and networks but this tutorial covers very basic functionlity related to streams and I/O. We would see most commonly used example one by one:
Reading Console Input:

Java input console is accomplished by reading from System.in. To obtain a character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. Here is most common syntax to obtain BufferedReader:

BufferedReader br = new BufferedReader(new
                      InputStreamReader(System.in));

Once BufferedReader is obtained, we can use read( ) method to reach a character or readLine( ) method to read a string from the console.
Reading Characters from Console:

To read a character from a BufferedReader, we would read( ) method whose sytax is as follows:

int read( ) throws IOException

Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns .1 when the end of the stream is encountered. As you can see, it can throw an IOException.

The following program demonstrates read( ) by reading characters from the console until the user types a "q":

// Use a BufferedReader to read characters from the console.

import java.io.*;

class BRRead {
   public static void main(String args[]) throws IOException
   {
      char c;
      // Create a BufferedReader using System.in
      BufferedReader br = new BufferedReader(new
                         InputStreamReader(System.in));
      System.out.println("Enter characters, 'q' to quit.");
      // read characters
      do {
         c = (char) br.read();
         System.out.println(c);
      } while(c != 'q');
   }
}

Here is a sample run:

Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q

Reading Strings from Console:

To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. Its general form is shown here:

String readLine( ) throws IOException

The following program demonstrates BufferedReader and the readLine( ) method. The program reads and displays lines of text until you enter the word "end":

// Read a string from console using a BufferedReader.
import java.io.*;
class BRReadLines {
   public static void main(String args[]) throws IOException
   {
      // Create a BufferedReader using System.in
      BufferedReader br = new BufferedReader(new
                              InputStreamReader(System.in));
      String str;
      System.out.println("Enter lines of text.");
      System.out.println("Enter 'end' to quit.");
      do {
         str = br.readLine();
         System.out.println(str);
      } while(!str.equals("end"));
   }
}

Here is a sample run:

Enter lines of text.
Enter 'end' to quit.
This is line one
This is line one
This is line two
This is line two
end
end

Saturday, 19 May 2012

JAVA CODE FOR Getting Current Date & Time

This is very easy to get current date and time in Java. You can use a simple Date object with toString() method to print current date and time as follows:

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());
   }
}

output for this above code:

Mon May 19 09:51:52 CDT 2012



Simple DateFormat format codes:

To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following:

Character    Description    Example

G             Era designator             AD
y             Year in four digits    2001
M            Month in year            July or 07
d             Day in month            10
h            Hour in A.M./P.M. (1~12) 12
H            Hour in day (0~23)    22
m            Minute in hour    30
s              Second in minute    55
S              Millisecond    234
E             Day in week    Tuesday
D              Day in year    360
F           Day of week in month    2 (second Wed. in July)
w             Week in year    40
W              Week in month    1
a            A.M./P.M. marker    PM
k            Hour in day (1~24)    24
K            Hour in A.M./P.M. (0~11)    10
z               Time zone    Eastern Standard Time
'            Escape for text    Delimiter
"         Single quote    `

Thursday, 17 May 2012

Java - Encapsulation


Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
Example:

Let us look at an example that depicts encapsulation:

/* File name : EncapTest.java */
public class EncapTest{

   private String name;
   private String idNum;
   private int age;

   public int getAge(){
      return age;
   }

   public String getName(){
      return name;
   }

   public String getIdNum(){
      return idNum;
   }

   public void setAge( int newAge){
      age = newAge;
   }

   public void setName(String newName){
      name = newName;
   }

   public void setIdNum( String newId){
      idNum = newId;
   }
}

The public methods are the access points to this class.s fields from the outside java world. Normally these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters.

The variables of the EncapTest class can be access as below::

/* File name : RunEncap.java */
public class RunEncap{

   public static void main(String args[]){
      EncapTest encap = new EncapTest();
      encap.setName("James");
      encap.setAge(20);
      encap.setIdNum("12343ms");

      System.out.print("Name : " + encap.getName()+
                             " Age : "+ encap.getAge());
    }
}

This would produce following result:

Name : James Age : 20

Benefits of Encapsulation:

    The fields of a class can be made read-only or write-only.

    A class can have total control over what is stored in its fields.

    The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.

Wednesday, 16 May 2012

How To Create an Executable jar File

In Java, it is common to combine several classes in one file  .jar ("java archive") file.  Library classes are stored that way.  Larger projects (such as the Case Study in the AP program) use jar files.  You can create your own jar file combining several classes, too.

jar files are created using the jar.exe utility program from JDK.  You can make your jar file runnable by saying that jar.exe which class has main.  To do that, you first need to create a manifest file.  A manifest is a one-line text file with a "Main-Class" directive.  For example:

Main-Class: Viaworld

This line must end with a newline.

A jar file created with a main class manifest can be used both as a library and a runnable jar.  If you use it as a library, you can edit and compile any of the classes included in the jar, and add it to your project.  Then it will override the one in the jar file.

You can create a manifest file in any text editor, or even by using the MS-DOS echo command.  You can give your manifest file any name, but it’s better to use something standard, such as manifest.txt.

Once you have a manifest and all your classes have been compiled, you need to run JDK’s jar.exe utility.  It is located in the JDK’s bin folder, the same place where javac.exe and java.exe. are.  jar.exe takes command-line arguments; if you run it without any arguments, it will display the usage information and examples.  You need

C\myprog> jar cvfm MyJarName.jar manifest.txt *.class

cvfm means "create a jar; show verbose output; specify the output jar file name; specify the manifest file name."  This is followed by the name you wish to give to your jar file, the name of your manifest file, and the list of .class files that you want included in the jar.  *.class means all class files in the current directory.

Below are the detailed steps for doing this in Command Prompt and in JCreator.
Creating a jar File in JCreator
You can configure a "tool" that will automate the jar creation process.  You only need to do it once.

    Click on Configure/Options.
    Click on Tools in the left column.
    Click New, and choose Create Jar file.
    Click on the newly created entry Create Jar File in the left column under Tools.
    Edit the middle line labeled Arguments: it should have

    cvfm $[PrjName].jar manifest.txt *.class

    Click OK.

Now set up a project for your program, create a manifest file manifest.txt or copy and edit an existing one.  Place manifest.txt in the same folder where the .class files go.  Under View/Toolbars check the Tools toolbar.  Click on the corresponding tool button or press Ctrl-1 (or Ctrl-n if this is the n-th tool) to run the Create Jar File tool.

With Windows Explorer, go to the jar file that you just created and double click on it to run.
Creating a jar File in Command Prompt

    Start Command Prompt.
    Navigate to the folder that holds your class files:

    C:\>cd \myprog

    Set path to include JDK’s bin.  For example:

    C:\myprog> path c:\Program Files\Java\jdk1.5.0_09\bin;%path%

    Compile your class(es):

    C:\myprog> javac *.java

    Create a manifest file:

    C:\myprog> echo Main-Class: Viaworld>manifest.txt

    Create a jar file:

    C:\myprog> jar cvfm Viaworld.jar manifest.txt *.class

    Test your jar:

    C:\myprog> Viaworld.jar

Tuesday, 15 May 2012

How to write a Code For Fibonacci in java



logic For Fibonacci
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34
fib(10) = 55


import java.io.*;
class Fibonacci {

 public static void main(String args[]) {
 System.out.println("How many numbers of the sequence would you like?");
    InputStreamReader sr = new InputStreamReader(System.in);
    BufferedReader br    = new BufferedReader(sr);
 try {
      String input = br.readLine();
      int n = Integer.valueOf(input).intValue();
      fibonacci(n);
    } catch (NumberFormatException e){
      System.out.println("That is no integer. Please enter an integer value only");
    } catch (IOException e) {
      System.out.println("I did not recieve an input");
    }
  }

public static void fibonacci(int n){
    int a=0,b=1;

    for (int i=0;i<n;i++){
      System.out.println(a);
      a=a+b;
      b=a-b;
    }
  }
}

Monday, 14 May 2012

XML and Java - Parsing XML using

Parsing XML
If you are a beginner to XML using Java then this is the perfect sample to parse a XML file create Java Objects and manipulate them.

The idea here is to parse the employees.xml file with content as below

<?xml version="1.0" encoding="UTF-8"?>
<Personnel>
  <Employee type="permanent">
        <Name>Seagull</Name>
        <Id>3674</Id>
        <Age>34</Age>
   </Employee>
  <Employee type="contract">
        <Name>Robin</Name>
        <Id>3675</Id>
        <Age>25</Age>
    </Employee>
  <Employee type="permanent">
        <Name>Crow</Name>
        <Id>3676</Id>
        <Age>28</Age>
    </Employee>
</Personnel>

From the parsed content create a list of Employee objects and print it to the console. The output would be something like


Employee Details - Name:Seagull, Type:permanent, Id:3674, Age:34.
Employee Details - Name:Robin, Type:contract, Id:3675, Age:25.
Employee Details - Name:Crow, Type:permanent, Id:3676, Age:28.

We will start with a DOM parser to parse the xml file, create Employee value objects and add them to a list. To ensure we parsed the file correctly let's iterate through the list and print the employees data to the console. Later we will see how to implement the same using SAX parser.
In a real world situation you might get a xml file from a third party vendor which you need to parse and update your database.

Using DOM
    This program DomParserExample.java uses DOM API.

The steps are

    Get a document builder using document builder factory and parse the xml file to create a DOM object
    Get a list of employee elements from the DOM
    For each employee element get the id, name, age and type. Create an employee value object and add it to the list.
    At the end iterate through the list and print the employees to verify we parsed it right.

a) Getting a document builder

    private void parseXmlFile(){
        //get the factory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {

            //Using factory get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();

            //parse using builder to get DOM representation of the XML file
            dom = db.parse("employees.xml");


        }catch(ParserConfigurationException pce) {
            pce.printStackTrace();
        }catch(SAXException se) {
            se.printStackTrace();
        }catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }


b) Get a list of employee elements
Get the rootElement from the DOM object.From the root element get all employee elements. Iterate through each employee element to load the data.


    private void parseDocument(){
        //get the root element
        Element docEle = dom.getDocumentElement();

        //get a nodelist of
 elements
        NodeList nl = docEle.getElementsByTagName("Employee");
        if(nl != null && nl.getLength() > 0) {
            for(int i = 0 ; i < nl.getLength();i++) {

                //get the employee element
                Element el = (Element)nl.item(i);

                //get the Employee object
                Employee e = getEmployee(el);

                //add it to list
                myEmpls.add(e);
            }
        }
    }

c) Reading in data from each employee.


    /**
     * I take an employee element and read the values in, create
     * an Employee object and return it
     */
    private Employee getEmployee(Element empEl) {

        //for each <employee> element get text or int values of
        //name ,id, age and name
        String name = getTextValue(empEl,"Name");
        int id = getIntValue(empEl,"Id");
        int age = getIntValue(empEl,"Age");

        String type = empEl.getAttribute("type");

        //Create a new Employee with the value read from the xml nodes
        Employee e = new Employee(name,id,age,type);

        return e;
    }


    /**
     * I take a xml element and the tag name, look for the tag and get
     * the text content
     * i.e for <employee><name>John</name></employee> xml snippet if
     * the Element points to employee node and tagName is 'name' I will return John
     */
    private String getTextValue(Element ele, String tagName) {
        String textVal = null;
        NodeList nl = ele.getElementsByTagName(tagName);
        if(nl != null && nl.getLength() > 0) {
            Element el = (Element)nl.item(0);
            textVal = el.getFirstChild().getNodeValue();
        }

        return textVal;
    }


    /**
     * Calls getTextValue and returns a int value
     */
    private int getIntValue(Element ele, String tagName) {
        //in production application you would catch the exception
        return Integer.parseInt(getTextValue(ele,tagName));
    }

d) Iterating and printing.


    private void printData(){

        System.out.println("No of Employees '" + myEmpls.size() + "'.");

        Iterator it = myEmpls.iterator();
        while(it.hasNext()) {
            System.out.println(it.next().toString());
        }
    }

Using the Java plugin in Firefox


Warning: there is a vulnerability in older versions of Java, which allows malicious website to gain control over your computer. Firefox versions block this to protect you. To Java to work again, to open the Java plugin.

Many pages use Java for Interactive content to your online game. Before Firefox can run Java do Java plugin must be installed correctly and enabled. Java is the language of the court runs on Windows, Mac, Linux, and computer system. This article will help you install or update Java and it works in Firefox.

    Java is not the same thing as JavaScript (this article for information about JavaScript).
Testing Java

A number of online tools for you if Java is installed and enabled on Firefox.

    You can visit the Java test page at java.com.
    You can visit the Information page in the Java BrowserSpy.dk.
    Java MAT includes links to verify your Java version and whether Java is enabled.

Enable Java

If Java is not working, make sure that the Java plugin is enabled in the Add-ons Manager tab:

    In the top of the Firefox window, click on the Firefox Button (template in Windows XP), and then click on the Add-ons. Add-ons Manager tab is opened.
    In the Add-ons Manager tab, select the Plugins panel.
    Click on the Java (TM) platform plugin to read it.
    Click the Enable Button (if it says Disable Java is already enabled).

Note: You need only to your "Java (TM) platform," plugin, if it is disabled. In the "Java Toolkit to provide" Java plugin from here to identify your version of Java and Java applications to use and is not enabled for Java to work.
The other software that may block Java

If we were able to in Java installed Firefox and Firefox Add-ons or other software that may be hindered by:

    The ZoneAlarm Pro Firewall can block Java. For more information on the Java through this program, see the ZoneAlarm Pro forum.

    The NoScript extension for Firefox will block Java. For more information, see the NoScript FAQ

Installing or updating Java
Manual install or update

    The download page at java.com.
    Click on the Free Java Download and more.
    Take it to download and click the Start Free Download Java installer to your computer.
    After the user is finished, close Firefox.
    To open the file you downloaded to start the Java installation.

Automatic Update

Java for Windows includes a Java Update feature in Windows 2000 and later, periodically checks for updates and notifies you when the update is available for installation.
Note: To eliminate potential safety problems and to save disk space, you remove any older Java versions that are still installed. It's java.com.

Friday, 11 May 2012

How To connect sql server to java application


package com.javacodegeeks.snippets.core;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectToSQLServer {

  public static void main(String[] args) {

    Connection connection = null;
    try {
        // Load the NetDirect JDBC driver
        String driverName = "com.jnetdirect.jsql.JSQLDriver";
        Class.forName(driverName);

        // Create a connection to the database
        String serverName = "localhost";
        String serverPort = "1433";
        String database = serverName + ":" + serverPort;
        String url = "jdbc:JSQLConnect://" + database;
        String username = "username";
        String password = "password";
        connection = DriverManager.getConnection(url, username, password);
       
        System.out.println("Successfully Connected to the database!");
       
    } catch (ClassNotFoundException e) {
        System.out.println("Could not find the database driver " + e.getMessage());
    } catch (SQLException e) {
        System.out.println("Could not connect to the database " + e.getMessage());
    }

 }

}


Output:

Successfully Connected to the database!

hOW TO Create an new Android Project

An Android project contains all the files that comprise the source code for your Android app. The Android SDK tools make it easy to start a new Android project with a set of default project directories and files.

This lesson shows how to create a new project either using Eclipse (with the ADT plugin) or using the SDK tools from a command line.

Note: You should already have the Android SDK installed, and if you're using Eclipse, you should have installed the ADT plugin as well. If you have not installed these, see Installing the Android SDK and return here when you've completed the installation.

Create a Project with Eclipse

Figure 1. The new project wizard in Eclipse.

    In Eclipse, select File > New > Project. The resulting dialog should have a folder labeled Android. (If you don’t see the Android folder, then you have not installed the ADT plugin—see Installing the ADT Plugin).
    Open the Android folder, select Android Project and click Next.
    Enter a project name (such as "MyFirstApp") and click Next.
    Select a build target. This is the platform version against which you will compile your app.

    We recommend that you select the latest version possible. You can still build your app to support older versions, but setting the build target to the latest version allows you to easily optimize your app for a great user experience on the latest Android-powered devices.

    If you don't see any built targets listed, you need to install some using the Android SDK Manager tool. See step 4 in the installing guide.

    Click Next.
    Specify other app details, such as the:
        Application Name: The app name that appears to the user. Enter "My First App".
        Package Name: The package namespace for your app (following the same rules as packages in the Java programming language). Your package name must be unique across all packages installed on the Android system. For this reason, it's important that you use a standard domain-style package name that’s appropriate to your company or publisher entity. For your first app, you can use something like "com.example.myapp." However, you cannot publish your app using the "com.example" namespace.
        Create Activity: This is the class name for the primary user activity in your app (an activity represents a single screen in your app). Enter "MyFirstActivity".
        Minimum SDK: Select 4 (Android 1.6).

        Because this version is lower than the build target selected for the app, a warning appears, but that's alright. You simply need to be sure that you don't use any APIs that require an API level greater than the minimum SDK version without first using some code to verify the device's system version (you'll see this in some other classes).

    Click Finish.

Your Android project is now set up with some default files and you’re ready to begin building the app

Thursday, 10 May 2012

java hash Code


While the Java language does not provide direct support for associative arrays -- arrays that can take any object as an index -- the presence of the hashCode() method in the root Object class clearly anticipates the ubiquitous use of HashMap (and its predecessor, Hashtable). Under ideal conditions, hash-based containers offer both efficient insertion and efficient retrieval; supporting hashing directly in the object model facilitates the development and use of hash-based containers.

Defining equality

The Object class has two methods for making inferences about an object's identity: equals() and hashCode(). In general, if you override one of these methods, you must override both, as there are important relationships between them that must be maintained. In particular, if two objects are equal according to the equals() method, they must have the same hashCode() value (although the reverse is not generally true).

The semantics of equals() for a given class are left to the implementer; defining what equals() means for a given class is part of the design work for that class. The default implementation, provided by Object, is simply reference equality:

  public boolean equals(Object obj) {
    return (this == obj);
  }


Under this default implementation, two references are equal only if they refer to the exact same object. Similarly, the default implementation of hashCode() provided by Object is derived by mapping the memory address of the object to an integer value. Because on some architectures the address space is larger than the range of values for int, it is possible that two distinct objects could have the same hashCode(). If you override hashCode(), you can still use the System.identityHashCode() method to access this default value.

Overriding equals() -- a simple example

An identity-based implementation for equals() and hashCode() is a sensible default, but for some classes, it is desirable to relax the definition of equality somewhat. For example, the Integer class defines equals() similarly to this:

  public boolean equals(Object obj) {
    return (obj instanceof Integer
            && intValue() == ((Integer) obj).intValue());
  }


Under this definition, two Integer objects are equal only if they contain the same integer value. This, along with Integer being immutable, makes it practical to use an Integer as a key in a HashMap. This value-based approach to equality is used by all the primitive wrapper classes in the Java class library, such as Integer, Float, Character, and Boolean, as well as String (two String objects are equal if they contain the same sequence of characters). Because these classes are immutable and implement hashCode() and equals() sensibly, they all make good hash keys.

Why override equals() and hashCode()?

What would happen if Integer did not override equals() and hashCode()? Nothing, if we never used an Integer as a key in a HashMap or other hash-based collection. However, if we were to use such an Integer object for a key in a HashMap, we would not be able to reliably retrieve the associated value, unless we used the exact same Integer instance in the get() call as we did in the put() call. This would require ensuring that we only use a single instance of the Integer object corresponding to a particular integer value throughout our program. Needless to say, this approach would be inconvenient and error prone.

The interface contract for Object requires that if two objects are equal according to equals(), then they must have the same hashCode() value. Why does our root object class need hashCode(), when its discriminating ability is entirely subsumed by that of equals()? The hashCode() method exists purely for efficiency. The Java platform architects anticipated the importance of hash-based collection classes -- such as Hashtable, HashMap, and HashSet -- in typical Java applications, and comparing against many objects with equals() can be computationally expensive. Having every Java object support hashCode() allows for efficient storage and retrieval using hash-based collections

Requirements for implementing equals() and hashCode()

There are some restrictions placed on the behavior of equals() and hashCode(), which are enumerated in the documentation for Object. In particular, the equals() method must exhibit the following properties:

    Symmetry: For two references, a and b, a.equals(b) if and only if b.equals(a)
    Reflexivity: For all non-null references, a.equals(a)
    Transitivity: If a.equals(b) and b.equals(c), then a.equals(c)
    Consistency with hashCode(): Two equal objects must have the same hashCode() value

The specification for Object offers a vague guideline that equals() and hashCode() be consistent -- that their results will be the same for subsequent invocations, provided that "no information used in equals comparison on the object is modified." This sounds sort of like "the result of the calculation shouldn't change, unless it does." This vague statement is generally interpreted to mean that equality and hash value calculations should be a deterministic function of an object's state and nothing else.

Wednesday, 9 May 2012

threading Example in android

package test12.tt;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Test12Activity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final TextView txt1 = (TextView) findViewById(R.id.sm);

        new Thread(new Runnable() {
            public void run(){

        txt1.setText("Thread!!");


            }
    }).start();

    }

}


And the Android XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
android:id = "@+id/sm"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>

Monday, 7 May 2012

Google phones on AT & T links to the bag and Verizon

After much hoopla, launched in the last bag, Nexus S in September last year, but only available on Monday's version of T-Mobile phone and not a writer. Verizon announced that their relations with the galaxy, is found to not support the Google wallet. Verizon argued that the Google bag "must be integrated into a new, safe, and proprietary hardware features of our phones" and continue discussions with Google on the issue of trade.

With the new App update links users on AT & T and Verizon now install Google wallet directly from the Android Market. Many users had received a copy of the torn page will load it on their devices, but now might be comforting to get the latest official version from Google.

AT & T links with users, or GSM connection galaxy just need to search the galaxy connection and install it. These devices are recognized on the market and there is a 1-click isntall.


Verizon for the connection of the galaxy, the process takes a few steps outside. Do visit the Android Market site, install the browser, and to provide its services in the official App. It may sound like a little much, but it only takes about a minute to complete.

    A phone, open the browser and go to http://market.android.com. (Hint:. Preventing violence to cleanse and market knowledge, and standard browser before)
    Search for "Google Wallet." (If your browser prompts you to open the market, no. Just to stay in the browser.)
    When the results come to know this bag in the Google icon.
    Click the "Install" button on your browser and sign into your Google account. (Likewise, this is from the browser, not the App Market.)
    I logged in, send it to the redirected page in the browser.
    Of course not in there with the ability to install a bond is a VZW can not be maintained.
    Press Back for more, or until Market Browser market to choose again.
    In the Market to open a Google page with the option to install the bag.

If it does not work right away, just a sign of the Android Market site through your browser and try the steps again. I tried this on my Verizon connection galaxy and 2 worked in the experiment. Before I loaded the older version of Google-bag and install updated to the latest version without any problems.

They are not affiliated or GSM connection in torn T-Mobile to try this trick out, but hopefully in time and drives well. It may be in one hand, if we learn more of the bag available as himself.

At least AT & T is now allowing a sack for Android phones with NFC, and hopefully Verizon close to reaching an agreement with Google.

crack Java bytes code encryption


If I encrypt. Class files and use a custom ClassLoader to load and decrypt on the go, this is not decompilation?

The problem is not Java-bytes code decompilation is almost as old as language itself. Despite a series of terror, the instruments available in the market, novice Java programmers to continue to think of new and clever ways to protect intellectual property. In this Java Q & A installment, I will dispel some myths about the idea frequently rehashed in discussion forums.

The last facility in Java. Java class files can be restored to the original sources closely resemble much of the design goals and compromises with the Java code bytes. Among other Java bytes code designed for a joint, a platform-independent, network mobility and facilitate the analysis of the bytes code interpreters and JIT (just-in-time) / HotSpot dynamic compilers. Namely, they are compiled. Family Files express intention of the programmer, much easier to analyze than the source code.

When several persons have to be done, not against him but of a difficult if it is not at all I do. For, as you the steps of the writing of the Post-it can be complicated. Kind of data bytes to the code harder to read with or decompiled, or more difficult to decompile it into Java code (or). Technology, making the method name overloading works well in the past, and change the flow control is not possible to create a governance structure to represent the Java syntax works well with the latter. More successful using a mixture of commercial obfuscators and the arts.

Unfortunately, such approaches actually change the code, the JVM is running, and many users are afraid (rightly) that the conversion of new bugs in their applications. In addition, the method and field renaming a device called an end. Change the actual class and package names that violate a number of other Java APIS (JNDI (Java Name and Directory soft), URL providers, etc.). In addition to a change of name, the link between the bytes of code offsets and line number of the changes can recover the original Stack traces an exception was made difficult.

So who is to obscure the original Java source code. But basically this is causing a similar set of problems.
Encrypt, not hard to understand?

Perhaps we have done for you, "Well, if I encrypt all the classes for manipulating bytecode after compilation and decrypt on the fly within the JVM (which can be accomplished with a custom ClassLoader) when the JVM is running bytecode my original, however, is not to decompile or reverse engineer, right? "

You evil, and you'd think of you this thing to be the first to act and works. And, therefore, encryption does not belong to the force of reason.

Saturday, 5 May 2012

Java Get IP Address


This section illustrates you how to obtain the IP Address of local host.

An IP address is either a 32-bit or 128-bit unsigned number used by the internet protocol. To store the host name resolutions, the class InetAddress is used. The method getLocalHost() returns the local host and the method getHostAddress() returns the IP address.

   Java Get IP Address
Posted on: October 15, 2008 at 12:00 AM
An IP address is either a 32-bit or 128-bit unsigned number used by the internet protocol. To store the host name resolutions, the class InetAddress is used.
Java Get IP Address

    

This section illustrates you how to obtain the IP Address of local host.

An IP address is either a 32-bit or 128-bit unsigned number used by the internet protocol. To store the host name resolutions, the class InetAddress is used. The method getLocalHost() returns the local host and the method getHostAddress() returns the IP address.





Here is the code of Java Get IP Address Example
import java.net.*;
import java.io.*;

public class GetIPAddress {
public static void main(String [] args) {
try {
InetAddress thisIp =InetAddress.getLocalHost();
System.out.println("IP:"+thisIp.getHostAddress());
}
catch(Exception e) {
e.printStackTrace();
}
}
}


Output will be displayed as:
c:/>javac GetIPAddress.java
c:/>java GetIPAddress
IP:192.168.10.205

Friday, 4 May 2012

Connect to Access Database using JDBC-ODBC bridge


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class Main {
  public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement();
    // st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    st = conn.createStatement();
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    ResultSetMetaData rsMetaData = rs.getMetaData();

    int numberOfColumns = rsMetaData.getColumnCount();
    System.out.println("resultSet MetaData column Count=" + numberOfColumns);

    st.close();
    conn.close();
  }

  private static Connection getConnection() throws Exception {
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    String url = "jdbc:odbc:northwind";
    String username = "";
    String password = "";
    Class.forName(driver);
    return DriverManager.getConnection(url, username, password);
  }
}

Thursday, 3 May 2012

Java Collection Interview call.

How HashMap in Java?
This is a classic interview question Java collections I have to say about living in a HashMap in Java, the question was that the collection is mostly in the conference, AVP's role in the investment and there are a lot of questions in response to the Interviewer, to what key HashMap need to be changed, that they are conditions in the list in the HashMap, and how to adjust the amount of HashMap in Java for explanations and answers to this, please. see the link above.

The difference between failure and Iterators is not safe?
This is a collection of interview questions and tips if you want to hear the word quickly and safely in the first Iterators Fail-fast bow. ConcurrentModificationException. When the thread is iterating over the collection, and the collection and control structure by adding, deleting or modifying the underlying objects in the collection. Are known to quickly fail because they try to throw up, but with the lack of experience when Iterators are not safe to work in the collection of the original collection.


The difference between synchronization and data collection. ConcurrentCollection is?
Java5 added several classes. ConcurrentCollection to ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue etc., in an interview with a collection of Java, although Java is a trickier way to copy the collection to ArrayList, HashMap, using Collections. . synchronizedMap () utility function.One principal difference is that ConccurentCollections. More efficient data collection that is closed to the specific section of the map to achieve concurrency and synchronization. The difference between SynchronizedCollection and ConcurrentCollection in Java for more information.



Again we list the difference, and what is it?
This is a collection of interview questions and the most junior of the conference to have more experience in Java 2 to 3 years in the functionality that is unique, with the exception of the detailed Again. to take away the () the manner and the second, to navigate to different pages. Again we Collection.Another is easy to list and does not allow other threads to modify the methods of collection at the second () and throws in Java VS Enumeraiton ConcurrentModificaitonException Again we see the difference.


The difference between HashMap and Hashtable?
This is another classic collection of interviews with many of the Java and Java is the beginning of the content, there are predefined, this conversation is not the same questions as HashMap hashtalbe not. HashMap is faster than the hashtable that can be wrong is if you put that question to another, such as HashMap in Java, or can replace Hashtable with ConcurrentHashMap, etc. VS HashMap HashTable in Java in the details of the conference. this time

When you are using. ConcurrentHashMap in Java?
The other is that which is gathered of which are located in Java, known as the interviewers are augmented by the following. ConcurrentHashMap or a ConcurrentHashMap. Well suited for situations where there are many readers and.
A writer or less, with maps that have been closed by the write operation. If, as many readers as writers ConcurrentHashMap. The hashtable is implemented in a synchronized HashMap.

In between sets and lists in Java?
Another classic was a collection of Java that is popular in the first round of interviews over the phone. Java How to keep the lakes, especially in the arts, in general, it is not lawful to insert This is not as a race who can teach a pain Interviewer. in accordance with the requirements.

How such objects in the collection?
This is a collection of interviews, not only serves two. However, a test program to prioritize the idea but also as a collection of various utilty for creating the collection and sorting. Sorting is performed using the paired comparison in Java, and with you. Collections.sort () will be made in the manner specified in the order of nature to compare the Collections.sort (related) to an object based on the comparison () method of comparison. Sorting in Java using the compare and see for the details.


The difference between the bars, and ArrayList is it?
Interview question to start with a collection of still more popular, especially on the phone with ArrayList in Java is the most collected and used and are asking about. ArrayList.See the difference between the bars, and the response to our ArrayList for this conference.


The difference between HashMap and HashSet is?
This collection of interview questions are asked with the view hashtable HashMap VS VS HashMap HashSet for detailed answers.

Wednesday, 2 May 2012

Let Your Android Application Out of the Box with SMS Integration


Google’s Android allows developers a great deal of access to the phone. Enable your applications to communicate with the outside world using SMS messages.
by Chris Haseman
ushing data to and from a third-party mobile application on demand has always been a tricky proposition. BREW allows, with the blessing of Qualcoom, SMS messages to be directed at a particular application resident on the phone. Apple's iPhone messaging platform, which, as of press time, is still in testing, allows for similar functionality through HTTP push messaging. As for Java ME, well, we're just not going to talk about Java ME. Doing data push and remote application activation with Android is somewhat similar to BREW's directed SMS process. By the time you finish this article, you should have a steady grasp of how to send and receive SMS messages from your application in Android.

You'll explore the SMS functionality in two ways. First, you'll set up a BroadcastReceiver to intercept and inspect SMS messages as they are delivered to the phone. Once you've received them you'll be able to inspect their contents, activate an application, process data, or, as we'll explore in the second part, send a return SMS message.

Author's Note: This code for this article is based on version 1.0 BETA of the Android SDK, and I'd recommend an update to the latest version of Android before trying any of the code below.

Receiving SMS Messages
Receiving and reacting to SMS events can be broken down into two tasks: registering for SMS_RECIEVED intents through the AndroidManifest.xml file, and writing code that combs through those events looking for specific text.

Registering for SMS BroadcastIntents
For you copy/paste programmers out there, you can find the entire contents of this test application here.

With absolutely nothing else, here's what the AndroidManifest.xml file looks like:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.devx.SMSExample">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<receiver android:name=".SmsIntentReceiver" android:enabled="true">
<intent-filter>
<action android:name=
"android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>

The file contains a few notable pieces of information. First, but not necessarily foremost, is the <uses-permissions> tag. This line must appear within the manifest tag but before the definition of the application. This tells Android that you'll be using the RECEIVE_SMS and SEND_SMS permissions. Currently, Android has not announced how it will deal with user notifications and permission filtering. For now, it's enough to know that the application won't work without these permission declarations.

Second, is the <receiver> tag. This block of XML tells the Android OS the name of the class to load, in this case SmsIntentReceiver, and which BroadcastIntents on which to load it. You'll tell Android which intents to send us by registering for <action> tags inside the <intent-filter> tag. In this case, you'll register for the android.provider.Telephony.SMS_RECIEVED intent. This intent is fired each time an SMS hits the phone.

Author's Note: Currently, Android does not allow one BroadcastReceiver to accept and consume an Intent. This is a major technical hurdle that must be overcome before Android is released into the world. Because you cannot consume SMS message intents, both the application and Android's native SMS application will receive the incoming SMS message. As you'll see later, this means you'll have to keep filter text for the SMS messages human readable—as they'll end up in the inbox of the person receiving the message.




Processing Incoming Messages
Okay, so your BroadcastReceiver is set up to be called each time a new SMS intent hits the phone. Now, you'll need to process these incoming messages and do something with them.

Once upon a time, Android included a function called getMessagesFromIntent() which, in their infinite wisdom, they decided to remove from the 1.0 SDK. Because I'm a nice guy, I've re-written this function for you. I won't go into too much detail on it, instead I'll just give you the source code:


private SmsMessage[]
getMessagesFromIntent(Intent intent)
{
SmsMessage retMsgs[] = null;
Bundle bdl = intent.getExtras();
try{
Object pdus[] = (Object [])bdl.get("pdus");
retMsgs = new SmsMessage[pdus.length];
for(int n=0; n < pdus.length; n++)
{
byte[] byteData = (byte[])pdus[n];
retMsgs[n] =
SmsMessage.createFromPdu(byteData);
}
}
catch(Exception e)
{
Log.e("GetMessages", "fail", e);
}
return retMsgs;
}

Again, for you copy/paste programmers, click here for the full project data. Now that you've got the Intent extras converted into SMSMessages, check out Listing 1 to see the example onReceive function.

All right, that's a fair amount of code. Let's walk through it a little bit at a time. Your first task is to be sure you've received the correct Intent. To do this, you'll need to call getAction() on the passed-in Intent class.

Next, you'll need to retrieve an array of messages that are currently in the SMS hopper. This was a tough function to track down as it's incredibly poorly documented in the Android docs (this usually means that it will change in a later release). The task involves calling getMessagesFromIntent() while again passing in the intent object, which will return an array of SmsMessage objects. You'll need to loop through these messages searching for specific trigger texts. To get the messages body out of the SmsMessage object you'll have to call getDisplayMessageBody() on each SmsMessage in the array.

Again, because Android doesn't give us a chance to pull Intents out of the broadcast stack, you'll have to make the triggers humanly readable. In this little sample application, you can see two distinct triggers. The first trigger starts an application, while the second performs a GPS lookup and fires back an SMS detailing the location of the phone. We'll get into GPS information and sending SMS messages in a minute. First things first. Let's look, really quickly, at firing up an application or Activity from a BroadcastReceiver.

Waking Up the Application
Waking up your test application on an incoming SMS simply requires you, once you've received the correct SMS, to create the appropriate Intent and send it on it's way. First, you'll need an Activity with which to start your application. For those of you who are old hands at Android development, this section is going to be a bit of a review.

The first step is to add an activity to your AndroidManifest.xml file. If you started a new project from scratch (or your cheated and downloaded the source code), chances are you already have a "hello world" activity. For reference, here's what the new activity will look like, pay careful attention to the additional action in the intent receiver tag.


<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".BaseScreen" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="com.devx.SMSExample.WAKE_UP"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Insert the above listing inside the application tag alongside the receiver you defined earlier. Notice the com.devx.SMSExample.WAKE_UP action: This is the intent you'll need to send to wake up the Activity. Here’s the source code that will wake up your sample activity:


private void triggerAppLaunch(Context context)
{
Intent broadcast = new Intent("com.devx.SMSExample.WAKE_UP");
broadcast.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(new Intent(broadcast));
}

Create a new Intent with the action defined above in the AnroidManifest.xml. Because you're starting a new Activity from a BroadcastReceiver, you'll need to add the FLAG_ACTIVITY_NEW_TASK flag to the intent before calling startActivity. At this point, the incoming SMS message will launch your shiny new "hello world" activity. What you do with that activity at this point is your own business.




Sending an SMS
So far, you've learned how to listen for and respond to incoming SMS messages. To close the loop, you'll have to be able to send text messages. As an example, you'll extend the SMS listener so that it will report the GPS coordanates of the phone.

Where Did I Leave My Phone?
As a means to demonstrate sending an SMS message, you'll have to extend your SMS listener application to report, through text messaging, where it is. Because you're already listening for incoming text messages, you can just flesh out the function alluded to above. You'll just need to finish getGPSData() and sendGPSData(). Because this article isn't about position locations, you're going to be on your own for the GPS stuff. You can, however, check out one of my previous DevX articles for information on completing a GPS position lookup.

Assume, for the sake of simplicity and expediency, that you have used the phone's GPS module to obtain it's location. Further assume that you'll need to send that data back to the device requesting it. Android makes it very easy to build and send SMS messages. Listing 2 shows the code to do so.

Simple, right? Okay, maybe not so much. You'll need to build a string to send off in the text message, using the predetermined lat and lon address. You'll also need to grab the default SmsManager instance. You must, with the 0.9 version of the SDK, create a PendingIntent that can eventually be passed into the sendTextMessage call; more on that in a second. Next, you'll want to grab the return address on the incoming text message so you can address the SMS back out.

With all these pieces in place its time to call sendTextMessage.