Friday, 29 June 2012

phonegap-android-eclipse-quickstart

   
phonegap-android-eclipse-quickstart

Requirements

It is assumed that you have the Android SDK installed and working. If not, then you need to install it before proceeding. You can find the download and installation instructions here. Also, ensure that you have created at least one Android virtual device (AVD). You will need an AVD to run your project in the Android emulator.

You also need to:
    Download the latest copy of PhoneGap and extract its contents. We are only interested in the Android directory.

In Eclipse, ensure that you have told Eclipse where the Android SDK is installed in Preferences > Android.

Building The Sample Project



File > New > Android Project



    Select Create new project from existing source
    Click Browse and point it to the location of the sample app provided with your PhoneGap 0.9.4 download

Don't bother using older versions of Android. Use the highest SDK target available. Phonegap will take care of backwards compatibility for you.  Note: You may experience issues with Android 3.0 so try using Android 2.2 or 2.3 first.



(You might experience an error here, where Eclipse can't find phonegap.jar. In this case, right click on the /libs folder and go to Build Paths/ > Configure Build Paths. Then, in the Libraries tab, add phonegap.jar to the Project. If Eclipse is being temperamental, you might need to refresh (F5) the project.)



You can now run you project as an Android Application. Right click the project and go to Run As and click Android Application.  Eclipse might ask you to select an appropriate AVD. If there isn't one, then you'll need to create it before you can continue.

Creating A New Project



File > New > Android Project
And give it some sensible defaults.

 Don't bother using older versions of Android. Use the highest SDK target available. Phonegap will take care of backwards compatibility for you.



From the PhoneGap download earlier, we need the following two files:

    Android/phonegap-1.0.0.jar
    Android/phonegap-1.0.0.js



In the root directory of the project you created in Eclipse, create two new directories:

    /libs
    /assets /www



Now copy

    Android/phonegap-1.0.0.jar to /libs
    Android/phonegap-1.0.0.js  to /assets/www



In Eclipse, select the project in the Package Explorer and refresh (F5) the project. The copied file will appear in the project.



Now, create index.html in your www folder and add some code like so:



<!DOCTYPE HTML>
<html>

  <head>
    <title>PhoneGap</title>

  <script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>    

  <script type="text/javascript" charset="utf-8">

     function onLoad(){

          document.addEventListener("deviceready", onDeviceReady, true);

     }

     function onDeviceReady(){

          navigator.notification.alert("PhoneGap is working");

     }

  </script>

  </head>

  <body onload="onLoad();">
       <h1>Welcome to PhoneGap</h1>

       <h2>Edit assets/www/index.html</h2>

  </body>

</html>

Make a few adjustments to the project's main Java file found in the src folder in Eclipse.

    Change the class's extend from Activity to DroidGap
    Replace the setContentView() line with super.loadUrl("file:///android_asset/www/index.html");
    Add import com.phonegap.*;

<supports-screens
        android:largeScreens="true"
        android:normalScreens="true"
        android:smallScreens="true"
        android:resizeable="true"
        android:anyDensity="true"
        />
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-permission android:name="android.permission.VIBRATE" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
        <uses-permission android:name="android.permission.READ_PHONE_STATE" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.RECEIVE_SMS" />
        <uses-permission android:name="android.permission.RECORD_AUDIO" />
        <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
        <uses-permission android:name="android.permission.READ_CONTACTS" />
        <uses-permission android:name="android.permission.WRITE_CONTACTS" /> 
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 

Thursday, 28 June 2012

Android JSON Parsing

Android JSON Parsing

JSON is the best alternative to XML for storing data in files. It is easy to parse and access data stored in JSON format. Previously i explained parsing XML and today i am going to discuess parsing JSON data with an example.

The JSON Structure

I am taking an example of following JSON which will give you list of contacts and each contact will have details like name, email, address, phone number ertc,

{
    "contacts": [
        {
                "id": "c200",
                "name": "dream",
                "email": "dream@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c201",
                "name": "Johnny Depp",
                "email": "johnny_depp@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        .
        .
        .
        .
  ]

The difference between [ and { - (Square brackets and Curly brackets)

If you observe normally JSON data will have square brackets and curly brackets. The difference between [ and { is, the square bracket represents starting of an JSONArray node whereas curly bracket represents JSONObject. While accessing these elements we need to call different methods to access these nodes.


Writing JSON Parser Class

In your project create a class file and name it as JSONParser.java. The parser class has a method which will make http request to get JSON data and returns a JSONObject.

JSONParser.java
package com.androidhive.jsonparsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();        

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

Wednesday, 27 June 2012

android resource

android resource


Contains resource classes used by applications included in the platform and defines application permissions for system features.

You can use some resources directly from these R classes in your own applications, but you should generally use only resources that you've provided directly in your application, in order to provide a cohesive application package that has no external dependencies. In particular, you should not use drawable resources from the android package, because they may change between platform versions, causing unforeseen conflicts with your design. Typically, styles are the only resources you should use directly from these resources

API resources

You should always externalize resources such as images and strings from your application code, so that you can maintain them independently. Externalizing your resources also allows you to provide alternative resources that support specific device configurations such as different languages or screen sizes, which becomes increasingly important as more Android-powered devices become available with different configurations. In order to provide compatibility with different configurations, you must organize resources in your project's res/ directory, using various sub-directories that group resources by type and configuration.
For any type of resource, you can specify default and multiple alternative resources for your application:

    Default resources are those that should be used regardless of the device configuration or when there are no alternative resources that match the current configuration.
    Alternative resources are those that you've designed for use with a specific configuration. To specify that a group of resources are for a specific configuration, append an appropriate configuration qualifier to the directory name.

For example, while your default UI layout is saved in the res/layout/ directory, you might specify a different layout to be used when the screen is in landscape orientation, by saving it in the res/layout-land/ directory. Android automatically applies the appropriate resources by matching the device's current configuration to your resource directory names.

Figure 1 illustrates how the system applies the same layout for two different devices when there are no alternative resources available. Figure 2 shows the same application when it adds an alternative layout resource for larger screens.

The following documents provide a complete guide to how you can organize your application resources, specify alternative resources, access them in your application, and more:

Providing Resources
    What kinds of resources you can provide in your app, where to save them, and how to create alternative resources for specific device configurations.
Accessing Resources
    How to use the resources you've provided, either by referencing them from your application code or from other XML resources.
Handling Runtime Changes
    How to manage configuration changes that occur while your Activity is running.
Localization
    A bottom-up guide to localizing your application using alternative resources. While this is just one specific use of alternative resources, it is very important in order to reach more users.
Resource Types
    A reference of various resource types you can provide, describing their XML elements, attributes, and syntax. For example, this reference shows you how to create a resource for application menus, drawables, animations, and more.

Monday, 25 June 2012

Java Internet security



Java programming is becoming increasingly widespread in today's computing environments. For example, you might be using the IBM Toolbox for Java or the IBM Development Kit for Java on your system to develop new applications. Consequently, you must prepare to deal with the security issues that are associated with Java. Although a firewall is a good defense against most general Internet security risks, it does not provide protection for many risks that using Java presents. Your security policy should include details for protecting your system against three areas of concern for Java: applications, applets, and servlets. Also, you should understand how Java and resource security interact in terms of authentication and authorization for Java programs.

Java applications

As a language, Java has some characteristics that protect Java programmers from unintentional errors that can cause integrity problems. (Other languages that are commonly used for PC applications, such as C or C++ do not protect the programmers from unintentional errors as strongly as Java does.) For example, Java uses strong typing which protects the programmer from using objects in unintended ways. Java does not allow pointer manipulation, which protects the programmer from accidentally going outside the memory boundaries of the program. From an application development perspective, you can view Java as you do other high-level languages. You should apply the same security rules for application design that you apply with other languages on your iSeries server.

Java applets

Java applets are small Java programs that you can include in your HTML pages. Because applets run on the client, what they do is a concern to the client. However, a Java applet has the potential to access your iSeries server. (An ODBC program or an advanced program-to-program communications (APPC) program that operates on a PC in your network can also access your iSeries.) In general, Java applets can establish a session only with the server from which the applet originated. Therefore, a Java applet can access your iSeries from a connected PC only when the applet came from your iSeries server (such as from your web server).

An applet can attempt to connect to any TCP/IP port on a server. It does not have to talk to a software server that is written in Java. But, for servers that are written with the IBM Toolbox for Java, the applet must provide a user ID and password when it establishes connections back to the server. In this material, the servers described are all iSeries servers. (A server written in Java does not have to use the IBM Toolbox for Java). Typically, the IBM Toolbox for Java class prompts the user for a user ID and password for the first connection.

The applet can perform functions on the iSeries server only if the user profile has authorization to those functions. Therefore, a good resource security scheme is essential when you begin to use Java applets to provide new application function. When the system processes the requests from applets, it does not use the limited capability value in the profile of the user.

The applet viewer allows you to test an applet on the server system; however, it is not subject to browser security restrictions. Therefore, you should use the applet viewer to test your own applets only, never to run applets from outside sources. Java applets often write to the PC drive of the user, which may allow the applet the opportunity to perform a destructive action. However, you can use a digital certificate to sign a Java applet to establish its authenticity. The signed applet can write to the PC's local drives, even though the default setting for the browser prevents it. The signed applet can also write to mapped drives on your iSeries server because they appear to the PC to be local drives.
Note:
The behavior described above is generally true for Netscape Navigator and MS Internet Explorer. What actually happens depends on how you configure and manage the browsers that you use.

For Java applets that originate from your iSeries server, you might need to use signed applets. However, you should instruct your users in general not to accept signed applets from unknown sources.

Beginning with V4R4, you can use the IBM Toolbox for Java to set up a Secure Sockets Layer (SSL) environment . You can also use the IBM Developer Toolkit for Java to make a Java application secure with SSL. Using SSL with your Java applications ensures encryption of the data, including the user IDs and passwords that pass between the client and server. You can use Digital Certificate Manager to configure registered Java programs to use SSL.

Friday, 22 June 2012

java flex interview questions


java flex interview questions


Q 1. Types of Binding
Ans: Using the curly braces ({}) syntax
Using ActionScript expressions in curly braces
Using the tag in MXML
Using bindings in ActionScript(BindingUtils)

Q 2. How to create your own event
Ans: Creating a subclass from the Event class
Using the Event metadata tag
Dispatching an event

Q 3. Event Bubbling
Ans: The mechanism through which event objects are passed from the objects that generates an event up through the containership hierarchy

Q 4. Life cycle of Flex Application/Component?
Ans: Preinitialize: The application has been instantiated but has not yet created any child components.
Initialize: The application has created child components but has not yet laid out those components.
creationComplete: The application has been completely instantiated and has laid out all components

Q 5. How you implement MVC in your Application
Ans: Cairngorm is based on the MVC model. It is specifically designed to facilitate complex state and data synchronization between the client and the server, while keeping the programming of the View layer detached from the data implementation.
The role of the View layer in a Cairngorm application is to throw events and bind to data stored in the Model. Components on the View can bind to Value Objects or other properties in the Model (data) layer.
In a Cairngorm Model, related data are stored in Value Objects (VOs), while simple variables can be stored as direct properties of the ModelLocator class. A static reference to the ModelLocator singleton instance is used by the View layers to locate the required data.
The Controller is the most sophisticated part of the Cairngorm architecture. The Controller layer is implemented as a singleton FrontController. The FrontController instance, which receives every View-generated event, dispatches the events to the assigned Command class based on the event's declared type.
The Command class then processes the event by running the Command class' execute() method, which is an ICommand interface method. The event object may include additional data if required by the developer. The execute() method can update the central Model, as well as invoke a Service class which typically involves communication with a remote server. The IResponder interface, which is also implemented by the Command class, includes onResult and onFault methods to handle responses returned from the invoked remote service.

Q 6. Difference btw Java and Flex Getters Setters
Ans: When it comes to getters and setters, Java and AS are quite different, in that getters and setters are part of the core ECMAScript language, whereas in Java, getters and setters are done through a naming convention.
In Java, it is almost never a good idea to make member variables public. If you do decide to make member variables public and then later want to change the interface to use getter/setter functions, you will have to modify all callers of your interfaces, which is onerous at best and in many cases, not possible (expecially when you are creating code that is used by other people).
Meanwhile, in ECMAScript, the externally visible interface doesn’t change when I go from a member variable to a getter/setter and back again. In some sense, the interface hiding is already accomplished in the language. Creating public member variables is “safe” in this sense.
Perhaps this is already obvious to all the AS-heads out there, but it took me a bit of time to get used to the concept.

Q 7. How many events are fired when your focus goes in one text box, you enter some text and then press tab.
Ans: PreinitializeHandler(), initializeHandler(), itemEditBegin, itemEditEnd, creationComplete()

Q 8. How you use styles different ways of using Style sheet
Ans: Using external style sheets, Using local style definitions, Using the StyleManager class ,Using the setStyle() and getStyle() methods, Using inline stylesLoading style sheets at run time

Q 9. How can you use two Styles at the same time
Ans: Using external style sheets and use Inline style commands

Q 10. Try to remember properties of few imp components
Ans:
< id="WeatherService" wsdl="http:/example.com/ws/WeatherService?wsdl" useproxy="false">
< !-- Bind the value of the ZIP code entered in the TextInput control to the ZipCode parameter of the GetWeather operation. -->
< name="GetWeather">

<>{zip.text}
< /mx:request>
< /mx:operation>


Q 11. What is the difference between Flex 2.0 and Flex 3.0
Ans: Enhanced Features like Faster compilation time, SWF file size reduction, Flex/Ajax bridge, Advanced Datagrid, Interactive debugging, Cross-Domain, Versionable, Easy to Use,Security and Code Signing,Failover and Hosting,Cross-Domain RSL, Advanced DatagridDeep Linking, Resource Bundles and Runtime Localization, Flex Component Kit for Flash CS3, Compilation, Language IntelligenceRefactoring, Class Outline,Code Search, Profiler, Module Support, Multiple SDK Support, Skin Importer, Design View Zoom/Pan,Design Mode support for ItemRenderers, Advanced Constraints, CS3 Suite integration, CSS Outline, CSS Design View, Flex 3 SDK Skinning/Style Enhancements

Q 12. How will you call Java method from Flex?
Ans: Using RemoteObject. Explain the process to interviewer

Q 13. What are the config files used for connecting Java and Flex?
Ans:
data-management-config.xml,
messaging-config.xml,
proxy-config.xml,
remoting-config.xml,
services-config.xml

Q 14. What are the channels and their types
Ans: The Channel class is the base message channel class that all channels in the messaging system must extend.
Channels are specific protocol-based conduits for messages sent between MessageAgents and remote destinations. Preconfigured channels are obtained within the framework using the ServerConfig.getChannel() method. You can create a Channel directly using the new operator and add it to a ChannelSet directly
In Flex AMFChannel is used mostly. Action Message Format
Methods
applySettings (),connect(),connectFailed(),connectSuccess(), connectTimeoutHandler()
disconnect(),disconnectFailed(),disconnectSuccess(),flexClientWaitHandler(), getMessageResponder(),internalConnect(),internalDisconnect(),internalSend(),logout()
send(),setCredentials()
Properties
authenticated,channelSets,connected,connectTimeout,endpoint,failoverURIs,protocol,
reconnecting,recordMessageSizes,recordMessageTimes,requestTimeout,uri

Q 15. Give the name of Collection which can be mapped to java and Flex and vice-versa
Ans: java.lang.String String
java.lang.Boolean, boolean Boolean
java.lang.Integer, int int
java.lang.Short, short int
java.lang.Byte, byte[] int
java.lang.Byte[] flash.utils.ByteArray
java.lang.Double, double Number
java.lang.Long, long Number
java.lang.Float, float Number
java.lang.Character, char String
java.lang.Character[], char[] String
java. math.BigInteger String
java.math.BigDecimal String
java.util.Calendar Date
java.util.Date Date
java.util.Collection mx.collections.ArrayCollection(for example, java.util.ArrayList)java.lang.Object[] Arrayjava.util.Map Object (untyped). For example, a java.util.Map[] is converted to an array (of objects).
java.util.Dictionary Object (untyped)
org.w3c.dom.Document XML object
java.lang.Object (other than previously listed types) Typed Object
Objects are serialized by using JavaBean introspection rules and also include public fields. Fields that are static, transient, or nonpublic, as well as bean properties that are nonpublic or static, are excluded.

Q 16. How can you call JavaScript from MXML
Ans: IExternalInterface.call()

Q 17. How can you access a var defined in 1 MXML flex in to another MXML file
Ans: Create 1 object of MXML fiel into another MXML File

Q 18. Is it possible to make httpService Requests synchronous?
Ansvar mytoken:AsyncToken = yourservice.send();
mytoken.addResponder(new ItemResponder(function,errorFunction));
OR
You can create a result handler to your HTTPService.
remoteObjectName.Your method
name.addEventListener("result",HandlerFunction,false,0,true);

Q 19. I need to load an image from flickr into my application. Do I need a crossdomain.xml file on flickr?
Ans: every SWF file you view runs locally on your machine. This means that a SWF would have HTTP access to all machines behind the company firewall. To prevent this, every server other than the one the SWF is loaded from, needs to have a crossdomain.xml file in its root, listing all domains that have access to that particular server

Q 20. What is the difference between httpService and Data Service?
Basically, Flex allows three types of RPC services: HttpService, WebServices, and RemoteObject Services. In Flex, using the “RemoteObjects specifies named or unnamed sources and connects to an Action Message Format (AMF) gateway, whereas using the HTTPService and WebService use named services or raw URLs and connect to an HTTP proxy using text-based query parameters or XML”. Specifically, HTTPServices use raw HTTP requests, WebServices use the SOAP protocol and RemoteObjects uses AMF3.

Thursday, 21 June 2012

java Servlets interview questions

What is Servlets and explain the advantages of Servlet life cycle?

Servlets are modules that run within the server and receive and respond to the requests made by the client. Servlets retrieve most of the parameters using the input stream and send their responses using an output stream............
Read answer
Explain life cycle of Servlet.

Servlets life cycle involve three important methods, i.e. init, service and destroy.
Init() : Init method is called when Servlet first loaded in to the web server memory............
Read answer
What are different Authentication options available in Servlets.

There are four ways of Authentication options available in servlets
HTTP basic authentication: In this, server uses the username and password provided by the client and these credentials are transmitted using simple base64 encoding..........
Read answer
Explain why HttpServlet is declared abstract.

The Constructor HttpServlet() does nothing because this is an abstract class. Default implementations in a few Java classes like HttpServlet don’t really do anything. Hence, they need to be overridden.............
Read answer
Is possible to have a constructor for a servlet?

Yes, it is possible to have a constructor for a servlet. However, it is not practiced usually. The operations with the constructor can be performed as usual just that it cannot be called explicitly using the ‘new’ keyword.............
Read answer
What is the difference between an Applet and a Servlet?

Applets are applications designed to be transmitted over the network and executed by Java compatible web browsers.
An Applet is a client side java program that runs within a Web browser on the client machine.............
Read answer
Define HTTP Tunneling?

In some organizations, the intranet is blocked by a firewall to the internet. It is exposed to the outer networks only by means of webserver port that accept only Http requests...........
Read answer
List out the difference between ServletConfig and ServletContext?

Both are interfaces in the package javax.servlet. ServletConfig is a servlet configuration object. It is used by a servlet container to pass information to a servlet during initialization. The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets................
Read answer
What is the difference between doGet() and doPost()?

doGet() and doPost() are HTTP requests handled by servlet classes.
In doGet(), the parameters are appended to the URL and sent along with header information. This does not happen in case of doPost(). In doPost(), the parameters are sent separately..............
Read answer
What is the difference between using getSession(true) and getSession(false) methods?

getSession(true) will check whether a session already exists for the user. If yes, it will return that session object else it will create a new session object and return it...........
Read answer
List out the difference between a JavaBean from a Servlet?

Servlets are Java based analog to CGI programs, implemented by means of a servlet container associated with an HTTP server. Servlets run on the server side..............
Read answer
Explain how servlets differ from RMI. Explain the advantages and disadvantages of each technology.

RMI (Remote Method Invocation) are a means of client server communication. In this, the client invokes a method on the server machine and the server machine process returns the result back to the client. We need to run RMI registry to use RMI
Read answer
Define servlet mapping.

Servlet mapping controls how you access a servlet. It is recommended that you don’t use absolute URLs. Instead usage of relative URLs should be done.
Read answer
Explain javax.servlet.http package.
What is Java Servlet?

A servlet is a java class / a program that is a server side component and runs in web container
Read answer
Explain the life cycle of Servlet, i.e. Instantiation, Initialization, Service, Destroy, Unavailable.

The life cycle is managed by the Servlet container in which the servlet is deployed
Explain the purpose of Servlet interface.

The javax.servlet.HttpServlet / javax.servlet.Servlet is the interface that is to be implemented by all the servlets. The servlet’s code / actions / implementation is done by implementing this interface
Read answer
Explain the underlying method of Servlet interface.

The init() method
The service() method
The destroy() method
The getServletConfig()
The getServletInfo() method
Read answer
What is GenericServlet class?

This class implements Servlet and ServletConfig interfaces. This class can be extended by a servlet. It is a common practice that a servlet class extends protocol-specific,.................
Read answer
What is HTTPServlet class?

The HTTPServlet class provides an abstract class that is to be sub classed which is suitable for a web site. The subclass of HTTPServlet class must override any one of the following methods:....................
Read answer
What is Servlet context?

Servlet context is created by the container and can be viewed as a shared memory resource for all the servlets for a web application
Read answer
Explain session tracking in Java Servlet.

The state of requests for the same user is being maintained by the session of a servlet. Session tracking is a mechanism that is tracked and maintained by such requests by the user.................
Read answer
Describe Servlet collaboration.

Servlet collaboration is all about sharing information among the servlets. Collaborating servlets is to pass the common information that is to be shared directly by one servlet to another through various invocations of the methods.................
Read answer
Describe the basics of Servlets.

Servlets are java classes which run on a web server. The results produced by the servlet are viewed on a remote web server. Servlet is a server side component in web applications. The servlets performs the request / response paradigm using the web container. Servlets is the best alternative for CGI..............
Read answer
What are the important items in javax.servlets. Explain them

Servlets : Defines all the methods that a servlets implements. Servlets receives and responds to a request from the web clients. This interface has the methods that are to initialize a servlets, service a request and removal of a servlets from the server
Describe the main purpose of servlets.

A java enabled server’s functionality can be extended by a servlets. Usually a servlets is used to develop web applications in a web server

Wednesday, 20 June 2012

Java Design Patterns




Understand how adapters let disparate systems work togethe

Pretend you're back in 1999 and you've just landed a job with a dot-com. Much of your compensation comes from stock options, and you are content. Fortunately, your work is interesting. You're developing an application builder that lets users visually construct Swing applications. So you seize upon a novel idea: display a view's component hierarchy next to the view itself like this:

A user interface (UI) builder prototype. Click on thumbnail to view full-size image.

The left panel shows the component hierarchy for the upper-right panel, and the lower-right panel contains a button that updates the tree. The idea, of course, is that users drag components into the upper-right panel and subsequently click the show component tree button to update the tree. In this simple prototype, you're only interested in getting the tree to reflect the upper-right panel's component hierarchy; you'll leave the drag and drop to someone else.

You propose this idea of exposing component trees to your colleagues, and they are enthusiastic. How long, they wonder, will it take to implement? The response is up to you, but as we're about to find out, the Adapter design pattern makes this an easy job.


Introducing Adapter

Adapters are necessary because dissimilar elements need to interoperate. From wrenches to computer networks, physical adapters are abundant. In software, adapters make dissimilar software packages work together; for example, you might have a tree of objects (call them Nodes) you want to display using Swing's JTree. The JTree class can't display your Nodes directly, but it can display TreeNode instances. With an adapter, you can map your Nodes to TreeNodes. Because Swing trees use the Adapter pattern, you can display any kind of tree—from Document Object Model (DOM) to Swing component hierarchies to a compiler parse tree—just by implementing a simple adapter.

In Design Patterns, the authors describe the Adapter pattern like this:

    Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Tuesday, 19 June 2012

What is a Service?


Most confusion about the Service class actually revolves around what it is not:

    A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
    A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

Thus a Service itself is actually very simple, providing two main features:

    A facility for the application to tell the system about something it wants to be doing in the background (even when the user is not directly interacting with the application). This corresponds to calls to Context.startService(), which ask the system to schedule work for the service, to be run until the service or someone else explicitly stop it.
    A facility for an application to expose some of its functionality to other applications. This corresponds to calls to Context.bindService(), which allows a long-standing connection to be made to the service in order to interact with it.

When a Service component is actually created, for either of these reasons, all that the system actually does is instantiate the component and call its onCreate() and any other appropriate callbacks on the main thread. It is up to the Service to implement these with the appropriate behavior, such as creating a secondary thread in which it does its work.

Note that because Service itself is so simple, you can make your interaction with it as simple or complicated as you want: from treating it as a local Java object that you make direct method calls on (as illustrated by Local Service Sample), to providing a full remoteable interface using AIDL.
Service Lifecycle

There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them. See the linked documentation for more detail on the semantics.

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's IBinder). Usually the IBinder returned is for a complex interface that has been written in aidl.

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().
Permissions

Global access to a service can be enforced when it is declared in its manifest's <service> tag. By doing so, other applications will need to declare a corresponding <uses-permission> element in their own manifest to be able to start, stop, or bind to the service.

In addition, a service can protect individual IPC calls into it with permissions, by calling the checkCallingPermission(String) method before executing the implementation of that call.

See the Security and Permissions document for more information on permissions and security in general.
Process Lifecycle

The Android system will attempt to keep the process hosting a service around as long as the service has been started or has clients bound to it. When running low on memory and needing to kill existing processes, the priority of a process hosting the service will be the higher of the following possibilities:

    If the service is currently executing code in its onCreate(), onStartCommand(), or onDestroy() methods, then the hosting process will be a foreground process to ensure this code can execute without being killed.

    If the service has been started, then its hosting process is considered to be less important than any processes that are currently visible to the user on-screen, but more important than any process not visible. Because only a few processes are generally visible to the user, this means that the service should not be killed except in extreme low memory conditions.

    If there are clients bound to the service, then the service's hosting process is never less important than the most important client. That is, if one of its clients is visible to the user, then the service itself is considered to be visible.

    A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)

Note this means that most of the time your service is running, it may be killed by the system if it is under heavy memory pressure. If this happens, the system will later try to restart the service. An important consequence of this is that if you implement onStartCommand() to schedule work to be done asynchronously or in another thread, then you may want to use START_FLAG_REDELIVERY to have the system re-deliver an Intent for you so that it does not get lost if your service is killed while processing it.

Other application components running in the same process as the service (such as an Activity) can, of course, increase the importance of the overall process beyond just the importance of the service itself.
Local Service Sample

One of the most common uses of a Service is as a secondary component running alongside other parts of an application, in the same process as the rest of the components. All components of an .apk run in the same process unless explicitly stated otherwise, so this is a typical situation.

When used in this way, by assuming the components are in the same process, you can greatly simplify the interaction between them: clients of the service can simply cast the IBinder they receive from it to a concrete class published by the service.

An example of this use of a Service is shown here. First is the Service itself, publishing a custom class when bound:

Monday, 18 June 2012

Building iPhone/Android apps with Phonegap and jQuery Mobile

Building iPhone/Android apps with Phonegap and jQuery Mobile

Before a while I have started with my Startups mobile clients and was attracted by the “write once, run everywhere” thought of Phonegap. They also offer a build service which will make 5 apps for different platforms like Android, Blackberry or iPhone for you. Phonegap is plain JavaScript/HTML. And another cool thing, it can be combined with jQuery mobile. I wanted to use that, because I already knew jQuery. Now my apps are nearly finished. Time to recall some pretty nasty things I have struggled with.
jQuery mobile is not jQuery

While some stuff is pretty similar, jQuery mobile is a new framework you need to learn. It can give you some good hell if you don’t. Stop thinking as “just an API extension to jQuery”. The mobile code will enhance your components, like the wellknown bytecode enhancing in the java world. You should understand what that means, otherwise you get some trouble.

jQuery mobile is pretty nice. You can create several divs in your HTML page, giving them the data-role “page”. These are your pages. You can simply change pages when calling: $.mobile.changePage("#mainmenu");

If you update your lists, you should refresh them afterwards:
$('#myList').listview('refresh');

Otherwise your elements are not visible. If you add some buttons to your page or do other stuff which are not releated to ul lists, you even might need to re-create the whole page:
$('#page').page('destroy').page();
Don’t forget to destroy it before, as I did it, otherwise you go straight to hell.

If you think this is pain: you should know about the vclick event, which replaces somehow the click event of standard jQuery. In addition I can only recomment to learn what the .live function does:
$('.delete').live("vclick", delete);

Some binding need to be done earlier than others. You can bind at the “mobileinit” event of jQuery mobile. do it if you want to initialize your pages before entering them.

As you can see, there is some stuff you really need to know, which is not documented properly. Also the look&feel of jQuery mobile is different on the Android emulator than on the iPhone simulator. A little only, but it is.
And after all, as of today I have struggled for many hours with an AJAX problem on Android. So, you cannot rely that every function of phonegap or jQuery mobile is behaving the same.
Phonegap is somehow cool, but events…

As of the time of this writing, I simply could not fully understand which event is fired and when. I am talking about the “deviceready” event, which should be fired when – surprise – the device is ready to work with. Meanwhile I have deleted it. I simply could not catch it. I have tried the example from the docs.

This line will only work on the Android emulator, but not on the iPhone simulator:
document.addEventListener("deviceready", onDeviceReady, false);

Not sure why. Phonegap is a bit of a blackbox for me at the moment. It gives you some good starting points for your project, but somewhere in the middle, you cannot say what is going on.
Android pain

I took a good while until i reckognized that you need to call http://10.0.2.2 and not http://localhost if you want to send a request to your working machine (the machine, which runs the emulator). There is no documentation, just a bug somewhere in the Android project. This behavior is documented, but I did find it via the bug report. If you read this and if you are curious why your Ajax request does not arrive on your webserver, well, change the URL to 10.0.2.2.

And of course, you need to write a manifest file for android, giving it all permissions you can get. It has been said somewhere that you’ll need all permissions to make it work. So far I cannot agree to that, it works for me with just the internet enabled (I only need that one).

After all you will see the painful slow Android emulator. At one time I had 25 minutes boot time before I cancelled. You can solve this issue with setting your emulator to a low resolution (320×480). I cannot launch from Snapshot, because it will break the startup. Others have said this helps with startup time. When I first saw this low-speed beast, I really was not impressed. The iPhone Simulator is so much better. I remembered the old times when I tried to load a text adventure from tape into my C64. This is real pain.

What you’ll get, once it is running, is a pretty good error console.

BUT at the time of this writing – not all my AJAX requests are fired, even when they should. So far I cannot login with a specific user, with another I can. And then I see completely outdated sets of data. Not sure why. On the iPhone it works pretty well.

And no, the Android animations are slow and ugly. You can even see the .destroy calls of a page.

I am really disappointed of the Android emulator, I need to say it.
iPhone

The iPhone start logging later than Android, or never. Sometimes I get log messages, sometimes not. Don’t think about using Xcode for JavaScript development. The code formatter is drunken. But I have to admit, the iPhone simulator (compared to the Android one) is a quick beast and joy to work with.

What really bugs me is that I need to pay 99$ a year just to develop on the apple device. I mean what’s going on guys! Developing and deploying to a test device should be free of charge.
Summary

My Android app is still not usable. Phonegap/jQuery Mobile is not really platform independent. It is more “write once, debug everywhere” (I heard this about Java in old times).

I am still not sure what I do now, but it seems to me I will start the 0.1 version of my SaaS tool with iPhone first. At the moment my feeling says that I should not invest more money in Phonegap/jQuery mobile but start to develop a native app for Android. Of course the whole benefits of phonegap/jquery mobile are gone then. But I really cannot give that to my customers.

So cool html/javascript development on mobile is, it is future. Phonegap needs to be 100% platform independent. jQuery mobile and Phonegap need much better docs. Both frameworks need some more cycles to be really good.

Sunday, 17 June 2012

What is Android?



Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.
Features

    Application framework enabling reuse and replacement of components
    Dalvik virtual machine optimized for mobile devices
    Integrated browser based on the open source WebKit engine
    Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)
    SQLite for structured data storage
    Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
    GSM Telephony (hardware dependent)
    Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
    Camera, GPS, compass, and accelerometer (hardware dependent)
    Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE


Android Architecture

The following diagram shows the major components of the Android operating system. Each section is described in more detail below.

Applications

Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language.
Application Framework

By providing an open development platform, Android offers developers the ability to build extremely rich and innovative applications. Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more.

Developers have full access to the same framework APIs used by the core applications. The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities (subject to security constraints enforced by the framework). This same mechanism allows components to be replaced by the user.

Underlying all applications is a set of services and systems, including:

    A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser
    Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data
    A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files
    A Notification Manager that enables all applications to display custom alerts in the status bar
    An Activity Manager that manages the lifecycle of applications and provides a common navigation backstack

For more details and a walkthrough of an application, see the Notepad Tutorial.
Libraries

Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. Some of the core libraries are listed below:

    System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices
    Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG
    Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications
    LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view
    SGL - the underlying 2D graphics engine
    3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer
    FreeType - bitmap and vector font rendering
    SQLite - a powerful and lightweight relational database engine available to all applications

Android Runtime

Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.

Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool.

The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.
Linux Kernel

Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.

Friday, 15 June 2012

Android 4.0 Ice Cream Sandwich


Android 4.0 Ice Cream Sandwich

Android 4.0 (Ice Cream Sandwich) is the latest version of the Android platform for phones, tablets, and more. It builds on the things people love most about Android — easy multitasking, rich notifications, customizable home screens, resizable widgets, and deep interactivity — and adds powerful new ways of communicating and sharing.
Simple, Beautiful, Useful
Refined, evolved UI

Focused on bringing the power of Android to the surface, Android 4.0 makes common actions more visible and lets you navigate with simple, intuitive gestures. Refined animations and feedback throughout the system make interactions engaging and interesting. An entirely new typeface optimized for high-resolution screens improves readability and brings a polished, modern feel to the user interface.

Home screen folders and favorites tray

New home screen folders offer a new way for you to group your apps and shortcuts logically, just by dragging one onto another. Also, in All Apps launcher, you can now simply drag an app to get information about it or immediately uninstall it, or disable a pre-installed app.

Resizable widgets

Home screens in Android 4.0 are designed to be content-rich and customizable. You can do much more than add shortcutsyou can embed live application content directly through interactive widgets. Widgets let you check email, flip through a calendar, play music, check social streams, and more — right from the home screen, without having to launch apps. Widgets are resizable, so you can expand them to show more content or shrink them to save space.

New lock screen actions

The lock screens now let you do more without unlocking. From the slide lock screen, you can jump directly to the camera for a picture or pull down the notifications window to check for messages. When listening to music, you can even manage music tracks and see album art.
Quick responses for incoming calls

When an incoming call arrives, you can now quickly respond by text message, without needing to pick up the call or unlock the device. On the incoming call screen, you simply slide a control to see a list of text responses and then tap to send and end the call. You can add your own responses and manage the list from the Settings app.
Swipe to dismiss notifications, tasks, and browser tabs

Android 4.0 makes managing notifications, recent apps, and browser tabs even easier. You can now dismiss individual notifications, apps from the Recent Apps list, and browser tabs with a simple swipe of a finger.
A spell-checker lets you find errors and fix them faster.
A powerful voice input engine lets you dictate continuously.
Improved text input and spell-checking

The soft keyboard in Android 4.0 makes text input even faster and more accurate. Error correction and word suggestion are improved through a new set of default dictionaries and more accurate heuristics for handling cases such as double-typed characters, skipped letters, and omitted spaces
Powerful voice input engine

Android 4.0 introduces a powerful new voice input engine that offers a continuous "open microphone" experience and streaming voice recognition. The new voice input engine lets you dictate the text you want, for as long as you want, using the language you want. You can speak continously for a prolonged time, even pausing for intervals if needed, and dictate punctuation to create correct sentences. As the voice input engine enters text, it underlines possible dictation errors in gray.

Control over network data

Mobile devices can make extensive use of network data for streaming content, synchronizing data, downloading apps, and more. To meet the needs of you with tiered or metered data plans, Android 4.0 adds new controls for
Designed for accessibility

A variety of new features greatly enhance the accessibility of Android 4.0 for blind or visually impaired users. Most important is a new explore-by-touch mode that lets you navigate without having to see the screen. Touching the screen once triggers audible feedback that identifies the UI component below; a second touch in the same component activates it with a full touch event
Communication and sharing
People and profiles

Throughout the system, your social groups, profiles, and contacts are linked together and integrated for easy accessibility. At the center is a new People app that offers richer profile information, including a large profile picture, phone numbers, addresses and accounts, status updates, events, and a new button for connecting on integrated social networks.
Unified calendar, visual voicemail

To help organize appointments and events, an updated Calendar app brings together personal, work, school, and social agendas. With user permission, other applications can contribute events to the calendar and manage reminders, for an integrated view across multiple calendar providers. The app is redesigned to let you manage events more easily. Calendars are color-coded and you can swipe left or right to change dates and pinch to zoom in or out agendas.
Rich and versatile camera capabilities

The Camera app includes many new features that let you capture special moments with great photos and videos. After capturing images, you can edit and share them easily with friends.
Redesigned Gallery app with photo editor

The Gallery app now makes it easier to manage, show, and share photos and videos. For managing collections, a redesigned album layout shows many more albums and offers larger thumbnails.
Live Effects for transforming video

Live Effects is a collection of graphical transformations that add interest and fun to videos captured in the Camera app. For example, you can change the background behind them to any stock or custom image, for just the right setting when shooting video. Also available for video is Silly Faces,
Sharing with screenshots

You can now share what's on your screens more easily by taking screenshots. Hardware buttons let them snap a screenshot and store it locally.
Cloud-connected experience

Android has always been cloud-connected, letting you browse the web and sync photos, apps, games, email, and contacts — wherever you are and across all of your devices. Android 4.0 adds new browsing and email capabilities to let you take even more with them and keep communication organized.
Powerful web browsing

The Android Browser offers an experience that’s as rich and convenient as a desktop browser. It lets you instantly sync and manage Google Chrome bookmarks from all of your accounts, jump to your favorite content faster, and even save it for reading later in case there's no network available.

To get the most out of web content, you can now request full desktop versions of web sites, rather than their mobile versions

Thursday, 14 June 2012

JDBC Driver and Its Types



JDBC Driver Manager

The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture. It is quite small and simple.

This is a very important class. Its main purpose is to provide a means of managing the different types of JDBC database driver. On running an application, it is the DriverManager's responsibility to load all the drivers found in the system property jdbc. drivers. For example, this is where the driver for the Oracle database may be defined. This is not to say that a new driver cannot be explicitly stated in a program at runtime which is not included in jdbc.drivers. When opening a connection to a database it is the DriverManager' s role to choose the most appropriate driver from the previously loaded drivers.


Types of JDBC drivers

This topic defines the Java(TM) Database Connectivity (JDBC) driver types. Driver types are used to categorize the technology used to connect to the database. A JDBC driver vendor uses these types to describe how their product operates. Some JDBC driver types are better suited for some applications than others.

  There are  four types of JDBC drivers known as:

    JDBC-ODBC bridge plus ODBC driver, also called Type 1.
    Native-API, partly Java driver, also called Type 2.
    JDBC-Net, pure Java driver, also called Type 3.
    Native-protocol, pure Java driver, also called Type 4.


Type 1 Driver- the JDBC-ODBC bridge

The JDBC type 1 driver, also known as the JDBC-ODBC bridge is a database driver implementation that employs the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls. The bridge is usually used when there is no pure-Java driver available for a particular database.

The driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class and comes with the Java 2 SDK, Standard Edition. The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the operating system. Also, using this driver has got other dependencies such as ODBC must be installed on the computer having the driver and the database which is being connected to must support an ODBC driver. Hence the use of this driver is discouraged if the alternative of a pure-Java driver is available.

Type 2 Driver - the Native-API Driver

The JDBC type 2 driver, also known as the Native-API driver is a database driver implementation that uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API.

The type 2 driver is not written entirely in Java as it interfaces with non-Java code that makes the final database calls.
The driver is compiled for use with the particular operating system. For platform interoperability, the Type 4 driver, being
a full-Java implementation, is preferred over this driver.

A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.



Type 3 driver - the Network-Protocol Driver

The JDBC type 3 driver, also known as the network-protocol driver is a database driver implementation which makes use of a middle-tier between the calling program and the database. The middle-tier (application server) converts JDBC calls directly or indirectly into the vendor-specific database protocol.

This differs from the type 4 driver in that the protocol conversion logic resides not at the client, but in the middle-tier. However, like type 4 drivers, the type 3 driver is written entirely in Java.

The same driver can be used for multiple databases. It depends on the number of databases the middleware has been configured to support. The type 3 driver is platform-independent as the platform-related differences are taken care by the middleware. Also, making use of the middleware provides additional advantages of security and firewall access.


Type 4 - the Native-Protocol Driver

The JDBC type 4 driver, also known as the native-protocol driver is a database driver implementation that converts JDBC calls directly into the vendor-specific database protocol.

The type 4 driver is written completely in Java and is hence platform independent. It is installed inside the Java Virtual Machine of the client. It provides better performance over the type 1 and 2 drivers as it does not have the overhead of conversion of calls into ODBC or database API calls. Unlike the type 1 and 2 drivers, it does not need associated software to work.

 

Wednesday, 13 June 2012

Java - Exceptions Handling


An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:

    A user has entered invalid data.

    A file that needs to be opened cannot be found.

    A network connection has been lost in the middle of communications, or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.

To understand how exception handling works in Java, you need to understand the three categories of exceptions:

    Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.

    Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.

    Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.


Exception Hierarchy:

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors.

The Exception class has two main subclasses : IOException class and RuntimeException Class.
Java Exceptions
Exceptions Methods:

Following is the list of important medthods available in the Throwable class.
SN    Methods with Description
1    public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
2    public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3    public String toString()
Returns the name of the class concatenated with the result of getMessage()
4    public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5    public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
6    public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Java - Exceptions Handling



An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:

    A user has entered invalid data.

    A file that needs to be opened cannot be found.

    A network connection has been lost in the middle of communications, or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.

To understand how exception handling works in Java, you need to understand the three categories of exceptions:

    Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.

    Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.

    Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.


Exception Hierarchy:

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors.

The Exception class has two main subclasses : IOException class and RuntimeException Class.
Java Exceptions
Exceptions Methods:

Following is the list of important medthods available in the Throwable class.
SN    Methods with Description
1    public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
2    public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3    public String toString()
Returns the name of the class concatenated with the result of getMessage()
4    public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5    public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
6    public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Tuesday, 12 June 2012

java Servlet Container

java Servlet Container

A servlet container is nothing but a compiled, executable program. The main function of the container is to load, initialize and execute servlets. The servlet container is the official Reference Implementation for the Java Servlet and JavaServer Pages technologies. The Java Servlet and JavaServer Pages specifications are developed by Sun under the Java Community Process.

A container handles large number of requests as it can hold many active servlets, listeners etc. It is interesting to note here that the container and the objects in a container are multithreaded. So each object must be thread safe in a container as the multiple requests are being handled by the container due to the entrance of more than one thread to an object at a time.

Note : A Servlet container may run stand alone i.e. without a web server or even on another host.

We can categorize the servlet containers as:

I. A simple servlet container is not fully functional and therefore it can only run very simple servlets and does the following :

    Wait for HTTP request.
    Construct a ServletRequest object and a ServletResponse object.
    If the request is for a static resource, invoke the process method of the StaticResourceProcessor instance, passing the ServletRequest and ServletResponse objects.
    If the request is for a servlet, load the servlet class and invoke its service method, passing the ServletRequest and ServletResponse objects. Note that in this servlet container, the servlet class is loaded every time the servlet is requested.

II. A fully functional servlet container additionally does the following for each HTTP request for a servlet:

    When the servlet is called for the first time, load the servlet class and call its init method (once only).
    For each request, construct an instance of javax.servlet.ServletRequest and an instance of javax.servlet.ServletResponse.
    Invoke the servlet's service method, passing the ServletRequest and ServletResponse objects.
    When the servlet class is shut down, call the servlet's destroy method and unload the servlet class.

Now lets see what a servlet container does for each HTTP request for a servlet, in general :

    The servlet container loads the servlet class and calls the init method of the servlet as soon as the servlet is called for the first time.
    Then this container makes an instance of javax.servlet.ServletRequest and javax.servlet.ServletResponse for each request.
    Then it passes the ServletRequest and ServletResponse objects by invoking the servlet's service method.
    Finally, it calls the destroy method and unload the servlet class when the servlet class is to be shut down.

Monday, 11 June 2012

Demonstrate ArrayList.

ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)

The first constructor builds an empty array list. The second constructor builds an array list that is initialized with the elements of the collection c. The third constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.

The following program shows a simple use of ArrayList. An array list is created, and then objects of type String are added to it. (Recall that a quoted string is translated into a String object.) The list is then displayed. Some of the elements are removed and the list is displayed again.


Demonstrate ArrayList.

import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " +
al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);
}
}



The output from this program is shown here:


Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]

Sunday, 10 June 2012

About java


Java is a simple and yet powerful object oriented programming language and it is in many respects similar to C++. Java was given birth at Sun Microsystems, Inc. in 1991. Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. It was developed to provide a platform-independent programming language.
Platform independent

Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by Java virtual Machine (JVM) on whichever platform it is being run. 

Java Virtual Machine

What is the Java Virtual Machine? Why is its role?

Java was designed with a concept of ‘write once and run everywhere’. Java Virtual Machine plays the central role in this concept. The Java Virtual Machine (JVM) is the environment in which Java programs execute. It is a software that is implemented on top of real hardware and operating system.
When Java source code (.java files) is compiled, it is translated into Java bytecodes and then placed into (.class) files. The JVM executes Java bytecodes. So Java bytecodes can be thought of as the machine language of the JVM. A Java virtual machine can either interpret the bytecode one instruction at a time or the bytecode can be compiled further for the real microprocessor using what is called a just-in-time compiler. The JVM must be implemented on a particular platform before compiled Java programs can run on that platform.

Java has powerful features. The following are some of them:-
Java is object oriented

Since Java is an object oriented programming language it has following advantages:
Reusability of Code
Emphasis on data rather than procedure
Data is hidden and cannot be accessed by external functions
Objects can communicate with each other through functions
New data and functions can be easily added

Java is Distributed

With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and access the objects across net via URLs.

Java is Multithreaded

One of the powerful aspects of the Java language is that it allows multiple threads of execution to run concurrently within the same program A single Java program can have many different threads executing independently and continuously. Multiple Java applets can run on the browser at the same time sharing the CPU time.

Java is Secure

Java was designed to allow secure execution of code across network. To make Java secure many of the features of C and C++ were eliminated. Java does not use Pointers. Java programs cannot access arbitrary addresses in memory.

Garbage collection

Automatic garbage collection is another great feature of Java with which it prevents inadvertent corruption of memory. Similar to C++, Java has a new operator to allocate memory on the heap for a new object. But it does not use delete operator to free the memory as it is done in C++ to free the memory if the object is no longer needed. It is done automatically with garbage collector.

Application of Java

Java has evolved from a simple language providing interactive dynamic content for web pages to a predominant enterprise-enabled programming language suitable for developing significant and critical applications. Today, Java is used for many types of applications including Web based applications, Financial applications, Gaming applications, embedded systems, Distributed enterprise applications, mobile applications, Image processors, desktop applications and many more.