Wednesday, October 10, 2012

Complex Element


Complex Element

Complex Element : which element contains simple elements or other complex elements is call complex element.

We can create complex elements in two ways in xsd

1.creating complex type elements and using them
2.annoums complex element


1.creating complex type elements and using them

we can create a complex element in xsd by using "complexType" key word
as follows

we can resue the structure of the complex type (it is creating class in java)

compareing java class and complex type in xsd.










Class in java

Complex Type in xsd

Class name_of_class
{

         //statements


}


<complexType name=”name_of_complex _type”>
            <sequence/all>
  
                   //simple elements

            </sequence/all>
</complexType>

class ItemType
{
          String itemcode;
          int quantity;
}





<complexType name="itemtype">
                <sequance>
                                <element name="itemcode" type="string"/>
                                <element name="quantity" type="int"/>
                </sequance>
</complexType>


ItemType  item=new ItemType();



<element name=”item” type=”itemtype”>



Structure:

<complexType name="complex_type_name">
                <sequance/all>
                                //simple elements or complex elements
                </sequance/all>
</complexType>


Example:

complexType which contains simple elements

<complexType name="itemtype">
                <sequance>
                                <element name="itemcode" type="string"/>
                                <element name="quantity" type="int"/>
                </sequance>
</complexType>

complexType which contains complex elements

<complexType name="orderitemstype">
                <sequance>
                                <element name="quantity" type="itemtype"/>
                </sequance>
</complexType>


XML Well Form


XML Well Form
For well formed XML we follow the following rules.
Well form talks about the structure of the xml document
Rules:
·         XML file should start with prolog (optional)
·         Only one root tag is allowed
·         All the elements (tags) must be under Root Tag only
·         Every stating tag must have ending tag (closing tag)
·         The level of opening tag must be closed the same level
·         XML tags are case sensitive  i.e <Tag> and <tag> both are treated as different tags
Demo:
File Name: Demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<PURCHAGEORDER> <!- root tag opening at level 0 -->
                <ORDERITEMS> <!- opening tag at level 1 -->
                                <ITEM>  <!- opening tag at level 2 -->
                                                <ITEMCODE>NOKIA345</ITEMCODE>
                                                <QUANTITY>6</QUANTITY>
                                </ITEM><!- closing tag at level 2 -->
                </ORDERITEMS> <!- closing tag at level 1 -->
                <SHIPPINGADDRESS><!- opening tag at level 1 -->
                                <ADDR>SAN</ADDR><!- opening and closing tag at level 2 -->
                                <DORNO>77-98</DORNO><!- opening and closing tag at level 2 -->                                                                                                     <STREAT>GOPALNAGAR</STREAT><!- opening and closing tag at level 2 -->
                                <CITY>HYD</CITY><!- opening and closing tag at level 2 -->
                </SHIPPINGADDRESS><!- closing tag at level 1 -->
</PURCHAGEORDER><!- closing tag at level 0 -->

Note: above demo.xml file satisfy’s all the rules so its call well formed xml
1.     For checking is well formed or not open in the browser, if its shows the above content as it we wrote
Otherwise it shows the error where and what
2.     use the xml spy tool check whether the xml is well formed or not

SIMPLE WEB SERVICE PROVIDER SIDE APPLICATION


SIMPLE WEB SERVICE PROVIDER SIDE APPLICATION
Requirement:
                Develop a web service provider side application which, provide complete information about a book by giving a book name as input.
Web service development environment:
1.       Using Jax-rpc api si (sun implementation) 
2.       Contract as  last
3.       Synchronous reply/response message exchange pattern
4.       rpc-encoded
5.       servlet end-point
Software requirements:
1.       java 1.5.0_22and java 1.6.0 in between
2.       jax-rpc specific jar files
3.        apache- tomcat 6.x serve
4.       Jwsdp 2.0 tool
Development procedure:
Step 1:
                Create a dynamic project in eclipse as follows.
File->New->Others->Dynamic web project
Give the project name and set server as tomcat
project Name: bookproject
Create a package under project : bookproject as shown
Package name: com.bookweb.service
Step 2:
                Copy the all jax-rpc specific jar files into lib folder.
  Step 3:
                Create a SEI interface as follows
                Interface name: BookInterface
package com.bookweb.service;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface BookInterface extends Remote {
      
       float getBookPrice(String isbn) throws RemoteException;

}

Step 4:
                Implemented class name: BookImpl.java
                Provide implementation for SEI interface, which is full fill our business requirements
package com.bookweb.service;

import java.rmi.RemoteException;

public class BookImpl implements BookInterface {

       public float getBookPrice(String isbn) throws RemoteException {
              float bookprice=0.0f;
              if(isbn.equals("java"))
                     bookprice=234.56f;
              return bookprice;
       }

}


Step 5:

      
 Write a configuration file under WEB-INF folder as following tags
Configuration file name: config.xml
<?xml version="1.0" encoding="UTF-8"?>

<configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
       <service name="BookInfoService"
              targetNamespace="http://bookinfoservice.org/wsdl"
              typeNamespace="http://bookinfoservice.org/types"
              packageName="com.bookweb.service.binding">
              <interface name="com.bookweb.service.BookInterface"
                     servantName="com.bookweb.service.BookImpl" />
       </service>
</configuration>

Step 5:
                Install jwsdp2.0 tool
Set path for bin as C:\Sun\jwsdp-2.0\jaxrpc\bin
Run wscompile.bat with following options and pass config.xml as input
C:\Users\sant\workspace\BookService>wscompile -keep -verbose -gen:server -d src
-cp build\classes -model model-rpc-enc.xml.gz WebContent\WEB-INF\config.xml
It will generates wsdl file and model files and saxparsers and java classes
Move the wsdl and model file into WEB-INF folder
Step 5:
                Write one more configuration file jax-rpc.xml (file name with same name only) under WEB-INF
<?xml version="1.0" encoding="UTF-8"?>
<webServices
    xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/dd"
    version="1.0"
    targetNamespaceBase="http://bookinfoservice.org/wsdl"
    typeNamespaceBase="http://bookinfoservice.org/types"
    urlPatternBase="/getBookPrice">

    <endpoint
        name="booksriceservice"
        displayName="Book Service"
        description="A simple web service"
        wsdl="/WEB-INF/BookInfoService.wsdll"
        interface="com.bookweb.service.BookInterface" 
        implementation="com.bookweb.service.BookImpl"
            model="/WEB-INF/model-rpc-enc.xml.gz">
           
        </endpoint>

    <endpointMapping
        endpointName="booksriceservice"
        urlPattern="/getBookPrice"/>

</webServices>

Step 6:
                Export project as .war file
Give the war as input to the wsdeploy.bat
C:\wsdeploy –o taget.war bookproject.war
It generates the jax-rpc-runtime.xml and web.xml
Copy the same file into the project WEB-INF folder
Step 7:
Deploy the project in server and run the server and provide the url;
output as follows:
Web Services
Port Name
Status
Information
booksriceservice
ACTIVE
Address:
http://localhost:8080/bookproject/getBookPrice
WSDL:
Port QName:
{http://bookinfoservice.org/wsdl}BookInterfacePort
Remote interface:
com.bookweb.service.BookInterface
Implementation class:
com.bookweb.service.BookImpl
Model:

Saturday, May 19, 2012

public access modifier

RULE: public is key word and it is an access modifier, we can apply this modifier for classes,methods and variables .
we  can access from the program and out side of the program of out side packages.
Recommended for classes and method  but not variables.

Demo:
package demo.publ;
public class DemoPublic
{
      public methodDemo
      {
           System.out.println("public method in demo.publi.Demopublic");
      }
}

package demo.pub2;
import demo.publi.DemoPublic;
public class UsePublic
{
       public static void main(String at[])
       {
           Demopublic p=new Demopublic();
           p.methodDemo();
       }
}

Wednesday, April 18, 2012

multiple upload files

    package com.mp.ws;

    /**
    *
    * @author nitinaggarwal
    *
    */
    public interface IFileUpload {

    public byte[] get1File(String name);

    public byte[][] getMulitpleFiles(String names[]);

    public String getXmlFile(String name);

    }

    package com.mp.ws;

    /**
    *
    * @author nitinaggarwal
    *
    */
    public class FileUpload implements IFileUpload {

    public byte[] get1File(String name) {
    byte data[] = null;

    FileReader fr = new FileReader();
    try {
    data = fr.readBinFilePath(name);
    } catch (Exception e) {
    e.printStackTrace();
    }

    return data;
    }

    public String getXmlFile(String name) {
    String data = null;
    FileReader fr = new FileReader();
    try {
    data = fr.readTextFile(name);
    } catch (Exception e) {
    e.printStackTrace();
    }
    return data;
    }

    public byte[][] getMulitpleFiles(String[] fnames) {

    byte[][] data = new byte[fnames.length][];
    for (int i = 0; i < fnames.length; i++) {
    FileReader fr = new FileReader();
    try {
    data[i] = fr.readBinFilePath(fnames[i]);

    System.out.println("abc" + data[i]);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    return data;
    }

    }

    package com.mp.ws;

    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;

    /**
    *
    * @author nitinaggarwal
    *
    */
    public class FileReader {

    public String readTextFile(final String name) throws Exception {
    StringBuffer xmlFromFile = new StringBuffer();
    InputStream instr = null;
    //instr = getFilePath2(name);

    instr = new FileInputStream(name);

    if (instr == null)
    throw new FileNotFoundException();
    InputStreamReader streamreader = null;

    try {

    streamreader = new InputStreamReader(instr);
    int x = 0;
    x = streamreader.read();

    while (x != -1) {
    xmlFromFile.append((char) x);
    x = streamreader.read();

    }

    } catch (Exception e) {

    System.out.println("Exception " + e.getMessage());
    throw e;

    } finally {
    streamreader.close();

    }

    return xmlFromFile.toString();

    }

    public byte[] readBinFileFromClassPath(final String name) throws Exception {

    byte bytearray[] = null;
    FileInputStream fileinputstream = null;
    try {

    fileinputstream = new FileInputStream(getFilePath(name));
    int numberBytes = fileinputstream.available();
    bytearray = new byte[numberBytes];
    fileinputstream.read(bytearray);

    } catch (Exception e) {
    System.out.println("Exception " + e.getMessage());
    throw e;

    } finally {
    if (fileinputstream != null)
    fileinputstream.close();
    }

    return bytearray;
    }

    public byte[] readBinFilePath(final String name) throws Exception {

    byte bytearray[] = null;
    FileInputStream fileinputstream = null;
    try {

    fileinputstream = new FileInputStream(name);
    int numberBytes = fileinputstream.available();
    bytearray = new byte[numberBytes];
    fileinputstream.read(bytearray);

    } catch (Exception e) {
    System.out.println("Exception " + e.getMessage());
    throw e;

    } finally {
    if (fileinputstream != null)
    fileinputstream.close();
    }

    return bytearray;
    }

    public void writeBinFileToPath(String name, byte data[]) throws IOException {

    FileOutputStream fileoutputstream = new FileOutputStream(name);

    try {
    fileoutputstream.write(data);

    } catch (IOException e) {
    System.out.println(e.getMessage());

    } finally {
    if (fileoutputstream != null)
    fileoutputstream.close();
    data = null;
    }

    }

    private InputStream getFilePath2(String filename) {
    return this.getClass().getClassLoader().getResourceAsStream(filename);

    }

    private String getFilePath(String filename) throws FileNotFoundException {
    String path = this.getClass().getClassLoader().getResource(filename)
    .getPath();
    if ("".equals(path))
    throw new FileNotFoundException();
    return path;

    }

    }

    package com.mp.ws;

    /**
    *
    * @author nitinaggarwal
    *
    */
    @javax.jws.WebService(targetNamespace = "http://ws.mp.com/", serviceName = "FileUploadService", portName = "FileUploadPort")
    public class FileUploadDelegate {

    com.mp.ws.FileUpload fileUpload = new com.mp.ws.FileUpload();

    public byte[] get1File(String name) {
    return fileUpload.get1File(name);
    }

    public byte[][] getMulitpleFiles(String[] fnames) {
    return fileUpload.getMulitpleFiles(fnames);
    }

    public String getXmlFile(String name) {
    return fileUpload.getXmlFile(name);
    }

    }

    package com.mp.ws;
    /**
    *
    * @author nitinaggarwal
    *
    */
    public class FileUploadTester {

    public static void main(String[] args) {
    FileUpload fu = new FileUpload();
    String fnames[]= {"c:/uploadme.doc","c:/uploadme.doc","c:/uploadme.doc"};

    byte[][] data = fu.getMulitpleFiles(fnames);

    }
    }

multiple file upload helpful website urls

1.  http://digitarald.de/project/fancyupload/  
2.  http://swfupload.org           
3.  http://jupload.sourceforge.net/
4.  http://jumploader.com/
5.  http://code.google.com/apis/gears/samples/hello_world_file_system.html
6.  http://www.telerik.com/products/aspnet-ajax/upload.aspx#uploading-files
7.  http://www.element-it.com/multiple-file-upload/flash-uploader.aspx
8.  http://stackoverflow.com/questions/582126/best-way-to-upload-multiple-files-from-a-browser

Wednesday, January 25, 2012

arithmetic operators


//arthemetic operators using switch
import java.io.*;
class Input2
{
public static void main(String[] args)throws IOException
{
char ch;
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ir);
System.out.println("enter values of x");
int x=Integer.parseInt(br.readLine());
System.out.println("enter values of y");
int y=Integer.parseInt(br.readLine());
System.out.println("enter u r choice");
System.out.println("+ for additon");
System.out.println("- for subtraction");
System.out.println("/ for divide");
System.out.println("* for multipiy");
System.out.println("% for remainder");
ch=(char)br.read();
switch(ch)
{
case '+':
System.out.println("additon:"+(x+y));
break;
case '-':
System.out.println("sub:"+(x-y));
break;
case '*':
System.out.println("mul:"+(x*y));
break;
case '/':
System.out.println("divide:"+(x/y));
break;
case '%':
System.out.println("Remainder:"+(x%y));
break;
}
}
}

Reading an integer from keyboard


// input from key board
import java.io.*;
class Inputint
{
public static void main(String r[])throws IOException
{
InputStreamReader id=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(id);

System.out.println("enter a interger");

int s=Integer.parseInt(br.readLine());

System.out.println("enter "+s);
}
}

reading a string from keyboard

// input from key board
import java.io.*;
class Inputstring
{
public static void main(String r[])throws IOException
{
//InputStreamReader id=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a String vslue");
String s=br.readLine();
System.out.println("enter "+s);
}
}

Simple AJAX Program

Simple AJAX application using java script and JSP.


Files required.

1. ajax.js
2. mainpage.jsp
3. process.jsp
4. web.xml

Code :


1. ajax.js



var xmlHttp;
function postRequest(url) {


if (window.XMLHttpRequest) { // Mozilla, Safari, ...
//alert("other than IE");
 xmlHttp = new XMLHttpRequest();


} else if (window.ActiveXObject) { // IE
//alert("IE only");
 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");


}


xmlHttp.open('POST', url, true);
xmlHttp.onreadystatechange = function() {

if (xmlHttp.readyState == 4) {
updatepage(xmlHttp.responseText);


}


}


xmlHttp.send(url);


}




function updatepage(str){


document.getElementById("result").innerHTML = "<font color='green' size='15'>" + str + "</font>";


}


function showCurrentTime(){


var url="process.jsp";
postRequest(url);


}


2. mainpage.jsp



<%@ page import="java.util.*" %>
<html>
<head>


<title>Ajax Example</title>
<script type="text/javascript" src="ajax.js"> </script>
</head>


<body>


<h1 align="center"><font color="#000080">Ajax Example</font></h1>
<%
out.println(new Date());
%>
<p><font color="#000080">&nbsp;This very simple Ajax Example retrieves the
current date and time from server and shows on the form. To view the current
date and time click on the following button.</font></p>


<form name="f1">


<p align="center"><font color="#000080">&nbsp;<input value=" Show Time " 
type="button" onclick='JavaScript:showCurrentTime()' name="showdate"></font></p>
<div id="result" align="center"></div>


</form>
<div id=result></div>
</body>


</html>




3. process.jsp



<%@ page import="java.util.*" %>
<%
out.println(new Date());
%>


4. web.xml



<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>AjaxApp1</display-name>
  
  <welcome-file-list>
      <welcome-file>mainpage.jsp</welcome-file>
    
  </welcome-file-list>
</web-app>