xiaoxing tech

July 30, 2007

use Regular Expressions in Java

Filed under: Java — xiaoxing @ 3:42 pm

detect if a String is like an E-Mail address:

public boolean isEmailAddr(String str) {
    Pattern email = Pattern.compile(“^\\S+@\\S+$“);
    Matcher fit = email.matcher(str);
    return fit.matches();
}

There are four diffrent types of elements in reg-ex:

–  Assertions ( “Starts With” and “Ends With”)
–  Literal characters ( “Literally an @”)
–  Any character from a group ( “a non-space character”)
–  Counts (1 or more of those)

^    starts with
\S    a non-space character
+    one or more of the one before
@    literal value
$    end of string

so, the reg-ex is: ^\S+@\S+$

and, in order to compile this reg-ex, we need to escape \, so we need another \

 

Finally we get:

^\\S+@\\S+$

 

also,

To match literally a character that's special to the regular
expression engine, you also need to precede the character
with a \, but in this case the \ must itself be protected as
you require it to be passed on through the double quote
handler and reach the compile method. Thus, to match a
String that literally contains a + character, you would
write: Pattern adder = Pattern.compile("\\+")
 
What do ^ and $ do?
Example:
	Pattern feline = Pattern.compile("^cat");
matches:
	-- cat
	-- catalogue
but not:
	-- The use of regular expressions is vindicated

Example:
	Pattern feline = Pattern.compile("cat$");
matches:
	-- cat
but not:
	-- catalogue
	-- The use of regular expressions is vindicated

 

CHARACTER GROUPS:
compile("[abcde]")one of the letters
compile("[a-z]")any lower case letter
compile("[0-9a-fA-F]")any hexadecimal character
compile("[^a-z]")any character except a lower case letter
compile("[^%0-9]")any character except a digit or a % character
\s	any white space character
\dany digit
\wany word character (letter, digit, underscore)
If you want any character except one of these, use a capital
letter:
\Sany character that is not a white space
\Dany character that is not a digit
\Wany character that is not a word character
 

*****************************

appendix: This is page http://www.wellho.net/solutions/java-regular-expressions-in-java.html


Java Regular Expressions

As from release 1.4, Java 2 comes with a regular expression
class that supports patterns similar in style to Perl
regular expressions. This page gives you a brief
introduction to regular expressions if you're not already
familiar with them, then covers Java-specific topics such as
compile and match methods, Pattern objects and
PatternSyntaxExceptions.

BASIC HANDLING OF STRINGS

The Java language includes a primitive data type char, which
holds a 16-bit unicode character. You can hold multiple
characters in a String object, or in a StringBuffer object. 

Methods such as equals and equalsIgnoreCase, startsWith and
endsWith allow you to test Strings against one another.
Methods such as indexOf and substring allow you to perform
operations on a String. parseInt and other similarly named
methods allow you to extract a number (in this example an
int) from a String, although you do need to remember to
catch the exception that may be thrown. 

In certain specialist applications, such as Bioinformatics,
multiple characters can also be usefully held in a char
array, where they're likely to be dealt with
character-by-character in a loop, as in DNA and RNA
sequencing. 

The StringTokenizer class allows you to take a String and
step through it element-by-element (token-by-token) to
handle it in chunks or sections. You can choose what
character or characters you use between the elements to
break up the string in the way you want. 

But, until Java release 1.4, the standard classes didn't
include any way to ask "does this string look like xxxxxxx".
Why would we want to? Well, we might want to ask, "Does this
string look like an email address?" and go on to define (in
simple terms) an email address as a series of non-spaces,
followed by an @ character, followed by another series of
non-spaces. Let's see how that is solved in Java 1.4: 

$ java Reg1 email graham@wellho.net or lisa@wellho.net for information
"email" is NOT an email address
"graham@wellho.net" IS a possible email address
"or" is NOT an email address
"lisa@wellho.net" IS a possible email address
"for" is NOT an email address
"information" is NOT an email address
$

Looks good. 

The Reg1 class is short too, but it includes some strange
looking text strings:

import java.util.regex.*;
public class Reg1 {
public static void main (String [] args) {
                Pattern email = Pattern.compile("^\\S+@\\S+$");
                for (int i=0; i<args.length; i++) {
                        Matcher fit = email.matcher(args[i]);
                        if (fit.matches()) {
                                System.out.println (
                                "\"" +args[i] +
                                "\" IS a possible email address");
                        } else {
                                System.out.println (
                                "\"" + args[i] +
                                "\" is NOT an email address");
                        }
                }
        }
}

AN INTRODUCTION TO REGULAR EXPRESSIONS

A regular expression works by matching a String against a
template or pattern (a Pattern object in Java), and in its
simplest form, returning a boolean to say "yes, the string
does look like the pattern" or "no, that doesn't match". 

Regular expressions have been around for many years. They
originated in Unix utilities such as "grep" – the Global
Regular Expression Processor, and are now supported by most
modern languages. They are, however, a mystery to many
people. That string of strange looking characters in our
example above:

                "^\\S+@\\S+$"

would be enough to put many people off. 

If you're familiar with grep, or have programmed in Perl,
PHP, awk or Tcl, you'll have come across regular expressions
already, at least to some extent. Beware. Each language has
its own regular expression engine (PHP has two!); although
the basics are the same, more advanced regular expressions
differ from one language to another. 

In the early days of Java, a regular expression engine was
written by Johnathan Locke, and donated to the Apache
Software Foundation; you can download it from:
        http://jakarta.apache.org/regexp/index.html
As of release 1.4 of Java, though, there's a standard
package
        java.util.regex
that's shipped with the JRE, and that's what we'll look at
in this module. 

THE ELEMENTS OF A REGULAR EXPRESSION.

A regular expression match is a "woolly match". When you
don't want to say "does ’a’ equal ’b’" but rather
"does ’a’ look like ’b’", then you're probably
looking for a regular expression. 

Does this seem a bit alien to the world of computers? Are
you expecting to be giving precise programming instructions
and getting a bit worried when I tell you that the match is
woolly or fuzzy? Fear not; it's up to the programmer to
define every element of the fuzzy-ness.   

Let's have a look at our crude email address matcher. What
does an email address look like?

It      STARTS WITH
                A NONE SPACE CHARACTER
                (and there's ONE OR MORE OF THOSE).
        That's followed by
                LITERALLY AN @ CHARACTER
        then    A NONE SPACE CHARACTER
                (and there's ONE OR MORE OF THOSE)
        and that's then
                THE END OF THE STRING

If you read it carefully, the description is reasonable
enough, even though I have laid it out in an odd way. That's
so that you can see in a moment how we translate this
description in English into a regular expression. 

Whether we're looking at English (or a regular expression),
we have four types of element in our description above:

--  Assertions ( "Starts With" and "Ends With")
--  Literal characters ( "Literally an @")
--  Any character from a group ( "a non-space character")
--  Counts (1 or more of those)
and those are the basic element groupings in a regular
expression. 

Translating, we'll add the regular expression down the right hand side;
        It      STARTS WITH	^
                A NONE SPACE CHARACTER	\S
                (and there's ONE OR MORE OF THOSE).	+
        That's followed by
                LITERALLY AN @ CHARACTER	@
        then    A NONE SPACE CHARACTER	\S
                (and there's ONE OR MORE OF THOSE)	+
        and that's then
                THE END OF THE STRING.	$

all we then need to do is combine it into a single string,
and add extra \ characters to ensure that the \ of \S gets
past the Java language and into the regex class, thus:
                "^\\S+@\\S+$"

Within Java, there are three stages to regular expression
matching. Firstly, you define a Pattern object against which
you can do the matching, and that typically takes a String
parameter. Chances are you'll have a number of matches to do
using the same pattern, so you don't want your Java to be
slowed down interpreting its curious input string every
time. So:
	Pattern email = Pattern.compile("^\\S+@\\S+$");
doesn't actually do any matching; it runs the regular
expression compiler and prepares to do the matching using
the object called email as the pattern or template. Only
when you go on and run the Matcher (and we happen to do this
within a loop):
	Matcher fit = email.matcher(args[i]);
is the matching done, and that creates an object of type
Matcher. 

The final stage of our matching is to get the result. In
this first instance, we're simply interested in knowing if
the match succeeded or not, so we'll use the boolean matches
method to find out:
	if (fit.matches()) {

EXPANDING THE POWER OF REGULAR EXPRESSIONS

There are complete books on regular expressions, and on our
Perl and PHP courses we spend up to half a day studying
them. We won't go quite so far in this module, but we will
look at each of the elements of the regular expression
handler in Java and show you the power and flexibility it
gives you. It's not yet a "core Java" subject, but in a
short time it may be! 

LITERAL CHARACTERS

If you use most characters within a regular expression, then
they are matched exactly. For example
	Pattern feline = Pattern.compile("cat");
sets up a pattern which will match to any String that
contains the letters c-a-t in that order somewhere within,
so it matches
-- cat
-- catalogue
-- The use of regular expressions is vindicated

To match literally a unicode or other character that's
special to the String handler, you precede it with a \ in
the usual way, thus you may have literals such as
		\n      \t      \u00a3  \\

To match literally a character that's special to the regular
expression engine, you also need to precede the character
with a \, but in this case the \ must itself be protected as
you require it to be passed on through the double quote
handler and reach the compile method. Thus, to match a
String that literally contains a + character, you would
write: Pattern adder = Pattern.compile("\\+");

ANCHORS AND ASSERTIONS

You'll have noticed that a regular expression that contains
only literal characters looks for the given pattern within
the string. It does not force a match against the whole
String.  

If you want to match at the start of a String, start your
pattern with a ^ character; if you want to match at the end,
conclude your pattern with a $ character. Should you specify
both a ^ and a $, then you're looking to match the complete
String to your regular expression. 

The ^ and $ elements are known as "anchors" as they tie the
start and/or the end of the String down; this group as a
whole is also known as "assertions" because they don't match
any specific characters in the incoming string, they just
assert that while the match is running a certain condition
must occur at the given point in the match. 

Example:
	Pattern feline = Pattern.compile("^cat");
matches:
	-- cat
	-- catalogue
but not:
	-- The use of regular expressions is vindicated

Example:
	Pattern feline = Pattern.compile("cat$");
matches:
	-- cat
but not:
	-- catalogue
	-- The use of regular expressions is vindicated

Important note: 

It might appear that Java regular expressions are default
anchored with both a ^ and $ character. This is how the
match method that we're using at present works. Alternative
methods such as find have anchors resume the traditional
(but more confusing) "default off" status that they have in
other programming languages. 

CHARACTER GROUPS

With anchors and literal characters, you can look for a
String that starts with, contains, ends with, or exactly
matches another String. The mechanism is clear enough, but
you could (if you think about it) have used methods such as
startsWith just as easily. The power of regular expressions
really comes into its own when you start adding in character
groups. 

If you write
        [abcdef]
in your regular expression, then you're matching any one
character from the list given (a b c d e or f). You can
expand this capability further by using a minus sign to
specify a character range, thus
	[a-z]	any lower case letter
	[0-9a-fA-F]	any hexadecimal character
and if you want to match any character except one from a
list, you can start the character list with an ^ character,
for example:
	[^a-z]	any character except a lower case letter
	[^%0-9]	any character except a digit or a % character
There are some very common character groups you may want to
specify; you could write "any white space character" as
	[ \t\n\r\f\xoB]
but that would get messy really fast, so there are some
common groupings available in Java's regular expressions:
	\s	any white space character
	\d	any digit
	\w		any word character (letter, digit, underscore)
If you want any character except one of these, use a capital
letter:
	\S	any character that is not a white space
	\D	any character that is not a digit
	\W	any character that is not a word character
Sequences such as \s will be familiar to you if you use
Perl's regular expressions, but there are other character
groups too; these use a POSIX standard definition of the
character groups, but it's extended and the format isn't
taken from Perl, nor PHP, nor Tcl nor SQL!
	\p{Space}	Alternative to \s for "any white space"
	\p{Blank}	Space or tab character
	\p{Alpha}	Any letter (upper or lower case)
	\p{Graph}	Any visible character
	\p{InGreek}	Any Greek letter
	\p{Sc}	A currency symbol
You can negate these groups using \P rather than \p thus
	\P{Graph}	Any character that is not visible
One final grouping, the ultimate group if you like, is the
"." (full stop or period) character, which matches virtually
any character.

COUNTS

The fourth main group (after anchors, literal characters,
and character groups) are the counts; you use these in
regular expressions if you want to give a quantity to a
literal character or group, and you add the count character
into you pattern directly after the element to which it
applies. There are three very common counts:
        +       one or more
        *       zero or more
        ?       zero or one
You might find it easier to read these as
	+       some
        *       perhaps some
        ?       perhaps a

Remember the example we started this section with?
                "^\\S+@\\S+$"
Well, we can now read it through from start to end...

AN EXAMPLE

Here's a sample program that lets you run a regular
expression engine against all the lines from a file. We've
really rewritten the "grep" utility in Java, but our handler
will take the more powerful regular expressions that Java
supports:

import java.util.regex.*;
import java.io.*;

public class Reg2 {

public static void main (String [] args)  throws IOException {

        File in = new File(args[1]);
        BufferedReader get = new BufferedReader(
                new FileReader( in ));

        Pattern hunter = Pattern.compile(args[0]);
        String line;
        int lines = 0;
        int matches = 0;
        System.out.print("Looking for "+args[0]);
        System.out.println(" in "+args[1]);

        while ((line = get.readLine()) != null) {
                        lines++;
                        Matcher fit = hunter.matcher(line);

                        if (fit.matches()) {
                                System.out.println (
                                "" + lines +": "+line);
                                matches++;
                        }
                }
        if (matches == 0) {
                System.out.println("No matches in "+lines+" lines");
                }
        }
}

And in use:

$ java Reg2 ".*dog.*" /usr/share/dict/words
Looking for .*dog.* in /usr/share/dict/words
6459: bulldog
6460: bulldogs
13394: dog
13396: dogged
13397: doggedly
13398: doggedness
13399: dogging
13400: doghouse
13401: dogma
13402: dogmas
13403: dogmatic
13404: dogmatism
13405: dogs
$ java Reg2 "[dD][aeiou]gg.*" /usr/share/dict/words
Looking for [dD][aeiou]gg.* in /usr/share/dict/words
11229: dagger
12597: digger
12598: diggers
12599: digging
12600: diggings
13396: dogged
13397: doggedly
13398: doggedness
13399: dogging
$

EXPANDING THE POWER OF PATTERN OBJECTS

FLAGS

How did we match to the word "dog"? We wrote ".*dog.*", but
alas that would not have matched "Dog" or "DOG" as it's case
sensitive. You can specify one or more flags (or'd together)
to your pattern constructor. Flags available include: 

CASE_INSENSITIVE	whole match case insensitive

MULTILINE	^ and $ to match at embedded new lines (by default
they match as start/end of String)

DOTALL	. to match new line characters (by default it does
not)

COMMENTS	White space and # to line end ignored, allowing you
to comment your regular expression

SPLITTING

If you want to divide an incoming String at a particular
regular expression, the split method allows you to do so.
It's an alternative to the StringTokenizer, and you can use
it without a loop and with a more complex separator. 

split returns an array of Strings. An optional additional
parameter allows you to specify a limit to the number of
strings that you want returned. 

Here's a data file which has a mixture of spaces (sometimes
several of them) and tabs between each field:

passwd:     files nisplus nis
shadow:     files nisplus nis
group:      files nisplus nis
hosts: files dns
bootparams: nisplus [NOTFOUND=return] files
ethers:     files
netmasks:   files
networks:   files
protocols:  files nisplus nis
rpc:        files
services:   files nisplus nis
netgroup:   files nisplus nis
publickey:  nisplus
automount:  files nisplus nis
aliases:    files nisplus

And we want to write an application which lets us find a
list of all the lookups (the first word on each line) may be
handled by a particular service (the following words).

import java.util.regex.*;
import java.io.*;

public class Reg3 {

public static void main (String [] args)  throws IOException {

        File in = new File("confdata");
        BufferedReader get = new BufferedReader(
                new FileReader( in ));

        Pattern hunter = Pattern.compile(args[0],
                        Pattern.CASE_INSENSITIVE);
        Pattern divisor = Pattern.compile(":?\\s+ # any white spaces",
                        Pattern.COMMENTS);

        String line;

        while ((line = get.readLine()) != null) {
                String [] parts = divisor.split(line);
                for (int i=1; i<parts.length; i++) {
                        if (hunter.matcher(parts[i]).matches())
                                System.out.println("Used for "+parts[0]);
                        }
                }
        }
}

And the results:

$ java Reg3 Nis
Used for passwd
Used for shadow
Used for group
Used for protocols
Used for services
Used for netgroup
Used for automount
$ java Reg3 DNS
Used for hosts
$

You'll notice how the separator characters have been
stripped out of the array of strings that has been returned
– a feature we've used to our benefit to strip off the
excess colon on the first field of each line of our incoming
data file. 

THE MATCHER

The Pattern object is only half of the equation. 

CAPTURING THE STRING THAT MATCHED A PATTERN

We've already made lightweight use of the Matcher object,
but it turns out that there's a lot more that we may want to
do. Recall our first example of matching email addresses?
For sure, it's useful to have the facility that allows us to
match against a regular expression and see whether or not we
have something of the format of an email address. We may
want to go a stage further and save the user name and domain
name (the bits before and after the @ character) into
separate variables. 

Now, when the matching has actually been performed, it's
clear that work has been done internally to see which bits
of the incoming pattern match which bits of the String that
we're matching against; all we need to add is:
	-- a way to say "this is a bit that I'm interested in"
 and	-- a way to get back these interesting bits
Firstly, we indicate the "interesting bits" in our regular
expression by grouping them in round brackets. Round
brackets have a dual function in that a count can also be
added directly after the brackets to repeat a pattern. We
then use the group method to return the group(s) to us.

import java.util.regex.*;

public class Reg4 {

public static void main (String [] args) {

        Pattern email = Pattern.compile("(\\S+)@(\\S+)");

        Matcher fit = email.matcher(args[0]);

        if (fit.find()) {
                for (int i=0; i<=fit.groupCount(); i++) {
                        System.out.println("We have "+
                                fit.group(i));
                        }
                }
        }
}

Let's run that:

$ java Reg4 "At home, graham@wellho.net but away ..."
We have graham@wellho.net
We have graham
We have wellho.net
$

Note:
-- use of "find" to look within the string
-- use of () capturing brackets for subsequences
-- The whole match is returned as group number 0.

If you call the find method a second and subsequent times on
the same Matcher, then you can make a series of successive
matches. You'll get a false return when it runs out. Thus,
simply by changing "if" to "while" in the previous example,
you can look for a whole series of email addresses in a line
of text.

$ java Reg5 "Use graham@wellho.net or lisa@wellho.net to reach us"
We have graham@wellho.net
We have graham
We have wellho.net
We have lisa@wellho.net
We have lisa
We have wellho.net
$

Further methods are available to have find start from a
particular position, to reset it to look from the start,
etc. There are also methods available that will return the
start and end positions in the incoming string of the match,
rather than the match string itself. 

USING REGULAR EXPRESSIONS TO REPLACE ONE STRING BY ANOTHER

There are methods available in the Matcher that will let you
replace a matched pattern with a specific string of text.
These are replaceFirst and replaceAll.  Let's change a phone
number from a UK number into a full international one:

import java.util.regex.*;

public class Reg6 {

public static void main (String [] args) {

        Pattern phone = Pattern.compile("\\s0");
        Matcher action = phone.matcher(args[0]);
        String worldwide = action.replaceAll(" +44 (0) ");
        System.out.println(worldwide);

        }
}

Which runs as:

$ java Reg6 "phone 01225 708225 or fax 01225 707126"
phone +44 (0) 1225 708225 or fax +44 (0) 1225 707126
$

OTHER REGULAR EXPRESSION TOPICS

There's a whole book on regular expressions written a number
of years ago before POSIX sequences, before Java ...before
all these extras. Here are a few extra pointers for you to
start you on your way to using the power of regular
expressions should they be the tool of choice for you: 

EXCEPTIONS

The regular expression engine can throw exceptions if you
look to define or match against ill-formed expressions.
Under most circumstances, you will not wish to let your user
provide a regular expression to your program, but if there's
a chance of problems you should catch
PatternSyntaxException. 

EXTENDING REGULAR EXPRESSIONS

There are a number of additional constructions available
within a regular expression that may be of use to you:
	|	is known as "alternation", and lets you specify "or" (for example cat|dog)
	{2,6}	is an example of an extended count; in this example, you are asking for between two and six of whatever precedes the count clause

There are also "reluctant" qualifiers. When we were just
matching and not capturing, the regular expression
        "<.*>"
would correctly identify a tag within a String. But if we
used that same regular expression when capturing, we need to
be more careful.  Consider the text:
        <i><b>Bold, Italic</b></i>
What would we get if we matched that against "<.*>"? 

You might hope to get a match to <i>, but you would not; you
would match the whole of the incoming string. There is a
subtext to the "*" count that reads "as many characters as
possible please". In other words, it is what we call a
"greedy" match. 

Java supports reluctant or sparse counts as well as greedy
ones. You can simply add an extra ? after the count
character. Bear in mind that the easier greedy match is what
you want in 90% of cases, but using this last example, you
can match a single tag by writing
        "<.*?>"

OPERATIONS ON STRINGBUFFERS 

The Matcher matches against a String, as you have seen in
this module, but it can also be used to match against any
other object that implements the CharSequence interface.
Other standard classes that implement this interface are
StringBuffer and CharBuffer.

July 27, 2007

create view on fly

Filed under: SQL — xiaoxing @ 3:37 pm

This is a simple creating-view-on-fly example:

Select MyView.CustomerID, MyView.OrderID, Customer.ZipCode
from
Customer,
(Select CustomerID, OrderID, SKU from Orders) MyView
where
Customer.CustomerID = MyView.CustomerID;

 

This is a complicated one, with the use of “left join”.
“left join” ensures that list all the elements found in the left table, include the elements that don’t have a match from the right table.

SELECT mv.id, mv.TYPE, mv.description, mv.pegasus_param_valud_id, mv.uom,
 tbhch.pcst_master_param_pegasus.pegasus_table,tbhch.pcst_master_param_pegasus.pegasus_special_case
 from
(SELECT tbhch.pcst_master_param_detail.id, tbhch.pcst_master_param_detail.TYPE,
   tbhch.pcst_master_param_detail.description, tbhch.pcst_master_param_detail.pegasus_param_valud_id,
    tbhch.pcst_master_uom.description AS uom
FROM tbhch.pcst_master_param_detail left join tbhch.pcst_master_uom
ON tbhch.pcst_master_param_detail.uom_id=tbhch.pcst_master_uom.id) mv
left join tbhch.pcst_master_param_pegasus
ON mv.pegasus_param_valud_id=tbhch.pcst_master_param_pegasus.pegasus_param_value_id

 

Parameter all properties:

SELECT mvvv.*, tbhch.pcst_master_tab.description AS tab from
(SELECT mvv.*, tbhch.pcst_master_param_codetype.tab_id from
(SELECT mv.id, mv.TYPE, mv.description, mv.pegasus_param_valud_id AS pegaid, mv.uom,
 tbhch.pcst_master_param_pegasus.pegasus_table,
 tbhch.pcst_master_param_pegasus.pegasus_special_case AS pegasus_label,
 tbhch.pcst_master_param_pegasus.pegasus_value_column AS pegacol
 from
(SELECT tbhch.pcst_master_param_detail.id, tbhch.pcst_master_param_detail.TYPE,
   tbhch.pcst_master_param_detail.description, tbhch.pcst_master_param_detail.pegasus_param_valud_id,
    tbhch.pcst_master_uom.description AS uom
FROM tbhch.pcst_master_param_detail left join tbhch.pcst_master_uom
ON tbhch.pcst_master_param_detail.uom_id=tbhch.pcst_master_uom.id) mv
left join tbhch.pcst_master_param_pegasus
ON mv.pegasus_param_valud_id=tbhch.pcst_master_param_pegasus.pegasus_param_value_id) mvv
left join tbhch.pcst_master_param_codetype
ON mvv.id=tbhch.pcst_master_param_codetype.param_id) mvvv
left join tbhch.pcst_master_tab
ON mvvv.tab_id=tbhch.pcst_master_tab.id

 

July 25, 2007

JSP day 3, writing code

Filed under: JSP — xiaoxing @ 5:07 pm

1. The character sequences <%= and %> enclose Java expressions, which are evaluated at run time.
Write this in jsp file: <%= new java.util.Date() %>
You’ll get current time.
Only good for simple java code.

2. You do Scriptlets by placing your larger Java code between <% and %> characters (just like expressions, but without the = sign at the start of the sequence.)

<HTML><BODY><%    // This is a scriptlet.  Notice that the "date"    // variable we declare here is available in the    // embedded expression later on.    System.out.println( "Evaluating date now" );    java.util.Date date = new java.util.Date();%>Hello!  The time is now <%= date %></BODY></HTML>

Notice the output from the "System.out.println" will be on the server log.

3. Using “out” variable in Scriptlet, to generate HTML.

<HTML><BODY><%    // This scriptlet declares and initializes "date"    System.out.println( "Evaluating date now" );    java.util.Date date = new java.util.Date();%>Hello!  The time is now<%    // This scriptlet generates HTML output    out.println( String.valueOf( date ));%></BODY></HTML>

The "out" variable is of type javax.servlet.jsp.JspWriter.

4. Using “request” variable of type javax.servlet.http.HttpServletRequest

<HTML><BODY><%    // This scriptlet declares and initializes "date"    System.out.println( "Evaluating date now" );    java.util.Date date = new java.util.Date();%>Hello!  The time is now<%    out.println( date );    out.println( "<BR>Your machine's address is " );    out.println( request.getRemoteHost());%></BODY></HTML>

Note: request variable is sent by client, processed by server, and return the result of the method to client.

5. Generate a dynamic table, by mixing HTML, Scriptlet and Java-Expression

<HTML><BODY>        <% int n = 120; %>        <TABLE BORDER=1>            <%            for ( int i = 0; i < n; i++ ) {            %>            <TR>                <TD>Number</TD>                <TD><%= i+1 %></TD>            </TR>            <%            }            %>        </TABLE></BODY></HTML>

Note: declare a variable n =120, the <TR> … </TR> will run 120 times. With two columns.

Just another example:
       
        <% boolean hello = false; %>
        <%
        if ( hello ) {
        %>
        <P>Hello, world
        <%
        } else {
        %>
        <P>Goodbye, world
        <%
        }
        %>

To get system’s properties:
<%=System.getProperties().toString() %>

6. import (a directive)

<%@ page import="java.util.*" %><HTML><BODY><%    System.out.println( "Evaluating date now" );    Date date = new Date();%>Hello!  The time is now <%= date %></BODY></HTML>

Note: The first line in the above example is called a “directive“.  A JSP “directive” starts with <%@ characters.
This one is a “page directive“.
To import more than one item:

<%@ page import="java.util.*,java.text.*" %>

7. include directive

<HTML><BODY>Going to include hello.jsp...<BR><%@ include file="hello.jsp" %></BODY></HTML>

8. Tag (jsp tags and non-jsp tags)

jsp:include
usage

<HTML><BODY>Going to include hello.jsp...<BR><jsp:include page="hello.jsp"/></BODY></HTML>

Note: another way of doing include. Tags have XML style.

do forward:
<jsp:forward page=”zxx.html”/>

8. use session
in first page, use a “Form” and a “Text Input” to accept user’s input
        <FORM METHOD=POST ACTION=”SaveName.jsp”>
            What’s your name? <INPUT TYPE=TEXT NAME=username SIZE=20>
            <P><INPUT TYPE=SUBMIT>
        </FORM>

in second page, save the “name” to a variable.
<%
   String name = request.getParameter( “username” );
   session.setAttribute( “theName”, name );
%>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
        <title>JSP Page</title>
    </head>
    <body>
    <h1>JSP Page</h1>
    <A HREF=”NextPage.jsp”>Continue</A>
    </body>
</html>
then in the third page, user can still retrieve the value
<%= session.getAttribute( “theName” ) %>

9. use bean to correspond HTML form.
i. design a HTML form

<HTML><BODY><FORM METHOD=POST ACTION="SaveName.jsp">What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4><P><INPUT TYPE=SUBMIT></FORM></BODY></HTML>

ii. define a Java class with fields "username", "email" and "age"class: UserData		package: me

iii. use this class in the file "SaveName.jsp"<jsp:useBean id="user" class="me.UserData" scope="session"/><jsp:setProperty name="user" property="*"/> 

These two lines of code will handle all the properties.
It will save the user’s data in the bean instance.

iv. in “NextPage.jsp“, retrieve the properties
<jsp:useBean id=”user” class=”me.UserData” scope=”session”/>
in <body>, use <%= user.getUsername() %>

Powered by ScribeFire.

JVM terminated. Exit code=-1

Filed under: Eclipse — xiaoxing @ 4:33 pm

Can’t open Eclipse.

http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=12&t=004485

Symptom:
When starting IBM’s Rational Application Developer (IRAD 7) using eclipse.exe, you get the following error:
JVM terminated. Exit code=1
C:\Program Files\IBM\SDP70\jdk\jre\bin\javaw.exe
-Xquickstart
-Xms512m
-Xmx1024m
-Xgcpolicy:gencon
-Xsharedclasses:singleJVM,keep
-Xnolinenumbers
-XX:MaxPermSize=1024
blah…blah…blah
Problem: eclipse.ini file duplicates existing configuration entries

Quick fix:

 backup the eclipse.ini file,

 and then blank out the origial

 so there is no text in the

eclipse.ini file

 

(deleted content:)

-showsplash
org.eclipse.platform
–launcher.XXMaxPermSize
128M
-vmargs
-Xms40m
-Xmx512m

Proper fix: call IBM support and follow thier instructions. This is not an IBM supported, or IBM recommended fix.
Long, Self-Indulgent, Dialog:
Okay, it’s Christmas, and the best gifts to give are the ones you give yourself. So, I went out and bought myself a refurbished eMachine with a semaphone processor and 1.5 Gigs of RAM. IRAD 7 has just been released, and I wanted a taste of it. Some people spend time with their families at Christmas – I spend time with my computer.
Anyways, I’m a total WebSphere dude, so I was looking forward to installing and testing out IRAD 7. I downloaded like 10 CDs worth of files from IBM, and began the install.
The installation begins with the installation of an installation installer. This always annoys me. Why am I installing an installer to install a product? Why can’t I just install the product? Well, I know the idea – that the IBM Installation Manager can manage the installation, just like Java Web Start technology, or even Windows Update. Still, it annoys me, but I do accept that the people at IBM are much smarter and wiser than me, so I defer to their greater wisdom.
The installation went smoothly, and I selected just about every option possible, with an eye on Portal development tools, as that’s what’s on my plate right now. The installation went well, and after completion, the IRAD tool started up, and I created a workspace and a project. Life was good.
I shutdown the eMachine, and came back about a day later. When I rebooted, I got the annoying message that siad JVM Terminated. Exit Code=1
I googled the error, and realized that I wasn’t the only person running into the problem.
This thread suggested that the metadata/lock file was the problem, especially if eclipse didn’t shut down correct. I had a lock file and deleted it, but still, Exit Code=1 kept coming up.
Digging a little deeper, this other thread suggested I needed to install JDK 1.5, and set the PATH and JAVA_HOME. It suggested that IRAD might get upset if there was another JDK version on the filesystem or something. Now, this seemed strange, because I had a brand new operating system, with nothing but a barebones Windows XP. There was no DB2 or Oracle that might surreptitiously have installed a JDK. Furthermore, IRAD installs its own JRE 1.5, so it should be using its own. Still, I set the PATH and JAVA_HOME to point at the JDK installed by the glorious Installation Manager. I rebooted, but still, I kept getting JVM Terminated. Exit Code=1
Now, somebody mentioned that maybe I should up the Xms512 to somethig larger. Pehaps the JVM wasn’t getting enough memory. However, the launcher just called the eclipse.exe file. I was curiousas to where the parameters were being initialized, which is what lead me to the eclipse.ini file.
Now what I noticed was that the things that were being displayed in the error weren’t in the same order as the eclipse.ini file. When I looked closer, I saw that parameters for a javaw.exe were being set, and then they were being SET AGAIN, and the second time around, the initializations were in the same order as the eclipse.ini file. So, eclipse was getting run with various initialization parameters, and then it was reading the eclipse.ini file, and trying to do all the initializations again.
So, I backed up the eclipse.ini file, and then erased the contents of the original. Then I launched IBM’s Rational Application Developer 7, and guess what? The darn thing started up.
I shut it down and replaced the new eclipse.ini file with the old one, and guess what? JVM Terminated: Exit Code 1.
So, it looks like the fabulous installation manager is managing to incorrectly configure IRAD 7, especially when you choose to install almost all of the funky features like portal and so on.
Still, it’s just a little bump in the road. I can’t wait to see what else IRAD 7 has in store for me.
Happy WebSphere!
-Cameron McKenzie

[ December 26, 2006: Message edited by: Cameron W. McKenzie ]

JSP day 2, Using Netbeans 5.5.1

Filed under: JSP — xiaoxing @ 9:21 am

1. Create a new Web Application: “PCSWebUpdater”, the Context Path is /PCSWebUpdater. Version: J2EE 1.4
2. Source structure: Java BluePrints
3. Server: Bundled Tomcat 5.5.17
4. Click “Finish”.
5. index.jsp is opened in the source file editor.
6. Add a Java Class: “Handler” into
Source Packages. Package: “me”.
7. Handler.java is opened in the source file editor.
8. Writing code. Remember, to generate Getter and Setter Methods, you need to do:
Right-click the word name in the field
declaration at the start of the class and choose Refactor > Encapsulate Fields.
Click Next to run the command with its default options. Click Do Refactoring.
9. Open index.jsp file in editor.
10. In the Palette on the right side of the Source Editor, expand HTML Forms and
drag a Form item below the <h1> tags in the Source Editor.
11. “Insert Form” window appears.
12.
Set the following values:

  • Action: response.jsp
  • Method: GET
  • Name: Name Input Form

Click OK. The Form is added to the index.jsp file.
13. Drag a Text Input item to just before the </form> tag.

Set the following values:

  • Name: name
  • Type: text

Click OK. The Text Input is added between the <form> tags.
14. Drag a Button item to just before the </form> tag.

Set the following values:

  • Label: OK
  • Type: submit

Click OK. The Button is added between the <form> tags.
15. Type Enter your name: in front of the first <input> tag and change the text between the
<h1> tags to Entry Form.
16. Creating response.jsp (New > JSP in Web Pages node)
17. In the Palette on the right side of the Source Editor, expand JSP and
drag a Use Bean item right below the <body> tag in the Source Editor.

Set the following values:

  • ID: mybean
  • Class: org.me.hello.NameHandler
  • Scope: session

Click OK. The Use Bean is added below the <body> tag.
18. Add a Get Bean Property item and a Set Bean Property item from the Palette. Then
change the code so that the tags between the <body> tags look as follows:

<jsp:useBean id="mybean" scope="session" class="org.me.hello.NameHandler" /><jsp:setProperty name="mybean" property="*" /><h1>Hello, <jsp:getProperty name="mybean" property="name" />!</h1>

***************************************************************************************************



Ready to run. Input your name......

Powered by ScribeFire.

July 24, 2007

JSP day 1, to set up a server

Filed under: JSP — xiaoxing @ 11:02 pm

http://www.jsptut.com/Getfamiliar.jsp

What I need is a “Tomcat”. Here is the versions list.

Servlet/JSP Spec Apache Tomcat version
2.5/2.1 6.0.13
2.4/2.0 5.5.23
2.3/1.2 4.1.36
2.2/1.1 3.3.2

What if I use the latest version, 6.0.13?
From here: http://tomcat.apache.org/download-60.cgi#6.0.13
Then click here: Windows Service Installer
(pgp,
md5)
It’s around 5 MB of size.

The default installation path: C:\Program Files\Apache Software Foundation\Tomcat 6.0

Setting:

java path: C:\Program Files\Java\jre1.6.0_02

Now the installation is done, and ready to work.
go to: http://localhost:8080/
You’ll see sth like this:

My local folder for web pages is:
C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\ROOT

And the default page is:
C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\ROOT\index.html

Now I’ll run a sample application, from a WAR file:
I downloaded the WAR file from:
http://tomcat.apache.org/tomcat-6.0-doc/appdev/sample/sample.war
Then, put this file in:
C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps

Go to: http://localhost:8080/sample/
to run this application.

******************************************************************
Make a text file with name: zxx.jsp
content:

Hello, world zxx

Put this file in:
C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\ROOT

Go to: http://localhost:8080/zxx.jsp
You’ll see the page.
******************************************************************

Memo For Configuring New PCS Oracle DB

Filed under: Oracle — xiaoxing @ 1:42 pm

Access
to EUEOLTD1 Development Database and change password (
by using SQL*Plus,
the tool comes with Oracle database, this program is at
C:\oracle\ora81\bin\SQLPLUSW.EXE):

 

step
1: Open tnsnames.ora with Notepad

        (this file is at: C:\oracle\ora81\network\ADMIN\tnsnames.ora)

        Add the following five lines of code
to the end of that file:

        eueoltd1  =

  (DESCRIPTION =

    (ADDRESS =
(PROTOCOL = TCP)(Host = 3.59.41.217)(Port = 1598))

    (CONNECT_DATA =
(SID = eueoltd1))

  )

step
2: Try log into DB through SQL*Plus by using your

        username, password and Host String:
eueoltd1

        If it works, done.

        If it doesn’t work, open the same
folder that containing tnsnames.ora.

        Delete (or move) the file: sqlnet.ora.

        Then try again.

step
3: change password: Open SQL*Plus, fill in user name, password, and eueoltd1 as
Host String

 

Type
password in the command line:

input
the old password then input a new password twice,

it’s
done!

 

The
JDBC DB url is: jdbc:oracle:thin:@3.59.41.217:1598:eueoltd1

 

 

 

Powered by ScribeFire.

Blog at WordPress.com.