Saturday, 28 April 2012

FTP - What Does FTP Stand For?



Definition: FTP allows you to transfer files between two computers on the Internet. FTP is a simple network protocol based on Internet Protocol and also a term used when referring to the process of copying files when using FTP technology.

To transfer files with FTP, you use a program often called the "client." The FTP client program initiates a connection to a remote computer running FTP "server" software. After the connection is established, the client can choose to send and/or receive copies of files, singly or in groups. To connect to an FTP server, a client requires a username and password as set by the administrator of the server. Many public FTP archives follow a special convention for that accepts a username of "anonymous."

Simple FTP clients are included with most network operating systems, but most of these clients (such as FTP.EXE on Windows) support a relatively unfriendly command-line interface. Many alternative freeware / shareware third-party FTP clients have been developed that support graphic user interfaces (GUIs) and additional convenience features. In any FTP interface, clients identify the FTP server either by its IP address (such as 192.168.0.1) or by its host name (such as ftp.about.com).

FTP supports two modes of data transfer: plain text (ASCII), and binary. You set the mode in the FTP client. A common error when using FTP is attempting to transfer a binary file (such as a program or music file) while in text mode, causing the transfered file to be unusable.
Also Known As: File Transfer Protocol


   
how to connect FTP server in java ?


import com.enterprisedt.net.ftp.*;
import java.net.*;
import java.io.*;
import java.net.InetAddress;
import java.text.*;
import java.util.*;


public class myFTPClient
{
String str[];
public static void main(String args[]) throws IOException, FTPException{

FTPClient f= new FTPClient("10.4.3.20");

f.login("ibolt","ibolt");

//FTPClient f = New FTPClient("10.1.1.4");
System.out.println("connection establish");

f.setConnectMode(FTPConnectMode.ACTIVE);
f.setType(FTPTransferType.ASCII);


//System.out.println("connection establish1");
f.get("C:/temp/pp.txt","map1.txt");

//System.out.println("connection establish3");

//System.out.println("connection released");


}



}

Thursday, 26 April 2012

6 Common Errors in Setting Java Heap Size


Two JVM options are often used to tune JVM heap size: -Xmx for maximum heap size, and -Xms for initial heap size. Here are some common mistakes I have seen when using them:

    Missing m, M, g or G at the end (they are case insensitive). For example,

    java -Xmx128 BigApp
    java.lang.OutOfMemoryError: Java heap space

    The correct command should be: java -Xmx128m BigApp. To be precise, -Xmx128 is a valid setting for very small apps, like HelloWorld. But in real life, I guess you really mean -Xmx128m

    Extra space in JVM options, or incorrectly use =. For example,

    java -Xmx 128m BigApp
    Invalid maximum heap size: -Xmx
    Could not create the Java virtual machine.

    java -Xmx=512m HelloWorld
    Invalid maximum heap size: -Xmx=512m
    Could not create the Java virtual machine.

    The correct command should be java -Xmx128m BigApp, with no whitespace nor =. -X options are different than -Dkey=value system properties, where = is used.

    Only setting -Xms JVM option and its value is greater than the default maximum heap size, which is 64m. The default minimum heap size seems to be 0. For example,

    java -Xms128m BigApp
    Error occurred during initialization of VM
    Incompatible initial and maximum heap sizes specified

    The correct command should be java -Xms128m -Xmx128m BigApp. It's a good idea to set the minimum and maximum heap size to the same value. In any case, don't let the minimum heap size exceed the maximum heap size.

    Heap size is larger than your computer's physical memory. For example,

    java -Xmx2g BigApp
    Error occurred during initialization of VM
    Could not reserve enough space for object heap
    Could not create the Java virtual machine.

    The fix is to make it lower than the physical memory: java -Xmx1g BigApp

    Incorrectly use mb as the unit, where m or M should be used instead.

    java -Xms256mb -Xmx256mb BigApp
    Invalid initial heap size: -Xms256mb
    Could not create the Java virtual machine.

    The heap size is larger than JVM thinks you would ever need. For example,

    java -Xmx256g BigApp
    Invalid maximum heap size: -Xmx256g
    The specified size exceeds the maximum representable size.
    Could not create the Java virtual machine.

    The fix is to lower it to a reasonable value: java -Xmx256m BigApp

    The value is not expressed in whole number. For example,

    java -Xmx0.9g BigApp
    Invalid maximum heap size: -Xmx0.9g
    Could not create the Java virtual machine.

    The correct command should be java -Xmx928m BigApp

PS:

How to set java heap size in Tomcat?
Stop Tomcat server, set environment variable CATALINA_OPTS, and then restart Tomcat. Look at the file tomcat-install/bin/catalina.sh or catalina.bat for how this variable is used. For example,

set CATALINA_OPTS=-Xms512m -Xmx512m  (Windows, no "" around the value)
export CATALINA_OPTS="-Xms512m -Xmx512m"  (ksh/bash, "" around the value)
setenv CATALINA_OPTS "-Xms512m -Xmx512m"  (tcsh/csh, "" around the value)

In catalina.bat or catallina.sh, you may have noticed CATALINA_OPTS, JAVA_OPTS, or both can be used to specify Tomcat JVM options. What is the difference between CATALINA_OPTS and JAVA_OPTS? The name CATALINA_OPTS is specific for Tomcat servlet container, whereas JAVA_OPTS may be used by other java applications (e.g., JBoss). Since environment variables are shared by all applications, we don't want Tomcat to inadvertently pick up the JVM options intended for other apps. I prefer to use CATALINA_OPTS.

How to set java heap size in JBoss?
Stop JBoss server, edit $JBOSS_HOME/bin/run.conf, and then restart JBoss server. You can change the line with JAVA_OPTS to something like:

JAVA_OPTS="-server -Xms128m -Xmx128m"

How to set java heap size in Eclipse?
You have 2 options:
1. Edit eclipse-home/eclipse.ini to be something like the following and restart Eclipse.

-vmargs
-Xms64m
-Xmx256m

2. Or, you can just run eclipse command with additional options at the very end. Anything after -vmargs will be treated as JVM options and passed directly to the JVM. JVM options specified in the command line this way will always override those in eclipse.ini. For example,

eclipse -vmargs -Xms64m -Xmx256m

How to set java heap size in NetBeans?
Exit NetBeans, edit the file netbeans-install/etc/netbeans.conf. For example,

netbeans_default_options="-J-Xms512m -J-Xmx512m -J-XX:PermSize=32m -J-XX:MaxPermSize=128m -J-Xverify:none

How to set java heap size in Apache Ant?
Set environment variable ANT_OPTS. Look at the file $ANT_HOME/bin/ant or %ANT_HOME%\bin\ant.bat, for how this variable is used by Ant runtime.

set ANT_OPTS=-Xms512m -Xmx512m  (Windows)
export ANT_OPTS="-Xms512m -Xmx512m"  (ksh/bash)
setenv ANT_OPTS "-Xms512m -Xmx512m"  (tcsh/csh)

How to set java heap size in jEdit?
jEdit is a java application, and basically you need to set minimum/maximum heap size JVM options when you run java command. jEdit by default runs with a default maximum heap size 64m. When you work on large files, you are likely to get these errors:

java.lang.OutOfMemoryError: Java heap space
at java.lang.String.concat(String.java:2001)
at org.gjt.sp.jedit.buffer.UndoManager.contentInserted(UndoManager.java:160)
at org.gjt.sp.jedit.Buffer.insert(Buffer.java:1139)
at org.gjt.sp.jedit.textarea.JEditTextArea.setSelectedText(JEditTextArea.java:2052)
at org.gjt.sp.jedit.textarea.JEditTextArea.setSelectedText(JEditTextArea.java:2028)
at org.gjt.sp.jedit.Registers.paste(Registers.java:263)


How to fix it? If you click a desktop icon, or Start menu item to start jEdit: right-click the icon or menu item, view its property, and you can see its target is something like:

C:\jdk6\bin\javaw.exe -jar "C:\jedit\jedit.jar"

You can change that line to:

C:\jdk6\bin\javaw.exe -Xmx128m -Xms128m -jar "C:\jedit\jedit.jar"

If you run a script to start jEdit: just add these JVM options to the java line inside the script file:

java -Xmx128m -Xms128m -jar jedit.jar

If you start jEdit by running java command: just add these JVM options to your java command:

java -Xmx128m -Xms128m -jar jedit.jar

Note that when you run java with -jar option, anything after -jar jar-file will be treated as application arguments. So you should always put JVM options before -jar. Otherwise, you will get error:

C:\jedit>java -jar jedit.jar -Xmx128m
Unknown option: -Xmx128m
Usage: jedit [options] [files]

How to set java heap size in JavaEE SDK/J2EE SDK/Glassfish/Sun Java System Application Server?
Stop the application server, edit
$GLASSFISH_HOME/domains/domain1/config/domain.xml, search for XML element name java-config and jvm-options. For example,

<java-config suffix="...">
<jvm-options>-Xmx512m</jvm-options>
<jvm-options>-XX:NewRatio=2</jvm-options>
<jvm-options>-XX:MaxPermSize=128m</jvm-options>
...</java-config>

You can also change these settings in the web-based admin console, typically at http://localhost:4848/, or https://localhost:4848/. Go to Application Server near the top of the left panel, and then on the right panel, click JVM Settings | JVM Options, and you will see a list of existing JVM options. You can add new ones and modify existing ones there.

Yet another option is to use its Command Line Interface (CLI) tool command, such as:

./asadmin help create-jvm-options
./asadmin help delete-jvm-options

They may be a bit hard to use manually, but are well suited for automated scripts.

Wednesday, 25 April 2012

Connecting to a MySQL Database using Connector JDBC Driver

 What are Database URLs in JDBC?
    Why and how to specify a JDBC Driver name?
    How to create a connection to a Database?
    An example on how to connect to a MySQL Database?

What are Database URLs in JDBC?
URL stands for "Uniform Resource Locator". You will be familiar with HTTP URLs that you normally use to access a web site e.g. http://www.stardeveloper.com. URLs are used to identify a resource using a unique name.

Same goes for database URLs in JDBC. JDBC requires that all database connection strings should be represented by URLs. The URLs used in JDBC have following structure:
jdbc:subprotocol:subname

In HTTP you begin a URL with the protocol name i.e. http:, similarly in JDBC driver URLs, you start the URL with protocol name i.e. jdbc:. Next subprotocol represents the database you want to connect to e.g. mysql, oracle, odbc etc. While subname provides additional information on how and where to connect.
Examples of Database URLs
Following are some examples of JDBC database URLs:

    jdbc:odbc:dsn_name;UID=your_uid;PWD=your_pwd - JDBC-ODBC Bridge Driver URL.
    jdbc:oracle:thin:@machine_name:port_number:instance_name - Orace Type 4 JDBC Driver.
    jdbc:mysql://host_name:port/dbname - MySQL Connector/J JDBC Driver.

Why and how to specify a JDBC Driver name?
Next thing you need to know besides the database URL is the full class name of your JDBC driver e.g. com.mysql.jdbc.Driver in case of MySQL Connector/J JDBC driver. The name of the driver is a requirement and is not optional.
You can tell JVM about what driver/s to use by using one of the following methods:

    To load the the driver/s at JVM startup, specify the driver/s in jdbc.drivers system property like this:

    java -Djdbc.drivers=com.mysql.jdbc.Driver YourJavaProgram

    To explicitly load the driver, use Class.forName() method in your code like this:

    Class.forName("com.mysql.jdbc.Driver").newInstance();


The example discussed in this tutorial makes use of the second option discussed above.

How to create a connection to a Database?
To create a connection to a database, you will have to use java.sql.DriverManager's getConnection() method. This method takes as an argument the database URL (that we discussed earlier) you want to connect to. It then internally finds the appropriate driver which has been loaded in the JVM and then delegates the work of creating the connection to that driver.

An example on how to connect to a MySQL Database?
After learning the theory behind connecting to a database, we'll now move on to create a Java program which will connect to a MySQL database running on your local system.

Tuesday, 24 April 2012

Package javax.interceptor


Contains annotations and interfaces for defining interceptor methods, interceptor classes and for binding interceptor classes to target classes.
Interceptor methods

An interceptor method may be defined on a target class itself or on an interceptor class associated with the target class.

There are three kinds of interceptor method:

    method interceptor methods for methods of a target class (e.g. managed bean / EJB component)
    timeout method interceptor methods for timeout methods of a target class (e.g. EJB component)
    lifecycle callback interceptor methods for @PostConstruct and @PreDestroy callbacks of managed beans and EJB components and for @PrePassivate and @PostActivate methods of EJB stateful session beans.

An interceptor method may be defined by annotating the method, or using the EJB deployment descriptor. Interceptor methods may not be declared static or final.

An interceptor class or target class may have multiple interceptor methods. However, an interceptor class or target class may have no more than one interceptor method for a certain type of interception: AroundInvoke, AroundTimeout, PostConstruct, PreDestroy, PrePassivate or PostActivate.
Interceptor classes

An interceptor class is a class (distinct from the target class) whose methods are invoked in response to invocations and/or lifecycle events on the target class. Any number of interceptor classes may be associated with a target class.

An interceptor class must have a public constructor with no parameters.

Interceptor classes may be annotated @Interceptor, but this is not required when @Interceptors or the EJB deployment descriptor are used to bind the interceptor to its target classes.
Defining the interceptor classes of a target class

Interceptor classes of a target class or method of a target class may be defined in several ways:

    By annotating the target class or method of the target class with @Interceptors and specifying the interceptor class.
    If the target class is an EJB component, by using the EJB deployment descriptor.
    If the target class is a CDI bean, by annotating both the interceptor class and the target class with an interceptor binding.

Any interceptor class may be defined to apply to a target class at the class level. In the case of method interceptors, the interceptor applies to all methods of the target class. In the case of timeout method interceptors, the interceptor applies to all timeout methods of the target class.

@ExcludeClassInterceptors or the EJB deployment descriptor may be used to exclude the invocation of class level interceptors for a method of a target class.

A method interceptor may be defined to apply only to a specific method of the target class. Likewise, a timeout method interceptor may be defined to apply only to a specific timeout method of the target class. However, if an interceptor class that defines lifecycle callback interceptor methods is defined to apply to a target class at the method level, the lifecycle callback interceptor methods are not invoked.
Default Interceptors

Default interceptors may be defined to apply to a set of target classes using the EJB deployment descriptor. The default interceptors are invoked before any other interceptors for a target class. The EJB deployment descriptor may be used to specify alternative orderings.

@ExcludeDefaultInterceptors or the EJB deployment descriptor may be used to exclude the invocation of default interceptors for a target class or method of a target class.
Interceptor lifecycle

The lifecycle of an interceptor instance is the same as that of the target class instance with which it is associated. When the target instance is created, a corresponding interceptor instance is created for each associated interceptor class. These interceptor instances are destroyed when the target instance is destroyed.

Both the interceptor instance and the target instance are created before any @PostConstruct callbacks are invoked. Any @PreDestroy callbacks are invoked before the destruction of either the target instance or interceptor instance.

An interceptor instance may hold state. An interceptor instance may be the target of dependency injection. Dependency injection is performed when the interceptor instance is created, using the naming context of the associated target class. The @PostConstruct interceptor callback method is invoked after this dependency injection has taken place on both the interceptor instances and the target instance.

An interceptor class shares the enterprise naming context of its associated target class. Annotations and/or XML deployment descriptor elements for dependency injection or for direct JNDI lookup refer to this shared naming context.
Interceptors for lifecycle callbacks

A lifecycle callback interceptor method is a non-final, non-static method with return type void of the target class (or superclass) or of any interceptor class. A lifecycle callback interceptor method declared by the target class (or superclass) must have no parameters. A lifecycle callback interceptor method declared by an interceptor class must have a single parameter of type InvocationContext.

Wednesday, 18 April 2012

Java Servelets must to Know?

1. What are Java Servlets?
Servlets are Java technology's answer to CGI programming. They are programs that run on a Web server and build Web pages. Building Web pages on the fly is useful (and commonly done) for a number of reasons:

    The Web page is based on data submitted by the user. For example the results pages from search engines are generated this way, and programs that process orders for e-commerce sites do this as well.
    The data changes frequently. For example, a weather-report or news headlines page might build the page dynamically, perhaps returning a previously built page if it is still up to date.
    The Web page uses information from corporate databases or other such sources. For example, you would use this for making a Web page at an on-line store that lists current prices and number of items in stock.

2. What are the Advantage of Servlets Over "Traditional" CGI?
Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI and than many alternative CGI-like technologies. (More importantly, servlet developers get paid more than Perl programmers :-).

    Efficient. With traditional CGI, a new process is started for each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the code for the CGI program is loaded into memory N times. With servlets, however, there are N threads but only a single copy of the servlet class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping database connections open, and the like.
    Convenient. Hey, you already know Java. Why learn Perl too? Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.
    Powerful. Java servlets let you easily do several things that are difficult or impossible with regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI programs can't). This simplifies operations that need to look up images and other data stored in standard places. Servlets can also share data among each other, making useful things like database connection pools easy to implement. They can also maintain information from request to request, simplifying things like session tracking and caching of previous computations.
    Portable. Servlets are written in Java and follow a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a plugin on almost every major Web server.
    Inexpensive. There are a number of free or very inexpensive Web servers available that are good for "personal" use or low-volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that server, adding servlet support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap.

3. What is JSP?
Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with dynamically-generated HTML. Many Web pages that are built by CGI programs are mostly static, with the dynamic part limited to a few small locations. But most CGI variations, including servlets, make you generate the entire page via your program, even though most of it is always the same. JSP lets you create the two parts separately. Here's an example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>Welcome to Our Store</TITLE></HEAD>
<BODY>
<H1>Welcome to Our Store</H1>
<SMALL>Welcome,
<!-- User name is "New User" for first-time visitors -->
<% out.println(Utils.getUserNameFromCookie(request)); %>
To access your account settings, click
<A HREF="Account-Settings.html">here.</A></SMALL>
<P>
Regular HTML for all the rest of the on-line store's Web page.
</BODY></HTML>

4. What are the Advantages of JSP?

    vs. Active Server Pages (ASP). ASP is a similar technology from Microsoft. The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS-specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers.
    vs. Pure Servlets. JSP doesn't give you anything that you couldn't in principle do with a servlet. But it is more convenient to write (and to modify!) regular HTML than to have a zillion println statements that generate the HTML. Plus, by separating the look from the content you can put different people on different tasks: your Web page design experts can build the HTML, leaving places for your servlet programmers to insert the dynamic content.
    vs. Server-Side Includes (SSI). SSI is a widely-supported technology for including externally-defined pieces into a static Web page. JSP is better because it lets you use servlets instead of a separate program to generate that dynamic part. Besides, SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like.
    vs. JavaScript. JavaScript can generate HTML dynamically on the client. This is a useful capability, but only handles situations where the dynamic information is based on the client's environment. With the exception of cookies, HTTP and form submission data is not available to JavaScript. And, since it runs on the client, JavaScript can't access server-side resources like databases, catalogs, pricing information, and the like.
    vs. Static HTML. Regular HTML, of course, cannot contain dynamic information. JSP is so easy and convenient that it is quite feasible to augment HTML pages that only benefit marginally by the insertion of small amounts of dynamic data. Previously, the cost of using dynamic data would preclude its use in all but the most valuable instances.

Tuesday, 17 April 2012

As an Interactive Voice Response (IVR) functions

Meet Emily. Emily works for Bell Canada, answers phones for the service. It comes from the province of New Brunswick, graduated from Carleton University and has music in his spare time. It is also a computer.

"Emily" is the title reaction Bell Canada Interactive Voice Response (IVR) system (Bio she asked '] press release is available.) When a customer calls to inquire about the account or to speak Support Specialist, will speak to Emily first. In a quiet, pre-recorded voice, Emily leads them through the menu, the software for voice recognition is the difference between "Billing" and understand "support." If the customer wants "real" customer service rep to speak, he can always press zero. Emily will not be offended.

It is difficult for a customer-oriented company that does not go by human operators IVR mind. If you call your credit card, you can use IVR to pay the balance or report a fraudulent charge. Airlines use extensive IVR booking process and make sure that real-time flight status. Pharmacies use IVRs for refilling regulations. And almost everyone uses a separate call to the IVR extension or access the company phone directory.

Large and small businesses have adopted IVR technology because it saves money that would otherwise be used for living, breathing staff (expensive). IVR system efficiency is the percentage of callers who rated ask the live operator. The lower the percentage, the more successful system. Of course there are some IVR systems that you never to speak to a live operator. But for fans of the IVR, it is bad practice.

Working as automated phone systems? Let's talk about the truth of the robot or just a smart piece of software? Read on to learn more about the technology for IVR systems.

Tuesday, 10 April 2012

What Is a Package?


Programmers are an organized bunch when it comes to writing code. They like to arrange their programs so that they flow in a logical way, calling separate blocks of code that each has a particular job. Organizing the classes they write is done by creating packages.

What Are Packages?

A package allows a developer to group classes (and interfaces) together. These classes will all be related in some way – they might all be to do with a specific application or perform a specific set of tasks. For example, the Java API is full of packages. One of them is the javax.xml package. It and its subpackages contain all the classes in the Java API to do with handling XML.

Defining a Package

To group classes into a package each class must have a package statement defined at the top of its .java file. It lets the compiler know which package the class belongs to and must be the first line of code. For example, imagine you're making a simple Battleships game. It makes sense to put all the classes needed in a package called battleships:

 package battleships

 class GameBoard{

 }
Every class with the above package statement at the top will now be part of the Battleships package.

Typically packages are stored in a corresponding directory on the filesystem but it is possible to store them in a database. The directory on the filesystem must have the same name as the package. It's where all the classes belonging to that package are stored. For example, if the battleships package contains the classes GameBoard, Ship, ClientGUI then there will be files called GameBoard.java, Ship.java and ClientGUI.java stored in a directory call battleships.

Creating a Hierarchy

Organizing classes doesn't have to be at just one level. Every package can have as many subpackages as needed. To distinguish the package and subpackage a "." is placed in-between the package names. For example, the name of the javax.xml package shows that xml is a subpackage of the javax package. It doesn't stop there, under xml there are 11 subpackages: bind, crypto, datatype, namespace, parsers, soap, stream, transform, validation, ws and xpath.

The directories on the file system must match the package hierarchy. For example, the classes in the javax.xml.crypto package will live in a directory structure of ..\javax\xml\crypto.

It should be noted that the hierarchy created is not recognized by the compiler. The names of the packages and subpackages show the relationship that the classes they contain have with each other. But, as far as the compiler is concerned each package is a distinct set of classes. It does not view a class in a subpackage as being part of its parent package. This distinction becomes more apparent when it comes to using packages.

Naming Packages

There is a standard naming convention for packages. Names should be in lowercase. With small projects that only have a few packages the names are typically simple (but meaningful!) names:

 package pokeranalyzer
 package mycalculator
In software companies and large projects, where the packages might be imported into other classes, the names need to be distinctive. If two different packages contain a class with the same name it's important that there can be no naming conflict. This is done by ensuring the package names are different by starting the package name with the company domain, before being split into layers or features:

 package com.mycompany.utilities
 package org.bobscompany.application.userinterface

Friday, 6 April 2012

What is polymorphism in Java? Method overloading or overriding?

Polymorphism is an important Object oriented concept and widely used in Java and other programming language.  Polymorphism in java is supported along with other concept like abstraction, encapsulation and inheritance. bit on historical side polymorphism word comes from ancient Greek where poly means many so polymorphic are something which can take many form. In this java polymorphism tutorial we will see what polymorphism in Java is, how polymorphism is implemented in Java, why should we use polymorphism and how can we take advantage of polymorphism while writing code in Java. Along the way we will also see a real world example of using polymorphism in Java.

By the way I learned about abstraction, encapsulation and polymorphism during my college time but never able to recognize its real potential until I started doing programming and involved in bigger projects. On theory Polymorphism is a simple concept where One variable can denote multiple object but in real life it just a gem and a code written using polymorphism concept is much flexible to change and quite easy to maintain than the one which is written without polymorphism.

What is polymorphism in Java
Polymorphism is an Oops concept which advice use of common interface instead of concrete implementation while writing code. When we program for interface our code is capable of handling any new requirement or enhancement arise in near future due to new implementation of our common interface. If we don't use common interface and rely on concrete implementation, we always need to change and duplicate most of our code to support new implementation. Its not only java but other object oriented language like C++ also supports polymorphism and it comes as fundamental along with encapsulation , abstraction and inheritance.

How Polymorphism supported in Java
Java has excellent support of polymorphism in terms of Inheritance, method overloading and method overriding. Method overriding allows java to invoke method based on a particular object at run-time instead of declared type while coding. To get hold of concept let's see an example of polymorphism in java:

class TradingSystem{
public String getDescription(){
return "electronic trading system";
}
}

class DirectMarketAccessSystem extends TradingSystem{
public String getDescription(){
return "direct market access system";
}
}

class CommodityTradingSystem extends TradingSystem{
public String getDescription(){
return "Futures trading system";
}
}

Here we have a super class called TradingSystem and there two implementation DirectMarketAccessSystem and CommodityTradingSystem and here we will write code which is flexible enough to work with any future implementation of TradingSystem we can achieve this by using polymorphism in java which we will see in further example.

Where to use Polymorphism in code
Probably this is the most important part of this java polymorphism tutorial and It’s good to know where you can use polymorphism in java while writing code. Its common practice to always replace concrete implementation with interface it’s not that easy and s comes with practice but here are some common places where I check for polymorphism:


1) Method argument:
Always use super type in method argument that will give you leverage to pass any implementation while invoking method. For example:

public void showDescription(TradingSystem tradingSystem){
tradingSystem.description();
}
If you have used concrete implementation e.g. CommodityTradingSystem or DMATradingSystem then that code will require frequent changes whenever you add new Trading system.



2) Variable names:
Always use Super type while you are storing reference returned from any Factory object, this gives you Flexibility to accommodate any new implementation from Factory. Here is an example of polymorphism while writing java code which you can use retrieving reference from Factory:

String systemName = Configuration.getSystemName();
TradingSystem system = TradingSystemFactory.getSystem(systemName);


Method overloading and method overriding in Java
Method is overloading and method overriding uses concept of polymorphism in java where method name remains same in two classes but actual method called by JVM depends upon object. Java supports both overloading and overriding of methods. In case of overloading method signature changes while in case of overriding method signature remains same and binding and invocation of method is decided on runtime based on actual object. This facility allows java programmer to write very flexibly and maintainable code using interfaces without worrying about concrete implementation. One disadvantage of using polymorphism in code is that while reading code you don't know the actual type which annoys while you are looking to find bugs or trying to debug program. But if you do java debugging in IDE you will definitely be able to see the actual object and the method call and variable associated with it.


Parameteric Polymorphism in Java
Java started to support parametric polymorphism with introduction of generic in JDK1.5. Collection classes in JDK 1.5 are written using Generic Type which allows Collections to hold any type of object in run time without any change in code and this has been achieved by passing actual Type as parameter. For example see the below code of a parametric cache written using generic which shows use of parametric polymorphism in Java.

interface cache{
public void put(K key, V value);
public V get(K key);
}



That’s all on polymorphism in java for now, please suggest and share some of other coding practices which involve use o f polymorphic behavior of java for benefit of all. Thank you.

Thursday, 5 April 2012

ANDROID INTERVIEW QUESTIONS AND ANSWERS

How do you declare 4 components of android in mainfestfile?



What are intent filters?
Intents filter are used to register activity, services, broadcast receiver as being capable of performing an action on a particular kind of action.
How many ways data stored in android?
Shared preferences
Internal storage
External storage
Sqlite database
Network connetion
User interface types?
Views
Notifications
Types of notification in android?
Tost notification
Status bar notification
Dialog notification
How do you find any view element into your program?
Findviewbyid
What is handler class do in android?
Handler allows yo to send and process message and runnable objects associated with a thread’s message queue.
Describe the APK format.
The APK file is compressed the AndroidManifest.xml file, application code (.dex files), resource files, and other files. A project is compiled into a single .apk file.
What is an action?
The Intent Sender desires something or doing some task
What is activity?
A single screen in an application, with supporting Java code.
What is intent in Android?
A class (Intent) will describes what a caller desires to do. The caller will send this intent to Android's intent resolver, which finds the most suitable activity for the intent. E.g. opening a PDF document is an intent, and the Adobe Reader apps will be the perfect activity for that intent(class).
What is a Sticky Intent?
sendStickyBroadcast() performs a sendBroadcast (Intent) known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver (BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).
Example for sticky broadcast
When you call registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.
How the nine-patch Image different from a regular bitmap? or Different between nine-patch Image vs regular Bitmap Image
It is one of a resizable bitmap resource which is being used as backgrounds or other images on the device. The NinePatch class allows drawing a bitmap in nine sections. The four corners are unscaled; the middle of the image is scaled in both axes, the four edges are scaled into one axis.
What Programming languages does Android support for application development?
Android applications supports using Java Programming Language. which is coded in Java and complied using Android SDK.
What is a resource?
A user defined JSON, XML, bitmap, or other file, injected into the application build process, which can later be loaded from code.
How will you record a phone call in Android? or How to handle on Audio Stream for a call in Android?
Permissions.PROCESS_OUTGOING_CALLS: Will Allows an application to monitor, modify, or abort outgoing calls. So through that we can monitor the Phone calls.
What's the difference between class, file and activity in android?
Class - The Class file is complied from .java file. Android will use this .class file to produce the executable apk.
File - It is a block of resources, srbitrary information. It can be any file type.
Activity - An activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view.
Does Android support the Bluetooth serial port profile?
A. Yes.
Can an application be started on powerup?
A. Yes.
What is APK format.
The APK file is compressed AndroidManifest.xml file with extension .apk, Which have application code (.dex files), resource files, and other files which is compressed into single .apk file.
How to Translate in android
The Google translator translates the data of one language into another language by using XMPP to transmit data. You can type the message in English and select the language which is understood by the citizens of the country in order to reach the message to the citizens.
What is an action?
A description of something that an Intent sender desires.
What are the advantages of Android?
The following are the advantages of Android:
* The customer will be benefited from wide range of mobile applications to choose, since the monopoly of wireless carriers like Orange and AT&T will be broken by Google Android.
* Features like weather details, live RSS feeds, opening screen, icon on the opening screen can be customized
* Innovative products like the location-aware services, location of a nearby convenience store etc., are some of the additive facilities in Android.
Introduction Android:
Android is an operating system for mobile devices that includes middleware and key applications, and uses a modified version of the Linux kernel. It was initially developed by Android Inc..It allows developers to write managed code in the Java language, controlling the device via Google-developed Java libraries…..
The Android SDK includes a comprehensive set of development tools . These include a debugger, libraries, a handset emulator (based on QEMU), documentation, sample code, and tutorials. Currently supported development platforms include x86-architecture computers running Linux (any modern desktop Linux distribution), Mac OS X 10.4.8 or later, Windows XP or Vista.
Android does not use established Java standards, i.e. Java SE and ME. This prevents compatibility among Java applications written for those platforms and those for the Android platform. Android only reuses the Java language syntax, but does not provide the full-class libraries and APIs bundled with Java SE or ME
What is android?
Android is a stack of software for mobile devices which has Operating System, middleware and some key applications. The application executes within its own process and its own instance of Dalvik Virtual Machine. Many Virtual Machines run efficiently by a DVM device. DVM executes Java language?s byte code which later transforms into .dex format files.
What are the advantages of Android?
The following are the advantages of Android:
* The customer will be benefited from wide range of mobile applications to choose, since the monopoly of wireless carriers like AT&T and Orange will be broken by Google Android.
* Features like weather details, live RSS feeds, opening screen, icon on the opening screen can be customized
* Innovative products like the location-aware services, location of a nearby convenience store etc., are some of the additive facilities in Android.
Components can be reused and replaced by the application framework.
*Optimized DVM for mobile devices
*SQLite enables to store the data in a structured manner.
*Supports GSM telephone and Bluetooth, WiFi, 3G and EDGE technologies
*The development is a combination of a device emulator, debugging tools, memory profiling and plug-in for Eclipse IDE.
Features of Android
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.§
Explain about the exceptions of Android?
The following are the exceptions that are supported by Android
* InflateException : When an error conditions are occurred, this exception is thrown
* Surface.OutOfResourceException: When a surface is not created or resized, this exception is thrown
* SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS
* WindowManager.BadTokenException: This exception is thrown at the time of trying to add view an invalid WindowManager.LayoutParamstoken.
Describe the APK format.
The APK file is compressed the AndroidManifest.xml file, application code (.dex files), resource files, and other files. A project is compiled into a single .apk file.
What is .apk extension?
The extension for an Android package file, which typically contains all of the files related to a single Android application. The file itself is a compressed collection of an AndroidManifest.xml file, application code (.dex files), resource files, and other files. A project is compiled into a single .apk file.
What is .dex extension
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created by automatically translating compiled applications written in the Java programming language
What is an adb ?
Android Debug Bridge, a command-line debugging application shipped with the SDK. It provides tools to browse the device, copy tools on the device, and forward ports for debugging.
What is an Application ?
A collection of one or more activities, services, listeners, and intent receivers. An application has a single manifest, and is compiled into a single .apk file on the device.
What is a Content Provider ?
A class built on ContentProvider that handles content query strings of a specific format to return data in a specific format. See Reading and writing data to a content provider for information on using content providers.
What is a Dalvik ?
The name of Android’s virtual machine. The Dalvik VM is an interpreter-only virtual machine that executes files in the Dalvik Executable (.dex) format, a format that is optimized for efficient storage and memory-mappable execution. The virtual machine is register-based, and it can run classes compiled by a Java language compiler that have been transformed into its native format using the included “dx” tool. The VM runs on top of Posix-compliant operating systems, which it relies on for underlying functionality (such as threading and low level memory management). The Dalvik core class library is intended to provide a familiar development base for those used to programming with Java Standard Edition, but it is geared specifically to the needs of a small mobile device.
What is an DDMS
Dalvik Debug Monitor Service, a GUI debugging application shipped with the SDK. It provides screen capture, log dump, and process examination capabilities.
What is Drawable?
A compiled visual resource that can be used as a background, title, or other part of the screen. It is compiled into an android.graphics.drawable subclass.
What is an Intent?
A class (Intent) that contains several fields describing what a caller would like to do. The caller sends this intent to Android’s intent resolver, which looks through the intent filters of all applications to find the activity most suited to handle this intent. Intent fields include the desired action, a category, a data string, the MIME type of the data, a handling class, and other restrictions.
What is an Intent Filter ?
Activities and intent receivers include one or more filters in their manifest to describe what kinds of intents or messages they can handle or want to receive. An intent filter lists a set of requirements, such as data type, action requested, and URI format, that the Intent or message must fulfill. For Activities, Android searches for the Activity with the most closely matching valid match between the Intent and the activity filter. For messages, Android will forward a message to all receivers with matching intent filters.
What is an Intent Receiver?
An application class that listens for messages broadcast by calling Context.broadcastIntent
What is a Layout resource?
An XML file that describes the layout of an Activity screen.
What is a Manifest ?
An XML file associated with each Application that describes the various activies, intent filters, services, and other items that it exposes.
What is a Resource
A user-supplied XML, bitmap, or other file, entered into an application build process, which can later be loaded from code. Android can accept resources of many types; see Resources for a full description. Application-defined resources should be stored in the res/ subfolders.
What is a Service ?
A class that runs in the background to perform various persistent actions, such as playing music or monitoring network activity.
What is a Theme ?
A set of properties (text size, background color, and so on) bundled together to define various default display settings. Android provides a few standard themes, listed in R.style (starting with “Theme_”).
What is an URIs?
Android uses URI strings both for requesting data (e.g., a list of contacts) and for requesting actions (e.g., opening a Web page in a browser). Both are valid URI strings, but have different values. All requests for data must start with the string “content://”. Action strings are valid URIs that can be handled appropriately by applications on the device; for example, a URI starting with “http://” will be handled by the browser.
Can I write code for Android using C/C++?
Yes, but need to use NDK
Android applications are written using the Java programming language. 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.
Android only supports applications written using the Java programming language at this time.
What is an action?
A description of something that an Intent sender desires.
What is activity?
A single screen in an application, with supporting Java code.
What is intent?
A class (Intent) describes what a caller desires to do. The caller sends this intent to Android’s intent resolver, which finds the most suitable activity for the intent. E.g. opening a PDF file is an intent, and the Adobe Reader is the suitable activity for this intent.
How is nine-patch image different from a regular bitmap?
It is a resizable bitmap resource that can be used for backgrounds or other images on the device. The NinePatch class permits drawing a bitmap in nine sections. The four corners are unscaled; the four edges are scaled in one axis, and the middle is scaled in both axes.
What languages does Android support for application development?
Android applications are written using the Java programming language.
What is a resource?
A user-supplied XML, bitmap, or other file, injected into the application build process, which can later be loaded from code.
How will you record a phone call in Android? How to get a handle on Audio Stream for a call in Android?
Permissions.PROCESS_OUTGOING_CALLS: Allows an application to monitor, modify, or abort outgoing calls.
What’s the difference between file, class and activity in android?
File – It is a block of arbitrary information, or resource for storing information. It can be of any type.
Class – Its a compiled form of .Java file . Android finally used this .class files to produce an executable apk
Activity – An activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view.
What is a Sticky Intent?
sendStickyBroadcast() performs a sendBroadcast (Intent) that is “sticky,” i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver (BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).
One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver() for that action — even with a null BroadcastReceiver — you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.
Does Android support the Bluetooth serial port profile?
Yes.
Can an application be started on powerup?
Yes.
How to Remove Desktop icons and Widgets
A. Press and Hold the icon or widget. The phone will vibrate and on the bottom of the phone you will see anoption to remove. While still holding the icon or widget drag it to the remove button. Once remove turns red drop the item and it is gone
Describe a real time scenario where android can be used?
Imagine a situation that you are in a country where no one understands the language you speak and you can not read or write. However, you have mobile phone with you.
With a mobile phone with android, the Google translator translates the data of one language into another language by using XMPP to transmit data. You can type the message in English and select the language which is understood by the citizens of the country in order to reach the message to the citizens.
How to select more than one option from list in android xml file?
Give an example.
Specify android id, layout height and width as depicted in the following example.
What languages does Android support for application development?
Android applications are written using the Java programming language.
Describe Android Application Architecture.
Android Application Architecture has the following components:
• Services – like Network Operation
• Intent – To perform inter-communication between activities or services
• Resource Externalization – such as strings and graphics
• Notification signaling users – light, sound, icon, notification, dialog etc.
• Content Providers – They share data between applications
Common Tricky questions
Remember that the GUI layer doesn’t request data directly from the web; data is always loaded from a local database.§
The service layer periodically updates the local database.§
What is the risk in blocking the Main thread when performing a lengthy operation such as web access or heavy computation? Application_Not_Responding exception will be thrown which will crash and restart the application.§
Why is List View not recommended to have active components? Clicking on the active text box will pop up the software keyboard but this will resize the list, removing focus from the clicked element.§
Open Source
What is the Android Open Source Project?
We use the phrase “Android Open Source Project” or “AOSP” to refer to the people, the processes, and the source code that make up Android.
The people oversee the project and develop the actual source code. The processes refer to the tools and procedures we use to manage the development of the software. The net result is the source code that you can use to build cell phone and other devices.
Why did we open the Android source code?
Google started the Android project in response to our own experiences launching mobile apps. We wanted to make sure that there would always be an open platform available for carriers, OEMs, and developers to use to make their innovative ideas a reality. We also wanted to make sure that there was no central point of failure, so that no single industry player could restrict or control the innovations of any other. The single most important goal of the Android Open-Source Project (AOSP) is to make sure that the open-source Android software is implemented as widely and compatibly as possible, to everyone’s benefit.
You can find more information on this topic at our Project Philosophy page.
What kind of open-source project is Android?
Google oversees the development of the core Android open-source platform, and works to create robust developer and user communities. For the most part the Android source code is licensed under the permissive Apache Software License 2.0, rather than a “copyleft” license. The main reason for this is because our most important goal is widespread adoption of the software, and we believe that the ASL2.0 license best achieves that goal.
You can find more information on this topic at our Project Philosophy and Licensing pages.
Why is Google in charge of Android?
Launching a software platform is complex. Openness is vital to the long-term success of a platform, since openness is required to attract investment from developers and ensure a level playing field. However, the platform itself must also be a compelling product to end users.
That’s why Google has committed the professional engineering resources necessary to ensure that Android is a fully competitive software platform. Google treats the Android project as a full-scale product development operation, and strikes the business deals necessary to make sure that great devices running Android actually make it to market.
By making sure that Android is a success with end users, we help ensure the vitality of Android as a platform, and as an open-source project. After all, who wants the source code to an unsuccessful product?
Google’s goal is to ensure a successful ecosystem around Android, but no one is required to participate, of course. We opened the Android source code so anyone can modify and distribute the software to meet their own needs.
What is Google’s overall strategy for Android product development?
We focus on releasing great devices into a competitive marketplace, and then incorporate the innovations and enhancements we made into the core platform, as the next version.
In practice, this means that the Android engineering team typically focuses on a small number of “flagship” devices, and develops the next version of the Android software to support those product launches. These flagship devices absorb much of the product risk and blaze a trail for the broad OEM community, who follow up with many more devices that take advantage of the new features. In this way, we make sure that the Android platform evolves according to the actual needs of real-world devices.
How is the Android software developed?
Each platform version of Android (such as 1.5, 1.6, and so on) has a corresponding branch in the open-source tree. At any given moment, the most recent such branch will be considered the “current stable” branch version. This current stable branch is the one that manufacturers port to their devices. This branch is kept suitable for release at all times.
Simultaneously, there is also a “current experimental” branch, which is where speculative contributions, such as large next-generation features, are developed. Bug fixes and other contributions can be included in the current stable branch from the experimental branch as appropriate.
Finally, Google works on the next version of the Android platform in tandem with developing a flagship device. This branch pulls in changes from the experimental and stable branches as appropriate.
You can find more information on this topic at our Branches and Releases.
Why are parts of Android developed in private?
It typically takes over a year to bring a device to market, but of course device manufacturers want to ship the latest software they can. Developers, meanwhile, don’t want to have to constantly track new versions of the platform when writing apps. Both groups experience a tension between shipping products, and not wanting to fall behind.
To address this, some parts of the next version of Android including the core platform APIs are developed in a private branch. These APIs constitute the next version of Android. Our aim is to focus attention on the current stable version of the Android source code, while we create the next version of the platform as driven by flagship Android devices. This allows developers and OEMs to focus on a single version without having to track unfinished future work just to keep up. Other parts of the Android system that aren’t related to application compatibility are developed in the open, however. It’s our intention to move more of these parts to open development over time.
When are source code releases made?
When they are ready. Some parts of Android are developed in the open, so that source code is always available. Other parts are developed first in a private tree, and that source code is released when the next platform version is ready.
In some releases, core platform APIs will be ready far enough in advance that we can push the source code out for an early look in advance of the device’s release; however in others, this isn’t possible. In all cases, we release the platform source when we feel the version has stabilized enough, and when the development process permits. Releasing the source code is a fairly complex process.
What is involved in releasing the source code for a new Android version?
Releasing the source code for a new version of the Android platform is a significant process. First, the software gets built into a system image for a device, and put through various forms of certification, including government regulatory certification for the regions the phones will be deployed. It also goes through operator testing. This is an important phase of the process, since it helps shake out a lot of software bugs.
Once the release is approved by the regulators and operators, the manufacturer begins mass producing devices, and we turn to releasing the source code.
Simultaneous to mass production the Google team kicks off several efforts to prepare the open source release. These efforts include final API changes and documentation (to reflect any changes that were made during qualification testing, for example), preparing an SDK for the new version, and launching the platform compatibility information.
Also included is a final legal sign-off to release the code into open source. Just as open source contributors are required to sign a Contributors License Agreement attesting to their IP ownership of their contribution, Google too must verify that it is clear to make contributions.
Starting at the time mass production begins, the software release process usually takes around a month, which often roughly places source code releases around the same time that the devices reach users.
How does the AOSP relate to the Android Compatibility Program?
The Android Open-Source Project maintains the Android software, and develops new versions. Since it’s open-source, this software can be used for any purpose, including to ship devices that are not compatible with other devices based on the same source.
The function of the Android Compatibility Program is to define a baseline implementation of Android that is compatible with third-party apps written by developers. Devices that are “Android compatible” may participate in the Android ecosystem, including Android Market; devices that don’t meet the compatibility requirements exist outside that ecosystem.
In other words, the Android Compatibility Program is how we separate “Android compatible devices” from devices that merely run derivatives of the source code. We welcome all uses of the Android source code, but only Android compatible devices — as defined and tested by the Android Compatibility Program — may participate in the Android ecosystem.
How can I contribute to Android?
There are a number of ways you can contribute to Android. You can report bugs, write apps for Android, or contribute source code to the Android Open-Source Project.
There are some limits on the kinds of code contributions we are willing or able to accept. For instance, someone might want to contribute an alternative application API, such as a full C++-based environment. We would decline that contribution, since Android is focused on applications that run in the Dalvik VM. Alternatively, we won’t accept contributions such as GPL or LGPL libraries that are incompatible with our licensing goals.
We encourage those interested in contributing source code to contact us via the AOSP Community page prior to beginning any work. You can find more information on this topic at the Getting Involved page.
How do I become an Android committer?
The Android Open Source Project doesn’t really have a notion of a “committer”. All contributions — including those authored by Google employees — go through a web-based system known as “gerrit” that’s part of the Android engineering process. This system works in tandem with the git source code management system to cleanly manage source code contributions.
Once submitted, changes need to be accepted by a designated Approver. Approvers are typically Google employees, but the same approvers are responsible for all submissions, regardless of origin.
You can find more information on this topic at the Submitting Patches page.
Compatibility
What does “compatibility” mean?
We define an “Android compatible” device as one that can run any application written by third-party developers using the Android SDK and NDK. We use this as a filter to separate devices that can participate in the Android app ecosystem, and those that cannot. Devices that are properly compatible can seek approval to use the Android trademark. Devices that are not compatible are merely derived from the Android source code and may not use the Android trademark.
In other words, compatibility is a prerequisite to participate in the Android apps ecosystem. Anyone is welcome to use the Android source code, but if the device isn’t compatible, it’s not considered part of the Android ecosystem.
What is the role of Android Market in compatibility?
Devices that are Android compatible may seek to license the Android Market client software. This allows them to become part of the Android app ecosystem, by allowing users to download developers’ apps from a catalog shared by all compatible devices. This option isn’t available to devices that aren’t compatible.
What kinds of devices can be Android compatible?
The Android software can be ported to a lot of different kinds of devices, including some on which third-party apps won’t run properly. The Android Compatibility Definition Document (CDD) spells out the specific device configurations that will be considered compatible.
For example, though the Android source code could be ported to run on a phone that doesn’t have a camera, the CDD requires that in order to be compatible, all phones must have a camera. This allows developers to rely on a consistent set of capabilities when writing their apps.
The CDD will evolve over time to reflect market realities. For instance, the 1.6 CDD only allows cell phones, but the 2.1 CDD allows devices to omit telephony hardware, allowing for non-phone devices such as tablet-style music players to be compatible. As we make these changes, we will also augment Android Market to allow developers to retain control over where their apps are available. To continue the telephony example, an app that manages SMS text messages would not be useful on a media player, so Android Market allows the developer to restrict that app exclusively to phone devices.
If my device is compatible, does it automatically have access to Android Market and branding?
Android Market is a service operated by Google. Achieving compatibility is a prerequisite for obtaining access to the Android Market software and branding. Device manufacturers should contact Google to obtain access to Android Market.
If I am not a manufacturer, how can I get Android Market?
Android Market is only licensed to handset manufacturers shipping devices. For questions about specific cases, contact android-partnerships@google.com.
How can I get access to the Google apps for Android, such as Maps?
The Google apps for Android, such as YouTube, Google Maps and Navigation, Gmail, and so on are Google properties that are not part of Android, and are licensed separately. Contact android-partnerships@google.com for inquiries related to those apps.
Is compatibility mandatory?
No. The Android Compatibility Program is optional. Since the Android source code is open, anyone can use it to build any kind of device. However, if a manufacturer wishes to use the Android name with their product, or wants access to Android Market, they must first demonstrate that the device is compatible.
How much does compatibility certification cost?
There is no cost to obtain Android compatibility for a device. The Compatibility Test Suite is open-source and available to anyone to use to test a device.
How long does compatibility take?
The process is automated. The Compatibility Test Suite generates a report that can be provided to Google to verify compatibility. Eventually we intend to provide self-service tools to upload these reports to a public database.
Who determines what will be part of the compatibility definition?
Since Google is responsible for the overall direction of Android as a platform and product, Google maintains the Compatibility Definition Document for each release. We draft the CDD for a new Android version in consultation with a number of OEMs, who provide input on its contents.
How long will each Android version be supported for new devices?
Since Android’s code is open-source, we can’t prevent someone from using an old version to launch a device. Instead, Google chooses not to license the Android Market client software for use on versions that are considered obsolete. This allows anyone to continue to ship old versions of Android, but those devices won’t use the Android name and will exist outside the Android apps ecosystem, just as if they were non-compatible.
Can a device have a different user interface and still be compatible?
The Android Compatibility Program focuses on whether a device can run third-party applications. The user interface components shipped with a device (such as home screen, dialer, color scheme, and so on) does not generally have much effect on third-party apps. As such, device builders are free to customize the user interface as much as they like. The Compatibility Definition Document does restrict the degree to which OEMs may alter the system user interface for areas that do impact third-party apps.
When are compatibility definitions released for new Android versions?
Our goal is to release new versions of Android Compatibility Definition Documents (CDDs) once the corresponding Android platform version has converged enough to permit it. While we can’t release a final draft of a CDD for an Android software version before the first flagship device ships with that software, final CDDs will always be released after the first device. However, wherever practical we will make draft versions of CDDs available.
How are device manufacturers’ compatibility claims validated?
There is no validation process for Android device compatibility. However, if the device is to include Android Market, Google will typically validate the device for compatibility before agreeing to license the Market client software.
What happens if a device that claims compatibility is later found to have compatibility problems?
Typically, Google’s relationships with Android Market licensees allow us to ask them to release updated system images that fix the problems.
Compatibility Test Suite
What is the purpose of the CTS?
The Compatibility Test Suite is a tool used by device manufacturers to help ensure their devices are compatible, and to report test results for validations. The CTS is intended to be run frequently by OEMs throughout the engineering process to catch compatibility issues early.
What kinds of things does the CTS test?
The CTS currently tests that all of the supported Android strong-typed APIs are present and behave correctly. It also tests other non-API system behaviors such as application lifecycle and performance. We plan to add support in future CTS versions to test “soft” APIs such as Intents as well.
Will the CTS reports be made public?
Yes. While not currently implemented, Google intends to provide web-based self-service tools for OEMs to publish CTS reports so that they can be viewed by anyone. CTS reports can be shared as widely as manufacturers prefer.
How is the CTS licensed?
The CTS is licensed under the same Apache Software License 2.0 that the bulk of Android uses.
Does the CTS accept contributions?
Yes please! The Android Open-Source Project accepts contributions to improve the CTS in the same way as for any other component. In fact, improving the coverage and quality of the CTS test cases is one of the best ways to help out Android.
Can anyone use the CTS on existing devices?
The Compatibility Definition Document requires that compatible devices implement the ‘adb’ debugging utility. This means that any compatible device — including ones available at retail — must be able to run the CTS tests.
For more information on Cheap Air Tickets ( Domestic Flights and International Flight ) , Bus Booking , tour packages, rail tickets , hotels booking please check on via .com

Tuesday, 3 April 2012

Android and different notification sounds and E-mail Notifier


How to set individual notification sounds for different types of messages (SMS, calendar, email) on Android smartphone. Yes, HTC has support and it's possible to have different sounds for incoming SMS and Email.

Navigate to Notification Sound settings (Personalize menu on HTC can be opened directly - just click on palette icon in the lower right corner):
Menu -> Settings -> Personalize -> Notification Sound

After "Notification Sound" is opened, you can set different sounds for:
Default notification
Message
Calendar
Email

Unfortunately, default HTC mail client supports only one sound for all email accounts. I'm not happy but I can live with that. On the other hand, K-9 email client (which has many excellent features and is free) supports different notification sounds for each email account. At least it always exists alternative option in Android World.


E-mail Notifier for incoming email notification - currently for Gmail and K-9 Mail accounts (only popup for K9).

IMPORTANT:

You need Gmail 2.3.4 or older. Latest Gmail (2.3.5) update will not work! Unfortunately, the new Gmail update enforces signature-type permission which can't be accessed by any 3rd party notification app.


Features:
* On-screen preview of new email
* Shows number of unread email conversations
* Multiple email accounts (Gmail / K-9 Mail)
* E-mail Privacy
* Sound, vibration and LED
* Reminders
* Quiet hours feature

Recent changes:
From v1.3.4:
Improved Gmail and K-9 Mail detection code and other fixes.

!!! You need Gmail 2.3.4 or older for Gmail notification. Latest Gmail (2.3.5) update will not work! Unfortunately, the new Gmail update enforces signature-type permission. We're hoping Google will let us allow access Gmail's API in some of the Gmail's upcoming updates.

From v1.3:
*NEW* K-9 support - extends K-9's notification functionality with interactive or non-interactive per account customizable on-screen popups

java for Android applications


1 - Java MSN Messenger Library (Jml)
If you want to use the MSN Messenger protocol in your application, Jml is the best choice. Jml a Java library support for MSN MSNP8-MSNP12. Is. It is optimized for different users and is designed to be very easy to use and follow.
A number of developers and their design is supposed to be used in a series of projects, including but not limited to: '


    JClaim (general circulation within the public IM + UI)
    Communicate with SIP - the Java VoIP and IM clients
    Openfire IM Gateway plugin
    MSN alerts
    MSN2Go
    Omnivide
    Instant Kiosk

SourceForge site, you can make some quick examples, resources and useful links too.

2 - Marauroa - Arianne multiplayer online engine
Arianne Marauroa is a multiplayer online engine, you can use to build their own online games using Marauroa for object management, perseverance and understanding based database

Client-server communication.
Marauroa completely written in Java using a multithreaded server architecture with a TCP oriented network, a MySQL based persistence engine or H2 and a flexible

System in open systems is fully upgraded and modified by developers. Rules can be written in Java, and Python scripts can be used is small.
Arianne - multiplayer online role playing game development framework for

Full API documentation and a page on this site you can find.


3 - Using Skype JSkype Java programming
JSkype
At this site you can use Java JSkype allows customers to use the Skype API to find. But the old version, but I think Skype will not solve the problem.

4 - Facebook API
Facebook for Android Wiki
Facebook Android SDK
Alpha version of the official SDK to integrate Facebook into their mobile Android application there.

5 - API Twitter
There are a number of additional deputy Documentation on Twitter.
For Java developers:
Twitter4J by Yusuke Yamamoto. Open source, mavenized Google and Twitter API Library Java engine security software, released under the BSD License.
Java DeWitt Clinton Twitter. Pure Java interface for the Twitter API.
jtwitter by Daniel Winterstein. Open source pure Java interface to Twitter.
The gist of Twitter client, Java client companies to connect to the API.

Sunday, 1 April 2012

Java Synchronization


Introduction

The Java programming language supports multiple threads, using a monitor construction for synchronization. In the Java language, a method can be declared as synchronized. A built-in mechanism ensures that only one Java thread can execute an object's synchronized methods at a time. The mechanism also allows threads to wait for resources to become available, and allows a thread that makes a resource available to notify other threads that are waiting for the resource. This web page describes this mechanism and its use. But first, we need to look at an example that illustrates why synchronization is needed.

The Bounded Buffer Problem

In the Bounded Buffers problem, there are two kinds of processes or threads: producers and consumers. Producers take buffers from a queue of empty buffers, put content into the buffers, and place the buffers into a queue of full buffers. Consumers take buffers from a queue of full buffers, do something with the buffers' contents, and place the buffers back onto the queue of empty buffers. Each of the buffer queues has a bounded capacity for buffers. Processes communicating through a pipe or communicating through mailboxes are examples of the Bounded Buffers problem.

There is generally only one queue of empty buffers, maintained by the operating system. It provides all buffers for processes or threads. There can be multiple producers, consumers, and queues of full buffers. The queues of full buffers usually have a small capacity, on the order of 10 buffers. We generally only need to consider a single queue of full buffers at a time. The following picture illustrates the flow of buffers.

Figure 1. Buffer flow in the Bounded Buffers Problem.
java synchronizedbuffer-flow


A First Solution

When we have a good solution to the Bounded Buffers problem, the coordination between producers and consumers will be controlled by two BufferQueue objects representing the queue of empty buffers and the queue of full buffers. The following code is an implementation of a BufferQueue class that works well in a single-threaded environment.
Testing the First Solution

We are limited in the kind of testing we can do on this first version of the BufferQueue class. There is no good way of making producers wait for empty buffers or making consumers wait for full buffers. So we will only use producers. Initially the queue of empty buffers has 10 buffers and the queue of full buffers has none. We first run a single producer that moves buffers from the queue of empty buffers to the queue of full buffers as long as the queue of empty buffers is not empty. The producer kills time for 20 milliseconds on the average after removing a buffer from the queue of empty buffers and kills time for 20 milliseconds on the average after putting the buffer on the queue of full buffers