Wednesday, July 28, 2010

Ant

> Ant is a pure Java build tool

> Ant allows the developer to automate the repeated process involved in the development of J2EE application.

> Developers can easily write the script to automate the build process like compilation, archiving and deployment.


> Downloading and Installing Ant
> Set the class path to the bin directory of the ant.

Let's assume that Ant is installed in c:\ant\. The following code has to be put into autoexec.bat file:

set ANT_HOME=c:\ant
set JAVA_HOME=c:\Program Files\Java\jdk1.6.0\
set PATH=%PATH%;%ANT_HOME%\bin

Testing Ant

Go to command prompt and issue the following command.

C:\anttest>Ant

Buildfile: build.xml does not exist!Build failed

C:\anttest>

If every this is installed correctly Ant will give the above message.

Now its time to do some work with Ant.

Ant uses configuration file called build.xml to work. This is the file where you defines the process of compiling, building and deploying.

Writing build.xml file

build.xml is a xml file used by ant utility to compile, build and deploy or run the application.

Now here is code of simple build.xml file which compiles a java file present in src directory and places compiled class file in build/src directory.


<?xml version="1.0"?>

<!-- Build file for our first application -->

< project name="Ant test project" default="build" basedir=".">

< target name="build" >

< javac srcdir="src" destdir="build/src" debug="true"

includes="**/*.java"

/>

</target>

</project>

-------------------------------------------------------------------------
The project tag:


requires three attributes namely name, default and basedir.

Here is the description of the attributes:

name |Represents the name of the project.
----------------------------------------------------
default |Name of the default target to use when no target is supplied.
basedir |Name of the base directory from which all path calculations are done.

All the attributes are required.


—-build1.xml ——–
< project name=”hello” default=”hello”>
< target name=”hello”>
< echo message=”Hello, World”/>
</target>

< target name=”goodbye”>
< echo message=”Goodbye, end of Hello world script”/>
< /target>
< /project>

Monday, July 26, 2010

mysql dump

>mysql -u root -p password

How to backup MySQL database? - using mysqldump -


>mysqldump -u [user] -p [database_name] > [backupfile].dump



dump restore

>mysql [database_name] < [backup_file].dump


drop the schema

>mysqladmin -u root -p drop schema_name


> mv rt3newdump.sql /home/karthik/temp
>mysqladmin -u root -p create rt3
>mysql -u root -p rt3 < rt3newdump.sql


How do I quickly rename a mysql database (change schema name)?

mysqldump -u username -p -v olddatabase > olddbdump.sql
mysqladmin -u username -p create newdatabase
mysql -u username -p newdatabase < olddbdump.sql

Thursday, July 22, 2010

Formatter Class in J2SE 1.5

Java 1.5 introduces a new class named java.util.Formatter that allows you to do string formatting similar to the printf function in C. It depends heavily on the varargs feature being introduced in 1.5

System.out.printf

String initials = "rk";
String comment = "just because";
System.out.printf("reason: %s (noted by %s)", comment, initials);

The example prints the following output on the console:

reason: just because (noted by rk)

----------------
String.format

If you only want to obtain a formatted string, but not print it, you can use the static method format on the String class. Here's an example that also demonstrates a few numeric conversions:

int a = 65;
String s =
String.format("char: %c integral: %d octal: %o hex: %x %n",
a, a, a, a);

The %n at the end of the format string indicates a platform-specific line separator. When printed, the String s looks like this:

char: A integral: 65 octal: 101 hex: 41

Numeric conversions also support flags for padding, grouping, justification, and sign.
-----------------------
Dates

Formatter provides an extensive number of date-related conversions. The following code:

String.format("%1$td %1$tb %1$ty", new Date())

produces a string with the value:

26 Feb 04

-----------------------------------------
java.util.Formatter

The Formatter class is at the core of the new formatting capability. It fully supports internationalization by letting you pass a Locale to the constructor; the other formatting methods (e.g. String.format) also allow this.

Formatter also lets you pass an Appendable object. This is a new interface that defines append methods so that the formatter can store its results in a text collector such as a stream object. Sun has modified all relevant Java classes, such as StringBuffer and PrintStream, to implement this interface. Here's how you might use it:

double avogadro = 6.0e23;
StringBuffer buffer = new StringBuffer();
Formatter formatter = new Formatter(buffer, Locale.US);
formatter.format("avogadro's number: %e %n", avogadro);
formatter.format("base of the natural log: %e %n", Math.E);
System.out.println(buffer.toString());

The corresponding output:

avogadro's number: 6.000000e+23
base of the natural log: 2.718282e+00

Web Server Benchmarking

1.Web site load analysis
2.performance tests

Web server benchmarking is useful in testing your infrastructure to see if it can with stand expected visitor growth and maintain a reasonable response under load
(i.e. requests per sec, latency, bandwidth).

>>Apache Benchmark Tool: ab
>>Benchmarking Tool: httperf

Apache Benchmark Tool: ab

The Apache httpd web server comes with a benchmarking tool to simulate a high load and to gather data for analysis.

>ab -n 1000 -c 10 -g test_data.txt http://www.karthik.com/index.html

Option Description
-n number of requests. Default is 1 which is useless.
-c concurrent requests. Default 1
-g GNU plot output. Labels are on first line of output.
-q Suppress progress stattus output to stderr.
-t Time limit. Maximum number of seconds.
-A username:password Specify authentication credentials.
-X proxy[:port] Specify a proxy server.

Console output:
Finished 1000 requests


Server Software: Apache/2.2.3
Server Hostname: www.karthik.com
Server Port: 80

Document Path: /index.html
Document Length: 83241 bytes

Concurrency Level: 10
Time taken for tests: 14.793312 seconds
Complete requests: 1000
Failed requests: 0
Write errors: 0
Total transferred: 83608000 bytes
HTML transferred: 83241000 bytes
Requests per second: 67.60 [#/sec] (mean)
Time per request: 147.933 [ms] (mean)
Time per request: 14.793 [ms] (mean, across all concurrent requests)
Transfer rate: 5519.25 [Kbytes/sec] received

Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 20 250.2 0 3000
Processing: 53 126 52.7 120 317
Waiting: 19 51 29.5 46 246
Total: 53 147 260.2 120 3305

Percentage of the requests served within a certain time (ms)
50% 120
66% 142
75% 159
80% 172
90% 198
95% 227
98% 282
99% 314
100% 3305 (longest request)

This shows the load limit of the server.
---------------------------------------------------------------------------------

Benchmarking Tool: httperf


Web performance benchmarking tool httperf. Httperf sends requests to the web server at a specified rate and gathers stats. Increase till one finds the saturation point.
Installation:

* apt-get install httperf

Example usage:

* Print performance stats for home page of your-domain.com: httperf --hog --server www.your-domain.com
* Create 100 connections at a rate of 10/sec: httperf --hog --server http://www.your-domain.com/ --num-conn 100 --rate 10 --timeout 5
* Generate 10 sessions at a rate of one session/sec every 2 seconds: httperf --hog --ser=www --wsess=10,5,2 --rate 1 --timeout 5

httperf command line options:

Command Command Description
--hog Use as many TCP ports as necessary to generate stats (else limited to port 1024-5000)
--num-calls Session oriented workloads.
--max-connections=# Limit the number of connections to that specified.
--num-calls=# Specify the number of calls to issue on each connection before closing it.
--server host-name Default localhost. Specify IP address of host name.
--wsess=N1,N2,X Specify session where
N1: number of sessions
N2: number of calls per session
X: delay between calls (sec)
--timeout Stop if there is no response within timeout period.

Wednesday, July 21, 2010

Java 6 core package

Packages are usually defined using a hierarchical naming pattern, with levels in the hierarchy separated by periods (.) (pronounced "dot"). Although packages lower in the naming hierarchy are often referred to as "subpackages" of the corresponding packages higher in the hierarchy, there is no semantic relationship between packages.

Monday, July 19, 2010

Unit Tests - "Written Once and Forgotten Forever"

Unit test cases that are written once and forgotten for ever, with all the dataset/environmental dependencies in it. What is the importance of dataset/environment? Let's take an example, observe the test case below.

public void testEmpFinder () {
//Weird Test case for Fun!!!
String result = "JOHN";
//Passing employee id returns employee object.
//verify the name matches.

Employee emp = EmpFinder.find(1);
assertEquals(emp.getName,result);
}

What's wrong? The developer had made an assumption, that on querying with employeeid='1' will return employee with the name "JOHN". The data could be coming from a database table "EMPLOYEE". But It’s very evident this test case would fail if run on an environment where the employeeid='1' data doesn't exists. This makes the test cases obsolete the moment they are written.

java first

Java is a popular and widely used programming language. It was originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems’ Java platform. The language’s syntax has much in common with C and C++, but its object model is simpler and has less low-level facilities. Undoubtedly, one of Java’s strong points is an automatic memory management. The developer determines when objects are created, but it’s a runtime task to free memory, when objects are no longer in use.

java Tutorials

>>downloads and installation(jdk and any IDE(netbeans or eclipse)
>>Hello World


download

First of all you have to download some stuff from the Internet:

1.Download the latest JDK from: http://java.sun.com/javase/downloads/index.jsp
2.Download Eclipse IDE for Java Developers from: http://www.eclipse.org/downloads/


hello world

HelloWorld.java

public class HelloWorld {
/**

* @param args

*/

public static void main(String[] args) {

System.out.println("Hello World! I am new to Java.");

}

}

First of all, Java is an object-oriented programming language. Thus, Java program necessarily consists of classes. There are no global variables and functions, as you may see in C++. We called the class HelloWorld

public class HelloWorld {


}


Draw attention to the fact, that filename of the file is .java. It is obligatory in Java.

Entry point

Each application in Java has an entry point to start from. It is a public static method called main. Arguments to application are passed through args parameter.

public static void main(String[] args) {


}

Print command
System.out.println("Hello World! I am new to Java.");

Comments
Above the main method declaration you see comments block:

/**

* @param args

*/

It is special comments, called Javadoc. Using this system, one may automatically generate documentation for properly commented source.

Build and run

Building
Enter the directory with your source file and run the following command:

javac HelloWorld.java
After it is executed you will see a new file HelloWorld.class. This file is a compiled HelloWorld class.

Running
Now you can run it using following command:

java HelloWorld

Thursday, July 15, 2010

Java Classpath

The classpath in Java defines which java class are available.

For example if you want to use an external Java library you have to add this library to your classpath to use it in your your program.

Your first Java program

// The smallest Java program possible

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hi java..");
}
}
Compile the code

directory structure


c:\temp\java\HelloWorld.java .

c:\temp\java\javac Helloworld.java

c:\temp\java\java Helloworld

Now is working fine..

classpath setting and run the code in different directory

Check the content of the directory with the command "dir". The directory contains now a file "HelloWorld.class".

Start-> Run -> cmd

c:\>java HelloWorld

now: we will get this error message:

If you are not in the directory in which the compiled class is stored then the system should result an error message Exception in thread "main" java.lang.NoClassDefFoundError: test/TestClass

how to solve this problem using Classpath

c:\> java -classpath "mydirectory" HelloWorld . Replace "mydirectory" with the directory which contains the test directory. You should again see the "HelloWorld" output.

C:\>java -classpath C:\temp\java HelloWorld

How to install Java JRE in CentOS Linux

Step 1: Making a new folder


#mkdir /software
#cd /software

Step2: Download JRE javafrom Sun.com

Now, go to http://java.sun.com/javase/downloads/index.jsp#jdkJavaEE, download the latest JRE java and put it into 'software' folder. My current version is 1.6.0_20. You version might be different.

Step3: Change the file attribute of the downloaded file

Let is change the file mode bit / attribute of the file. chmod +x command is change jre-6u20-linux-i586-rpm.bin from readonly mode to executable mode.

#chmod +x jre-6u20-linux-i586-rpm.bin

Step3: Execute the jre*.bin file

Execute the jre*.bin file now. the ./ is to command to run the jre file at this location.

#./jre-6u20-linux-i586-rpm.bin


After you run the above command, you will see a long list of agreement, you must accept it. Type "yes" then press to start the java installation.



Step4 : Verify your jre installation


# java -version

Monday, July 12, 2010

Java-System internals exec

public class MyAutorun
{
public void autoruns()
{
try
{
System.out.println("AutoRun");
Process p = Runtime.getRuntime().exec("C:\\Utils\\autoruns.exe");
} catch (IOException ex) {
Logger.getLogger(MyAutorun.class.getName()).log(Level.SEVERE, null, ex);
}
}

Tuesday, July 6, 2010

Software Development Life Cycle Models

The General Model

Software life cycle models describe phases of the software cycle and the order in which those phases are executed. There are tons of models, and many companies adopt their own, but all have very similar patterns. The general, basic model is shown below:



Each phase produces deliverables required by the next phase in the life cycle. Requirements are translated into design. Code is produced during implementation that is driven by the design. Testing verifies the deliverable of the implementation phase against requirements.

Requirements

Business requirements are gathered in this phase. This phase is the main focus of the project managers and stake holders. Meetings with managers, stake holders and users are held in order to determine the requirements. Who is going to use the system? How will they use the system? What data should be input into the system? What data should be output by the system? These are general questions that get answered during a requirements gathering phase. This produces a nice big list of functionality that the system should provide, which describes functions the system should perform, business logic that processes data, what data is stored and used by the system, and how the user interface should work. The overall result is the system as a whole and how it performs, not how it is actually going to do it.

Design

The software system design is produced from the results of the requirements phase. Architects have the ball in their court during this phase and this is the phase in which their focus lies. This is where the details on how the system will work is produced. Architecture, including hardware and software, communication, software design (UML is produced here) are all part of the deliverables of a design phase.

Implementation

Code is produced from the deliverables of the design phase during implementation, and this is the longest phase of the software development life cycle. For a developer, this is the main focus of the life cycle because this is where the code is produced. Implementation my overlap with both the design and testing phases. Many tools exists (CASE tools) to actually automate the production of code using information gathered and produced during the design phase.

Testing

During testing, the implementation is tested against the requirements to make sure that the product is actually solving the needs addressed and gathered during the requirements phase. Unit tests and system/acceptance tests are done during this phase. Unit tests act on a specific component of the system, while system tests act on the system as a whole.

So in a nutshell, that is a very basic overview of the general software development life cycle model. Now lets delve into some of the traditional and widely used variations.

Waterfall Model

This is the most common and classic of life cycle models, also referred to as a linear-sequential life cycle model. It is very simple to understand and use. In a waterfall model, each phase must be completed in its entirety before the next phase can begin. At the end of each phase, a review takes place to determine if the project is on the right path and whether or not to continue or discard the project. Unlike what I mentioned in the general model, phases do not overlap in a waterfall model.



Advantages
  • Simple and easy to use.
  • Easy to manage due to the rigidity of the model – each phase has specific deliverables and a review process.
  • Phases are processed and completed one at a time.
  • Works well for smaller projects where requirements are very well understood.

Disadvantages

  • Adjusting scope during the life cycle can kill a project
  • No working software is produced until late during the life cycle.
  • High amounts of risk and uncertainty.
  • Poor model for complex and object-oriented projects.
  • Poor model for long and ongoing projects.
  • Poor model where requirements are at a moderate to high risk of changing.

V-Shaped Model

Just like the waterfall model, the V-Shaped life cycle is a sequential path of execution of processes. Each phase must be completed before the next phase begins. Testing is emphasized in this model more so than the waterfall model though. The testing procedures are developed early in the life cycle before any coding is done, during each of the phases preceding implementation.

Requirements begin the life cycle model just like the waterfall model. Before development is started, a system test plan is created. The test plan focuses on meeting the functionality specified in the requirements gathering.

The high-level design phase focuses on system architecture and design. An integration test plan is created in this phase as well in order to test the pieces of the software systems ability to work together.

The low-level design phase is where the actual software components are designed, and unit tests are created in this phase as well.

The implementation phase is, again, where all coding takes place. Once coding is complete, the path of execution continues up the right side of the V where the test plans developed earlier are now put to use.



Advantages
  • Simple and easy to use.
  • Each phase has specific deliverables.
  • Higher chance of success over the waterfall model due to the development of test plans early on during the life cycle.
  • Works well for small projects where requirements are easily understood.

Disadvantages

  • Very rigid, like the waterfall model.
  • Little flexibility and adjusting scope is difficult and expensive.
  • Software is developed during the implementation phase, so no early prototypes of the software are produced.
  • Model doesn’t provide a clear path for problems found during testing phases.
Incremental Model

The incremental model is an intuitive approach to the waterfall model. Multiple development cycles take place here, making the life cycle a “multi-waterfall” cycle. Cycles are divided up into smaller, more easily managed iterations. Each iteration passes through the requirements, design, implementation and testing phases.

A working version of software is produced during the first iteration, so you have working software early on during the software life cycle. Subsequent iterations build on the initial software produced during the first iteration.





Advantages
  • Generates working software quickly and early during the software life cycle.
  • More flexible – less costly to change scope and requirements.
  • Easier to test and debug during a smaller iteration.
  • Easier to manage risk because risky pieces are identified and handled during its iteration.
  • Each iteration is an easily managed milestone.

Disadvantages

  • Each phase of an iteration is rigid and do not overlap each other.
  • Problems may arise pertaining to system architecture because not all requirements are gathered up front for the entire software life cycle.

Spiral Model

The spiral model is similar to the incremental model, with more emphases placed on risk analysis. The spiral model has four phases: Planning, Risk Analysis, Engineering and Evaluation. A software project repeatedly passes through these phases in iterations (called Spirals in this model). The baseline spiral, starting in the planning phase, requirements are gathered and risk is assessed. Each subsequent spirals builds on the baseline spiral.

Requirements are gathered during the planning phase. In the risk analysis phase, a process is undertaken to identify risk and alternate solutions. A prototype is produced at the end of the risk analysis phase.

Software is produced in the engineering phase, along with testing at the end of the phase. The evaluation phase allows the customer to evaluate the output of the project to date before the project continues to the next spiral.

In the spiral model, the angular component represents progress, and the radius of the spiral represents cost.



Advantages

  • High amount of risk analysis
  • Good for large and mission-critical projects.
  • Software is produced early in the software life cycle.

Disadvantages

  • Can be a costly model to use.
  • Risk analysis requires highly specific expertise.
  • Project’s success is highly dependent on the risk analysis phase.
  • Doesn’t work well for smaller projects.

Sunday, July 4, 2010

PATH

set the PATH permanently.

Start the system editor.> start-run- sysedit

Go to the window that is displaying AUTOEXEC.BAT

C:> edit c:\autoexec.bat
   c:> path
eg:
C:>PATH C:\WINDOWS;C:\WINDOWS\COMMAND;c:\jdk1.6\bin

--------------------------------------------------------------

set ANT_HOME=c:\ant\bin

set JAVA_HOME=c:\Program Files\java\jdk1.6.0\

set PATH=%PATH%;%ANT_HOME%;%JAVA_HOME%

Saturday, July 3, 2010

MySQL import and export dump file

First lets look at what is mySQL database?
MySQL is a relational database management system (RDBMS) which has more than 11 million installations. The program runs as a server providing multi-user access to a number of databases.
Why use import or export of sql dump file (scenario)?
I have two MySQL databases located on a server somewhere. I connect via secure shell. I don't know all of the details about the configuration of this particular server but it obviously has MySQL installed/configured properly and you can assume that any other 'very likely' items would also be resident. I need to completley copy one database into the other (one is currently quite large, the second is empty).

And the easiest way to do this is use sql export to dump file and sql import of dump file to mySQL database.
How to create mySQL dump file (export database to sql file)?
The easiest way to export is use next syntax in command prompt (cmd):
mysqldump -u USER -p PASSWORD DATABASE > filename.sql

For example we have database with next parameters: database username baseu01 database password h4z56s3 database name database01 sql export file name export.sql
Appropriate command line for export is:
>mysqldump -u baseu01 -p h4z56s3 database01 > filename.sql

After executing export command you will have file "export.sql" in your folder.
How to import sql dump file to mySQL database?
The scenario: server crashes and you got mysql dump file stored on your hard drive. First you install mySQL database - then create database, database user and database password and then use next command line:

>mysql -u username -p password database_name < filename.sql

If we use the same example as we used for export command line for export is:
mysql -u baseu01 -p h4z56s3 database01 export.sql ------------------------------------------------------------------------------------------------
Advanced options for exporting or importing a database
How to Export A MySQL Database Structures Only
If you no longer need the data inside the database’s tables (unlikely), simply add –no-data switch to export only the tables’ structures.

For example, the syntax is:
>mysqldump -u username -ppassword –no-data database_name > dump.sql
How to Backup Only Data of a MySQL Database
If you only want the data to be backed up, use –no-create-info option. With this setting, the dump will not re-create the database, tables, fields, and other structures when importing. Use this only if you pretty sure that you have a duplicate databases with same structure, where you only need to refresh the data. Syntax:
>mysqldump -u username -ppassword –no-create-info database_name > dump.sql
How to Dump Several MySQL Databases into Text File
–databases option allows you to specify more than 1 database.

Example syntax:
>mysqldump -u username -ppassword –databases db_name1 [db_name2 ...] > dump.sql
How to Dump All Databases in MySQL Server
To dump all databases, use the –all-databases option, and no databases’ name need to be specified anymore. mysqldump -u username -ppassword –all-databases > dump.sql

Friday, July 2, 2010

Java Tips

if (2 + 2 == 3)

; // empty statement

else

System.out.println("2 + 2 is not equal to 3");

ans: 2 + 2 is not equal to 3
---------------------------

if (!(2 + 2 == 3))

System.out.println("2 + 2 is not equal to 3");


ans:2 + 2 is not equal to 3

Java

"Java" as another term for coffee, the computer science world uses it to refer to a programming language developed by Sun Microsystems.
The syntax of Java is much like that of C/C++, but it is object-oriented and structured around "classes" instead of functions.
Java can also be used for programming applets -- small programs that can be embedded in Web sites.
The language is becoming increasingly popular among Desktop apps,Web apps ,Mobile apps and software developers since it is efficient and easy-to-use.

Java as a "simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, high-performance, multithreaded, dynamic, buzzword-compliant, general-purpose programming language."