Posts Tagged ‘String[]’

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec and test methods of RegExp, and with the match, replace, search, and split methods of String. This chapter describes JavaScript regular expressions.

Creating a Regular Expression

You construct a regular expression in one of two ways:

  • Using a regular expression literal, as follows:
    1
    var re = /ab+c/;

    Regular expression literals provide compilation of the regular expression when the script is evaluated. When the regular expression will remain constant, use this for better performance.

  • Calling the constructor function of the RegExpobject, as follows:
    1
    var re = new RegExp("ab+c");

    Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don’t know the pattern and are getting it from another source, such as user input.

Writing a Regular Expression Pattern

A regular expression pattern is composed of simple characters, such as /abc/, or a combination of simple and special characters, such as /ab*c/ or /Chapter (\d+)\.\d*/. The last example includes parentheses which are used as a memory device. The match made with this part of the pattern is remembered for later use, as described in Using Parenthesized Substring Matches.

Using Simple Patterns

Simple patterns are constructed of characters for which you want to find a direct match. For example, the pattern /abc/ matches character combinations in strings only when exactly the characters ‘abc’ occur together and in that order. Such a match would succeed in the strings “Hi, do you know your abc’s?” and “The latest airplane designs evolved from slabcraft.” In both cases the match is with the substring ‘abc’. There is no match in the string “Grab crab” because it does not contain the substring ‘abc’.

Using Special Characters

When the search for a match requires something more than a direct match, such as finding one or more b’s, or finding white space, the pattern includes special characters. For example, the pattern /ab*c/ matches any character combination in which a single ‘a’ is followed by zero or more ‘b’s (* means 0 or more occurrences of the preceding item) and then immediately followed by ‘c’. In the string “cbbabbbbcdebc,” the pattern matches the substring ‘abbbbc’.

The following table provides a complete list and description of the special characters that can be used in regular expressions.

Table 4.1 Special characters in regular expressions.
Character Meaning
\ Either of the following:

  • For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally.
  • For example, /b/ matches the character ‘b’. By placing a backslash in front of b, that is by using /\b/, the character becomes special to mean match a word boundary.
  • For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally.
  • For example, * is a special character that means 0 or more occurrences of the preceding item should be matched; for example, /a*/ means match 0 or more a’s. To match * literally, precede it with a backslash; for example, /a\*/ matches ‘a*’.
  • Also do not forget to escape \ itself while using the new RegExp(“pattern”) notation since \ is also an escape character in strings.
^ Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character.

For example, /^A/ does not match the ‘A’ in “an A”, but does match the ‘A’ in “An E”.
This character has a different meaning when it appears as the first character in a character set pattern.

For example, /[^a-z\s]/ matches the ‘3’ in “I have 3 sisters”.

$ Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character.

For example, /t$/ does not match the ‘t’ in “eater”, but does match it in “eat”.

* Matches the preceding character 0 or more times.

For example, /bo*/ matches ‘boooo’ in “A ghost booooed” and ‘b’ in “A bird warbled”, but nothing in “A goat grunted”.

+ Matches the preceding character 1 or more times. Equivalent to {1,}.

For example, /a+/ matches the ‘a’ in “candy” and all the a’s in “caaaaaaandy”.

? Matches the preceding character 0 or 1 time. Equivalent to {0,1}.

For example, /e?le?/ matches the ‘el’ in “angel” and the ‘le’ in “angle” and also the ‘l’ in “oslo”.

If used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier non-greedy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times). For example, using /\d+/ non-global match “123abc” return “123”, if using /\d+?/, only “1” will be matched.

Also used in lookahead assertions, described under x(?=y) and x(?!y) in this table.

. (The decimal point) matches any single character except the newline character.

For example, /.n/ matches ‘an’ and ‘on’ in “nay, an apple is on the tree”, but not ‘nay’.

(x) Matches ‘x’ and remembers the match. These are called capturing parentheses.

For example, /(foo)/ matches and remembers ‘foo’ in “foo bar.” The matched substring can be recalled from the resulting array’s elements [1], …, [n].

(?:x) Matches ‘x’ but does not remember the match. These are called non-capturing parentheses. The matched substring can not be recalled from the resulting array’s elements [1], …, [n].
x(?=y) Matches ‘x’ only if ‘x’ is followed by ‘y’. This is called a lookahead.

For example, /Jack(?=Sprat)/ matches ‘Jack’ only if it is followed by ‘Sprat’. /Jack(?=Sprat|Frost)/ matches ‘Jack’ only if it is followed by ‘Sprat’ or ‘Frost’. However, neither ‘Sprat’ nor ‘Frost’ is part of the match results.

x(?!y) Matches ‘x’ only if ‘x’ is not followed by ‘y’. This is called a negated lookahead.

For example, /\d+(?!\.)/ matches a number only if it is not followed by a decimal point. The regular expression /\d+(?!\.)/.exec("3.141") matches ‘141’ but not ‘3.141’.

x|y Matches either ‘x’ or ‘y’.

For example, /green|red/ matches ‘green’ in “green apple” and ‘red’ in “red apple.”

{n} Where n is a positive integer. Matches exactly n occurrences of the preceding character.

For example, /a{2}/ doesn’t match the ‘a’ in “candy,” but it matches all of the a’s in “caandy,” and the first two a’s in “caaandy.”

{n,m} Where n and m are positive integers. Matches at least n and at most m occurrences of the preceding character. When either n or m is zero, it can be omitted.

For example, /a{1,3}/ matches nothing in “cndy”, the ‘a’ in “candy,” the first two a’s in “caandy,” and the first three a’s in “caaaaaaandy” Notice that when matching “caaaaaaandy”, the match is “aaa”, even though the original string had more a’s in it.

[xyz] A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen. Special characters (such as the dot (.) and the asterisk (*)) do not have any special meaning inside a character set. They need not be escaped. Escape sequences also work.

For example, [abcd] is the same as [a-d]. They match the ‘b’ in “brisket” and the ‘c’ in “city”. /[a-z.]+/ and /[\w.]+/ both match everything in “test.i.ng”.

[^xyz] A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen. Everything that works in the normal character set also works here.

For example, [^abc] is the same as [^a-c]. They initially match ‘r’ in “brisket” and ‘h’ in “chop.”

[\b] Matches a backspace (U+0008). (Not to be confused with \ b.)
\b Matches a word boundary. A word boundary matches the position where a word character is not followed or preceeded by another word-character. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero. (Not to be confused with [\b].)

Examples:
/\bmoo/ matches the ‘m’ in “moon” ;
/oo\b/ does not match the ‘oo’ in “moon”, because ‘oo’ is followed by ‘n’ which is a word character;
/oon\b/ matches the ‘oon’ in “moon”, because ‘oon’ is the end of the string, thus not followed by a word character;
/\w\b\w/ will never match anything, because a word character can never be followed by both a non-word and a word character.

\B Matches a non-word boundary. This matches a position where the previous and next character are of the same type: Either both must be words, or both must be non-words. The beginning and end of a string are considered non-words.

For example, /\B../ matches ‘oo’ in “noonday” (, and /y\B./ matches ‘ye’ in “possibly yesterday.”

\cX Where X is a character ranging from A to Z. Matches a control character in a string.

For example, /\cM/ matches control-M (U+000D) in a string.

\d Matches a digit character. Equivalent to [0-9].

For example, /\d/ or /[0-9]/ matches ‘2’ in “B2 is the suite number.”

\D Matches any non-digit character. Equivalent to [^0-9].

For example, /\D/ or /[^0-9]/ matches ‘B’ in “B2 is the suite number.”

\f Matches a form feed (U+000C).
\n Matches a line feed (U+000A).
\r Matches a carriage return (U+000D).
\s Matches a single white space character, including space, tab, form feed, line feed. Equivalent to [ \f\n\r\t\v​\u00A0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​ \u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​\u2028\u2029​ \u202f\u205f​\u3000].

For example, /\s\w*/ matches ‘ bar’ in “foo bar.”

\S Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v​\u00A0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​ \u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​\u2028\u2029​ \u202f\u205f​\u3000].

For example, /\S\w*/ matches ‘foo’ in “foo bar.”

\t Matches a tab (U+0009).
\v Matches a vertical tab (U+000B).
\w Matches any alphanumeric character including the underscore. Equivalent to [A-Za-z0-9_].

For example, /\w/ matches ‘a’ in “apple,” ‘5’ in “$5.28,” and ‘3’ in “3D.”

\W Matches any non-word character. Equivalent to [^A-Za-z0-9_].

For example, /\W/ or /[^A-Za-z0-9_]/ matches ‘%’ in “50%.”

\n Where n is a positive integer. A back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses).

For example, /apple(,)\sorange\1/ matches ‘apple, orange,’ in “apple, orange, cherry, peach.”

Matches a NULL (U+0000) character. Do not follow this with another digit, because <digits> is an octal escape sequence.
\xhh Matches the character with the code hh (two hexadecimal digits)
\uhhhh Matches the character with the code hhhh (four hexadecimal digits).

Using Parentheses

Parentheses around any part of the regular expression pattern cause that part of the matched substring to be remembered. Once remembered, the substring can be recalled for other use, as described in Using Parenthesized Substring Matches.

For example, the pattern /Chapter (\d+)\.\d*/ illustrates additional escaped and special characters and indicates that part of the pattern should be remembered. It matches precisely the characters ‘Chapter ‘ followed by one or more numeric characters (\d means any numeric character and + means 1 or more times), followed by a decimal point (which in itself is a special character; preceding the decimal point with \ means the pattern must look for the literal character ‘.’), followed by any numeric character 0 or more times (\d means numeric character, * means 0 or more times). In addition, parentheses are used to remember the first matched numeric characters.

This pattern is found in “Open Chapter 4.3, paragraph 6” and ‘4’ is remembered. The pattern is not found in “Chapter 3 and 4”, because that string does not have a period after the ‘3’.

To match a substring without causing the matched part to be remembered, within the parentheses preface the pattern with ?:. For example, (?:\d+) matches one or more numeric characters but does not remember the matched characters.

Working with Regular Expressions

Regular expressions are used with the RegExp methods test and exec and with the String methods match, replace, search, and split. These methods are explained in detail in the JavaScript Reference.

Table 4.2 Methods that use regular expressions
Method Description
exec A RegExp method that executes a search for a match in a string. It returns an array of information.
test A RegExp method that tests for a match in a string. It returns true or false.
match A String method that executes a search for a match in a string. It returns an array of information or null on a mismatch.
search A String method that tests for a match in a string. It returns the index of the match, or -1 if the search fails.
replace A String method that executes a search for a match in a string, and replaces the matched substring with a replacement substring.
split A String method that uses a regular expression or a fixed string to break a string into an array of substrings.

When you want to know whether a pattern is found in a string, use the test or search method; for more information (but slower execution) use the exec or match methods. If you use exec or match and if the match succeeds, these methods return an array and update properties of the associated regular expression object and also of the predefined regular expression object, RegExp. If the match fails, the exec method returns null (which converts to false).

In the following example, the script uses the exec method to find a match in a string.

1
2
var myRe = /d(b+)d/g;
var myArray = myRe.exec("cdbbdbsbz");

If you do not need to access the properties of the regular expression, an alternative way of creating myArray is with this script:

1
var myArray = /d(b+)d/g.exec("cdbbdbsbz");

If you want to construct the regular expression from a string, yet another alternative is this script:

1
2
var myRe = new RegExp("d(b+)d", "g");
var myArray = myRe.exec("cdbbdbsbz");

With these scripts, the match succeeds and returns the array and updates the properties shown in the following table.

Table 4.3 Results of regular expression execution.
Object Property or index Description In this example
myArray The matched string and all remembered substrings. ["dbbd", "bb"]
index The 0-based index of the match in the input string. 1
input The original string. "cdbbdbsbz"
[0] The last matched characters. "dbbd"
myRe lastIndex The index at which to start the next match. (This property is set only if the regular expression uses the g option, described in Advanced Searching With Flags.) 5
source The text of the pattern. Updated at the time that the regular expression is created, not executed. "d(b+)d"

As shown in the second form of this example, you can use a regular expression created with an object initializer without assigning it to a variable. If you do, however, every occurrence is a new regular expression. For this reason, if you use this form without assigning it to a variable, you cannot subsequently access the properties of that regular expression. For example, assume you have this script:

1
2
3
var myRe = /d(b+)d/g;
var myArray = myRe.exec("cdbbdbsbz");
console.log("The value of lastIndex is " + myRe.lastIndex);

This script displays:

The value of lastIndex is 5

However, if you have this script:

1
2
var myArray = /d(b+)d/g.exec("cdbbdbsbz");
console.log("The value of lastIndex is " + /d(b+)d/g.lastIndex);

It displays:

The value of lastIndex is 0

The occurrences of /d(b+)d/g in the two statements are different regular expression objects and hence have different values for their lastIndex property. If you need to access the properties of a regular expression created with an object initializer, you should first assign it to a variable.

Using Parenthesized Substring Matches

Including parentheses in a regular expression pattern causes the corresponding submatch to be remembered. For example, /a(b)c/ matches the characters ‘abc’ and remembers ‘b’. To recall these parenthesized substring matches, use the Array elements [1], …, [n].

The number of possible parenthesized substrings is unlimited. The returned array holds all that were found. The following examples illustrate how to use parenthesized substring matches.

Example 1

The following script uses the replace() method to switch the words in the string. For the replacement text, the script uses the $1 and $2 in the replacement to denote the first and second parenthesized substring matches.

1
2
3
4
var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
console.log(newstr);

This prints “Smith, John”.

Advanced Searching With Flags

Regular expressions have four optional flags that allow for global and case insensitive searching. To indicate a global search, use the g flag. To indicate a case-insensitive search, use the i flag. To indicate a multi-line search, use the m flag. To perform a “sticky” search, that matches starting at the current position in the target string, use the y flag. These flags can be used separately or together in any order, and are included as part of the regular expression.

Firefox 3 note

Support for the y flag was added in Firefox 3. The y flag fails if the match doesn’t succeed at the current position in the target string.

To include a flag with the regular expression, use this syntax:

1
var re = /pattern/flags;

or

1
var re = new RegExp("pattern", "flags");

Note that the flags are an integral part of a regular expression. They cannot be added or removed later.

For example, re = /\w+\s/g creates a regular expression that looks for one or more characters followed by a space, and it looks for this combination throughout the string.

1
2
3
4
var re = /\w+\s/g;
var str = "fee fi fo fum";
var myArray = str.match(re);
console.log(myArray);

This displays [“fee “, “fi “, “fo “]. In this example, you could replace the line:

1
var re = /\w+\s/g;

with:

1
var re = new RegExp("\\w+\\s", "g");

and get the same result.

The m flag is used to specify that a multiline input string should be treated as multiple lines. If the m flag is used, ^ and $ match at the start or end of any line within the input string instead of the start or end of the entire string.

Examples

The following examples show some uses of regular expressions.

Changing the Order in an Input String

The following example illustrates the formation of regular expressions and the use of string.split() and string.replace(). It cleans a roughly formatted input string containing names (first name first) separated by blanks, tabs and exactly one semicolon. Finally, it reverses the name order (last name first) and sorts the list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// The name string contains multiple spaces and tabs,
// and may have multiple spaces between first and last names.
var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ; Chris Hand ";
var output = ["---------- Original String\n", names + "\n"];
// Prepare two regular expression patterns and array storage.
// Split the string into array elements.
// pattern: possible white space then semicolon then possible white space
var pattern = /\s*;\s*/;
// Break the string into pieces separated by the pattern above and
// store the pieces in an array called nameList
var nameList = names.split(pattern);
// new pattern: one or more characters then spaces then characters.
// Use parentheses to "memorize" portions of the pattern.
// The memorized portions are referred to later.
pattern = /(\w+)\s+(\w+)/;
// New array for holding names being processed.
var bySurnameList = [];
// Display the name array and populate the new array
// with comma-separated names, last first.
//
// The replace method removes anything matching the pattern
// and replaces it with the memorized string—second memorized portion
// followed by comma space followed by first memorized portion.
//
// The variables $1 and $2 refer to the portions
// memorized while matching the pattern.
output.push("---------- After Split by Regular Expression");
var i, len;
for (i = 0, len = nameList.length; i < len; i++){
  output.push(nameList[i]);
  bySurnameList[i] = nameList[i].replace(pattern, "$2, $1");
}
// Display the new array.
output.push("---------- Names Reversed");
for (i = 0, len = bySurnameList.length; i < len; i++){
  output.push(bySurnameList[i]);
}
// Sort by last name, then display the sorted array.
bySurnameList.sort();
output.push("---------- Sorted");
for (i = 0, len = bySurnameList.length; i < len; i++){
  output.push(bySurnameList[i]);
}
output.push("---------- End");
console.log(output.join("\n"));

Using Special Characters to Verify Input

In the following example, the user is expected to enter a phone number. When the user presses the “Check” button, the script checks the validity of the number. If the number is valid (matches the character sequence specified by the regular expression), the script shows a message thanking the user and confirming the number. If the number is invalid, the script informs the user that the phone number is not valid at all.

The regular expression looks for zero or one open parenthesis \(?, followed by three digits \d{3}, followed by zero or one close parenthesis \)?, followed by one dash, forward slash, or decimal point and when found, remember the character ([-\/\.]), followed by three digits \d{3}, followed by the remembered match of a dash, forward slash, or decimal point \1, followed by four digits \d{4}.

The Change event activated when the user presses Enter sets the value of RegExp.input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html
  <head
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"
    <meta http-equiv="Content-Script-Type" content="text/javascript"
    <script type="text/javascript"
      var re = /\(?\d{3}\)?([-\/\.])\d{3}\1\d{4}/; 
      function testInfo(phoneInput){ 
        var OK = re.exec(phoneInput.value); 
        if (!OK) 
          window.alert(RegExp.input + " isn't a phone number with area code!"); 
        else
          window.alert("Thanks, your phone number is " + OK[0]); 
      
    </script
  </head
  <body
    <p>Enter your phone number (with area code) and then click "Check".
        <br>The expected format is like ###-###-####.</p>
    <form action="#"
      <input id="phone"><button onclick="testInfo(document.getElementById('phone'));">Check</button>
    </form
  </body
</html>

 

1. XML Introduction

1.1. XML Overview

XML stands for Extensible Markup Language and was defined 1998 by the World Wide Web Consortium (W3C).

A XML document consists out of elements, each element has a start tag, content and an end tag. A XML document must have exactly one root element, e.g. one tag which encloses the remaining tags. XML makes a difference between capital and non-capital letters.

A XML file is required to be well-formated.

Well-formated XML must apply to the following conditions:

  • A XML document always starts with a prolog (see below for an explanation of what a prolog is)
  • Every tag has a closing tag.
  • All tags are completely nested.

 

A XML file is valid if it is well-formated and if it is contains a link to a XML schema and is valid according to the schema.

In general the following is considered as advantages in using XML for data processing / representation.

  • XML is Plain text
  • XML allows the data identification without any display information
  • Style can be defined via XSL
  • Easily processed due to it regular and consistent notation
  • XML files are hierarchical

 

1.2. XML Example

The following is a valid, well-formated XML file.

 

				
<?xml version="1.0"?>
<!-- This is a comment -->
<address>
	<name>Lars </name>
	<street> Test </street>
	<telephon number= "0123"/>
</address>

 

1.3. XML Elements

1.3.1. Prolog

A XML document always starts with a prolog which describes XML file. This prolog can be minimal, e.g. <?xml version=”1.0″?> or can contain other information, e.g. the encoding, e.g. <?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes” ?>

1.3.2. Empty Tag

A tag which doesn’t enclose any content is know as an “empty tag”. For example: <flag/>

1.3.3. Commends

Comments in XML are defined as: <! COMMENT>

2. Java XML Overview

Java contains several methods to access XML. The following is a short overview of the available methods.

Java provides the DOM API (Document Object Model). In DOM your access the XML document over an object tree. DOM can be used to read and write XML files.

SAX (Simple API for XML) is an Java API to sequential reading of XML files. SAX can only read XML documents. SAX provides an Event-Driven XML Processing following the Push-Parsing Model. What this model means is that in SAX, Applications will register Listeners in the form of Handlers to the Parser and will get notified through Call-back methods. Here the SAX Parser takes the control over Application thread by Pushing Events to the Application. Both DOM and Sax are older API’s and I recommend not to use them anymore.

Stax (Streaming API for XML) is an API for reading and writing XML Documents. Introduced in Java 6.0 and considered as superior to SAX and DOM.

Java Architecture for XML Binding ( JAXB ) is a Java standard that defines how Java objects are converted to/from XML (specified using a standard set of mappings. JAXB defines a programmer API for reading and writing Java objects to / from XML documents and a service provider which / from from XML documents allows the selection of the JAXB implementation JAXB applies a lot of defaults thus making reading and writing of XML via Java very easy.

The following will explain the Stax interface, for an introduction into JAXB please see JAXB tutorial.

3. Streaming API for XML (StaX)

3.1. Overview

Streaming API for XML, called StaX, is an API for reading and writing XML Documents.

StaX is a Pull-Parsing model. Application can take the control over parsing the XML documents by pulling (taking) the events from the parser.

The core StaX API falls into two categories and they are listed below. They are

  • Cursor API
  • Event Iterator API

 

Applications can any of these two API for parsing XML documents. The following will focus on the event iterator API as I consider it more convenient to use.

3.2. Event Iterator API

The event iterator API has two main interfaces: XMLEventReader for parsing XML and XMLEventWriter for generating XML.

3.3. XMLEventReader – Read XML Example

This example is stored in project “de.vogella.xml.stax.reader”.

Applications loop over the entire document requesting for the Next Event. The Event Iterator API is implemented on top of Cursor API.

In this example we will read the following XML document and create objects from it. file.

 

				
<?xml version="1.0" encoding="UTF-8"?>
<config>
	<item date="January 2009">
		<mode>1</mode>
		<unit>900</unit>
		<current>1</current>
		<interactive>1</interactive>
	</item>
	<item date="February 2009">
		<mode>2</mode>
		<unit>400</unit>
		<current>2</current>
		<interactive>5</interactive>
	</item>
	<item date="December 2009">
		<mode>9</mode>
		<unit>5</unit>
		<current>100</current>
		<interactive>3</interactive>
	</item>
</config>

 

Define therefore the following class to store the individual entries of the XML file.

 

				
package de.vogella.xml.stax.model;

public class Item {
	private String date; 
	private String mode;
	private String unit;
	private String current;
	private String interactive;

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}
	public String getMode() {
		return mode;
	}
	public void setMode(String mode) {
		this.mode = mode;
	}
	public String getUnit() {
		return unit;
	}
	public void setUnit(String unit) {
		this.unit = unit;
	}
	public String getCurrent() {
		return current;
	}
	public void setCurrent(String current) {
		this.current = current;
	}
	public String getInteractive() {
		return interactive;
	}
	public void setInteractive(String interactive) {
		this.interactive = interactive;
	}

	@Override
	public String toString() {
		return "Item [current=" + current + ", date=" + date + ", interactive="
				+ interactive + ", mode=" + mode + ", unit=" + unit + "]";
	}
}

 

The following reads the XML file and creates a List of object Items from the entries in the XML file.

 

				
package de.vogella.xml.stax.read;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

import de.vogella.xml.stax.model.Item;

public class StaXParser {
	static final String DATE = "date";
	static final String ITEM = "item";
	static final String MODE = "mode";
	static final String UNIT = "unit";
	static final String CURRENT = "current";
	static final String INTERACTIVE = "interactive";

	@SuppressWarnings({ "unchecked", "null" })
	public List<Item> readConfig(String configFile) {
		List<Item> items = new ArrayList<Item>();
		try {
			// First create a new XMLInputFactory
			XMLInputFactory inputFactory = XMLInputFactory.newInstance();
			// Setup a new eventReader
			InputStream in = new FileInputStream(configFile);
			XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
			// Read the XML document
			Item item = null;

			while (eventReader.hasNext()) {
				XMLEvent event = eventReader.nextEvent();

				if (event.isStartElement()) {
					StartElement startElement = event.asStartElement();
					// If we have a item element we create a new item
					if (startElement.getName().getLocalPart() == (ITEM)) {
						item = new Item();
						// We read the attributes from this tag and add the date
						// attribute to our object
						Iterator<Attribute> attributes = startElement
								.getAttributes();
						while (attributes.hasNext()) {
							Attribute attribute = attributes.next();
							if (attribute.getName().toString().equals(DATE)) {
								item.setDate(attribute.getValue());
							}

						}
					}

					if (event.isStartElement()) {
						if (event.asStartElement().getName().getLocalPart()
								.equals(MODE)) {
							event = eventReader.nextEvent();
							item.setMode(event.asCharacters().getData());
							continue;
						}
					}
					if (event.asStartElement().getName().getLocalPart()
							.equals(UNIT)) {
						event = eventReader.nextEvent();
						item.setUnit(event.asCharacters().getData());
						continue;
					}

					if (event.asStartElement().getName().getLocalPart()
							.equals(CURRENT)) {
						event = eventReader.nextEvent();
						item.setCurrent(event.asCharacters().getData());
						continue;
					}

					if (event.asStartElement().getName().getLocalPart()
							.equals(INTERACTIVE)) {
						event = eventReader.nextEvent();
						item.setInteractive(event.asCharacters().getData());
						continue;
					}
				}
				// If we reach the end of an item element we add it to the list
				if (event.isEndElement()) {
					EndElement endElement = event.asEndElement();
					if (endElement.getName().getLocalPart() == (ITEM)) {
						items.add(item);
					}
				}

			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (XMLStreamException e) {
			e.printStackTrace();
		}
		return items;
	}

}

 

You can test the parser via the following test program. Please note that the file config.xml must exist in the Java project folder.

 

				
package de.vogella.xml.stax.read;

import java.util.List;

import de.vogella.xml.stax.model.Item;

public class TestRead {
	public static void main(String args[]) {
		StaXParser read = new StaXParser();
		List<Item> readConfig = read.readConfig("config.xml");
		for (Item item : readConfig) {
			System.out.println(item);
		}
	}
}

 

3.4. Write XML File- Example

This example is stored in project “de.vogella.xml.stax.writer”.

Lets assume you would like to write the following simple XML file.

 

				
<?xml version="1.0" encoding="UTF-8"?>
<config>
	<mode>1</mode>
	<unit>900</unit>
	<current>1</current>
	<interactive>1</interactive>
</config>

 

StaX does not provide functionality to format the XML file automatically. So you have to add end-of-lines and tab information to your XML file.

 

				
package de.vogella.xml.stax.writer;

import java.io.FileOutputStream;

import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

public class StaxWriter {
	private String configFile;

	public void setFile(String configFile) {
		this.configFile = configFile;
	}

	public void saveConfig() throws Exception {
		// Create a XMLOutputFactory
		XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
		// Create XMLEventWriter
		XMLEventWriter eventWriter = outputFactory
				.createXMLEventWriter(new FileOutputStream(configFile));
		// Create a EventFactory
		XMLEventFactory eventFactory = XMLEventFactory.newInstance();
		XMLEvent end = eventFactory.createDTD("\n");
		// Create and write Start Tag
		StartDocument startDocument = eventFactory.createStartDocument();
		eventWriter.add(startDocument);

		// Create config open tag
		StartElement configStartElement = eventFactory.createStartElement("",
				"", "config");
		eventWriter.add(configStartElement);
		eventWriter.add(end);
		// Write the different nodes
		createNode(eventWriter, "mode", "1");
		createNode(eventWriter, "unit", "901");
		createNode(eventWriter, "current", "0");
		createNode(eventWriter, "interactive", "0");

		eventWriter.add(eventFactory.createEndElement("", "", "config"));
		eventWriter.add(end);
		eventWriter.add(eventFactory.createEndDocument());
		eventWriter.close();
	}

	private void createNode(XMLEventWriter eventWriter, String name,
			String value) throws XMLStreamException {

		XMLEventFactory eventFactory = XMLEventFactory.newInstance();
		XMLEvent end = eventFactory.createDTD("\n");
		XMLEvent tab = eventFactory.createDTD("\t");
		// Create Start node
		StartElement sElement = eventFactory.createStartElement("", "", name);
		eventWriter.add(tab);
		eventWriter.add(sElement);
		// Create Content
		Characters characters = eventFactory.createCharacters(value);
		eventWriter.add(characters);
		// Create End node
		EndElement eElement = eventFactory.createEndElement("", "", name);
		eventWriter.add(eElement);
		eventWriter.add(end);

	}

}

 

And a little test.

 

				
package de.vogella.xml.stax.writer;

public class TestWrite {

	public static void main(String[] args) {
		StaxWriter configFile = new StaxWriter();
		configFile.setFile("config2.xml");
		try {
			configFile.saveConfig();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

For another (more complex example of using Stax please see Reading and creating RSS feeds via Java (with Stax)

4. XPath

4.1. Overview

XPath (XML Path Language) is a language for selecting / searching nodes from an XML document. Java 5 introduced the javax.xml.xpath package which provides a XPath library.

The following explains how to use XPath to query an XML document via Java.

4.2. Using XPath

The following explains how to use XPath. Create a new Java project called “UsingXPath”.

Create the following xml file.

 

				
<?xml version="1.0" encoding="UTF-8"?>
<people>
	<person>
		<firstname>Lars</firstname>
		<lastname>Vogel</lastname>
		<city>Heidelberg</city>
	</person>
	<person>
		<firstname>Jim</firstname>
		<lastname>Knopf</lastname>
		<city>Heidelberg</city>
	</person>
	<person>
		<firstname>Lars</firstname>
		<lastname>Strangelastname</lastname>
		<city>London</city>
	</person>
	<person>
		<firstname>Landerman</firstname>
		<lastname>Petrelli</lastname>
		<city>Somewhere</city>
	</person>
	<person>
		<firstname>Lars</firstname>
		<lastname>Tim</lastname>
		<city>SomewhereElse</city>
	</person>
</people>

 

Create a new package “myxml” and a new Java class “QueryXML”.

 

				
package myxml;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class QueryXML {
	public void query() throws ParserConfigurationException, SAXException,
			IOException, XPathExpressionException {
		// Standard of reading a XML file
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder builder;
		Document doc = null;
		XPathExpression expr = null;
		builder = factory.newDocumentBuilder();
		doc = builder.parse("person.xml");

		// Create a XPathFactory
		XPathFactory xFactory = XPathFactory.newInstance();

		// Create a XPath object
		XPath xpath = xFactory.newXPath();

		// Compile the XPath expression
		expr = xpath.compile("//person[firstname='Lars']/lastname/text()");
		// Run the query and get a nodeset
		Object result = expr.evaluate(doc, XPathConstants.NODESET);

		// Cast the result to a DOM NodeList
		NodeList nodes = (NodeList) result;
		for (int i=0; i<nodes.getLength();i++){
			System.out.println(nodes.item(i).getNodeValue());
		}

		// New XPath expression to get the number of people with name lars
		expr = xpath.compile("count(//person[firstname='Lars'])");
		// Run the query and get the number of nodes
		Double number = (Double) expr.evaluate(doc, XPathConstants.NUMBER);
		System.out.println("Number of objects " +number);

		// Do we have more then 2 people with name lars?
		expr = xpath.compile("count(//person[firstname='Lars']) >2");
		// Run the query and get the number of nodes
		Boolean check = (Boolean) expr.evaluate(doc, XPathConstants.BOOLEAN);
		System.out.println(check);

	}

	public static void main(String[] args) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
		QueryXML process = new QueryXML();
		process.query();
	}
}

 

5. Thank you

 

Using client side JavaScript is an efficient way to validate the user input in web forms. When there are many fields in the form, the JavaScript validation becomes too complex.

The JavaScript class presented here makes the form validations many times easier.

Contents

  1. Download the JavaScript form validation script
  2. Using the form validation script
  3. Adding a custom validation
  4. Table of Validation Descriptors
  5. Showing the form validation errors next to the element
  6. ‘Conditional’ form validations
  7. Form validation without coding!

How to add JavaScript Form Validation quickly

First, download the JavaScript form validation script here.
The zip file contains the javascript file, examples.

The script has a catalog of almost all the common validation types built-in.

The idea is to create a set of “validation descriptors” associated with each element in a form. The “validation descriptor” is nothing but a string specifying the type of validation to be performed.

Each field in the form can have zero one or more validations. For example, you can have an input field that should not be empty, should be less than 25 chars and should be alpha-numeric.

In other words, in order to validate a field, you just associate a set of validation descriptors for each input field in the form.

Just Choose Validations!
Simfatic Forms is a feature-rich web form maker.
You just have to choose the validations. More info & downloads

Using the form validation script

  1. Include gen_validatorv4.js in your html file just before closing the HEAD tag
<script src="gen_validatorv4.js" type="text/javascript"></script>
</head>
  1. Just after defining your form, create a Validator() object passing the name of the form
<form id='myform' action="">
 <!----Your input fields go here -->
 </form>
<script type="text/javascript">
 var frmvalidator  = new Validator("myform");
                     //where myform is the name/id of your form
  1. Now, add the validations required
frmvalidator.addValidation("FirstName","req","Please enter your First Name");

The format of the addValidation() function is:

frmvalidator.addValidation(Field Name, Validation Descriptor, Error String);

See below for the complete list of validation descriptors. The third parameter ( Error string ) is optional.
You can add any number of validations to a field.

frmvalidator.addValidation("FirstName","req","Please enter your First Name");
frmvalidator.addValidation("FirstName","maxlen=40",
                                          "Max length for FirstName is 40");

Example

Here is a complete example:

<form action="" id="myform" >
<p>
    <label for='FirstName'>First Name:</label>
    <input type="text" id="FirstName" name="FirstName" />
</p>
<p>
    <label for='LastName'>Last Name:</label>
    <input type="text" id="LastName" name="LastName" />
</p>
<p>
    <label for='EMail'>EMail:</label>
    <input type="text" id="EMail" name="EMail" />
</p>
<p>
    <label for='Phone'>Phone:</label>
    <input type="text" id="Phone" name="Phone" />
</p>
<p>
    <label for='Address'>Address:</label>
    <textarea cols="20" rows="5" id="Address" name="Address"></textarea>
</p>
<p>
    <label for='Country'>Country:</label>
    <select id="Country"  name="Country">
        <option value="000" selected="selected">[choose yours]</option>
        <option value="008">Albania</option>
        <option value="012">Algeria</option>
        <option value="016">American Samoa</option>
        <option value="020">Andorra</option>
        <option value="024">Angola</option>
        <option value="660">Anguilla</option>
        <option value="010">Antarctica</option>
        <option value="028">Antigua And Barbuda</option>
        <option value="032">Argentina</option>
        <option value="051">Armenia</option>
        <option value="533">Aruba</option>
    </select>
</p>
<p>
    <input type="submit" name="submit" value="Submit">
</p>
</form>
<script  type="text/javascript">
 var frmvalidator = new Validator("myform");
 frmvalidator.addValidation("FirstName","req","Please enter your First Name");
 frmvalidator.addValidation("FirstName","maxlen=20",
        "Max length for FirstName is 20");
 frmvalidator.addValidation("LastName","req");
 frmvalidator.addValidation("LastName","maxlen=20");
 frmvalidator.addValidation("Email","maxlen=50");
 frmvalidator.addValidation("Email","req");
 frmvalidator.addValidation("Email","email");
 frmvalidator.addValidation("Phone","maxlen=50");
 frmvalidator.addValidation("Phone","numeric");
 frmvalidator.addValidation("Address","maxlen=50");
 frmvalidator.addValidation("Country","dontselect=000");
</script>

Some Additional Notes

  • The form validators should be created only after defining the HTML form (only after the tag. )
  • Your form should have a distinguished name. If there are more than one form in the same page, you can add validators for each of them. The names of the forms and the validators should not clash.
  • You can’t use the javascript onsubmit event of the form if it you are using this validator script. It is because the validator script automatically overrides the onsubmit event. If you want to add a custom validation, see the section below

Adding a custom validation

If you want to add a custom validation, which is not provided by the validation descriptors, you can do so. Here are the steps:

  1. Create a javascript function which returns true or false depending on the validation
function DoCustomValidation()
{
  var frm = document.forms["myform"];
  if(frm.pwd1.value != frm.pwd2.value)
  {
    sfm_show_error_msg('The Password and verified password does not match!',frm.pwd1);
    return false;
  }
  else
  {
    return true;
  }
}

sfm_show_error_msg() function displays the error message in your chosen style. The first parameter is the error message and the second parameter is the input object.

  1. Associate the validation function with the validator object.
frmvalidator.setAddnlValidationFunction("DoCustomValidation");

The custom validation function will be called automatically after other validations.

If you want to do more than one custom validations, you can do all those validations in the same function.

function DoCustomValidation()
{
  var frm = document.forms["myform"];
  if(false == DoMyValidationOne())
  {
    sfm_show_error_msg('Validation One Failed!');
    return false;
  }
  else
  if(false == DoMyValidationTwo())
  {
    sfm_show_error_msg('Validation Two Failed!');
    return false;
  }
  else
  {
    return true;
  }
}

where DoMyValidationOne() and DoMyValidationTwo() are custom functions for validation.

Clear All Validations

In some dynamically programmed pages, it may be required to change the validations in the form at run time. For such cases, a function is included which clears all validations in the validator object.

frmvalidator.clearAllValidations();

This function call clears all validations you set.

Set focus on validation failure

By default, if there is a validation error, the focus is set on the input element having the error. You can disable this behavior by calling:

frmvalidator.EnableFocusOnError(false);

Table of Validation Descriptors

Validation Descriptor Usage
required or
req
The field should not be empty.Note that this validation if for fields like Textbox and multi-line text box. For ‘selections’ like drop down and radio group, use an appropriate validation like ‘dontselect’ or ‘selone_radio’.
maxlen=??? or
maxlength=???
Limits the length of the input.
For example, if the maximum size permitted is 25, give the validation descriptor as “maxlen=25″
minlen=??? or
minlength=???
Checks the length of the entered string to the required minimum.
Example “minlen=5″
alphanumeric or
alnum
The input can contain alphabetic or numeric characters only.
(Note that space or punctuation also are not allowed since those characters are not alpha numeric)
alphanumeric_space
alnum_s
Allows only alphabetic, numeric and space characters
num
numeric
Allow numbers only
alpha
alphabetic
Allow only alphabetic characters.
alpha_s
alphabetic_space
Allows alphabetic and space characters
email Validates the field to be a proper email address.
(Note, However that the validation can’t check whether the email address exists or not)
lt=???
lessthan=???
Verify the data to be less than the value passed. Valid only for numeric fields.
Example: if the value should be less than 1000 give validation description as “lt=1000″
gt=???
greaterthan=???
Verify the data to be greater than the value passed. Valid only for numeric fields.
Example: if the value should be greater than 10 give validation description as “gt=10″
regexp=??? Match the input with a regular expression.
Example: “regexp=^[A-Za-z]{1,20}$” allow up to 20 alphabetic characters.
dontselect=?? This validation descriptor is valid only for drop down lists. The drop down select list boxes usually will have one item saying ‘Select One’ (and that item will be selected by default). The user should select an option other than this ‘Select One’ item.
If the valueof this default option is ’000′, the validation description should be “dontselect=000″Dropdown box with default selected

Drop down list source

dontselectchk=?? This validation descriptor is only for check boxes. The user should not select the given check box. Provide the value of the check box instead of ??
For example, dontselectchk=on
shouldselchk=?? This validation descriptor is only for check boxes. The user should select the given check box. Provide the value of the check box instead of ??
For example, shouldselchk=on
selone_radio One of the radio buttons should be selected.
Example:

chktestValidator.addValidation("Options","selone");
Compare two input elements
eqelmnt=??? Compare two input elements. For example: password and confirm password. Replace ??? with the name of the other input element.
Example:

frmvalidator.addValidation("confpassword","eqelmnt=password",
 "The confirmed password is not same as password");
neelmnt=??? The value should not be equal to the other input element
Example:

frmvalidator.addValidation("password","neelmnt=username",
"The password should not be same as username");
ltelmnt=??? The input should be less than the other input. Give the name of the other input instead of ???
leelmnt=??? The input should be less than or equal to the other input. Give the name of the other input instead of ???
gtelmnt=??? The input should be greater than the other input. Give the name of the other input instead of ???
geelmnt=??? The input should be greater than or equal to the other input. Give the name of the other input instead of ???

Go to the second part of this post to learn about the advanced features of this validation script.

The example below illustrates how you can convert the HTML of RadEditor to PDF format using an HTML2PDF convertor tool of Tall Components. For a live demo, please go to http://www.tallcomponents.com/cp0803.aspx

 

ASPX code

<form id=”Form1″ method=”post” runat=”server”>
    RadEditor id=”RadEditor1″ Runat=”server”>
    <asp:button id=”showPDF” runat=”server” Text=”Show PDF”></asp:button>

C# code

private void showPDF_Click(object sender, EventArgs e)
{
    string html = “<html>” + RadEditor1.Html + “</html>”;
    TallComponents.PDF.Layout.Document document = new TallComponents.PDF.Layout.Document();
    TallComponents.PDF.Layout.Section section = document.Sections.Add();
    TallComponents.PDF.Layout.HtmlParagraph htmlParagraph = new TallComponents.PDF.Layout.HtmlParagraph();
    htmlParagraph.FontPath = “fonts“;
    htmlParagraph.Text = html;
    section.Paragraphs.Add( htmlParagraph );
    Response.Clear();
    document.Write( Response );
    Response.End();
}

VB.NET code

Private Sub showPDF_Click(ByVal sender As Object, ByVal e As EventArgs)
 Dim html As String = “<html>” + RadEditor1.Html + “</html>”
 Dim document As TallComponents.PDF.Layout.Document = New TallComponents.PDF.Layout.Document
 Dim section As TallComponents.PDF.Layout.Section = document.Sections.Add
 Dim htmlParagraph As TallComponents.PDF.Layout.HtmlParagraph = New TallComponents.PDF.Layout.HtmlParagraph
 htmlParagraph.FontPath = “fonts”
 htmlParagraph.Text = html
 section.Paragraphs.Add(htmlParagraph)
 Response.Clear
 document.Write(Response)
 Response.End
End Sub

ASPX code

<form id=”Form1″ method=”post” runat=”server”>
    ScriptManager ID=”ScriptManager1″ runat=”server” />
    <telerik:RadEditor id=”RadEditor1″ Runat=”server”>
    <asp:button id=”showPDF” runat=”server” Text=”Show PDF”></asp:button>
</form>

C# code

private void showPDF_Click(object sender, EventArgs e)
{
    string html = “<html>” + RadEditor1.Content + “</html>”;
    TallComponents.PDF.Layout.Document document = new TallComponents.PDF.Layout.Document();
    TallComponents.PDF.Layout.Section section = document.Sections.Add();
    TallComponents.PDF.Layout.HtmlParagraph htmlParagraph = new TallComponents.PDF.Layout.HtmlParagraph();
    htmlParagraph.FontPath = “fonts”;
    htmlParagraph.Text = html;
    section.Paragraphs.Add( htmlParagraph );
    Response.Clear();
    document.Write( Response );
    Response.End();
}

VB.NET code

Private Sub showPDF_Click(ByVal sender As Object, ByVal e As EventArgs)
 Dim html As String = “<html>” + RadEditor1.Content+ “</html>”
 Dim document As TallComponents.PDF.Layout.Document = New TallComponents.PDF.Layout.Document
 Dim section As TallComponents.PDF.Layout.Section = document.Sections.Add
 Dim htmlParagraph As TallComponents.PDF.Layout.HtmlParagraph = New TallComponents.PDF.Layout.HtmlParagraph
 htmlParagraph.FontPath = “fonts”
 htmlParagraph.Text = html
 section.Paragraphs.Add(htmlParagraph)
 Response.Clear
 document.Write(Response)
 Response.End
End Sub

In the “Article Files” section, there is attached a sample project with RadEditor 6.1 demonstrating the described functionality.

Article Links

I can provide two ways,

a.jsp:

<html>
<script language="javascript" type="text/javascript">
function call(){
var name = "xyz";
window.location.replace("a.jsp?name="+name);
}
</script>
<input type="button" value="Get" onclick='call()'>
<%
String name=request.getParameter("name");
if(name!=null){
out.println(name);
}
%>
</html>

2)b.jsp:

<script>
var v="xyz";
</script>
<% String st="<script>document.writeln(v)</script>";
out.println("value="+st); %>

  

import java.sql.CallableStatement;

import java.sql.Connection;

import java.sql.DriverManager;

public class Main {

  public static void main(String[] argsthrows Exception {

    Connection conn = getOracleConnection();

    // Step-2: identify the stored procedure

    String proc3StoredProcedure = “{ call proc3(?, ?, ?) }”;

    // Step-3: prepare the callable statement

    CallableStatement cs = conn.prepareCall(proc3StoredProcedure);

    // Step-4: set input parameters …

    // first input argument

    cs.setString(1“abcd”);

    // third input argument

    cs.setInt(310);

    // Step-5: register output parameters …

    cs.registerOutParameter(2, java.sql.Types.VARCHAR);

    cs.registerOutParameter(3, java.sql.Types.INTEGER);

    // Step-6: execute the stored procedures: proc3

    cs.execute();

    // Step-7: extract the output parameters

    // get parameter 2 as output

    String param2 = cs.getString(2);

    // get parameter 3 as output

    int param3 = cs.getInt(3);

    System.out.println(“param2=” + param2);

    System.out.println(“param3=” + param3);

    conn.close();

  }

  private static Connection getHSQLConnection() throws Exception {

    Class.forName(“org.hsqldb.jdbcDriver”);

    System.out.println(“Driver Loaded.”);

    String url = “jdbc:hsqldb:data/tutorial”;

    return DriverManager.getConnection(url, “sa”“”);

  }

  public static Connection getMySqlConnection() throws Exception {

    String driver = “org.gjt.mm.mysql.Driver”;

    String url = “jdbc:mysql://localhost/demo2s”;

    String username = “oost”;

    String password = “oost”;

    Class.forName(driver);

    Connection conn = DriverManager.getConnection(url, username, password);

    return conn;

  }

  public static Connection getOracleConnection() throws Exception {

    String driver = “oracle.jdbc.driver.OracleDriver”;

    String url = “jdbc:oracle:thin:@localhost:1521:caspian”;

    String username = “mp”;

    String password = “mp2”;

    Class.forName(driver)// load Oracle driver

    Connection conn = DriverManager.getConnection(url, username, password);

    return conn;

  }

}

           

         

    

  

CallStoresProcedureInOracleAndPassInOutParameters.zip( 3,849 k)

Conversion PDF to Byte and Vice verse

Posted: January 13, 2012 in Random Posts
Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Simple conversion easily enjoy the word of JAVA……………….

public static byte[] convertPDFToByteArray(String sourcePath) {
byte[] bytes=null;
InputStream inputStream;

File file = new File(sourcePath);

try {
inputStream = new FileInputStream(file);
bytes = new byte[(int)file.length()];
int read = inputStream.read(bytes);
} catch (IOException ex) {
Logger.getLogger(

DesktopApplication3View.class.getName()).log(Level.SEVERE, null, ex);
}return bytes;

}

public void convertByteArrayToPDF(String sourcePath,byte[] bytes) {
OutputStream out;
try {
out = new FileOutputStream(sourcePath);
try {
out.write(bytes);
out.close();
} catch (IOException ex) {
Logger.getLogger(DesktopApplication3View.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(DesktopApplication3View.class.getName()).log(Level.SEVERE, null, ex);
}

}

·

Introduction

 

In
this tutorial we will create a simple web service and a client web application
using eclipse IDE along with
Lomboz
plug
in.
We
will also deploy and test the web service on Tomcat 5.5.4 web application
server. This application, while simple, provides a good introduction to Web
service development and some of the Web development tools available.

 

·
Environment

 

J2SDK
1.4.2

http://java.sun.com/

 

Eclipse
3.1

 

http://www.eclipse.org/

 

 

Tomcat
5.5.4

 

http://tomcat.apache.org/

 

 

Lomboz
3.1RC2

http://lomboz.objectweb.org/

 

 

 

·
Installation

 

Install
JDK (in D:\j2sdk1.4.2_04)

 

Install
Tomcat (in E:\Tomcat5.5)

 

Install
Eclipse (in E:\Eclipse3.1)

 

Install
Lomboz (in E:\Eclipse3.1)

 

·
Setting up

 

  1. Set
    up the installed JRE in eclipse (Windows -> Preferences -> Java ->
    Installed JREs)
     

 

 

  1. Set
    up the installed runtime for server in eclipse (Windows -> Preferences
    -> Server -> Installed Runtimes)
     

 

 

  1. Set
    up the Server view in eclipse (Windows -> Show View -> Other)
     

 


 

 

  1. Set
    up the Tomcat Server by right clicking and selecting New -> Server option
    from the Server view in eclipse
     

 

 

 

 

 

 

·
Creating a Web service

 

  1. Create
    a new Dynamic Web Project in eclipse (File -> New -> Other)
     

 

 

 

  1. Enter
    name as ?WebServiceTutorial?, select project location as ?E:\Test?
    and select Apache Tomcat v5.5 as the Target server.
     

 

 

 

  1. Now
    create a new Java class from the Project Explorer (Dynamic Web Projects
    -> Java Source -> New -> Class)
     

 

 

 

  1. Enter
    name as ?Hello? and package as ?com.tutorial?.
     

 

 

  1. Add
    a simple method in the ?Hello? class as below.
     


public String sayHello(String name){

 


return “Hello ” + name;

 


}

 


 

 

  1. Save
    and build the project.
     
  2. Create
    a new Web service in eclipse (File -> New -> Other)
     

 

 

  1. Select
    Generate a proxy.
     
  2. Select
    Test the Web service.
     
  3. Select
    Overwrite files without warning.
     

 

 

  1. Select
    or enter the Bean name as ?com.tutorial.Hello?. This is the java class
    that we just now created.
     

 

 

  1. Continue
    the wizard by clicking Next and finish.
     
  2. On
    Finish, the Tomcat server starts up and launches the Test client.
     
  3. Verify
    the generated contents. Look for Hello.class and the generated JSPs as
    below.
     

 

 

 

 

 

  1. Verify
    the Tomcat folder and ensure the newly created web applications ?
    WebServiceTutorial, WebServiceTutorialClient.
     

 

 

 

 

  1. We
    can also run the following url from the browser to access/test the Web
    service.
     

http://localhost:8080/WebServiceTutorialClient/sampleHelloProxy/TestClient.jsp

 

 

  1. If
    servlet error ?org.eclipse.jst.ws.util.JspUtils cannot be resolved or is
    not a type? is thrown on the browser, then copy the webserviceutils.jar
    file from the E:\Eclipse3.1\eclipse\plugins\org.eclipse.jst.ws.consumption_0.7.0
    into the WEB-INF\lib folder of the WebServiceTutorialClient application and
    restart the Tomcat server.
     
  1. The
    browser displays the methods available in the web service.
     

 

 

 

  1. Click
    on the sayHello(..) method, enter your name (for e.g. ?Jeeva?) in
    the inputs section and click ?Invoke?.
     

 

 

 

  1. The
    browser greets using the web service.
     

 

 

 

 

 

  1. The
    WSDL for the Hello Web service can be found in E:\Test\WebServiceTutorial\WebContent\wsdl\Hello.wsdl.
    On double-click, the WSDL opens in a graphical editor.
     

 

 

 

  1. Right-click
    on the WSDL file and explore the options to test the web service / publish
    the WSDL file / generate client / etc.
     

 

 

 

 

·
Conclusion

 

In this
tutorial we learned how to create a simple web service and a client web
application using eclipse IDE along with
Lomboz
plug
in.
We
also deployed and tested the web service on Tomcat 5.5.4 web application server.
This application, while simple, provides a good introduction to Web service
development and some of the Web development tools available.

Reference # http://www.roseindia.net/webservices/buildingsimplewebservice.shtml

 

Java PDF Generation with IText

Posted: January 4, 2012 in Random Posts
Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Multi Site Keyword Extractor Tool
Analyze Keywords

First Method creates ur PDF File and Second Download your file from the relative Path in JSF

public String mypdfGeneratorAmd() {
// fileCreation();
List mylist = this.getListDfAmd();
if (mylist != null) {
Document pdf = new Document();
Date today = new Date();
ServletContext servletContext = null;
// (ServletContext)
// FacesContext.getCurrentInstance().getExternalContext().getContext();
// String logo1 = servletContext.getRealPath(“”) + “/” +
// “WebContent”
// + “/” + “reports” + “/”;

String fileName = “AssistedMaintenanceDocking.pdf”;

File f;
String fileTitle = “AssistedMaintenanceDocking ”
+ (new Date().toString());
servletContext = (ServletContext) FacesContext.getCurrentInstance()
.getExternalContext().getContext();
String logo = servletContext.getRealPath(“”) + “/” + “images” + “/”
+ “user-image.jpg”;

int rowCount = mylist.size();
PdfPTable t = new PdfPTable(5);
Paragraph title1 = new Paragraph();
try {
Image img = Image.getInstance(logo);
String mypdfFile = servletContext.getRealPath(“”) + “/”
+ “reports” + “/” + “DefectAndHistory.pdf”;
f = new File(mypdfFile);
// “/home/shussain/workspace2/DNRMS-PMSA/WebContent/reports/”+
// “AssistedMaintenanceDocking.pdf”);
if (!f.exists()) {
try {
f.createNewFile();
System.out
.println(“New file ‘AssistedMaintenanceDocking.pdf’ has been created to the current directory”);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out
.println(“File ‘AssistedMaintenanceDocking.pdf’ Already in the current directory”);
}
PdfWriter.getInstance(pdf, new FileOutputStream(f));
pdf.addTitle(fileTitle);
pdf.setMargins((float) 1.5, (float) 1.5, 30, 30);
pdf.addAuthor(session.getAttribute(“sessionUserName”)
.toString());
pdf.addCreationDate();
pdf.addCreator(session.getAttribute(“sessionUserName”)
.toString());
pdf.addSubject(“Assisted Maintenance Docking”);
pdf.open();

title1.add(new Paragraph(“Assisted Maintenance Docking” + “\n”
+ (new Date().toString()), FontFactory.getFont(
FontFactory.HELVETICA, 20, Font.BOLD,
new Color(0, 0, 0))));
title1.setAlignment(“CENTER”);
Chapter chapter1 = new Chapter(title1, 1);
chapter1.setNumberDepth(0);

pdf.add(chapter1);
addEmptyLine(title1, 2);
Phrase phraseOfImage = new Phrase();
phraseOfImage.add(new Chunk(img, 18, -18));
pdf.add(phraseOfImage);

pdf.add(Chunk.NEWLINE);
pdf.add(Chunk.NEWLINE);

t.setWidthPercentage(90);
Phrase phrase1 = null;

float[] columnWidths = { 200, 200, 200, 200, 200 };
t.setWidths(columnWidths);

PdfPCell c1 = new PdfPCell(new Phrase(“Ship/Unit”,
FontFactory.getFont(FontFactory.HELVETICA, 12,
Font.BOLD, Color.BLACK)));

c1.setBackgroundColor(Color.gray);
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
t.addCell(c1);

c1 = new PdfPCell(new Phrase(“Last AMD”, FontFactory.getFont(
FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK)));
c1.setBackgroundColor(Color.gray);
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
t.addCell(c1);

c1 = new PdfPCell(new Phrase(“AMD Plan”, FontFactory.getFont(
FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK)));
c1.setBackgroundColor(Color.gray);
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
t.addCell(c1);

c1 = new PdfPCell(new Phrase(“Duration”, FontFactory.getFont(
FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK)));
c1.setBackgroundColor(Color.gray);
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
t.addCell(c1);

c1 = new PdfPCell(new Phrase(“Package”, FontFactory.getFont(
FontFactory.HELVETICA, 12, Font.BOLD, Color.BLACK)));
c1.setBackgroundColor(Color.gray);
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
t.addCell(c1);

t.setHeaderRows(1);

for (int i = 0; i < rowCount; i++) {

dfamd = (DfAmd) mylist.get(i);
t.addCell(dfamd.getDfShipUnits().getShip());

t.addCell(dfamd.getLastAmd());
t.addCell(dfamd.getAmdPlan());
t.addCell(dfamd.getDuration());
t.addCell(dfamd.getPackage_());

}

pdf.add(t);

// section1.add(t);
pdf.setPageSize(PageSize.A4);

pdf.add(pdf.getPageSize());

} catch (DocumentException e) {
System.err.println(e.getMessage());
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
pdf.close();
try {
downloadPDF();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
msging = new FacesMessage(FacesMessage.SEVERITY_WARN, "Error",
"Your Report Is Empty Please Search Some Data");
// msging ="Your Report Is Empty Please Search Some Data";

}
FacesContext.getCurrentInstance().addMessage(null, msging);
return "success";
}

// put new line after specific Element
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i 0) {
output.write(buffer, 0, length);
}

// Finalize task.
output.flush();
} finally {
// Gently close streams.
close(output);
close(input);
}

facesContext.responseComplete();
}

private static void close(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {

e.printStackTrace();
}
}
}