Wednesday, 12 September 2018

PUBLISHER & SUBSCRIBER PATTERN

Using the UML Drawing Tool by implementing the code in Java demonstrate the Observer 


Design Pattern.
The Publisher-Subscriber design pattern helps to keep the state of cooperating components synchronized. To achieve this it enables one-way propagation of changes: one publisher notifies any number of subscribers about changes to its state.

Structure:



Participant Classes:
Subject: Keeps track of its observers. Provides an interface for attaching and detaching Observer objects

Observer: Defines an interface for update notification

ConcreteSubject: The object being observed. stores state of interest to ConcreteObserver objects. Sends a notification to its observers when its state changes

ConcreteObserver: The observing object. Stores state that should stay consistent with the subject's. Implements the Observer update interface to keep its state consistent with the ConcreteSubject

Problem Statement:
A situation often arises in which data changes in one place, but many other components depend on this data. The classical example is user interface elements:  when some internal data element changes all views that depend on this data have to be updated. We could solve the problem by  introducing direct calling dependencies  along which  to propagate  the  changes,  but  this  solution  is  inflexible  and  not reusable. We are looking for a more general change-propagation mechanism that is applicable in many contexts.

Solution:
One dedicated component takes the role of the publisher (called subject). All components dependent on changes in the publisher are its subscribers (called observers).











Source code

import java.util.Observable;

import java.util.Observer;         
import java.io.*;

class Publisher extends Observable 
{
private String name;
public Publisher(String name)
{
                        this.name=name;
                        System.out.println("Subject is Created with the name "+name);
}
public void setobserver()
    {
           BufferedReader br = new BufferedReader(new InputStreamReader( System.in));
            System.out.print("Enter new name> ");
            try
            {
                        name = br.readLine();
                        setChanged();
                        notifyObservers(name);
            }
            catch(Exception e)
            {
            }       
    }
}

class Subscriber1 implements Observer
{
    private String resp;
 public void update (Observable obj, Object arg)
    {
        if (arg instanceof String)
        {
            resp = (String) arg;
           System.out.println("\nReceived Response in Subscriber1 and name changed to "+resp);
        }
    }
}


class Subscriber2 implements Observer
{
    private String resp;
    public void update (Observable obj, Object arg)
    {
        if (arg instanceof String)
        {
            resp = (String) arg;
            System.out.println("\nReceived Response in Subscriber2 and name changed to "+resp);
        }
    }
}

public class Publisher_Subscriber
{
    public static void main(String args[])
    {
        Publisher pub = new Publisher("Summer");
        Subscriber1 sub1 = new  Subscriber1(); 
        Subscriber2 sub2 = new  Subscriber2();
        pub.addObserver(sub1);
        pub.addObserver(sub2);
        pub.setobserver();
    }
}

Output
Subject is Created with the name Summer
Enter new name> Winter
Received Response in Subscriber2 and name changed to Winter
Received Response in Subscriber1 and name changed to Winter

Expert Patten



        Using the UML Drawing Tool by implementing the code in Java demonstrate the Expert 


1.Design Pattern.
An Expert pattern is useful in maintaining encapsulation of information, it promotes low coupling and also provides highly cohesive classes which can cause a class to become excessively complex.





Code Implementation: 

Product Description.java:
import java.io.*;
public class ProductDescription
{
   private float price=43.89f;
   public float getPrice ()
   {
            return price;
   }
}


SalesCounter.java:
import java.io.*;
 public class SaleCounter
{
public static void main (String [] args)
                        {
float total;
Sales s=new Sales();
total=s.getTotal();
System.out.println ("Total sale is: "+total);
}
}

Sales .java:
import java.io.*;
public class Sales
{
            private float total;
            public float getTotal()
{
                        ProductDescription pd=new ProductDescription ();
                        SalesLineItem sli=new SalesLineItem ();
                        total=(pd.getPrice()*sli.getSubTotal());
                        return total;
            }
}

SalesLineItem:
public class SalesLineItem
{
private int quantity=100;
public int getSubTotal()
{
                                    return quantity;
}
}















Wednesday, 28 March 2018

JSP to print Fibonacci Series


Write a jsp program to print range of  Fibonacci Series


i)index.html

<%@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>
        <h1>Enter the Limit of Fibonacci Series</h1>
        <form action="fibo.jsp">
            Enter the Number:<input type="text" name="n1"/><br/>
            <input type="submit" value="Enter"/>         
        </form>
    </body>
</html>

ii) fibo.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>The Value of Fibonacci Series</h1>
        <h1>
        <%
            String s=request.getParameter("n1");
            int n=Integer.parseInt(s);
            int i=1,f1=0,f2=1,f3;
            while(i<=n)
            {
              out.println(f1);
              f3=f1+f2;
              f1=f2;
              f2=f3;
              i=i+1; 
            }
        %>
        </h1>
    </body>
</html>

JDBC to Demonstrate PreparedStatement


package javaapplication34;
import java.sql.*;
import java.io.*;

public class JavaApplication34 {

 
public static void main(String args[])throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/empdb12","root","");

PreparedStatement ps=con.prepareStatement("insert into emp values(?,?,?)");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

do{
System.out.println("enter id:");
int id=Integer.parseInt(br.readLine());
System.out.println("enter name:");
String name=br.readLine();
System.out.println("enter salary:");
float salary=Float.parseFloat(br.readLine());

ps.setInt(1,id);
ps.setString(2,name);
ps.setFloat(3,salary);
int i=ps.executeUpdate();
System.out.println(i+" records affected");

System.out.println("Do you want to continue: y/n");
String s=br.readLine();
if(s.startsWith("n")){
break;
}
}while(true);

con.close();
}}



Monday, 26 March 2018

JSP to Demonstrate atrribute of page directive tag


Write a JSP program to implement all the attributes of page directive tag.


Note: create 3 diffrent jsp file and execute the project

//index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page Attributes </title>
</head>
<body>
<form action="Directive.jsp">
<h1>Enter the value of n1 and n2: </h1>
           Number1: <input type="number" name="n1"/><br/>
           Number:2<input type="number" name="n2"/><br/>
<input type="submit"/>
</form>
</body>
</html>

//Directive.jsp

<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ page info="composed by CITECH" %>
<%@ page language="java"%>
<%@ page buffer="16kb" %>
<%@ page autoFlush="true" %>
<%@ page isThreadSafe="true" %>
<%@ page errorPage="error.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page Attributes</title>
</head>
<body bgcolor="orange">
<h2> Usage of Import Attributes </h2>
<h2>Todays Date is: <%=new Date() %></h2>

<h2>To See the use of Error page enter n2 value  zero and click submit  </h2>

<% 
int n1=Integer.parseInt(request.getParameter("n1"));
int n2=Integer.parseInt(request.getParameter("n2"));      
   %>

<h2>Value of n1/n2 ==><%=n1/n2 %></h2>
</body>
</html>

//error.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page Attributes</title>
</head>
<body>
<h2>Value of n2 variable of zero (n/0 is infinity)</h2>
<h3> Sorry an exception occured!</h3><br/>
<h3> The exception is:   <%= exception%></h3>
</body>
</html>

Screen Shot




Sunday, 25 March 2018

jsp program to demonstrate include and farward


Write a JAVA JSP Program which uses jsp: include and jsp: forward action to display a Web page.
jsp:forward action tag with parameter

// index.jsp

<html> 
<body> 
<h2>this is index page</h2> 
 
<jsp:forward page="printdate.jsp " > 
<jsp:param name="name" value="javatpoint.com" /> 
</jsp:forward> 
 
</body> 
</html> 

Printdatejsp
<html> 
<body> 
 
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %> 

<%= request.getParameter("name") %> 
 
</body> 
</html>

jsp:include action tag without parameter

// index.jsp
<h2>this is index page</h2> 
 
<jsp:include page="printdate.jsp" /> 
 
<h2>end section of index page</h2> 

printdate.jsp

<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>



jsp to demonstrate import attribute

Write a JSP Program to demonstrate the import attributes..



//index.jsp
<%@ taglib uri="WEB-INF/tlds/mytags.tld" prefix="m" %> 
Cube of 4 is: <m:cube number="4"></m:cube> 

//CubeNumber.java
package reva; 
import javax.servlet.jsp.JspException; 
import javax.servlet.jsp.JspWriter; 
import javax.servlet.jsp.tagext.TagSupport; 
 
public class CubeNumber extends TagSupport{ 
private int number; 
     
public void setNumber(int number) { 
    this.number = number; 
} 
 
public int doStartTag() throws JspException { 
    JspWriter out=pageContext.getOut(); 
    try{ 
        out.print(number*number*number); 
    }catch(Exception e){e.printStackTrace();} 
      
    return SKIP_BODY;  } 
} 

//mytags.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
  <tlib-version>1.0</tlib-version>
  <short-name>mytags</short-name>
  <uri>/WEB-INF/tlds/mytags</uri>
   <description>A simple tab library for the examples</description> 
 
  <tag> 

    <name>cube</name> 
    <tag-class>reva.CubeNumber</tag-class> 
    <attribute> 
    <name>number</name> 
    <required>true</required> 
    </attribute> 
  </tag> 
</taglib>

output


PUBLISHER & SUBSCRIBER PATTERN

Using the UML Drawing Tool by implementing the code in Java demonstrate the Observer  Design Pattern. The Publisher-Subscriber desig...