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