0% found this document useful (0 votes)
21 views

WS Practical Journal (TCS2223077)

The document describes 10 practical experiments conducted by a student. It provides details of each practical including the aim, code samples, and outputs. The practicals cover topics like creating a time server web service, building a basic calculation web service, and creating a stock data retrieval service from a database.

Uploaded by

saad7teen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

WS Practical Journal (TCS2223077)

The document describes 10 practical experiments conducted by a student. It provides details of each practical including the aim, code samples, and outputs. The practicals cover topics like creating a time server web service, building a basic calculation web service, and creating a stock data retrieval service from a database.

Uploaded by

saad7teen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Name - Sumanth Ganeshan Udaiyar

Roll no - TCS2223077
Index:
Sr No. Practical No. Date
1 Practical No.1 07-08-2022
2 Practical No.2 20-08-2022
3 Practical No.3 20-08-2022
4 Practical No.4 20-08-2022
5 Practical No.5 15-09-2022
6 Practical No.6 15-09-2022
7 Practical No.7 15-09-2022
8 Practical No.8 14-10-2022
9 Practical No.9 14-10-2022
10 Practical No.10 14-10-2022

Practical No.1:
Aim:
Create a TimeServer web service in Java and consume it in java and
other technologies like php and .NET

Code and Output:


TimeService.java:
package ts;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;

/**
*
* @author User
*/
@WebService(serviceName = "TimeService")
public class TimeService {

/**
* Web service operation
*/
@WebMethod(operationName = "getTimeAsString")
public String getTimeAsString() {
//TODO write your implementation code here:
return new java.util.Date().toString();
}

/**
* Web service operation
*/
@WebMethod(operationName = "getTimeAsElapsed")
public long getTimeAsElapsed() {
//TODO write your implementation code here:
return new java.util.Date().getTime();
}
}
Index.jsp (Java client):
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%-- start web service invocation --%><hr/>
<%
try {
ts1.TimeService_Service service = new ts1.TimeService_Service();
ts1.TimeService port = service.getTimeServicePort();
// TODO process result here
long result = port.getTimeAsElapsed();
out.println("Time Elapsed is "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
%>
<%-- end web service invocation --%><hr/>
<%-- start web service invocation --%><hr/>
<%
try {
ts1.TimeService_Service service = new ts1.TimeService_Service();
ts1.TimeService port = service.getTimeServicePort();
// TODO process result here
java.lang.String result = port.getTimeAsString();
out.println("Time as String is "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
%>
<%-- end web service invocation --%><hr/>
</body>
</html>
Program.cs (.NET Client):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace client
{
class Program
{
static void Main(string[] args)
{
ServiceReference1.TimeServiceClient client1 = new ServiceReference1.TimeServiceClient();
Console.WriteLine("Time as String is " + client1.getTimeAsString());
Console.WriteLine("Time Elapsed is " + client1.getTimeAsElapsed());
Console.Read();
}
}
}

Changes in the php config file:

Client.php:
<?php
$client = new SoapClient("http://localhost:8080/TimeService/TimeService?WSDL");

$t1=$client->getTimeAsElapsed();

echo "Elapsed Time is ",$t1->return;

$t2=$client->getTimeAsString();

echo "<br> Time as String is ",$t2->return;

?>

Practical No.2:
Aim:
Create a java WS for performing basic calculations like addition,
subtraction, multiplication and division and create a java client that
consumes the same.

Code:
Operations.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package practical2;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;

/**
*
* @author sies
*/
@WebService(serviceName = "Operations")
public class Operations {

/**
* Web service operation
*/
@WebMethod(operationName = "Addition")
public int Addition(@WebParam(name = "First_Number") int First_Number, @WebParam(name =
"Second_Number") int Second_Number) {
//TODO write your implementation code here:
return First_Number + Second_Number;
}

/**
* Web service operation
*/
@WebMethod(operationName = "Subtraction")
public int Subtraction(@WebParam(name = "First") int First, @WebParam(name = "Second") int
Second) {
//TODO write your implementation code here:
return First-Second;
}

/**
* Web service operation
*/
@WebMethod(operationName = "Multiplication")
public int Multiplication(@WebParam(name = "First") int First, @WebParam(name = "Second") int
Second) {
//TODO write your implementation code here:
return First*Second;
}

/**
* Web service operation
*/
@WebMethod(operationName = "Division")
public float Division(@WebParam(name = "First") float First, @WebParam(name = "Second") float
Second) {
//TODO write your implementation code here:
return First/Second;
}
}

Index.html:
<!DOCTYPE html>

<html>

<head>

<title>TODO supply a title</title>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>

<form action="client.jsp">

Enter First Number: <input type="text" name="first" value="" />

<br>

Enter Second Number: <input type="text" name="second" value="" />

<br>

Select any one: <br>

Add<input type="radio" name="operations" value="add" /><br>

Subtract<input type="radio" name="operations" value="sub" /><br>

Multiply<input type="radio" name="operations" value="mul" /><br>

Divide<input type="radio" name="operations" value="div" />

<br>

<input type="submit" value="Submit" name="Submit" />

</form>

</body>

</html>

Client.jsp:
<%--
Document : client
Created on : Aug 11, 2022, 10:21:18 AM
Author : sies
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
int a = Integer.parseInt(request.getParameter("first"));
int b = Integer.parseInt(request.getParameter("second"));
String choice = request.getParameter("operations");
if(choice.equals("add"))
{
try {
Pra2.Operations_Service service = new Pra2.Operations_Service();
Pra2.Operations port = service.getOperationsPort();
// TODO initialize WS operation arguments here
int firstNumber = a;
int secondNumber = b;
// TODO process result here
int result = port.addition(firstNumber, secondNumber);
out.println("Addition = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
}
else if(choice.equals("sub"))
{
try {
Pra2.Operations_Service service = new Pra2.Operations_Service();
Pra2.Operations port = service.getOperationsPort();
// TODO initialize WS operation arguments here
int first = a;
int second = b;
// TODO process result here
int result = port.subtraction(first, second);
out.println("Subtraction = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}

}
else if(choice.equals("mul"))
{
try {
Pra2.Operations_Service service = new Pra2.Operations_Service();
Pra2.Operations port = service.getOperationsPort();
// TODO initialize WS operation arguments here
int first = a;
int second = b;
// TODO process result here
int result = port.multiplication(first, second);
out.println("Multiplication = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}

}
else if(choice.equals("div"))
{
try {
Pra2.Operations_Service service = new Pra2.Operations_Service();
Pra2.Operations port = service.getOperationsPort();
// TODO initialize WS operation arguments here
float first = a;
float second = b;
// TODO process result here
float result = port.division(first, second);
out.println("Division = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}

%>
</body>
</html>

Output:
Practical No.3:
Aim:
Create a web service that gives – (i)NSE Index, (ii)BSE index, (iii)Gold
Rate. The values are stored in database. Also create a web client for a
share trading firm that displays these values on its home page.

Code and Output:


Database:

StockService.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Stock;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import java.sql.*;
/**
*
* @author sies
*/
@WebService(serviceName = "StockService")
public class StockService {

/**
* Web service operation
*/
@WebMethod(operationName = "getNSE")
public long getNSE() {
long nse=0;
try
{
//load driver
Class.forName("org.apache.derby.jdbc.ClientDriver");
//Connection creation
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/StockDatabase",
"andy", "andyboi");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from stockdata");
rs.next();
nse = rs.getInt("NSE");
}
catch(Exception e)
{
e.printStackTrace();
}
return nse;
}

/**
* Web service operation
*/
@WebMethod(operationName = "getBSE")
public long getBSE() {
long bse=0;
try
{
//load driver
Class.forName("org.apache.derby.jdbc.ClientDriver");
//Connection creation
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/StockDatabase",
"andy", "andyboi");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from stockdata");
rs.next();
bse = rs.getInt("BSE");
}
catch(Exception e)
{
e.printStackTrace();
}
return bse;
}

/**
* Web service operation
*/
@WebMethod(operationName = "getGoldRate")
public long getGoldRate() {
long goldrate=0;
try
{
//load driver
Class.forName("org.apache.derby.jdbc.ClientDriver");
//Connection creation
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/StockDatabase",
"andy", "andyboi");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from stockdata");
rs.next();
goldrate = rs.getInt("GoldRate");
}
catch(Exception e)
{
e.printStackTrace();
}
return goldrate;
}
}
Index.jsp:
<%--
Document : index
Created on : Aug 18, 2022, 9:42:11 AM
Author : sies
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%-- start web service invocation --%><hr/>
<%
try {
stock.StockService_Service service = new stock.StockService_Service();
stock.StockService port = service.getStockServicePort();
// TODO process result here
long result = port.getNSE();
out.println("NSE Index = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
%>
<%-- end web service invocation --%><hr/>
<%-- start web service invocation --%><hr/>
<%
try {
stock.StockService_Service service = new stock.StockService_Service();
stock.StockService port = service.getStockServicePort();
// TODO process result here
long result = port.getBSE();
out.println("BSE Index = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
%>
<%-- end web service invocation --%><hr/>
<%-- start web service invocation --%><hr/>
<%
try {
stock.StockService_Service service = new stock.StockService_Service();
stock.StockService port = service.getStockServicePort();
// TODO process result here
long result = port.getGoldRate();
out.println("Gold Rate = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
%>
<%-- end web service invocation --%><hr/>

</body>
</html>
Practical No.4:
Aim:
Create a web service for UGC that contains a method which accepts
college name as parameter and returns the NAAC rating. The college
names and their ratings are stored in database. Design a web client to
test the above web service.

Code and Output:


Database:
RatingService.java:
/*

* To change this license header, choose License Headers in Project Properties.


* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

package rating;

import java.sql.DriverManager;

import javax.jws.WebService;

import javax.jws.WebMethod;

import javax.jws.WebParam;

import java.sql.*;

/**

* @author sies

*/

@WebService(serviceName = "RatingService")

public class RatingService {

/**

* Web service operation

*/

@WebMethod(operationName = "getRating")

public String getRating(@WebParam(name = "CollegeName") String CollegeName) {

String rating="";

try

//String Collegename ="";

Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con =
DriverManager.getConnection("jdbc:derby://localhost:1527/RatingDatabase", "andy", "andyboi");

PreparedStatement pstmt = con.prepareStatement("select * from RatingTable where


CollegeName = ?");

pstmt.setString(1, CollegeName);

ResultSet rs = pstmt.executeQuery();

rs.next();

rating=rs.getString("Rating");

catch (Exception e)

e.printStackTrace();

return rating;

}
Index.html:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="client.jsp">
Enter College Name: <input type="text" name="CollegeName" value="" />
<br>
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
</html>
Client.jsp:
<%--
Document : index
Created on : Aug 20, 2022, 5:29:00 PM
Author : User
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
try
{
rate.RatingService_Service service = new rate.RatingService_Service();
rate.RatingService port = service.getRatingServicePort();
// TODO initialize WS operation arguments here
java.lang.String collegeName = request.getParameter("CollegeName");
// TODO process result here
java.lang.String result = port.getRating(collegeName);
out.println("College Rating = "+result);
}
catch (Exception ex)
{
// TODO handle custom exceptions here
}
%>
</body>
</html>
Practical No.5:
Aim:
Design a Web Service for a channel containing 2 functions – 1st
function is called getBreakingNews which accepts date as String
parameter and returns special news of that day, 2nd function called
getPrediction accepts sunsign name as string parameter and returns
predictions as string. Design a client to test the above Web Service.

Code:
Database:

Prac5.java:
package pracs5;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import java.sql.*;

@WebService(serviceName = "Prac5")
public class Prac5 {

/**
* Web service operation
*/
@WebMethod(operationName = "getBreakingNews")
public String getBreakingNews(@WebParam(name = "Date") String Date)
{
String news="";
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con =
DriverManager.getConnection("jdbc:derby://localhost:1527/Practical5DB","andy","andyboi");
PreparedStatement pstmt = con.prepareStatement("select * from BreakingNews where
Date=?");
pstmt.setString(1, Date);
ResultSet rs = pstmt.executeQuery();
rs.next();
news=rs.getString("BreakingNews");
}
catch (Exception e)
{
e.printStackTrace();
}
return news;
}

/**
* Web service operation
*/
@WebMethod(operationName = "getPredictions")
public String getPredictions(@WebParam(name = "Sunsign") String Sunsign)
{
String predictions="";
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con =
DriverManager.getConnection("jdbc:derby://localhost:1527/Practical5DB","andy","andyboi");
PreparedStatement pstmt = con.prepareStatement("select * from Predictions where
Sunsign=?");
pstmt.setString(1, Sunsign);
ResultSet rs = pstmt.executeQuery();
rs.next();
predictions=rs.getString("Predictions");
}
catch (Exception e)
{
e.printStackTrace();
}
return predictions;
}
}
Index.html:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="client.jsp">
Enter Date: <input type="text" name="Date" value="" size="15" />
<br>
Enter Sunsign: <input type="text" name="Sunsign" value="" size="40" />
<br>
News: <input type="radio" name="Choice" value="News" />
<br>
Prediction: <input type="radio" name="Choice" value="Prediction" />
<br>
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
</html>

Client.jsp:
<%--
Document : client
Created on : Aug 25, 2022, 9:30:19 AM
Author : sies
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String choice1 = request.getParameter("Choice");
if(choice1.equals("News"))
{
try {
prac5.Prac5_Service service = new prac5.Prac5_Service();
prac5.Prac5 port = service.getPrac5Port();
// TODO initialize WS operation arguments here
java.lang.String date = request.getParameter("Date");
// TODO process result here
java.lang.String result = port.getBreakingNews(date);
out.println("Breaking News = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
}
else{

try {
prac5.Prac5_Service service = new prac5.Prac5_Service();
prac5.Prac5 port = service.getPrac5Port();
// TODO initialize WS operation arguments here
java.lang.String sunsign = request.getParameter("Sunsign");
// TODO process result here
java.lang.String result = port.getPredictions(sunsign);
out.println("Predictions = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
}
%>

</body>
</html>
Practical No.6:
Aim:
Design a Restful webservice from a database table Employee with
columns empid, empname and Designation. Test the webservice for
the various http requests.

Code:
Database:

Employee.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package emppack;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
*
* @author sies
*/
@Entity
@Table(name = "EMPLOYEE")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e")
, @NamedQuery(name = "Employee.findByEmpid", query = "SELECT e FROM Employee e WHERE
e.empid = :empid")
, @NamedQuery(name = "Employee.findByEmpname", query = "SELECT e FROM Employee e
WHERE e.empname = :empname")
, @NamedQuery(name = "Employee.findByDesignation", query = "SELECT e FROM Employee e
WHERE e.designation = :designation")})
public class Employee implements Serializable {

private static final long serialVersionUID = 1L;


@Id
@Basic(optional = false)
@NotNull
@Column(name = "EMPID")
private Integer empid;
@Size(max = 50)
@Column(name = "EMPNAME")
private String empname;
@Size(max = 50)
@Column(name = "DESIGNATION")
private String designation;
public Employee() {
}

public Employee(Integer empid) {


this.empid = empid;
}

public Integer getEmpid() {


return empid;
}

public void setEmpid(Integer empid) {


this.empid = empid;
}

public String getEmpname() {


return empname;
}

public void setEmpname(String empname) {


this.empname = empname;
}

public String getDesignation() {


return designation;
}

public void setDesignation(String designation) {


this.designation = designation;
}

@Override
public int hashCode() {
int hash = 0;
hash += (empid != null ? empid.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Employee)) {
return false;
}
Employee other = (Employee) object;
if ((this.empid == null && other.empid != null) || (this.empid != null &&
!this.empid.equals(other.empid))) {
return false;
}
return true;
}

@Override
public String toString() {
return "emppack.Employee[ empid=" + empid + " ]";
}

Output:
Practical No.7:
Aim:
Design a Restful webservice from a database table Student with
columns rollno, name and totalmarks. Create a restful client that
displays the data by accessing restful service.

Code:
Database:
Student.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package stupack;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
*
* @author sies
*/
@Entity
@Table(name = "STUDENT")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Student.findAll", query = "SELECT s FROM Student s")
, @NamedQuery(name = "Student.findByRollno", query = "SELECT s FROM Student s WHERE
s.rollno = :rollno")
, @NamedQuery(name = "Student.findByName", query = "SELECT s FROM Student s WHERE s.name
= :name")
, @NamedQuery(name = "Student.findByTotalmarks", query = "SELECT s FROM Student s WHERE
s.totalmarks = :totalmarks")})
public class Student implements Serializable {

private static final long serialVersionUID = 1L;


@Id
@Basic(optional = false)
@NotNull
@Column(name = "ROLLNO")
private Integer rollno;
@Size(max = 50)
@Column(name = "NAME")
private String name;
@Column(name = "TOTALMARKS")
private Integer totalmarks;

public Student() {
}

public Student(Integer rollno) {


this.rollno = rollno;
}

public Integer getRollno() {


return rollno;
}

public void setRollno(Integer rollno) {


this.rollno = rollno;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public Integer getTotalmarks() {


return totalmarks;
}

public void setTotalmarks(Integer totalmarks) {


this.totalmarks = totalmarks;
}

@Override
public int hashCode() {
int hash = 0;
hash += (rollno != null ? rollno.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Student)) {
return false;
}
Student other = (Student) object;
if ((this.rollno == null && other.rollno != null) || (this.rollno != null &&
!this.rollno.equals(other.rollno))) {
return false;
}
return true;
}

@Override
public String toString() {
return "stupack.Student[ rollno=" + rollno + " ]";
}

StudentFacadeREST.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package stupack.service;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import stupack.Student;

/**
*
* @author User
*/
@Stateless
@Path("stupack.student")
public class StudentFacadeREST extends AbstractFacade<Student> {

@PersistenceContext(unitName = "StudentPU")
private EntityManager em;

public StudentFacadeREST() {
super(Student.class);
}

@POST
@Override
@Consumes({MediaType.APPLICATION_JSON})
public void create(Student entity) {
super.create(entity);
}

@PUT
@Path("{id}")
@Consumes({MediaType.APPLICATION_JSON})
public void edit(@PathParam("id") Integer id, Student entity) {
super.edit(entity);
}

@DELETE
@Path("{id}")
public void remove(@PathParam("id") Integer id) {
super.remove(super.find(id));
}

@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_JSON})
public Student find(@PathParam("id") Integer id) {
return super.find(id);
}

@GET
@Override
@Produces({MediaType.APPLICATION_JSON})
public List<Student> findAll() {
return super.findAll();
}

@GET
@Path("{from}/{to}")
@Produces({MediaType.APPLICATION_JSON})
public List<Student> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
return super.findRange(new int[]{from, to});
}

@GET
@Path("count")
@Produces(MediaType.TEXT_PLAIN)
public String countREST() {
return String.valueOf(super.count());
}

@Override
protected EntityManager getEntityManager() {
return em;
}

Output:
Practical No.8:
Aim:
Create a WCF service to perform calculations like Addition,
Subtraction, Multiplication and Division. Create a client for WCF which
invokes the various operations.

Code:
IService1.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface
name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
double Sum(double a, double b);

[OperationContract]
double Diff(double a, double b);

[OperationContract]
double Mul(double a, double b);

[OperationContract]
double Div(double a, double b);
}
}

Service1.svc.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name
"Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or
Service1.svc.cs at the Solution Explorer and start debugging.
public class Service1 : IService1
{
public double Mul(double a, double b)
{
double result = a * b;
return result;
//throw new NotImplementedException();
}

public double Sum(double a, double b)


{
double result = a + b;
return result;
//throw new NotImplementedException();
}

public double Diff(double a, double b)


{
double result = a - b;
return result;
//throw new NotImplementedException();
}

public double Div(double a, double b)


{
double result = a / b;
return result;
//throw new NotImplementedException();
}
}
}

WebForm1.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="WcfClient.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<div>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add" />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Sub" />
<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="Multiply" />
<asp:Button ID="Button4" runat="server" OnClick="Button4_Click" Text="Div" />
<br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>

WebForm1.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WcfClient
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

protected void Button1_Click(object sender, EventArgs e)


{
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
double a = double.Parse(TextBox1.Text);
double b = double.Parse(TextBox2.Text);
TextBox3.Text = Convert.ToString(client.Sum(a, b));
}

protected void Button2_Click(object sender, EventArgs e)


{
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
double a = double.Parse(TextBox1.Text);
double b = double.Parse(TextBox2.Text);
TextBox3.Text = Convert.ToString(client.Diff(a, b));
}

protected void Button3_Click(object sender, EventArgs e)


{
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
double a = double.Parse(TextBox1.Text);
double b = double.Parse(TextBox2.Text);
TextBox3.Text = Convert.ToString(client.Mul(a, b));
}

protected void Button4_Click(object sender, EventArgs e)


{
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
double a = double.Parse(TextBox1.Text);
double b = double.Parse(TextBox2.Text);
TextBox3.Text = Convert.ToString(client.Div(a, b));
}
}
}

Output:

Practical No.9:
Aim:
Create a WCF service with different endpoint for Soap based and Rest
based implementation
Code:
IHelloService.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFHelloApp
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface
name "IHelloService" in both code and config file together.
[ServiceContract]
public interface IHelloService
{
[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "GET", UriTemplate = "/Sayhello/{value}",
RequestFormat = System.ServiceModel.Web.WebMessageFormat.Json, ResponseFormat =
System.ServiceModel.Web.WebMessageFormat.Json)]
string SayHello(string value);

}
}

HelloService.svc.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFHelloApp
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name
"HelloService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select HelloService.svc or
HelloService.svc.cs at the Solution Explorer and start debugging.
public class HelloService : IHelloService
{
public string SayHello(string value)
{
return string.Format($"Hello {value}! Welcome to WCF");
}
}
}

Web.config:
<?xml version="1.0"?>
<configuration>

<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1"/>
</system.web>
<system.serviceModel>
<services>
<service name="WCFHelloApp.HelloService">
<endpoint address="jsonservice" binding="webHttpBinding"
contract="WCFHelloApp.IHelloService" behaviorConfiguration="web">
</endpoint>
<endpoint address="soapservice" binding="basicHttpBinding"
contract="WCFHelloApp.IHelloService">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -
->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true.
Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>

</configuration>

Output:
Practical No.10:
Aim:
To create a RESTful client for Practical No.7

Code:
Index.html:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form>
<h1> </h1>
<br>
<input type="submit" formaction="getData.jsp" value="Get Data">
</form>
</body>
</html>

getData.jsp:
<%--
Document : getData
Created on : Oct 15, 2022, 7:17:22 PM
Author : User
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
<style>
table
{
font-family: arial, sans-serif;
border-collapse: collapse;
}

td, th
{
border: 1px solid #000000;
text-align: center;
padding: 8px;
}
</style>
<script>
var request = new XMLHttpRequest();
request.open('GET',
'http://localhost:8080/Student/webresources/stupack.student/', true);
request.onload = function ()
{
// begin accessing JSON data here
var data = JSON.parse(this.response);

for (var i = 0; i < data.length; i++)


{
var table = document.getElementById("myTable");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = data[i].rollno;
cell2.innerHTML = data[i].name;
cell3.innerHTML = data[i].totalmarks;
}
};

request.send();
</script>
</head>
<body>
<table id="myTable">
<tr>
<th>ROLL NO</th>
<th>NAME</th>
<th>TOTAL MARKS</th>
</tr>
</table>
</body>
</html>

Output:

You might also like