Monday, 23 July 2012

Simple Parser for Natural-ADABAS - 2

This example prints header info and prints detail lines for definitions. If requested it is possible to select code lines by simply commenting definition choice and uncommenting code choice.

The jj file follows:
options {
IGNORE_CASE = true;
DEBUG_PARSER = false;
 DEBUG_LOOKAHEAD = false;
DEBUG_TOKEN_MANAGER = false;
LOOKAHEAD = 2;
FORCE_LA_CHECK=true;
 }

PARSER_BEGIN(ProcessFile)

/** Simple Natural parser. */
public class ProcessFile {

/** Main entry point. */
public static void main(String args[]) throws ParseException {

ProcessFile parser = new ProcessFile(System.in); parser.Input();
}

}

PARSER_END(ProcessFile)

TOKEN: {
<CR_LF: "\r\n">
| <HEADER: ("*H**") (<GENERAL>)* <CR_LF>>
| <TITLE: ("*C**") (<GENERAL>)* <CR_LF>>
| <DETAIL: ("*D") (<GENERAL>)* <CR_LF>>
| <CODE_LINE: ("*S**" <LINE_NUM> (<GENERAL>)* <CR_LF>)>
| <#LINE_NUM: (["0"-"9"])(["0"-"9"])(["0"-"9"])(["0"-"9"]) >
| <DEFINE_LINE: ("*S****" ("DF" | "DRR" | "DFR" | "C" | "DV" | "DD" | "V" "DFR" | "DRR" | "DSR" |"HS" | "I") (<GENERAL>)* <CR_LF>)>
| <END_STATEMENT: "*E" <CR_LF>>
| <#GENERAL: (["a"-"z","A"-"Z", "0"-"9", "(", ")", "[", "]", ":", "\'", "*", "|", ";", "%", " ", "-", "/", ".", "=", "#", "@", "+", "_", "<", ">", "^", "$", "?", "&", ",", "ı", "İ", "ş", "Ş", "ü", "Ü", "ç", "Ç", "ğ", "Ğ", "ö", "Ö"])>
}

TOKEN : {
< NATURAL_WORD: (["a"-"z","0"-"9"])+ ( ("-" | "_" )+ (["a"-"z","0"-"9"])+ )* >
| < OTHER : ~[] >
}

/** Root production. */
void Input() : {
System.out.println("Start"); Token th,tc,td,tt,tf;
}
{
( (th=<HEADER> {System.out.print("header=" + th.image);} )

 | (tt=<TITLE> {System.out.print("title=" + tt.image);} )

 //| ( {System.out.print("\ntc=");} "*C**" (tc=<OTHER>{System.out.print(tc.image);})*
<CR_LF> )

 | (td=<DETAIL> {System.out.print("detail=" + td.image);} )

| tc=<CODE_LINE>      //{System.out.print("code=" + tc.image);}

 | tf=<DEFINE_LINE> {System.out.print(tf.image);} )* <END_STATEMENT> <EOF>
}

Parts from the output follows:


Simple Parser for Natural-ADABAS - 1

This is a very simple parser that parses Natural-ADABAS programs. The NATURAL source program is parsed at HEADER, TITLE, DETAIL, CODE_LINE, DEFINE_LINE level.

The first example will only check the type of the lines and verify whether it is one of these types. The JavaCC jj file follows.

options {
IGNORE_CASE = true;
DEBUG_PARSER = false;
DEBUG_LOOKAHEAD = false;
DEBUG_TOKEN_MANAGER = false;
LOOKAHEAD = 1;
FORCE_LA_CHECK=true;
}

PARSER_BEGIN(ProcessFile)
 /** Simple Java Parser. */
public class ProcessFile

{ /** Main entry point. */
public static void main(String args[]) throws ParseException {

ProcessFile parser = new ProcessFile(System.in); parser.Input();
}
}
 PARSER_END(ProcessFile)

TOKEN: {
<CR_LF: "\r\n">
 | <HEADER: ("*H**") (<GENERAL>)* <CR_LF>>
 | <TITLE: ("*C**") (<GENERAL>)* <CR_LF>>
| <DETAIL: ("*D") (<GENERAL>)* <CR_LF>>
 | <CODE_LINE: ("*S**" <LINE_NUM> (<GENERAL>)* <CR_LF>)>
| <#LINE_NUM: (["0"-"9"])(["0"-"9"])(["0"-"9"])(["0"-"9"]) >
| <DEFINE_LINE: ("*S****" ("DF" | "DRR" | "DFR" | "C" | "DV" | "DD" | "V" "DFR" | "DRR" | "DSR" |"HS" | "I") (<GENERAL>)* <CR_LF>)>
| <END_STATEMENT: "*E" <CR_LF>>
| <#GENERAL: (["a"-"z","A"-"Z", "0"-"9", "(", ")", "[", "]", ":", "\'", "*", "|", ";", "%", " ", "-", "/", ".", "=", "#", "@", "+", "_", "<", ">", "^", "$", "?", "&", ",", "ı", "İ", "ş", "Ş", "ü", "Ü", "ç", "Ç", "ğ", "Ğ", "ö", "Ö"])>
}
/** Root production. */
 void Input() : {
System.out.println("Parsing started!");
}
{
( (<HEADER> )
 | (<TITLE> )
 | (<DETAIL> )
| <CODE_LINE>
| <DEFINE_LINE> )*

 <END_STATEMENT>

<EOF>
{System.out.println("Parsing is completed with success!");} }

The input lies at the bottom.


The output:
*H**ENAT230320070927120267 MVS/ESA 1 0AE B


*C** ACCOUNT ACCB001 F S
*D01NAT2303F ACCOUNT ACCB001 DBA0240 DBA0240 0000 S
*D02 2007072602061052007072602061050000009132
*D03MVS/ESA CICS NATP
*D04
*S**0010************************************************************************
*S**0020* SYSTEM NAME : ACCOUNT *
*S**0030* PROGRAM NAME : ACCB001 *
*S**0040* PROGRAMER NAME : MAGED EL-SHARKAWY *
*S**0050* DATE WRITTEN : SEP-29-1999 *
*S**0060* DATE UPDATED : *
*S**0070************************************************************************
*S**0080* P U R P U S E : THIS PROGRAM IS REPORT ABOUT MONTHLY REPORT *
*S**0090************************************************************************
*S**0100* LANGUAGE NAME : NATURAL 2.2 *
*S**0110* GLOBAL DATA AREA : ACCG001 *
*S**0120* SCREEN NAME : ACCO001 *
*S**0130* CHAINED PROGRAMS : ACCP950 *
*S**0140************************************************************************
*S**0150DEFINE DATA
*S**0160 GLOBAL USING ACCG001
*S**0170 LOCAL USING ACCL001B
*S**0180END-DEFINE
*S**0190*
*S**0200FORMAT PS=62 LS=132
*S**0210INPUT #PARM
*S**0220EXAMINE #PARM FOR '@' REPLACE WITH ' '
*S**0230CALLNAT 'LANGCHK' +LANG +HDATE
*S**0240*
*S**0250MOVE #MONTH-DESC(#MONTH) TO #MONTH-DES
*S**0260MOVE #CHAP-DESC(#CHAPTER) TO #BAB-DESC
*S**0270AT TOP OF PAGE
*S**0280 WRITE NOTITLE NOHDR USING MAP 'ACCO001'
*S**0290END-TOPPAGE
*S**0300*
*S**0310MOVE #SIT TO #SITE1 #SITE2
*S**0320MOVE #YEAR TO #C-YEAR1 #C-YEAR2
*S**0330MOVE 999999 TO #C-NO2
*S**0340MOVE 999999999999 TO #ACNT-ACC2
*S**0350*
*S**0360IF #CHAPTER = 1
*S**0370 FIND TBBUDDST-V WITH DST_YEAR = #YEAR-SIT
*S**0380 SORTED BY DST_ACNT_G
*S**0390 WHERE DST_CHAPTER = #CHAPTER
*S**0400 AND DST_ITEM > 0
*S**0410 AND DST_ELEMENT = 0
*S**0420 AND DST_SUB_ITEM = 0
*S**0430 AND DST_DEPT_CODE = 0
*S**0440 MOVE DST_CHAPTER TO #ACNT-CHAPTER
*S**0450 #ACNT-CHAPTER2
*S**0460 MOVE DST_ITEM TO #ACNT-ITEM
*S**0470 #ACNT-ITEM2
*S**0480 MOVE DST_SHORT_NAME TO #ACNT-DESC
*S**0490 MOVE DST_PRIMARY TO #ACNT
*S**0500 ADD DST_PRIMARY TO #ACNT-T
*S**0510 PERFORM READ-JDT
*S**0520 WRITE NOTITLE NOHDR USING MAP 'ACCO001A'
*S**0530 RESET #ACNT #ACNT-CHAPTER #ACNT-DESC #ACNT-ELEMENT #ACNT-ITEM
*S**0540 #ACNT-SUB-ITEM #CURRENT #PAST #TOTAL
*S**0550 END-FIND
*S**0560 WRITE NOTITLE NOHDR USING MAP 'ACCO001B'
*S**0570 RESET #ACNT-T #CURRENT-T #PAST-T #TOTAL-T
*S**0580END-IF
*S**0590IF #CHAPTER = 2
*S**0600 FIND TBBUDDST-V WITH DST_YEAR = #YEAR-SIT
*S**0610 SORTED BY DST_ACNT_G
*S**0620 WHERE DST_CHAPTER = #CHAPTER
*S**0630 AND DST_ITEM > 0
*S**0640 MOVE DST_CHAPTER TO #ACNT-CHAPTER
*S**0650 #ACNT-CHAPTER2
*S**0660 MOVE DST_ITEM TO #ACNT-ITEM
*S**0670 #ACNT-ITEM2
*S**0680 MOVE DST_ELEMENT TO #ACNT-ELEMENT
*S**0690 #ACNT-ELEMENT2
*S**0700 IF DST_ITEM = 206 OR = 208 OR = 222
*S**0710 IF DST_ELEMENT = 0
*S**0720 OR NOT DST_SUB_ITEM = 0
*S**0730 OR NOT DST_DEPT_CODE = 0
*S**0740 ESCAPE TOP*S**0750 END-IF
*S**0760 PERFORM READ-JDT
*S**0770 ELSE
*S**0780 IF NOT DST_ELEMENT = 0
*S**0790 OR NOT DST_SUB_ITEM = 0
*S**0800 OR NOT DST_DEPT_CODE = 0
*S**0810 ESCAPE TOP
*S**0820 END-IF
*S**0830 MOVE 999 TO #ACNT-ELEMENT2
*S**0840 PERFORM READ-JDT
*S**0850 END-IF
*S**0860 MOVE DST_SHORT_NAME TO #ACNT-DESC
*S**0870 MOVE DST_PRIMARY TO #ACNT
*S**0880 ADD DST_PRIMARY TO #ACNT-T
*S**0890 WRITE NOTITLE NOHDR USING MAP 'ACCO001A'
*S**0900 RESET #ACNT #ACNT-CHAPTER #ACNT-DESC #ACNT-ELEMENT #ACNT-ITEM
*S**0910 #ACNT-SUB-ITEM #CURRENT #PAST #TOTAL
*S**0920 END-FIND
*S**0930 WRITE NOTITLE NOHDR USING MAP 'ACCO001B'
*S**0940END-IF
*S**0950*
*S**0960IF #CHAPTER = 3
*S**0970 FIND TBBUDDST-V WITH DST_YEAR = #YEAR-SIT
*S**0980 SORTED BY DST_ACNT_G
*S**0990 WHERE DST_CHAPTER = #CHAPTER
*S**1000 AND DST_ITEM > 0
*S**1010* AND DST_ELEMENT = 0
*S**1020* AND DST_SUB_ITEM = 0
*S**1030 AND DST_DEPT_CODE = 0
*S**1040 MOVE DST_ELEMENT TO #DST-ELEMENT
*S**1050 MOVE DST_ITEM TO #DST-ITEM
*S**1060 RESET #COUNT
*S**1070 PERFORM READ-DST
*S**1080 IF #COUNT = 1 AND DST_ELEMENT = 0
*S**1090 ESCAPE TOP
...

...
...
...
*S**2560END-FIND
*S**2570**************
*S**2580END-SUBROUTINE
*S**2590**************
*S**2600*
*S**2610END
*C** ACCOUNT ACCB002 F S
*D01NAT2303F ACCOUNT ACCB002 DBA0240 DBA0240 0000 S
*D02 2007072602061262007072602061260000005996
*D03MVS/ESA CICS NATP
*D04
*S**0010************************************************************************
*S**0020* SYSTEM NAME : ACCOUNT *
*S**0030* PROGRAM NAME : ACCB002 *
*S**0040* PROGRAMER NAME : BANDER *
*S**0050* DATE WRITTEN : DEC-11-2000 *
*S**0060* DATE UPDATED : *
*S**0070************************************************************************
*S**0080* P U R P U S E : THIS PROGRAM IS REPORT ABOUT MONTHLY REPORT *
*S**0090************************************************************************
*S**0100* LANGUAGE NAME : NATURAL 2.2 *
*S**0110* GLOBAL DATA AREA : ACCG001 *
*S**0120* SCREEN NAME : ACCO002 *
*S**0130* CHAINED PROGRAMS : ACCP950 *
*S**0140************************************************************************
*S**0150DEFINE DATA
*S**0160 GLOBAL USING ACCG001
*S**0170 LOCAL USING ACCL002B
*S**0180END-DEFINE
*S**0190*
*S**0200FORMAT PS=62 LS=132
*S**0210INPUT #PARM
*S**0220EXAMINE #PARM FOR '@' REPLACE WITH ' '
*S**0230CALLNAT 'LANGCHK' +LANG +HDAT
*S**0240*

...
...
...

Thursday, 19 July 2012

LL Parsing

LL parsing reads input from Left to write and and produces a Left most derivation. Following Java program uses the example provided at Wikipedia LL page.




/*
* converted to Java by Ali R+ SARAL
*/

package nbParse;

import com.sun.xml.internal.fastinfoset.util.CharArray;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
*
* @author Ali Riza SARAL
*/

public class LLparser {

public enum Symbols {
TS_L_PARENS, // (
TS_R_PARENS, // )
TS_A, // a
TS_PLUS, // +
TS_EOS, // $
TS_INVALID, // invalid token

// Non-terminal symbols:
NTS_S, // S
NTS_F
}



Symbols lexer(char c) {

switch (c) {

case '(':
return Symbols.TS_L_PARENS;

case ')':
return Symbols.TS_R_PARENS;

case 'a':
return Symbols.TS_A;

case '+':
return Symbols.TS_PLUS;

case '\0':
return Symbols.TS_EOS;

default:
return Symbols.TS_INVALID;
}
}

public static void main(String[] args) {

LLparser llparser = new LLparser();
System.out.println("Hello wonderful world!");
HashMap tt = new HashMap();
HashMap> table = new HashMap(); // LL Parser
Stack ss = new Stack(); // symbol stack

// char[] p = {'(','a', '+', 'a',')'}; // input buffer
char[] p = {'(','a', '+','(','a', '+', 'a',')',')'}; // input buffer
// char[] p = {'a','+','(','a', '+', 'a',')'}; // input buffer
// char[] p = {'(', 'a', '+', 'a', ')'}; // input buffer

int ppointer = 0;

// initialize the symbols stack
ss.addElement(Symbols.TS_EOS);
ss.addElement(Symbols.NTS_S);

//initialize the symbol stream cursor
ppointer = 0;

//setup the parsing table
tt.put(Symbols.TS_L_PARENS, 2);
table.put(Symbols.NTS_S, tt);

tt.put(Symbols.TS_A, 1);
table.put(Symbols.NTS_S, tt);

tt.put(Symbols.TS_A, 3);
table.put(Symbols.NTS_F, tt);

System.out.println("ss= " + ss.toString());
System.out.println("tt=" + tt);
System.out.println("table=" + table);
System.out.println("p= " + "(a+a)");

while (ss.size() > 1) {
System.out.println("\nppointer= " + ppointer);
System.out.println("lexer(p(ppointer))= " + llparser.lexer(p[ppointer]));
System.out.println("ss.lastElement= " + ss.lastElement());

if (llparser.lexer(p[ppointer]) == ss.lastElement()) {
System.out.println("Matched symbols " + llparser.lexer(p[ppointer]));

ppointer++;

ss.pop();

if (ppointer > (p.length - 1)) {

System.out.println("\nEnd of input string");
System.out.println(ss.toString());

if (ss.size() > 1) {
System.out.println("Parse is unsuccessful");
}

return;
}
} else {
HashMap tableItem = table.get(ss.lastElement());
System.out.println("Rule " + tableItem.get(llparser.lexer(p[ppointer])));

switch (tableItem.get(llparser.lexer(p[ppointer]))) {

case 1: // 1. s-> F
System.out.println("1. s-> F");
ss.pop();
ss.push(Symbols.NTS_F); // F
break;

case 2: // 2. s-> ( S + F )
System.out.println("2 s-> ( S + F )");
ss.pop();
ss.push(Symbols.TS_R_PARENS); // )
ss.push(Symbols.NTS_F); // F
ss.push(Symbols.TS_PLUS); // +
ss.push(Symbols.NTS_S); // S
ss.push(Symbols.TS_L_PARENS); // (

break;

case 3: // F -> A
System.out.println("3 F -> A");

ss.pop();
ss.push(Symbols.TS_A); // a

break;

default:
System.out.println("Parsing table default");

return;
}
}

System.out.println("ss= " + ss.toString());
System.out.println("ss.size()= " + ss.size());
}

System.out.println("Finished parsing");

return;
}
}



Output:

run:

Hello wonderful world!

ss= [TS_EOS, NTS_S]
tt={TS_A=3, TS_L_PARENS=2}
table={NTS_F={TS_A=3, TS_L_PARENS=2}, NTS_S={TS_A=3, TS_L_PARENS=2}}
p= (a+a)
ppointer= 0
lexer(p(ppointer))= TS_L_PARENS
ss.lastElement= NTS_S

Rule 2
2 s-> ( S + F )
ss= [TS_EOS, TS_R_PARENS, NTS_F, TS_PLUS, NTS_S, TS_L_PARENS]
ss.size()= 6

ppointer= 0
lexer(p(ppointer))= TS_L_PARENS
ss.lastElement= TS_L_PARENS

Matched symbols TS_L_PARENS
ss= [TS_EOS, TS_R_PARENS, NTS_F, TS_PLUS, NTS_S]
ss.size()= 5



ppointer= 1
lexer(p(ppointer))= TS_A
ss.lastElement= NTS_S

Rule 3
3 F -> A
ss= [TS_EOS, TS_R_PARENS, NTS_F, TS_PLUS, TS_A]
ss.size()= 5

ppointer= 1
lexer(p(ppointer))= TS_A
ss.lastElement= TS_A

Matched symbols TS_A
ss= [TS_EOS, TS_R_PARENS, NTS_F, TS_PLUS]
ss.size()= 4

ppointer= 2
lexer(p(ppointer))= TS_PLUS
ss.lastElement= TS_PLUS

Matched symbols TS_PLUS
ss= [TS_EOS, TS_R_PARENS, NTS_F]
ss.size()= 3

ppointer= 3
lexer(p(ppointer))= TS_L_PARENS
ss.lastElement= NTS_F

Rule 2
2 s-> ( S + F )
ss= [TS_EOS, TS_R_PARENS, TS_R_PARENS, NTS_F, TS_PLUS, NTS_S, TS_L_PARENS]
ss.size()= 7

ppointer= 3
lexer(p(ppointer))= TS_L_PARENS
ss.lastElement= TS_L_PARENS

Matched symbols TS_L_PARENS
ss= [TS_EOS, TS_R_PARENS, TS_R_PARENS, NTS_F, TS_PLUS, NTS_S]
ss.size()= 6

ppointer= 4
lexer(p(ppointer))= TS_A
ss.lastElement= NTS_S

Rule 3
3 F -> A
ss= [TS_EOS, TS_R_PARENS, TS_R_PARENS, NTS_F, TS_PLUS, TS_A]
ss.size()= 6

ppointer= 4
lexer(p(ppointer))= TS_A
ss.lastElement= TS_A

Matched symbols TS_A
ss= [TS_EOS, TS_R_PARENS, TS_R_PARENS, NTS_F, TS_PLUS]
ss.size()= 5

ppointer= 5
lexer(p(ppointer))= TS_PLUS
ss.lastElement= TS_PLUS

Matched symbols TS_PLUS
ss= [TS_EOS, TS_R_PARENS, TS_R_PARENS, NTS_F]
ss.size()= 4

ppointer= 6
lexer(p(ppointer))= TS_A
ss.lastElement= NTS_F

Rule 3
3 F -> A
ss= [TS_EOS, TS_R_PARENS, TS_R_PARENS, TS_A]
ss.size()= 4

ppointer= 6
lexer(p(ppointer))= TS_A
ss.lastElement= TS_A

Matched symbols TS_A
ss= [TS_EOS, TS_R_PARENS, TS_R_PARENS]
ss.size()= 3

ppointer= 7
lexer(p(ppointer))= TS_R_PARENS
ss.lastElement= TS_R_PARENS

Matched symbols TS_R_PARENS
ss= [TS_EOS, TS_R_PARENS]
ss.size()= 2

ppointer= 8
lexer(p(ppointer))= TS_R_PARENS
ss.lastElement= TS_R_PARENS

Matched symbols TS_R_PARENS


End of input string
[TS_EOS]

BUILD SUCCESSFUL (total time: 0 seconds)



LR parsing

SLR parsing is simple LR parsing, reads input from Left to write and and produces a Right most derivation. Following Java program uses the example provided at Wikipedia SLR page.


/*
* by Ali R+ SARAL
* Please indicate my name if you copy my work.
*/

package nbParse;
import com.sun.xml.internal.fastinfoset.util.CharArray;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
*
* @author Ali Riza SARAL
*/

public class LRparser {

    public enum Symbols {

      TS_ONE, // +
      TS_EOS, // $
      TS_INVALID, // invalid token

      // Non-terminal symbols:
      NTS_S, // S
      NTS_E
      }

   public enum States {
      ST_ZERO,
      ST_ONE,
      ST_TWO,
      ST_THREE
   }

   Symbols lexer(char c) {

      switch (c) {
      case '1':
      return Symbols.TS_ONE;

      case '$':
      return Symbols.TS_EOS;

      case 'E':
      return Symbols.NTS_E;

      default:
      return Symbols.TS_INVALID;
      }
   }

   public static void main(String[] args) {

      LRparser lrparser = new LRparser();
      StringBuilder p = new StringBuilder("111$"); // input buffer

      int ppointer = 0;
      int state = 0;

      //initialize the symbol stream cursor
      ppointer = 0;
      boolean reduced = false;

      for (ppointer = 0; ppointer < p.length(); ppointer++) {

         if (reduced) {
         ppointer = 0;
         reduced = false;
      }

      System.out.println("\np[" + ppointer + "]= " + p.charAt(ppointer));
      System.out.println("lexer(p(ppointer))= " + lrparser.lexer(p.charAt(ppointer)));
      System.out.println("state= " + state);
      System.out.println("p= " + p.toString());

switch (state) {

   case 0:
   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.TS_ONE) {
   System.out.println("1. shift one state 0");
   state = 1;
   }

   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.TS_EOS) {
   System.out.println("none");
   }

   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.NTS_E) {
   System.out.println("goto state 2");
   state = 2;
   }

   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.TS_INVALID) {
   System.out.println("invalid input");
   return;
   }

   break;

   case 1:
   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.TS_ONE) {
   System.out.println("1. shift one state 1");
   state = 1;
   }

   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.TS_EOS) {
   System.out.println("reduce 2 ");
   p.deleteCharAt(ppointer - 1);
   p.insert(ppointer - 1, 'E');
   state = 0;
   ppointer = 0;
   reduced = true;
   }

   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.NTS_E) {
   System.out.println("goto state 3");
   state = 3;
   }

   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.TS_INVALID) {
   System.out.println("invalid input");
   return;
   }

   break;

   case 2:
   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.TS_ONE) {
   System.out.println("none state 2.1");
   }

   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.TS_EOS) {
   System.out.println("accept ");
   state = 0;
   }

   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.NTS_E) {
   System.out.println("none state 2.3");
   }

   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.TS_INVALID) {
   System.out.println("invalid input");
   return;
   }

   break;

   case 3:
   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.TS_ONE) {
   System.out.println("none state 3.1");
   }

   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.TS_EOS) {
   System.out.println("reduce 1 ");
   p.deleteCharAt(ppointer - 2);
   state = 0;
   ppointer = 0;
   reduced = true;
   }

   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.NTS_E) {
   System.out.println("none state 3.3");
   }

   if (lrparser.lexer(p.charAt(ppointer)) == Symbols.TS_INVALID) {
   System.out.println("invalid input");
   return;
   }

   break;
   default:
   System.out.println("Parsing table default");
   return;
   }
   }

   System.out.println("Finished parsing");
   return;
   }
}


Output:

run:
p[0]= 1
lexer(p(ppointer))= TS_ONE
state= 0
p= 111$
1. shift one state 0

p[1]= 1
lexer(p(ppointer))= TS_ONE
state= 1
p= 111$
1. shift one state 1

p[2]= 1
lexer(p(ppointer))= TS_ONE
state= 1
p= 111$
1. shift one state 1

p[3]= $
lexer(p(ppointer))= TS_EOS
state= 1
p= 111$
reduce 2

p[0]= 1
lexer(p(ppointer))= TS_ONE
state= 0
p= 11E$
1. shift one state 0

p[1]= 1
lexer(p(ppointer))= TS_ONE
state= 1
p= 11E$
1. shift one state 1

p[2]= E
lexer(p(ppointer))= NTS_E
state= 1
p= 11E$
goto state 3

p[3]= $
lexer(p(ppointer))= TS_EOS
state= 3
p= 11E$
reduce 1

p[0]= 1
lexer(p(ppointer))= TS_ONE
state= 0
p= 1E$
1. shift one state 0

p[1]= E
lexer(p(ppointer))= NTS_E
state= 1
p= 1E$
goto state 3

p[2]= $
lexer(p(ppointer))= TS_EOS
state= 3
p= 1E$
reduce 1
none state 3.3

p[0]= E
lexer(p(ppointer))= NTS_E
state= 0
p= E$
goto state 2

p[1]= $
lexer(p(ppointer))= TS_EOS
state= 2
p= E$
accept

Finished parsing
BUILD SUCCESSFUL (total time: 0 seconds)

Tuesday, 17 July 2012

Simple2.jj Second Simple JavaCC example

The second example is a simple improvement.

This one does not abend when the input does not
have the word test in it. It gives due
warning instead.

options {
    IGNORE_CASE = true;
   DEBUG_PARSER = false;
   DEBUG_LOOKAHEAD = false;
   DEBUG_TOKEN_MANAGER = false;
   LOOKAHEAD = 2;
   FORCE_LA_CHECK=true;
}

PARSER_BEGIN(Simple2)

public class Simple2 {

   /** Main entry point. */
   public static void main(String args[]) throws ParseException {

   Simple2 parser = new Simple2(System.in);

   parser.Input();
   }

}

PARSER_END(Simple2)

SKIP : {
   " "
   "\t"
   "\n"
   "\r"
}
TOKEN: { < TEST: "test">}

TOKEN: {<CR_LF: "\r\n"> }

TOKEN : { <OTHER : ~[] > }

void Input() :
{
   System.out.println("Start");
   Token t1=null;}
{
   (
      (<OTHER>)*
      (t1=<TEST> {System.out.println("This line has test in it.");})?
      (<OTHER>)*

      <CR_LF> {if (t1==null) System.out.println("Sorry no test in this line!");}
   )*
   <EOF >
}

Simple1.jj First JavaCC example

options {
   IGNORE_CASE = true;
   DEBUG_PARSER = false;
   DEBUG_LOOKAHEAD = false;
   DEBUG_TOKEN_MANAGER = false;
   LOOKAHEAD = 2;
   FORCE_LA_CHECK=true;
}

PARSER_BEGIN(Simple1)

public class Simple1 {

   /** Main entry point. */
   public static void main(String args[]) throws ParseException {
   Simple1 parser = new Simple1(System.in);

   parser.Input();
   }
}

PARSER_END(Simple1)

SKIP : {
   " "
   "\t"
   "\n"
   "\r"
}
TOKEN: { < TEST: "test" > }

TOKEN: {<CR_LF: "\r\n"> }

TOKEN : { < OTHER : ~[] > }

void Input() :
{System.out.println("Start");}
{
   ((<OTHER>)* <TEST> (<OTHER>)* <CR_LF>)*
}



Natural-ADABAS to JAVA-Oracle-UNIX program conversion

This will be the first of many simle and advanced JavaCC and jjTree examples

that I will provide here in my Techne-Tekne blog.

I have produced these examples during a feasibility project which
is about the conversion of NATURAL-ADABAS software of an IBM mainframe
system to JAVA, STRUTS, ORACLE, UNIX 'mini' system which may be non-IBM.

I will provide many examples for: NATURAL local-global variable conversion to JAVA,
Transaction processing, flow control by using threads to enable online programs
to use maps, field value transfer from maps to the transaction program and vice versa.

Let's begin with some very simple JavaCC examples:
 
Please continue to: Simple1

Wednesday, 28 March 2012

A Few Notes on Programming Web Services with XML-RPC

http://www.tutorialspoint.com/xml-rpc/xml_rpc_examples.htm gives the below example:

import org.apache.xmlrpc.*;

public class JavaServer {

public Integer sum(int x, int y) {
return new Integer(x+y);
}

public static void main (String [] args) {
try {

System.out.println("Attempting to start XML-RPC Server...");
WebServer server = new WebServer(80);
server.addHandler("sample", new JavaServer());
server.start();
System.out.println("Started successfully.");
System.out.println("Accepting requests. (Halt program to stop.)");
} catch (Exception exception) {
System.err.println("JavaServer: " + exception);
}
}
}

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

import java.util.*;
import org.apache.xmlrpc.*;

public class JavaClient {
public static void main (String [] args) {
try {
XmlRpcClient server = new XmlRpcClient("http://localhost:80");
Vector params = new Vector();
params.addElement(new Integer(17));
params.addElement(new Integer(13));

Object result = server.execute("sample.sum", params);

int sum = ((Integer) result).intValue();
System.out.println("The sum is: "+ sum);

} catch (Exception exception) {
System.err.println("JavaClient: " + exception);
}
}
}

This requires: xmlrpc-1.2.jar
in the Java build path. It works OK. No problem.

I will use this example to solve minor problems of 3 examples from
books.google.com - "Programming Web Services with XML-RPC of Simon Laurent, Joe Johnston,
and Edd Dumbill."

The problems that I met are:


1- Installing the helma.xmlrpc Library
You can not find this lib because it has evolved toxmlrpc.jar
2-the location of the handler
The examples are given in such fashion that the position of the handler
is left ambiguous. It should be an inner class of the server class.
3- the handler must be static
4- client-or the server does not need io try catch
5- Some examples require import for io
6- port problem connection error
The examples suggests a port number which does not connect at least on my machine.

I removed param processing which can easily be restored. I also
put the server and client into the same project for simplicity.
You should put them in seperate projects also.

An example of batch running follows:

1- XML-RPChandler project


C:\Users\ars\Desktop\eclipseWS\eclipseJAXWSrpc\XML-RPCproject\bin>java -cp ../li
b/xmlrpc-1.2.jar;. JavaServer
Attempting to start XML-RPC Server...
Started successfully.
Accepting requests. (Halt program to stop.)


C:\Users\ars\Desktop\eclipseWS\eclipseJAXWSrpc\XML-RPCproject\bin>java -cp ../li
b/xmlrpc-1.2.jar;. JavaClient
The sum is: 30


The corrected and running solutions lie below:

import java.io.IOException;
//import helma.xmlrpc.WebServer;
//import helma.xmlrpc.XmlRpc;
import org.apache.xmlrpc.*;

public class AreaServer {

public static class AreaHandler {

public Double rectArea(double length, double width) {
return new Double(length * width);
}

public Double circleArea(double radius) {
double value = (radius * radius * Math.PI);
return new Double(value);
}

}

public static void main(String[] args) {
// if (args.length < 1) {
// System.out.println(
// "Usage: java AreaServer [port]");
// System.exit(-1);
// }

// try {

// Start the server, using built-in version
System.out.println("Attempting to start XML-RPC Server...");
// WebServer server = new WebServer(Integer.parseInt(args[0]));
WebServer server = new WebServer(80);

System.out.println("Started successfully.");

// Register our handler class as area
//server.addHandler("area", new AreaHandler());
server.addHandler("area", new AreaHandler());
System.out.println("Registered AreaHandler class to area.");
server.start();
System.out.println("Started successfully.");
System.out.println("Now accepting requests. (Halt program to stop.)");

// } catch (IOException e) {
// System.out.println("Could not start server: " +
// e.getMessage( ));
// }
}

}
----------------------------------
import java.io.IOException;
import java.util.Vector;
//import helma.xmlrpc.XmlRpc;
//import helma.xmlrpc.XmlRpcClient;
//import helma.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.*;

public class AreaClient {

public static void main(String args[]) {
// if (args.length < 1) {
// System.out.println(
// "Usage: java AreaClient [radius]");
// System.exit(-1);
// }

try {
// Create the client, identifying the server
XmlRpcClient client =
new XmlRpcClient("http://localhost:80/");

// Create the request parameters using user input
Vector params = new Vector( );
//params.addElement(new Double(args[0]));
params.addElement(new Double("5"));

// Issue a request
Object result =
client.execute("area.circleArea", params);

// Report the results
System.out.println("The area of the circle would be: " + result.toString( ));

} catch (IOException e) {
System.out.println("IO Exception: " + e.getMessage( ));
} catch (XmlRpcException e) {
System.out.println("Exception within XML-RPC: " + e.getMessage( ));
}
}

}



2.passing hash parameter example

import java.io.IOException;
import java.util.Hashtable;
//import helma.xmlrpc.WebServer;
//import helma.xmlrpc.XmlRpc;
import org.apache.xmlrpc.*;

public class AreaServer {

public static class AreaHandler {

public Double rectArea(double length, double width) {
return new Double(length * width);
}

public Double circleArea(double radius) {
double value = (radius * radius * Math.PI);
return new Double(value);
}

public Double anyArea(Hashtable arguments) {
Double value;
value=new Double(0);
String requestType=(String) arguments.get("type");
if (requestType.equals("circle")) {
Double radius=(Double) (arguments.get("radius"));
value=circleArea(radius.doubleValue( ));
}
if (requestType.equals("rectangle")) {
Double length=(Double) (arguments.get("length"));
Double width=(Double) (arguments.get("width"));
value=rectArea(length.doubleValue(), width.doubleValue( ));
}

return value;
}


}

public static void main(String[] args) {
// if (args.length < 1) {
// System.out.println(
// "Usage: java AreaServer [port]");
// System.exit(-1);
// }

// try {

// Start the server, using built-in version
System.out.println("Attempting to start XML-RPC Server...");
// WebServer server = new WebServer(Integer.parseInt(args[0]));
WebServer server = new WebServer(80);

System.out.println("Started successfully.");

// Register our handler class as area
//server.addHandler("area", new AreaHandler());
server.addHandler("area", new AreaHandler());
System.out.println("Registered AreaHandler class to area.");
server.start();
System.out.println("Started successfully.");
System.out.println("Now accepting requests. (Halt program to stop.)");

// } catch (IOException e) {
// System.out.println("Could not start server: " +
// e.getMessage( ));
// }
}

}
-------------------------------------------------
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
//import helma.xmlrpc.XmlRpc;
//import helma.xmlrpc.XmlRpcClient;
//import helma.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.*;

public class AreaClient {

public static void main(String args[]) {
// if (args.length < 1) {
// System.out.println(
// "Usage: java AreaClient [radius]");
// System.exit(-1);
// }

try {
// Create the client, identifying the server
XmlRpcClient client =
new XmlRpcClient("http://localhost:80/");

// Create a double from the user argument
//Double radius=new Double(args[0]);
Double radius=new Double("5");

// Create a hashtable and add a circle request
Hashtable requestHash = new Hashtable( );
requestHash.put("type", "circle");
requestHash.put("radius", radius);

// Create the request parameters using user input
Vector params = new Vector( );
params.addElement(requestHash);

// Issue a request
Object result =
client.execute("area.anyArea", params);

// Report the results
System.out.println("The area of the circle would be: " + result.toString( ));


} catch (IOException e) {
System.out.println("IO Exception: " + e.getMessage( ));
} catch (XmlRpcException e) {
System.out.println("Exception within XML-RPC: " + e.getMessage( ));
}
}

}


3. log service program
import java.io.IOException;
//import helma.xmlrpc.WebServer;
//import helma.xmlrpc.XmlRpc;
import org.apache.xmlrpc.*;

public class XLogServer {

public static class XLogHandler {
public String XLogReport(String address, String message) {
System.out.println("From: " + address);
System.out.println("Message: " + message);
return "ack";
}
}

public static void main(String[] args) {
// if (args.length < 1) {
// System.out.println("Usage: java AreaServer [port]");
// System.exit(-1);
// }

// try {
// Start the server, using built-in version
System.out.println("Attempting to start XML-RPC Server...");
// WebServer server = new WebServer(Integer.parseInt(args[0]));
WebServer server = new WebServer(Integer.parseInt("80"));

System.out.println("Started successfully.");

// Register our handler class as area
server.addHandler("XLog", new XLogHandler());
System.out.println("Registered XLogHandler class to XLog.");
server.start();
System.out.println("Started successfully.");
System.out.println("Now accepting requests. (Halt program to stop.)");

// } catch (IOException e) {
// System.out.println("Could not start server: " +
// e.getMessage( ));
// }
}
}
-----------------------------------------------------------
import java.io.IOException;
import java.net.*;
import java.util.Vector;
//import helma.xmlrpc.XmlRpc;
//import helma.xmlrpc.XmlRpcClient;
//import helma.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.*;

public class XLogClient {

public static void main(String args[]) {
try {
throw new Exception("help");
} catch (Exception e) {
report (e);
}
}

public static void report(Exception eReport) {
try {
// Create the client, identifying the server
XmlRpcClient client =
new XmlRpcClient("http://127.0.0.1:80/");
//new XmlRpcClient("http://192.168.2.191:80/");

//get local hostname and IP address
InetAddress address=InetAddress.getLocalHost( );
String ipAddress=address.toString( );

// Create the request parameters using user input
Vector params = new Vector( );
params.addElement(ipAddress);
params.addElement(eReport.getMessage( ));
// Issue a request
Object result =
client.execute("XLog.XLogReport", params);

// Report the results - this is just for the example
// In production, the 'ack' will be thrown away.
// Alternatively, the log system could be more interactive
// and the result might have meaning.
System.out.println("Response was: " + result.toString( ));

//If we can't report to server, report locally
} catch (IOException e) {
System.out.println("IO Exception: " + e.getMessage( ));
} catch (XmlRpcException e) {
System.out.println("Exception within XML-RPC: " + e.getMessage( ));
}
}
}

4. getting and setting a value

import java.io.IOException;
//import helma.xmlrpc.WebServer;
//import helma.xmlrpc.XmlRpc;
import org.apache.xmlrpc.*;

public class GetSetServer {

public static class GetSetHandler {
protected int value;

public GetSetHandler(int initialValue) {
value = initialValue;
}

public int getValue(String requester) {
return value;
}

public int setValue(String requester, int newValue) {
value = newValue;
return value;
}
}

public static void main(String[] args) {
// if (args.length < 1) {
// System.out.println(
// "Usage: java GetSetServer [port]");
// System.exit(-1);
// }
// try {
// Start the server, using built-in version
System.out.println("Attempting to start XML-RPC Server...");
// WebServer server = new WebServer(Integer.parseInt(args[0]));
WebServer server = new WebServer(Integer.parseInt("80"));

System.out.println("Started successfully.");

// Register our handler class as area
server.addHandler("getSet", new GetSetHandler(20));
System.out.println("Registered GetSetHandler class to getSet.");
server.start();
System.out.println("Started successfully.");
System.out.println("Now accepting requests. (Halt program to stop.)");

// } catch (IOException e) {
// System.out.println("Could not start server: " +
// e.getMessage( ));
// }
}
}
-------------------------------------------------
import java.io.IOException;
import java.net.*;
import java.util.Vector;
//import helma.xmlrpc.XmlRpc;
//import helma.xmlrpc.XmlRpcClient;
//import helma.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.*;

public class GetSetClient {

public static void main(String args[]) {
if (args.length < 1) {
System.out.println(
"Usage: java GetSetClient [get set] [value]");
System.exit(-1);
}

String getOrSet=new String(args[0]);

if (!((getOrSet.equals("get")) (getOrSet.equals("set")))) {
System.out.println(
"First argument must be get or set");
System.exit(-1);
}

try {
// Create the client, identifying the server
XmlRpcClient client =
new XmlRpcClient("http://localhost:80/");

//get local host IP address
InetAddress address=InetAddress.getLocalHost( );
String ipAddress=address.toString( );

// Create the request parameters using user input
Vector params = new Vector( );
params.addElement(ipAddress);
if (getOrSet.equals("set")) {
Integer newValue=new Integer(args[1]);
params.addElement(newValue);
}

// Issue a request
Object result=null;
if (getOrSet.equals("set")) {
result = client.execute("getSet.setValue", params);
} else {
result = client.execute("getSet.getValue", params);
}

// Report the results
System.out.println("The response was: " + result.toString( ));

} catch (IOException e) {
System.out.println("IO Exception: " + e.getMessage( ));
} catch (XmlRpcException e) {
System.out.println("Exception within XML-RPC: " + e.getMessage( ));
}
}
}
Converting JAX-WS examples from NB-GlassFish to Eclipse-GlassFish
This is a demo of converting JavaEE5-6 jaxws examples from NetBeans-GlassFish to Eclipse-GlassFish.

The difference occurs because of :

nlibraies.properties
libs.CopyLibs.classpath=\
${base}/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar
libs.javaee-endorsed-api-6.0.classpath=\
${base}/javaee-endorsed-api-6.0/javax.annotation.jar;\
${base}/javaee-endorsed-api-6.0/jaxb-api-osgi.jar;\
${base}/javaee-endorsed-api-6.0/webservices-api-osgi.jar
libs.javaee-endorsed-api-6.0.javadoc=\
${base}/javaee-endorsed-api-6.0/javaee6-doc-api.zip

--------------------------------
C:\Users\ars\Desktop\ARSnbWebService\jaxws\helloservice\lib\javaee-endorsed-api-6.0
webservices-api-osgi.jar
jaxb-api-osgi.jar
javax.annotation
jaxrpc
saaj
wsdl4j

The NetBeans uses Metro Services or JAX-WS Reference Implementation which utilizes the above jars at the top. The Eclipse uses the above jar files and the AXIS implementation. So, there are structural differences in the implementation of JAX-WS.




My solution for Eclipse-Tomcat conversion of the above Javaee5-6 example is:


You can find JAVAEE6 examples at
http://docs.oracle.com/javaee/6/tutorial/doc/ (page 366).
The service part remains the same in Eclipse(page 368).
package helloservice.endpoint;
import javax.jws.WebService;
import javax.jws.webMethod;
@WebService
public class Hello {
private String message = new String("Hello, ");
public void Hello() {
}
@WebMethod
public String sayHello(String name) {
return message + name + ".";
}
}
But the client side causes problems when/if implemented as below:
package appclient;
import helloservice.endpoint.HelloService;
import javax.xml.ws.WebServiceRef;

public class HelloAppClient {
@WebServiceRef(wsdlLocation =
"META-INF/wsdl/localhost_8080/helloservice/HelloService.wsdl")

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(sayHello("world"));
}
private static String sayHello(java.lang.String arg0) {
helloservice.endpoint.Hello port = service.getHelloPort();
return port.sayHello(arg0);
}
}

I have two solutions to fix the problems at the client:
1- This is the same with the Tomcat solution.


/*
* Copyright 2011 Oracle and/or its affiliates.
* All rights reserved. You may not modify, use,
* reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://developers.sun.com/license/berkeley_license.html
*/

package webclient;

import helloservice.endpoint.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.rmi.RemoteException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;
import javax.xml.ws.Service;

import org.apache.axis.AxisFault;

import java.net.MalformedURLException;
import java.net.URL;



@WebServlet(name = "HelloServlet", urlPatterns = { "/HelloServlet" })
public class HelloServlet extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request
* servlet request
* @param response
* servlet response
* @throws ServletException
* if a servlet-specific error occurs
* @throws IOException
* if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException, AxisFault ,Exception {
response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try {
out.println("<html lang=\"en\">");
out.println("<head>");
out.println("<title>Servlet HelloServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet HelloServlet at "
+ request.getContextPath() + "</h1>");
out.println("<p>" + sayHello("world") + "</p>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}

// <editor-fold defaultstate="collapsed"
// desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request
* servlet request
* @param response
* servlet response
* @throws ServletException
* if a servlet-specific error occurs
* @throws IOException
* if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try{
processRequest(request, response);
} catch(AxisFault af){}
catch(Exception e){}
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request
* servlet request
* @param response
* servlet response
* @throws ServletException
* if a servlet-specific error occurs
* @throws IOException
* if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try{
processRequest(request, response);
} catch(AxisFault af){}
catch(Exception e){}
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
} // </editor-fold>

private String sayHello(java.lang.String arg0) throws AxisFault ,Exception {

try {
// URL wsdlDocumentLocation = null;
// try {
// wsdlDocumentLocation = new URL(
// "http://localhost:8080/helloservice/HelloService?wsdl");
// //"http://localhost:8080/helloservice/services/Hello");
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// QName qname = new QName("http://endpoint.helloservice/", "HelloService");
//
// Service service = Service.create(wsdlDocumentLocation, qname);
// System.out.println("aaaaaaaaaaaaa3");
// Hello hello = service.getPort(Hello.class);
// System.out.println("aaaaaaaaaaaaa4");
// return hello.sayHello(arg0);
// } catch (RemoteException re) {
// }
// return ("error");
//
// }
HelloSoapBindingStub srv = new HelloSoapBindingStub(
new URL("http://localhost:8080/helloservice/services/Hello"),
new HelloServiceLocator());
return srv.sayHello(arg0);
} catch(AxisFault af){}
return "error";

}
}

Please notice the changes that replace the commented code. I used a stub and its binding to the web service address and a locator to call the sayHello. The rest of the staff is pretty strqight forward but if any problems do not hesitate to contact me at arsaral(at)yahoo.com .

2- The client for GlassFish follows:
/*
* Copyright 2011 Oracle and/or its affiliates.
* All rights reserved. You may not modify, use,
* reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://developers.sun.com/license/berkeley_license.html
*/

package webclient;

import helloservice.endpoint.HelloService;
import helloservice.endpoint.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.rmi.RemoteException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;
import javax.xml.ws.Service;

import java.net.MalformedURLException;
import java.net.URL;

import com.sun.xml.ws.api.pipe.TransportPipeFactory;

@WebServlet(name = "HelloServlet", urlPatterns = { "/HelloServlet" })
public class HelloServlet extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request
* servlet request
* @param response
* servlet response
* @throws ServletException
* if a servlet-specific error occurs
* @throws IOException
* if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try {
out.println("<html lang=\"en\">");
out.println("<head>");
out.println("<title>Servlet HelloServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet HelloServlet at "
+ request.getContextPath() + "</h1>");
out.println("<p>" + sayHello("world") + "</p>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}

// <editor-fold defaultstate="collapsed"
// desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request
* servlet request
* @param response
* servlet response
* @throws ServletException
* if a servlet-specific error occurs
* @throws IOException
* if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request
* servlet request
* @param response
* servlet response
* @throws ServletException
* if a servlet-specific error occurs
* @throws IOException
* if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
} // </editor-fold>

private String sayHello(java.lang.String arg0) {

try {
URL wsdlDocumentLocation = null;
try {
wsdlDocumentLocation = new URL(
"http://localhost:8080/helloservice/HelloService?wsdl");
} catch (MalformedURLException e) {
e.printStackTrace();
}
QName qname = new QName("http://endpoint.helloservice/",
"HelloService");

Service service = Service.create(wsdlDocumentLocation, qname);

Hello hello = service.getPort(Hello.class);

return hello.sayHello(arg0);
} catch (RemoteException re) {
}
return ("error");

}
}

Please notice at the sayHello that Service class is used to get the service object using the wsdlDocumentLocation and qname. Be careful about the minor qname problem that is you write

QName qname = new QName("http://endpoint.helloservice/HelloService");

Instead of QName qname = new QName("http://endpoint.helloservice/","HelloService");

The compiler compiles it but gives the below error at the runtime:

javax.xml.ws.WebServiceException: {http://endpoint.helloservice/}HelloService is not a valid service. Valid services are: {http://endpoint.helloservice}HelloService
at com.sun.xml.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:272)
at com.sun.xml.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:205)

Tuesday, 27 March 2012

Converting JAX-WS examples from NB-GlassFish to Eclipse-Tomcat



This is a demo of converting JavaEE5-6 jaxws examples from NetBeans-GlassFish to Eclipse-Tomcat and Eclipse-GlassFish.
You can find JAVAEE6 examples at
http://docs.oracle.com/javaee/6/tutorial/doc/ (page 366).

The service part remains the same in Eclipse.


package helloservice.endpoint;
import javax.jws.WebService;
import javax.jws.webMethod;

@WebService
public class Hello {
private String message = new String("Hello, ");
public void Hello() {
}
@WebMethod
public String sayHello(String name) {
return message + name + ".";
}
}

But the client side causes problems when/if implemented as below(page 368).:

package appclient;
import helloservice.endpoint.HelloService;
import javax.xml.ws.WebServiceRef;

public class HelloAppClient {
@WebServiceRef(wsdlLocation =
"META-INF/wsdl/localhost_8080/helloservice/HelloService.wsdl")

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(sayHello("world"));
}
private static String sayHello(java.lang.String arg0) {
helloservice.endpoint.Hello port = service.getHelloPort();
return port.sayHello(arg0);
}
}

My Eclipse-TOMCAT version follows:
/*
* Copyright 2011 Oracle and/or its affiliates.
* All rights reserved. You may not modify, use,
* reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://developers.sun.com/license/berkeley_license.html
*/

package webclient;

import helloservice.endpoint.HelloService;
import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.RemoteException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.rpc.ServiceException;
import javax.xml.ws.WebServiceRef;


@WebServlet(name = "HelloServlet", urlPatterns = {"/HelloServlet"})
public class HelloServlet extends HttpServlet {
//@WebServiceRef(wsdlLocation = "WEB-INF/wsdl/ars-PC_8080/helloservice/HelloService.wsdl")
@WebServiceRef(wsdlLocation = "http:///ars-PC:8080/helloservice/HelloService?wsdl")
public HelloService service;

/**
* Processes requests for both HTTP <code>GET</code>
* and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(
HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try {
out.println("<html lang=\"en\">");
out.println("<head>");
out.println("<title>Servlet HelloServlet</title>");
out.println("</head>");
out.println("<body>");
out.println(
"<h1>Servlet HelloServlet at " + request.getContextPath()
+ "</h1>");
out.println("<p>" + sayHello("world") + "</p>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(
HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
} // </editor-fold>

private String sayHello(java.lang.String arg0) {
try {
helloservice.endpoint.Hello port = service.getHello();
// port = service.getHelloPort();
return port.sayHello(arg0);
} catch(ServiceException e){}
catch(RemoteException re){};
return "error";
}
}

The problems I met during this effort:

javax.servlet.ServletException: Error instantiating servlet class webclient.HelloServlet
...
root cause

javax.naming.NameNotFoundException: Name webclient.HelloServlet is not bound in this Context
org.apache.naming.NamingContext.lookup(NamingContext.java:803)
org.apache.naming.NamingContext.lookup(NamingContext.java:159)

This error stops when I comment the @WebServiceRef line. But then the service.getHello() does not work due to the null service from the lack of injection.

Some other problems I met while dealing with this problem:
After
wsdlDocumentLocation = new URL(
// "http://localhost:8080/helloservice/HelloService?wsdl");
"http://localhost:8080/helloservice/services/Hello");

Mar 19, 2012 7:57:32 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Hello] in context with path [/webclient] threw exception
javax.xml.ws.WebServiceException: {http://endpoint.helloservice/}HelloService is not a valid service. Valid services are: {http://endpoint.helloservice}HelloService
at com.sun.xml.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:272)
at ...

I also got this at one point:

type Exception report
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
com.sun.xml.ws.util.ServiceConfigurationError: com.sun.xml.ws.api.pipe.TransportPipeFactory: Provider com.sun.enterprise.jbi.serviceengine.bridge.transport.JBITransportPipeFactory is specified in bundle://293.0:0/META-INF/services/com.sun.xml.ws.api.pipe.TransportPipeFactory but not found
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1 logs.

The solution of the problem is:


nlibraies.properties
libs.CopyLibs.classpath=\
${base}/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar
libs.javaee-endorsed-api-6.0.classpath=\
${base}/javaee-endorsed-api-6.0/javax.annotation.jar;\
${base}/javaee-endorsed-api-6.0/jaxb-api-osgi.jar;\
${base}/javaee-endorsed-api-6.0/webservices-api-osgi.jar
libs.javaee-endorsed-api-6.0.javadoc=\
${base}/javaee-endorsed-api-6.0/javaee6-doc-api.zip

--------------------------------
C:\Users\ars\Desktop\ARSnbWebService\jaxws\helloservice\lib\javaee-endorsed-api-6.0
webservices-api-osgi.jar
jaxb-api-osgi.jar
javax.annotation
jaxrpc
saaj
wsdl4j



The NetBeans-GlassFish uses Metro Services or JAX-WS Reference Implementation which utilizes the above jars at the top. The Eclipse-Tomcat uses the above jar files and the AXIS implementation. So, there are structural differences in the implementation of JAX-WS.

My solution for Eclipse-Tomcat conversion of the above Javaee5-6 example is:

/*
* Copyright 2011 Oracle and/or its affiliates.
* All rights reserved. You may not modify, use,
* reproduce, or distribute this software except in
* compliance with the terms of the License at:
* http://developers.sun.com/license/berkeley_license.html
*/

package webclient;

import helloservice.endpoint.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.rmi.RemoteException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;
import javax.xml.ws.Service;

import org.apache.axis.AxisFault;

import java.net.MalformedURLException;
import java.net.URL;

@WebServlet(name = "HelloServlet", urlPatterns = { "/HelloServlet" })
public class HelloServlet extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request
* servlet request
* @param response
* servlet response
* @throws ServletException
* if a servlet-specific error occurs
* @throws IOException
* if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException, AxisFault ,Exception {
response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try {
out.println("<html lang=\"en\">");
out.println("<head>");
out.println("<title>Servlet HelloServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet HelloServlet at "
+ request.getContextPath() + "</h1>");
out.println("<p>" + sayHello("world") + "</p>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}

// <editor-fold defaultstate="collapsed"
// desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request
* servlet request
* @param response
* servlet response
* @throws ServletException
* if a servlet-specific error occurs
* @throws IOException
* if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try{
processRequest(request, response);
} catch(AxisFault af){}
catch(Exception e){}
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request
* servlet request
* @param response
* servlet response
* @throws ServletException
* if a servlet-specific error occurs
* @throws IOException
* if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try{
processRequest(request, response);
} catch(AxisFault af){}
catch(Exception e){}
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
} // </editor-fold>

private String sayHello(java.lang.String arg0) throws AxisFault ,Exception {

try {
// URL wsdlDocumentLocation = null;
// try {
// wsdlDocumentLocation = new URL(
// "http://localhost:8080/helloservice/HelloService?wsdl");
// //"http://localhost:8080/helloservice/services/Hello");
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
// QName qname = new QName("http://endpoint.helloservice/", "HelloService");
//
// Service service = Service.create(wsdlDocumentLocation, qname);
// System.out.println("aaaaaaaaaaaaa3");
// Hello hello = service.getPort(Hello.class);
// System.out.println("aaaaaaaaaaaaa4");
// return hello.sayHello(arg0);
// } catch (RemoteException re) {
// }
// return ("error");
//
// }
HelloSoapBindingStub srv = new HelloSoapBindingStub(
new URL("http://localhost:8080/helloservice/services/Hello"),
new HelloServiceLocator());
return srv.sayHello(arg0);
} catch(AxisFault af){}
return "error";

}
}

Please notice the changes that replace the commented code. I used a stub and its binding to the web service address and a locator to call the sayHello. The rest of the staff is pretty straight forward but if any problems do not hesitate to contact me at arsaral(at)yahoo.com .

An example of Eclipse-GlassFish conversion of the NetBeans-GlassFish version will follow.