Thursday, February 28, 2008

Beginner's Guide To HTML

Whether you're looking to change the layout of your blog, or simply want to insert some funky effects into your website, HTML has long been the standard way of doing it. We're going to go through a little basic code to help you get going.


Beginner's Guide To HTML

Beginner's Guide To CSS

Learn what CSS is, and how it's used in web design. This film teaches you the very basics to give you a firm foundation to work from


Beginner's Guide To CSS

Formatting Text in HTML

If you want to create headings or add emphasis by using bold or italicized text, then these simple HTLM tags will do the trick. Learn how to format text in HTML.

Redirecting a Page using PHP

Redirecting a page in PHP is an easy task. You can use the PHP Header method to redirect a visitor to a new page. The header() method is used to send HTTP headers back to the browser. The headers can be sent back to the browser only if there's no content or error messages shown in the page.

Here's an example on how to redirect a visitor to http://www.newpage.com/

<?
header('Location: http://www.newpage.com/');
?>

The above example shows how to redirect the visitor to a static address. You can also dynamically create the location to which the visitor is to be redirected.
<?
$domain=http://www.google.com/search?q=;
$querystring="vinu thomas";
$redirectstr= $domain.$querystring;
header('Location:'. $redirectstr);
?>

The above code will create the URL for redirection as http://www.google.com/search?q=vinu%20thomas and then redirect them to the URL. You can also build php code which can conditionally redirect a page. See how this is done in the following example.
<?
if($user==="Admin")
{
header('Location:admin.php');
}
else
{
header('Location:login.php');
}
?>


For more information on the header() method, you can check out php.net's header manual at: http://www.php.net/manual/en/function.header.php

About the Author
Vinu Thomas is the author of vinuthomas.com. This tutorial is licensed under a Creative Commons License.

What is C++?

C++ (pronounced "see plus plus") is a general-purpose computer programming language. It is a statically typed free-form multi-paradigm language supporting procedural programming, data abstraction, object-oriented programming, and generic programming. Since the 1990s, C++ has been one of the most popular commercial programming languages.

Bell Labs' Bjarne Stroustrup developed C++ (originally named "C with Classes") in 1983 as an enhancement to the C programming language. Enhancements started with the addition of classes, followed by, among many features, virtual functions, operator overloading, multiple inheritance, templates, and exception handling. The C++ programming language standard was ratified in 1998 as ISO/IEC 14882:1998, the current version of which is the 2003 version, ISO/IEC 14882:2003. A new version of the standard (known informally as C++0x) is being developed.

History
Stroustrup began work on C with Classes in 1979. The idea of creating a new language originated from Stroustrup's experience programming for his Ph.D. thesis. Stroustrup found that Simula had features that were very helpful for large software development but was too slow for practical uses, while BCPL was fast but too low level and unsuitable for large software development. When Stroustrup started working in Bell Labs, he had the problem of analyzing the UNIX kernel with respect to distributed computing. Remembering his Ph.D. experience, Stroustrup set out to enhance the C language with Simula-like features. C was chosen because it is general-purpose, fast, and portable. Besides C and Simula some other languages which inspired him were: ALGOL 68, Ada, CLU and ML. At first, class (with data encapsulation), derived class, strong type checking, inlining, and default argument were features added to C, via the Cfront front-end. The first commercial release occurred in October 1985.

In 1983, the name of the language was changed from C with Classes to C++. New features that were added to the language included virtual functions, function name and operator overloading, references, constants, user-controlled free-store memory control, improved type checking, and new comment style (//). In 1985, the first edition of The C++ Programming Language was released, providing an important reference to the language, as there was not yet an official standard. In 1989, Release 2.0 of C++ was released. New features included multiple inheritance, abstract classes, static member functions, const member functions, and protected members. In 1990, The Annotated C++ Reference Manual was released and provided the basis for the future standard. Late addition of features included templates, exceptions, namespaces, new casts, and a Boolean type.

As the C++ language evolved, a standard library also evolved with it. The first addition to the C++ standard library was the stream I/O library which provided facilities to replace the traditional C functions such as printf and scanf. Later, among the most significant additions to the standard library, was the Standard Template Library.

After years of work, a joint ANSI-ISO committee standardized C++ in 1998 (ISO/IEC 14882:1998). For some years after the official release of the standard in 1998, the committee processed defect reports, and published a corrected version of the C++ standard in 2003. In 2005, a technical report, called the "Library Technical Report 1" (often known as TR1 for short) was released. While not an official part of the standard, it gives a number of extensions to the standard library which are expected to be included in the next version of C++. Support for TR1 is growing in almost all currently maintained C++ compilers.

No one owns the C++ language; it is royalty-free. The standard document itself is, however, not available for free.

Future development
C++ continues to evolve to meet future requirements. One group in particular, Boost.org, works to make the most of C++ in its current form and advises the C++ standards committee as to which features work well and which need improving. Current work indicates that C++ will capitalize on its multi-paradigm nature more and more. The work at Boost.org, for example, is greatly expanding C++'s functional and metaprogramming capabilities. The C++ standard does not cover implementation of name decoration, exception handling, and other implementation-specific features, making object code produced by different compilers incompatible; there are, however, 3rd-party standards for particular machines or OSs which attempt to standardise compilers on those platforms, for example C++ ABI.

C++ compilers still struggle to support the entire C++ standard, especially in the area of templates — a part of the language that was more-or-less entirely conceived by the standards committee. One particular point of contention is the export keyword, intended to allow template definitions to be separated from their declarations. The first compiler to implement export was Comeau C++, in early 2003 (5 years after the release of the standard); in 2004, beta compiler of Borland C++ Builder X was also released with export. Both of these compilers are based on the EDG C++ frontend. It should also be noted that many C++ books provide example code for implementing the keyword export (Ivor Horton's Beginning ANSI C++, pg. 827) which will not compile, but there is no reference to the problem with the keyword export mentioned. Other compilers such as Microsoft Visual C++ and GCC do not support it at all. Herb Sutter, secretary of the C++ standards committee, has recommended that export be removed from future versions of the C++ standard [1], but finally the decision was made to leave it in the C++ standard.

Other template issues include constructions such as partial template specialisation, which was poorly supported for several years after the C++ standard was released.

The name "C++"
This name is credited to Rick Mascitti (mid-1983) and was first used in December 1983. Earlier, during the research period, the developing language had been referred to as "C with Classes". The final name stems from C's "++" operator (which increments the value of a variable) and a common naming convention of using "+" to indicate an enhanced computer program, for example: "Wikipedia+". According to Stroustrup: "the name signifies the evolutionary nature of the changes from C". C+ was the name of an earlier, unrelated programming language.

Some C programmers have noted that if the statements x=3; and y=x++; are executed, then x==4 and y==3; x is incremented after its value is assigned to y. However, if the second statement is y=++x;, then y==4 and x==4. Following such reasoning, a more proper name for C++ might actually be ++C. However, c++ and ++c both increment c, and, on its own line, the form c++ is more common than ++c. However, the introduction of C++ did not change the C language itself, so an even more accurate name might be "C+1".

Stroustrup addresses this debate in the preface of later editions of his book, The C++ Programming Language, adding that another interpretation of the name "C++" might be inferred from the appendix of George Orwell's Nineteen Eighty-Four. Of the three segments of the fictional language Newspeak, the "C vocabulary" is the one dedicated to technical terms and jargon. "Doubleplus" is the superlative modifier for Newspeak adjectives. Thus, "C++" might hold the meaning "most extremely technical or jargonous" in Newspeak.

When Rick Mascitti was questioned informally in 1992 about the naming, he indicated that it was given in a tongue-in-cheek spirit. He never thought that it would become the formal name of the language.

Philosophy
In The Design and Evolution of C++ (1994), Bjarne Stroustrup describes some rules that he uses for the design of C++. Knowing the rules helps to understand why C++ is the way it is. The following is a summary of the rules. Much more detail can be found in The Design and Evolution of C++.

  • C++ is designed to be a statically typed, general-purpose language that is as efficient and portable as C
  • C++ is designed to directly and comprehensively support multiple programming styles (procedural programming, data abstraction, object-oriented programming, and generic programming)
  • C++ is designed to give the programmer choice, even if this makes it possible for the programmer to choose incorrectly
  • C++ is designed to be as compatible with C as possible, therefore providing a smooth transition from C
  • C++ avoids features that are platform specific or not general purpose
  • C++ does not incur overhead for features that are not used
  • C++ is designed to function without a sophisticated programming environment

Stanley B. Lippman documents in his in-depth book "Inside the C++ Object Model" (1996) how compilers convert C++ program statements into an in-memory layout. Lippman worked on implementing and maintaining C-front, the original C++ implementation at Bell Labs.

About this Terminology
This terminology is from The Wikipedia which is published under the GNU Free Documentation License.

How to Create a PHP Calendar

PHP calendars can be used for everything from simply displaying the date to creating complex reservation systems. See the steps to starting your own PHP calendar.

Wednesday, February 27, 2008

What is a JDBC Type 4 Driver?

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

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

As the database protocol is vendor-specific, separate drivers, usually vendor-supplied, need to be used to connect to the database.

About this Terminology
This terminology is from The Wikipedia which is published under the GNU Free Documentation License.

What is a JDBC Type 3 Driver?

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

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

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

About this Terminology
This terminology is from The Wikipedia which is published under the GNU Free Documentation License.

What is a JDBC Type 2 Driver?

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

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

However the type 2 driver provides more functionality and performance that the type 1 driver as it does not have the overhead of the additional ODBC function calls.

About this Terminology
This terminology is from The Wikipedia which is published under the GNU Free Documentation License.

What is a JDBC Type 1 Driver?

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

The driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class and comes with the Java 2 SDK, Standard Edition.

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

Type 1 is the simplest of all but platform specific i.e only to Microsoft platform.

About this Terminology
This terminology is from The Wikipedia which is published under the GNU Free Documentation License.

What is JDBC?

Java Database Connectivity (JDBC) is an API for the Java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases.

The Java Platform, Standard Edition includes the JDBC API together with an ODBC implementation of the API enabling connections to any relational database that supports ODBC. This driver is native code and not Java, and is closed source.

Overview
JDBC has been part of the Java Standard Edition since the release of JDK 1.1. The JDBC classes are contained in the java.sql package. Starting with version 3.0, JDBC has been developed under the Java Community Process. JSR 54 specifies JDBC 3.0, JSR 114 specifies the JDBC Rowset additions, and JSR 221 is the specification of JDBC 4.0.

JDBC allows multiple implementations to exist and be used by the same application. The API provides a mechanism for dynamically loading the correct Java packages and registering them with the JDBC Driver Manager. The Driver Manager is used as a connection factory for creating JDBC connections.

JDBC connections support creating and executing statements. These statements may be update statements such as SQL INSERT, UPDATE and DELETE or they may be query statements using the SELECT statement. Additionally, stored procedures may be invoked through a statement. Statements are one of the following types:

  • Statement – the statement is sent to the database server each and every time.
  • PreparedStatement – the statement is cached and the the execution path is pre determined on the database server allowing it to be executed multiple times in an efficient manner.
  • CallableStatement – used for executing stored procedures on the database.

Update statements such as INSERT, UPDATE and DELETE return an update count that indicates how many rows were affected in the database. These statements do not return any other information.

Query statements return a JDBC row result set. The row result set is used to walk over the result set. Individual columns in a row are retrieved either by name or by column number. There may be any number of rows in the result set. The row result set has metadata that describes the names of the columns and their types.

There is an extension to the basic JDBC API in the javax.sql package that allows for scrollable result sets and cursor support among other things.

Driver Types
There are commercial and free drivers available for most relational database servers. These drivers fall into one of the following types:

  • Type 1, the JDBC-ODBC bridge
  • Type 2, the Native-API driver
  • Type 3, the network-protocol driver
  • Type 4, the native-protocol drivers
  • Internal JDBC driver, driver embedded with JRE in Java-enabled SQL databases. Used for Java stored procedures.
  • JDBC URL, all Database Connection String

About this Terminology
This terminology is from The Wikipedia which is published under the GNU Free Documentation License.

How to Use SQLXML to Retrieve Data from SQL Server Database

Using SQL Server 2000 and above versions you can retrieve data from SQL Server in XML format directly from the database. Many XML related features were incorporated in the SQL Server database. This enables the development of XML enabled applications very easy and it makes exchange of data over internet easy. In this article we will discuss about how to use SQLXML to retrieve data directly from SQL server database in XML format.

There are some SQL commands and clauses that help you to retrieve data from the SQL Server in the XML format. Syntax for such is given below:

SELECT ... FOR XML mode [, XMLDATA] [, ELEMENTS] [, BINARY BASE64]
There are different modes and that take the values of
  • AUTO – In this mode every row of the result of the query forms an element in the returned XML document.
  • EXPLICIT – This mode defines how to map the columns of the results returned by the query to the XML elements and the attributes.
  • RAW - All the fields of the result are identified as attributes of an element.
  • NESTED – The result of this mode is the same as the AUTO mode but the formatting has to be done at the client side.

A simple example of using the above syntax is given below:

SELECT TOP 3 * FROM (SELECT FirstName+' '+LastName as Name FROM Employees) FOR XML AUTO

The query produces this result:

Employees Name="John Peter"
Employees Name="Andrew Dixon"
Employees Name="Tom Hanks"

There are optional parameters in the ‘FOR XML mode’ clause. The XMLDATA option adds an XSD schema which describes the XML format of the result returned. The ELEMENTS options make the fields of the tables in the database to be returned as child elements. If the ELEMENTS option is not there the fields of the tables are returned as attributes instead of child elements of the XML document. The ELEMENTS option is allowed only in the AUTO mode. The BINARY BASE64 option is used to retrieve any binary data. The returned binary data is returned in BASE64 encoded format. The binary data can be retrieved in the RAW or EXPLICIT mode.

An example of the RAW mode is given below:

SELECT EmpName, EmpCity from EMP for XML RAW

The above code returns a result like,

row EmpName=”John” EmpCity=”New York”

In the above result you can note that the fields of the resultset are returned as attributes of the element.

.Net provides with managed classes for interacting with SQL Server. The managed classes of SQLXML provided by .Net are:

  • SqlXmlCommand – This is used to perform queries that are stored in XML documents which are also called XML templates. This class also provides support for client side XML processing.
  • SqlXmlParameter – this is used to provide parameterized values and is used along with SqlXmlCommand object.
  • SqlXmlAdapter – this is the adapter class for SQLXML provider. This is used to fill the dataset.
  • SqlXmlException – this is used to trap the error information from the SQL Server.

A sample code using the managed classes is given below. For detailed information on the usage of the above managed classes you can refer to the MSDN documentation.

static string cstr = "Provider=SQLOLEDB;Server=(local);database=EmpPersonal;";

public static void testingSqlXml () {

Stream oStr = Console.OpenStandardOutput();

SqlXmlCommand sqlcmd = new SqlXmlCommand(cstr);

sqlcmd.Root = "Employees";

sqlcmd.CommandType = SqlXmlCommandType.Sql;

sqlcmd.CommandText = "SELECT EmpName, EmpCity FROM Employees FOR XML AUTO";

strm = sqlcmd.ExecuteToStream(oStr);

oStr.Close();

}

Thus we have seen that SQLXML can be used to retrieve data directly from the SQL Server in XML format. It is easy to handle and transmit data through the internet if it is in the XML format and this can be easily achieved using the SQLXML.

Want to stay current with the latest technology developments realted to XML. Visit Free XML Tutorial to get your FREE subscription now!

What is ODBC?

Open Database Connectivity (ODBC) is a standard software API specification for using database management systems (DBMS). ODBC is designed to be independent of programming language, database system and operating system.

Description
ODBC is a procedural API specification for using SQL queries to access data. An implementation of ODBC will contain one or more applications, a core ODBC library, and one or more "database drivers". The core library is independent of the applications and DBMSes, and acts as an "interpreter" between the applications and the database drivers. The DBMS-specific details are contained in the database drivers. Thus, it is possible to write applications that use standard types and features without concern for the specifics of each DBMS that might be used. Likewise, database driver implementors need only know how to attach to the core library. This makes ODBC modular.

To write ODBC code that exploits DBMS-specific features requires more advanced programming. An application must use introspection, calling ODBC metadata functions that return information about supported features, available types, syntax, limits, isolation levels, driver capabilities and other information.

ODBC is the foremost example of ubiquitous data access because there are hundreds of ODBC drivers for a large variety of data sources. ODBC is available for a variety of operating systems and there are drivers for non-relational data such as spreadsheets, text and XML files. Because ODBC dates back more than ten years, it offers connectivity to a wider variety of data sources than other data access APIs. There are more drivers for ODBC than drivers or providers for newer APIs such as OLE DB, JDBC and ADO.NET.

Despite the benefits of ubiquitous connectivity and platform independence, ODBC has certain drawbacks. Administering a large number of client machines can involve a diversity of drivers and DLLs. This complexity can increase system administration overhead. Large organizations with thousands of PCs have often turned to ODBC server technology to simplify the administration problem.

The layered architecture of ODBC can introduce a minor performance penalty. The overhead of executing an additional layer of code is generally insignificant compared to network latency and other factors that influence query performance. Driver architecture is also a consideration. Many first-generation ODBC drivers operated with database client libraries supplied by a DBMS vendor. An ODBC driver for Oracle, for example, would use Oracle's network library (SQL*Net, Oracle Net) and OCI client library. Similarly, a driver for Sybase or Microsoft SQL Server would use a vendor-supplied network library to emit Tabular Data Stream (TDS) packets. Those earlier drivers have been largely supplanted by wire protocol drivers that do not use database client libraries. The newer type of driver communicates using protocols such as TDS, TNS, and DRDA without needing database client libraries.

Differences between drivers and driver maturity are also important issues. Newer ODBC drivers are often less stable than drivers that have been in production for years. Years of testing and deployment mean a driver is less likely to contain bugs.

To use DBMS-specific features with ODBC, a developer must understand adaptive programming techniques such as introspection and writing interoperable SQL statements. Even when using adaptive techniques, however, some advanced DBMS features might not be available with ODBC. The ODBC 3.x API is well-suited to traditional SQL applications such as OLTP but it has not evolved to support richer types introduced by SQL:1999 and SQL:2003.

Developers needing features or types not accessible with ODBC can use other SQL APIs. When platform independence is not a goal, developers can use proprietary APIs. If creating portable, platform-independent code is a goal, developers can use the JDBC API.

History
ODBC is based on the Call Level Interface (CLI) specifications from SQL Access Group, X/Open (now part of The Open Group), and the ISO/IEC. Microsoft created ODBC by adapting the SQL Access Group CLI. It released ODBC 1.0 in September, 1992. After ODBC 2.0, Microsoft decided to align ODBC 3.0 with the CLI specification making its way through X/Open and ISO. In 1995, SQL/CLI became part of the international SQL standard.

About this Terminology
This terminology is from The Wikipedia which is published under the GNU Free Documentation License.

Dates and Times in Perl

System Times

Time
There are two ways of measuring time: ages from today, and counting from an arbitrary date in the past. So, for example, you can get that a file is 28.5 days old, or you can find out that the file was created at 3:53 PM on January 21, 1985. In Perl, you measure the latter in seconds from “the start of the epoch”. The epoch is simply the earliest date your computer can use. For most Unix computers, this is the midnight before January 1, 1970, universal standard time. On the Macintosh, this is the midnight before January 1, 1904. You don’t really need to worry about that, since you’ll generally be feeding the number of seconds into special built-in functions that take the seconds and return information about that date that number represents.

The “time” function returns the current time, that is, the number of seconds since the epoch.

Time Information
The “localtime” and “gmtime” functions take a “seconds since the epoch” number and return information about the date that number represents. The “localtime” function returns information about what that time represents in whatever the local time is, and the “gmtime” returns the same information but relative to universal standard time.

They return a nine-element array:

0 - Seconds
1 - Minutes
2 - Hour
3 - Day of the month
4 - Month (0 for January, 11 for December)
5 - Year (0 for 1900, 100 for 2000: just add 1900)
6 - Weekday (0 for Sunday, 6 for Saturday)
7 - Day of the year, from 1 to 365
8 - 1 if the result represents daylight savings, 0 if not.

Here’s a simple program that returns the current date and time in a ‘human-readable’ format:

@Weekdays = 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
@Months = 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
@Now = localtime(time());
$Month = $Months[$Now[4]];
$Weekday = $Weekdays[$Now[6]];
$Hour = $Now[2];
if ($Hour > 12) {
$Hour = $Hour - 12;
$AMPM = "PM";
} else {
$Hour = 12 if $Hour == 0;
$AMPM ="AM";
}
Minute = $Now[1];
$Minute = "0$Minute" if $Minute < 10;
$Year = $Now[5]+1900;
print "$Weekday, $Month $Now[3], $Year $Hour:$Minute $AMPM\n";

This should produce something like the following:

Sunday, May 24, 1998 12:10 AM

File Times

You can get file times either with the -M or -C file check, or the eighth and ninth elements of the ‘stat’ function. The file checks return the age in days (including fractions) and the stat function returns the time in seconds since the ‘epoch’, or the earliest possible time on the computer. This is usually sometime early in the twentieth century.

Age in Days
The -M file check returns the age in days since the file was last changed. It includes fractional amounts, so if you want to compare days, you need to take the ‘int’ of the returned value. The -A file check returns the age in days since someone last looked at the file.

foreach $FileName (@ARGV) {
$FileAge = -M $FileName;
if ($FileAge < .5) {
print "\”$FileName\" is less than half a day old.\n";
} elsif ($FileAge < 1.5) {
print "\"$FileName\" is only a day old.\n";
} else {
$FileAge = int($FileAge+.5);
print "\"$FileName\" is $FileAge days old.\n";
}
}

Date Statistics
If you need more detailed information about the date of file modification, use the ‘stat’ function and ask for the ninth element. Then, use ‘localtime’ or ‘gmtime’ to get the day, month, year, and time that the file was changed.

@Weekdays = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
@Months = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
foreach $FileName (@ARGV) {
@Stats = stat($FileName);
$ModTime = $Stats[9];
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($ModTime);
$Weekday = $Weekdays[$wday];
$Month = $Months[$mon];
$year += 1900;
print "\"$FileName\" was last modified on $Weekday, $Month $mday, $year.\n";
}

Year 2,000
There are a number of year 2,000 problems. These have to do with not treating years correctly. As far as Perl is concerned, make sure that:

  • You add 1900 to your Perl-derived years. Don’t put the string “19” in front of your number! You will end up getting “19100” in the year 2,000. You treat leap years correctly.
  • There are three rules to follow to check for a leap year.
  • The actual year 2,000 problem is more complex. If you are interested, there are entire web sites devoted to the topic. But as long as you store your years as numbers in Perl, and look out for leap years, you should be fine within your Perl programs.

Leap Years
If you work with dates, you will occasionally want to know what a leap year is.

  • If it is divisible by 4, it is a leap year, except
  • If it is divisible by 100, it is not be a leap year, except
  • If it is divisible by 400, it is a leap year.
  • When figuring out what it is divisible, make sure you are using the real year! Add 1900 to it if you are using a Perl year. The year 1900 (divisible by 4 and 100) is not a leap year. The year 2000 (divisible by 4, 100, and 400) is a leap year.

About this Tutorial
This tutorial is written by Jerry Stratton and is published under the GNU Free Documentation License.

Tuesday, February 26, 2008

Backing Up And Restoring Your MySQL Database

If you've been using MySQL database to store your important data, it is imperative that you make a backup of your data to prevent any loss of data. This article shows you how to backup and restore data in your MySQL database. This process can also be used if you have to move your data to a new server.

Backing up your database
The quickest and easiest way to backup and restore your database would be to use MySQLDump. If you've got shell or telnet access to your server, you can backup MySQL data by issuing the mysqldump command. The syntax for the command is as follows.

mysqldump -u [uname] -p [pass] [dbname] > [backupfile.sql]

[uname] - this is your database username
[pass]- this is the password for your database
[dbname] - the name of your database
[backupfile.sql] - the filename for your database backup

To backup your database 'Customers' with the username 'sadmin' and password 'pass21' to a file custback.sql, you would issue the command
mysqldump -u sadmin -p pass21 Customers > custback.sql

Issuing this command will backup the database to custback.sql. This file can be copied to a safe location or a backup media and stored. For more information on MySQLDump, you can check out : http://www.mysql.com/doc/en/mysqldump.html

Restoring your database
If you have to re-build your database from scratch, you can easily restore the mysqldump file by issuing the following command. This method will not work if the tables already exist in your database.
mysql - u sadmin -p pass21 Customers < custback.sql

If you need to restore existing databases, you'll need to use MySQLImport. The syntax for mysqlimport is
mysqlimport [options] database textfile1

To restore your previously created custback.sql dump back to your Customers Database, you'd issue
mysqlimport -u sadmin -p pass21 Customers custback.sql

For more information on MySQLImport, you can check out : http://www.mysql.com/doc/en/mysqlimport.html

About The Author
Vinu Thomas is a consultant on Webdesign and Internet Technologies. His website is http://www.vinuthomas.com. You can discuss about this article or any PHP/MYSQL related issues in our Discussion Forums: http://www.vinuthomas.com/forum2.html

What is AWT?

The Abstract Windowing Toolkit (AWT) is Java's platform-independent windowing, graphics, and user-interface widget toolkit. The AWT is part of the Java Foundation Classes (JFC) - the standard API for providing a graphical user interface (GUI) for a Java program.

When Java was released, AWT was heavily criticized as one of the weakest components of Java. The basic flaw was that AWT provided only a very thin level of abstraction over the underlying native user interface. For example, creating an AWT check box would cause AWT to directly call the underlying native subroutine that created a check box. Unfortunately, a check box on Windows is not quite the same as a check box on MacOS or the various types of UNIX.

This poor design choice made life difficult for programmers trying to adhere to Java's "write once, run anywhere" motto, since AWT did not guarantee precisely how their application would look on all computer platforms. An AWT application that might look great on a Windows PC would turn out to be an unusable mess on a Macintosh system, and vice versa. A popular joke among programmers in the 1990s was that Java's real motto was "write once, test everywhere." One of the reasonable causes of this mediocrity is said to be that AWT was conceptualized and implemented in only one month.

In J2SE 1.2, the AWT's widgets were largely superseded by those of the Swing toolkit. Swing avoids the problems of AWT by drawing its own widgets (by calling into low-level subroutines in the local graphics subsystem), instead of relying on the operating system's high-level user interface module.

About this Terminology
This terminology is from The Wikipedia which is published under the GNU Free Documentation License.

Monday, February 25, 2008

Playing an Audio CD in Visual Basic

Ever wish you could play audio CDs from within your own Visual Basic programs? Well, you probably didn't wish that.. but I did, so I went and figured it out! The advantage of playing audio CDs (as opposed to playing large wave files off the hard drive) is that it takes very little CPU overhead and memory to do, and you can still play other sound effects over top of it. Handy for game purposes if you plan to distribute your game on a CD ROM. Simply store your songs as audio tracks on the CD along with your game data and play these audio tracks during your game, when appropriate.

Most of the cool things that you can do with Visual Basic require some sort of API call, and this is no exception. You have to utilize the MCI (Media Control Interface):

Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA"_
(ByVal lpstrCommand As String, ByVal lpstrReturnString As String, _
ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long

The lpstrCommand is where you tell the MCI what you'd like to do, I'll show examples later. lpstrReturnString is the string you pass to the function when you want a return value. uReturnLength is simply the length of the string you've passed as lpstrReturnString, and hwndCallback... just pass zero (0) and it works :)

So, how do you get this function to do anything useful? It's all in the lpstrCommand. First we'll use it to initialize the MCI cd audio session.
mciSendString "close all", 0, 0, 0
mciSendString "open cdaudio alias cd wait shareable", 0, 0, 0
mciSendString "set cd time format tmsf wait", 0, 0, 0

We pass "close all" to close any audio currently playing. "open cdaudio alias cd wait shareable" initializes the MCI CD audio, and "set cd time format tmsf wait" sets up the CD timing format. You need all of these things to play a CD, so be sure to use them all before attempting the next function:
mciSendString "play cd", 0, 0, 0

If you send the "play cd" string you will start the CD playing on the current track at the current time. If you haven't selected a track yet then this will cause the first track to start playing at the beginning.
mciSendString "stop cd wait", 0, 0, 0

This will stop the CD wherever it currently is. It will NOT start over again at the start of the track, this is more like a pause function than a stop function. If you send "play cd" again it will recommence playing at the exact location within the track that it left off.
mciSendString "seek cd to " & CurrentTrack, 0, 0, 0

This function will skip to the specified CurrentTrack where current track is an integer from 1 to the maximum number of tracks on the CD. Only call this function when you've previously called the "stop cd wait" function, or else things will get all messed up :)
Dim Tracks As String * 30
Dim NumTracks as Integer
mciSendString "status cd number of tracks wait", Tracks, Len(Tracks), 0
NumTracks = CInt(Mid$(Tracks, 1, 2))

In order to determine how many tracks exist on a CD, we must first set up a string of 30 characters and pass this as the lpstrReturnString. after sending "status cd number of tracks wait", the Tracks string will now be filled with the appropriate information. This information will be contained in the first two characters of the string. Even though we're only using the first two characters, we have to pass a string of 30 characters since this is required by the function.

About this Tutorial
This tutorial is from The Game Progamming Wiki which is published under the GNU Free Documentation License 1.2.

Playing WAV Sound Files in Visual Basic

Have you ever wanted to play a WAV file from your Visual Basic applicaiton? Here's the API call you need to use to play WAV files:

Private Declare Function sndPlaySound Lib "winmm.dll" Alias sndPlaySoundA"_
(ByVal lpszSoundName As String, ByVal uFlags As Long) As Long

All you have to do to play a WAV file now is tell the function what file you'd like to play (or in computer speak: ByVal lpszSoundName As String) and how you'd like to play it (ByVal uFlags As Long).

First things first. I'd like to play a WAV file in my windows\media directory called ding.wav, so for the lpszSoundName argument I pass "c:\windows\media\ding.wav". It's as simple as that! If the ding.wav were in the same directory as my program, however, I would pass App.path & "\ding.wav" since this will work no matter where my program is, so long as ding.wav is in the same place. (App.path returns a string containing the path to the directory in which the application is running.)

Second things second. I'd like to play my WAV file in a loop, how do I communicate that to the function? Well, most API calls come equipped with a few constants, and this function is no exception:
Const SND_ASYNC = &H1
Const SND_LOOP = &H8
Const SND_NODEFAULT = &H2
Const SND_SYNC = &H0
Const SND_NOSTOP = &H10
Const SND_MEMORY = &H4

To play my WAV file in a loop, all I have to do is declare the SND_LOOP constant in my declarations section and then pass SND_LOOP as my uFlags argument. So, the final function call would look something like this:
sndPlaySound App.path & "\ding.wav", SND_LOOP

A loop isn't the only method for playing a WAV file, however. As you can see, there are more constants yet unexplained:

SND_ASYNC
Allows us to play WAVs with the ability to interrupt currently playing WAVs. By that I mean that we can play our WAV at any time and ensure that it will be heard.

SND_NODEFAULT
Ensures that if the WAV file specified cannot be found then no other sound will be played in it's place (like some default windows noise!).

SND_SYNC
Plays a WAV file, but does not return control to the program until the WAV file has finished playing. This is very annoying if all we were interested in was playing a sound in the background of our program.

SND_NOSTOP
Ensures that if a WAV file is already playing, our WAV file will not interrupt it. Use this if you want to ensure that your WAVs are never cut short.

SND_MEMORY
Plays a WAV file that is already stored in memory. The routine to store a WAV file in memory will not be shown here, but it simply involves storing the WAV in a string using a get command (be sure to size the string properly first) and passing that string as the argument.

If we wish to use more than one of these constants in conjunction, we link them with an OR statement so that both constants will have an effect. For example, it is best to use SND_ASYNC along with SND_LOOP to ensure that the program can continue functioning while the looped WAV file is playing. If we used SND_SYNC with SND_LOOP, we would never get control back to our program! Example:
sndPlaySound App.path & "\ding.wav", SND_ASYNC or SND_LOOP

That's all there really is to know about playing WAV files using the windows API. To download sample source code using the principles discussed here click here.

About this Tutorial
This tutorial is from The Game Progamming Wiki which is published under the GNU Free Documentation License 1.2.

What is J2ME?

Java Platform, Micro Edition or Java ME (formerly referred to as J2ME), is a runtime and collection of Java APIs for the development of software for resource constrained devices such as PDAs, cell phones and other consumer appliances.

Java ME was designed by Sun Microsystems and is a replacement for a similar technology PersonalJava.

Java ME has become a popular option for creating games for cell phones, as they can be emulated on a PC during the development stage and easily uploaded to the phone. This contrasts with the difficulty of developing, testing, and loading games for other special gaming platforms such as those made by Nintendo, Sony, and others, as expensive system-specific hardware and kits are required.

Sun Microsystems has tended not to provide free binary implementations of its Java ME runtime environment for mobile devices, rather relying on third parties to provide their own, in stark contrast to the numerous binary implementations it provides for the full Java platform standard on server and workstation machines. One of the notable omissions is for Microsoft Windows Mobile (Pocket PC) based devices, despite an open letter campaign to Sun to release a rumoured complete project "Captain America" which is such an implementation.

Configurations and Profiles

Java ME devices implement a profile. The most common of these are the Mobile Information Device Profile aimed at mobile devices, such as cell phones, and the Personal Profile aimed at consumer products and embedded devices like Set-top boxes and PDAs.

A profile is a super set of a configuration, of which there are currently two: Connected Limited Device Configuration and Connected Device Configuration.

Connected Limited Device Configuration
The CLDC contains a strict subset of the Java class libraries, and is the minimal needed for a Java virtual machine to operate. CLDC is basically used to classify the myriad of devices into a fixed configuration.

Mobile Information Device Profile
Designed for cell phones, MIDP boasts an LCD-oriented GUI API, and MIDP 2.0 includes a basic 2D gaming API. Applications written for this profile are called MIDlets. Almost all new cell phones come with a MIDP implementation, and it is now the de facto standard for downloadable cell phone games.

Information Module Profile
The Information Module Profile (IMP) is a Java ME profile for embedded, "headless" devices such as vending machines, industrial embedded applications, security systems, and similar devices with either simple or no display and with some limited network connectivity.

Originally introduced by Siemens Mobile and Nokia as JSR-195, IMP 1.0 is a strict subset of MIDP 1.0 except that it doesn't include user interface APIs — in other words, it doesn't include support for the Java package javax.microedition.lcdui. JSR-228, also known as IMP-NG, is IMP's next generation that is based on MIDP 2.0, leveraging MIDP 2.0's new security and networking types and APIs, and other APIs such as PushRegistry and platformRequest(), but again it doesn't include UI APIs, nor the game API.

IMP applications are called IMlets, but in reality they are MIDlets. They subclass MIDlet, and follow the same packaging, deployment, security and life-cycle as MIDlets.

Connected Device Configuration
CDC is a smaller subset of Java SE, containing almost all the libraries that are not GUI related.

Foundation Profile
A headless version of Java SE.

Personal Basis Profile
Extends the Foundation Profile to include lightweight GUI support in the form of an AWT subset.

Personal Profile
This extension of Personal Basis Profile includes a more comprehensive AWT subset and adds applet support.

About this Terminology
This terminology is from The Wikipedia which is published under the GNU Free Documentation License.

Get the File Type Icon with Java

This tutorial will shows how to get the file system icon for a specific file.

Getting the Small Icon
For all platforms, the FileSystemView class provides a method for getting the small icon (16x16). To get the icon, you must specify a file on the file system for which you want to get an icon. The following code example shows how to use this class to get the icon:

//Create a temporary file with the specified extension
File file = File.createTempFile("icon", ".doc");

FileSystemView view = FileSystemView.getFileSystemView();
Icon icon = view.getSystemIcon(file);

//Delete the temporary file
file.delete();

In the example above, a temporary file is created with the extension for the specified document type. This file is passed to the instance of the FileSystemView class to get the icon. This will return the default icon size which is 16x16 pixels on most platforms. Once you have the Icon, you can display it in most Swing controls such as a JLabel, JButton, JMenuItem, etc.

Getting the Large Icon
Unfortunately, there isn't a standard API call to get the larger icons (32x32) for document types. For platforms using the Sun JVM, there is an undocumented class called sun.awt.shell.ShellFolder that does provide this functionality. The following code is a modified version of our previous example with changes to show how to use the sun.awt.shell.ShellFolder class.
import sun.awt.shell.ShellFolder;
...
//Create a temporary file with the specified extension
File file = File.createTempFile("icon", ".doc");

ShellFolder shellFolder = ShellFolder.getShellFolder(file);
Icon icon = new ImageIcon(shellFolder.getIcon(true));

//Delete the temporary file
file.delete();

What is a Stored Procedure?

A stored procedure is a program (or procedure) which is physically stored within a database. They are usually written in a proprietary database language like Transact-SQL for Microsoft SQL Server, PL/SQL for Oracle database, or PL/pgSQL for PostgreSQL. MySQL also supports stored procedures. The advantage of a stored procedure is that when it is run, in response to a user request, it is run directly by the database engine, which usually runs on a separate database server and is generally faster at processing database requests. The database server has direct access to the data it needs to manipulate and only needs to send the final results back to the user, doing away with the overhead of communicating potentially large amounts of interim data back and forth.

Typical uses for stored procedures include data validation which is integrated into the database structure (stored procedures used for this purpose are often called triggers), or encapsulating an API for some large or complex processing (such as manipulating a large dataset to produce a summarised result). A stored procedure that runs a (possibly complex) series of queries will often run faster as a stored procedure than if it had been implemented as, for example, a program running on a client computer which communicates with the database by submitting the SQL queries one by one, receiving results from them, and then deciding what other queries may need to be run. By having the logic run inside the database engine, this eliminates numerous context switches and a great deal of network traffic.

Stored procedures can also simplify data management when a database is manipulated from many external programs. Embedding "business logic" in the database using stored procedures eliminates the need to duplicate the same logic in each of the programs which accesses the data. This simplifies the creation and maintenance of the programs involved, and can help avoid the data corruption that can be introduced if one or another of those external systems fails to have the validation logic upgraded properly.

In some systems, stored procedures can be used to control transaction management; in others, stored procedures run inside a transaction such that transactions are effectively invisible to them.

In most systems, there is some notion of compilation of stored procedures. This commonly has to do with the database engine determining some query plan that will be reused over and over when the procedure is called. The more extensive (and expensive) the set of optimizations that the compiler applies, the more worthwhile the reuse can be expected to be.

About this Terminology
This terminology is from The Wikipedia which is published under the GNU Free Documentation License.

Sunday, February 24, 2008

Get the Short Names of the Days in Java

This tutorial shows how to get the short day names for the current locale or for a specific locale. Java provides an easy mechanism for getting localized short day names. To get the month names, you will use the DateFormatSymbols in the java.text package. By default, the constructor will create a DateFormatSymbols object based on the current locale.

DateFormatSymbols symbols = new DateFormatSymbols();
If the you are writting a web application, the locale on the web server is probably not the same as the user's locale. In this case you will need to specify the locale when creating the DateFormatSymbols object. Below is an example of specifying a German locale:
DateFormatSymbols symbols = new DateFormatSymbols(Locale.GERMAN);
Now that you have created a DateFormatSymbols object, you can get the short day names by using the getShortWeekdays() method. This will return a String array of the short day names in the specified locale.
String[] shortDayNames = symbols.getShortWeekdays();

Saturday, February 23, 2008

ImageFlow Swing Component

ImageFlow is a Java Swing component that is very similar to the CoverFlow control in Apple's iTunes.

Background
A few years ago, Romain Guy created a very cool demo application called Music Shelf. Romain has an extensive explanation of the math behind this demo on his web site:

http://www.curious-creature.org/2005/07/09/a-music-shelf-in-java2d/
Changes
The ImageFlow is component is pretty much the same as Romain's MusicShelf demo behind the scenes. The ImageFlow component has added new methods to make it similar to JList. This component has also removed the hard coded images in the code. Below is a more details list of changes.
2/17/2008 Changes
  • Removed image names and label strings from the code.
  • Images don't need to be part of the jar
  • Removed the CD case painting
  • Add support for non-square images (images are scaled proportionately)
  • Added the ability to specify a directory and have it load the images from that directory.
  • Added methods similar to those on a JList. These methods include: getSelectedIndex, getSelectedValue, isSelectedIndex, setSelectedIndex,
    addListSelectionListener, removeListSelectionListener.

Screenshot


Usage
Although the ImageFlow component doesn't extend JList, the methods to use it are very similar to a JList.


Constructors

ImageFlow(List items)
This constructs an ImageFlow component with a list of ImageFlowItem. An ImageFlowItem contains the image information and the text to display under the item.

ImageFlow(File directory)
This constructs an ImageFlow component that will load the images from a specified directory.

General Use

To get and set the selected items, the following methods can be used:

getSelectedIndex()
getSelectedValue()
isSelectedIndex(int index)
setSelectedIndex(int index)

To listen for the selected item changing in the component, a listener can be added to the ImageFlow component using the addListSelectionListener method.

Download
ImageFlow Component

Feedback
If you have questions, comments, or suggestions, post them below.

What is ASP.NET?

ASP.NET is a set of web development technologies marketed by Microsoft. Programmers can use it to build dynamic web sites, web applications and XML web services. It is part of Microsoft's .NET platform and is the successor to Microsoft's Active Server Pages (ASP) technology.

Principles of ASP.NET
Even though ASP.NET takes its name from Microsoft's old web development technology, ASP, the two differ significantly. Microsoft has completely rebuilt ASP.NET, based on the Common Language Runtime (CLR) shared by all Microsoft .NET applications. Programmers can write ASP.NET code using any of the different programming languages supported by the .NET framework, usually (proprietary) Visual Basic.NET, JScript .NET, or (standardized) C#, but also including open-source languages such as Perl and Python. ASP.NET has performance benefits over previous script-based technologies because the server-side code is compiled to one or a few DLL files on a web server.

ASP.NET attempts to simplify developers' transition from Windows application development to web development by allowing them to build pages composed of controls similar to a Windows user interface. A web control, such as a button or label, functions in very much the same way as its Windows counterpart: code can assign its properties and respond to its events. Controls know how to render themselves: whereas Windows controls draw themselves to the screen, web controls produce segments of HTML which form part of the resulting page sent to the end-user's browser.

ASP.NET encourages the programmer to develop applications using an event-driven GUI paradigm, rather than in the conventional web scripting fashion. The framework attempts to combine existing technologies such as JavaScript with internal components like "Viewstate" to bring persistent (inter-request) state to the inherently stateless web environment.

ASP.NET uses the .NET Framework as an infrastructure. The .NET Framework offers a managed runtime environment (like Java), providing a virtual machine with JIT and a class library.

The numerous .NET controls, classes and tools can cut down on development time by providing a rich set of features for common programming tasks. Data access provides one example, and comes tightly coupled with ASP.NET. A developer can make a page to display a list of records in a database, for example, significantly more readily using ASP.NET than with ASP.

Advantages of ASP.NET over ASP

  • Compiled code means applications run faster with more design-time errors trapped at the development stage
  • Significantly improved run-time error handling, making use of exceptions and Try-Catch blocks.
  • User-defined controls allow commonly used templates, such as menus
  • Similar metaphors to Windows applications such as controls and events, which make development of rich user interfaces, previously only found on the desktop, possible.
  • A rich set of controls and class libraries allows the rapid building of applications
  • ASP.NET leverages the multi language capabilities of the .NET CLR, allowing web pages to be coded in VB.NET, C#, J#, etc.
  • Ability to cache the whole page or just parts of it to improve performance.
  • Ability to use the CodeBehind development model to separate business logic from presentation.
  • If an ASP.NET application leaks memory, the ASP.NET runtime unloads the AppDomain hosting the erring application and reloads the application in a new AppDomain.
  • Session state in ASP.NET can be saved in a SQL Server database or in a separate process running on the same machine as the web server or on a different machine. That way session values are not lost when IIS is reset or the ASP.NET worker process is recycled.

Disadvantages to other platforms

  • The server framework runs natively on Microsoft IIS 5.0 or higher and Cassini, a web server developed in .NET (shipped with WebMatrix, a free ASP.NET 1.1 development environment, and Visual Studio 2005); however it can run on Linux on any of the alternative frameworks based on the ECMA standard. The most well known one is Mono Project, a free/opensource framework.
  • Previous versions of ASP.NET (1.0 and 1.1) were criticized for their lack of standards compliance. The generated HTML and JavaScript sent to the client browser would not always validate against W3C/ECMA standards. In addition, the framework's browser detection feature sometimes incorrectly identified web browsers other than Microsoft's own Internet Explorer as "downlevel" and returned HTML/JavaScript to these clients that was crippled or broken. However, in version 2.0, all controls generate valid HTML 4.0, XHTML 1.0 (the default), or XHTML 1.1 output, depending on the site configuration, detection of standards-compliant web browsers is more robust, and support for Cascading Style Sheets is more extensive.

About this Terminology
This terminology is from The Wikipedia which is published under the GNU Free Documentation License.

What is a Servlet?

The Java Servlet API, invented by Sun Microsystems, allows a software developer to add dynamic content to a web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets are the Java counterpart to dynamic web content technologies such as CGI, PHP or ASP. Servlets can maintain state across many server transactions by using HTTP Cookies, session variables or URL rewriting.

The Servlet API, contained in the javax.servlet package hierarchy, defines the expected interactions of a web container and a servlet. A web container is essentially the component of a web server that interacts with the servlets. The web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.

A Servlet is an object that receives requests (ServletRequest) and generates a response (ServletResponse) based on the request. The API package javax.servlet.http defines HTTP subclasses of the generic servlet (HttpServlet) request (HttpServletRequest) and response (HttpServletResponse) as well as an (HttpSession) that tracks multiple requests and responses between the web server and a client. Servlets may be packaged in a WAR file as a Web application.

Moreover, servlets can be generated automatically by Java Server Pages (JSP), or alternately by template engines such as WebMacro. Often servlets are used in conjunction with JSPs in a pattern called "Model 2", which is a flavor of the model-view-controller pattern.

History
In his blog on java.net, Sun veteran and GlassFish lead Jim Driscoll claims that he was the first user of servlet technology. James Gosling first thought of servlets in the early days of Java, but the concept did not become a product until Sun shipped the Java Web Server product. This was before what is now the Java Platform, Enterprise Edition was made into a specification.

About this Terminology
This terminology is from The Wikipedia which is published under the GNU Free Documentation License.

Watermarking Images in a Java Servlet

In our previous tutorial, we showed how to create dynamic images images in a servlet. In this tutorial, we are going to take it a step further by dynamically adding a text watermark to an image as it is requested.

Setting up the Servlet
In the web.xml, you will need to configure a filter that will be used to call the servlet. By creating a filter, this will simplify the url used to access the servlet and image. To an end user, the filter will look like part of the directory structure for the image.

The servlet will be invoked when the url contains the pattern /watermark/*. In our example, we will place the images in a directory called photos in the web application directory. To view the image without the watermark, you would use the url http://webserver/webapp/photos/car.jpg. To invoke the servlet, you would use the url http://webserver/webapp/watermark/photos/car.jpg.

<servlet>
<servlet-name>com.codebeach.servlet.WatermarkServlet</servlet-name>
<servlet-class>com.codebeach.servlet.WatermarkServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>com.codebeach.servlet.WatermarkServlet</servlet-name>
<url-pattern>/watermark/*</url-pattern>
</servlet-mapping>
Getting the File Name
When the servlet is invoked, the first thing we need to do is to know which file is being requested to have a watermark added.
File file = new File(req.getPathTranslated());
if (!file.exists())
{
res.sendError(res.SC_NOT_FOUND);
return;
}
The getPathTranslated() method of the HttpServletRequest object provides the file name with the that was specified on the url after the watermark filter. If the requested file does not exist, this will return a not found error.

Creating the AlphaComposite
To allow us to see through the watermark, we will create an AlphaComposite. For our example, we will use a value of 50%. Since we are only drawing text in our tutorial for the watermark, we could have easily created a Color object where the alpha level was 50%. AlphaComposite allows more flexibility since it can be used when you draw anything on top of the the source image. So if you want to use your logo as a watermark, the code for blending it with the source image will be the same.

//Create an alpha composite of 50%
Alph