Code examples for interfaces #Programming Code Examples #Java/J2EE/J2ME #Object Oriented Programming

****************************
Code examples for interfaces:

    * Class1.java implements Interface1.java
    * Abstract Class2.java implements Interface1.java and Interface2.java
    * Class3.java extends abstract class Class2.java
    * Interface3.java extends Interface1.java and Interface2.java
***************************
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Class1.java 
~~~~~~~~~~~~~~~~~~~~~~~~~~~

// This class is not abstract, so it must provide 
// implementations of method1 and method2.

public class Class1 extends SomeClass
                    implements Interface1 {
  public ReturnType1 method1(ArgType1 arg) {
    someCodeHere();
    ...
  }
                      
  public ReturnType2 method2(ArgType2 arg) {
        someCodeHere();
    ...
  }

  ...
}
>>>>>>>>>>>>>>>>>>>>>>>>>>
~~~~~~~~~~~~~~~~~~~~~~~~~~
Interface1.java
~~~~~~~~~~~~~~~~~~~~~~~~~~
public interface Interface1 {
   ReturnType1 method1(ArgType1 arg);
  ReturnType2 method2(ArgType2 arg);
}
>>>>>>>>>>>>>>>>>>>>>>>>>>
~~~~~~~~~~~~~~~~~~~~~~~~~~
Abstract Class2.java implements Interface1.java and Interface2.java
~~~~~~~~~~~~~~~~~~~~~~~~~~
Class2.java 
~~~~~~~~~~~~~~~~~~~~~~~~~~

// This class is abstract, so does not have to provide
// implementations of the methods of Interface 1 and 2.

public abstract class Class2 extends SomeOtherClass
                             implements Interface1,
                                        Interface2 {
  ...
}
>>>>>>>>>>>>>>>>>>>>>>>>>
~~~~~~~~~~~~~~~~~~~~~~~~~
Interface2.java
~~~~~~~~~~~~~~~~~~~~~~~~~

public interface Interface2 {
  ReturnType3 method3(ArgType3 arg);
}
~~~~~~~~~~~~~~~~~~~~~~~~~
# Class3.java extends abstract class Class2.java 
~~~~~~~~~~~~~~~~~~~~~~~~~
Class3.java
>>>>>>>>>>>>>>>>>>>>>>>>>

// This class is not abstract, so it must provide
// implementations of method1, method2, and method3.

public class Class3 extends Class2 {
  public ReturnType1 method1(ArgType1 arg) {
    someCodeHere();
    ...
  }
                      
  public ReturnType2 method2(ArgType2 arg) {
       someCodeHere();
    ...
  }

  public ReturnType3 method3(ArgType3 arg) {
     someCodeHere();
    ...
  }

  ...
}
>>>>>>>>>>>>>>>>>>>>>>>
# Interface3.java extends Interface1.java and Interface2.java
>>>>>>>>>>>>>>>>>>>>>>>
~~~~~~~~~~~~~~~~~~~~~~
Interface3.java 
~~~~~~~~~~~~~~~~~~~~~~

// This interface has three methods (by inheritance) and 
// two constants.

public interface Interface3 extends Interface1,
                                    Interface2 {
  int MIN_VALUE = 0;
  int MAX_VALUE = 1000;
}
< <<<<<<<<<<<<<<<<<<<<

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10393
Categories:Programming Code Examples, Java/J2EE/J2ME, Object Oriented Programming
Tags:Java/J2EE/J2MEObject Oriented Programming
Post Data:2017-01-02 16:04:39

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Speedboat.java Illustrates inheritance from Ship class #Programming Code Examples #Java/J2EE/J2ME #Object Oriented Programming

*****************************
Speedboat.java Illustrates inheritance from Ship class. See SpeedboatTest.java for a test.
*****************************
/** A fast Ship. Red and going 20 knots by default. 
 *
 ***********************
public class Speedboat extends Ship {
  private String color = "red";

  /** Builds a red Speedboat going N at 20 knots. */
  
  public Speedboat(String name) {
    super(name);
    setSpeed(20);
  }

  /** Builds a speedboat with specified parameters. */
  
  public Speedboat(double x, double y, double speed,
                   double direction, String name,
                   String color) {
    super(x, y, speed, direction, name);
    setColor(color);
  }

  /** Report location. Override version from Ship. */
  
  public void printLocation() {
    System.out.print(getColor().toUpperCase() + " ");
    super.printLocation();
  }
  
  /** Gets the Speedboat's color. */
  
  public String getColor() {
    return(color);
  }

  /** Sets the Speedboat's color. */
  
  public void setColor(String colorName) {
    color = colorName;
  }
}
**********************
SpeedboatTest.java 
**********************
/** Try a couple of Speedboats and a regular Ship. 
 *
*****************************

public class SpeedboatTest {
  public static void main(String[] args) {
    Speedboat s1 = new Speedboat("Speedboat1");
    Speedboat s2 = new Speedboat(0.0, 0.0, 2.0, 135.0,
                                 "Speedboat2", "blue");
    Ship s3 = new Ship(0.0, 0.0, 2.0, 135.0, "Ship1");
    s1.move();
    s2.move();
    s3.move();
    s1.printLocation();
    s2.printLocation();
    s3.printLocation();
  }
}
*****************************

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10392
Categories:Programming Code Examples, Java/J2EE/J2ME, Object Oriented Programming
Tags:Java/J2EE/J2MEObject Oriented Programming
Post Data:2017-01-02 16:04:39

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

A Ship class illustrating object-oriented programming concepts #Programming Code Examples #Java/J2EE/J2ME #Object Oriented Programming

************************
Ship.java A Ship class illustrating object-oriented programming concepts. Incorporates Javadoc comments. See ShipTest.java for a test. 
************************
/** Ship example to demonstrate OOP in Java.
 *
 *  @author 
 *          Larry Brown
 *  @version 2.0
 */

public class Ship {
  // Instance variables

  private double x=0.0, y=0.0, speed=1.0, direction=0.0;
  private String name;

  // Constructors

  /** Build a ship with specified parameters. */

  public Ship(double x, double y, double speed,
              double direction, String name) {
    setX(x);
    setY(y);
    setSpeed(speed);
    setDirection(direction);
    setName(name);
  }

  /** Build a ship with default values
   *  (x=0, y=0, speed=1.0, direction=0.0).
   */

  public Ship(String name) {
    setName(name);
  }

  /** Move ship one step at current speed/direction. */

  public void move() {
    moveInternal(1);
  }

  /** Move N steps. */

  public void move(int steps) {
    moveInternal(steps);
  }

  private void moveInternal(int steps) {
    double angle = degreesToRadians(direction);
    x = x + (double)steps * speed * Math.cos(angle);
    y = y + (double)steps * speed * Math.sin(angle);
  }

  private double degreesToRadians(double degrees) {
    return(degrees * Math.PI / 180.0);
  }

  /** Report location to standard output. */

  public void printLocation() {
    System.out.println(getName() + " is at (" + getX() +
                       "," + getY() + ").");
  }

  /** Get current X location. */

  public double getX() {
    return(x);
  }

  /** Set current X location. */

  public void setX(double x) {
    this.x = x;
  }

  /** Get current Y location. */

  public double getY() {
    return(y);
  }

  /** Set current Y location. */

  public void setY(double y) {
    this.y = y;
  }

  /** Get current speed. */

  public double getSpeed() {
    return(speed);
  }

  /** Set current speed. */

  public void setSpeed(double speed) {
    this.speed = speed;
  }

  /** Get current heading (0=East, 90=North, 180=West,
   *  270=South).  I.e., uses standard math angles, not
   *  nautical system where 0=North, 90=East, etc.
   */

  public double getDirection() {
    return(direction);
  }

  /** Set current direction (0=East, 90=North, 180=West,
   *  270=South). I.e., uses standard math angles,not
   *  nautical system where 0=North,90=East, etc.
   */

  public void setDirection(double direction) {
    this.direction = direction;
  }

  /** Get Ship's name. Can't be modified by user. */

  public String getName() {
    return(name);
  }

  private void setName(String name) {
    this.name = name;
  }
}
*********************
ShipTest.java 
*********************
public class ShipTest {
 public static void main(String[] args) {
    Ship s1 = new Ship("Ship1"); 
    Ship s2 = new Ship(0.0, 0.0, 2.0, 135.0, "Ship2");
    s1.move();
    s2.move(3);
    s1.printLocation();
    s2.printLocation();
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10391
Categories:Programming Code Examples, Java/J2EE/J2ME, Object Oriented Programming
Tags:Java/J2EE/J2MEObject Oriented Programming
Post Data:2017-01-02 16:04:39

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Demonstrates overloading methods in class Ship4 #Programming Code Examples #Java/J2EE/J2ME #Object Oriented Programming

*********************
class Ship4 {
  public double x=0.0, y=0.0, speed=1.0, direction=0.0;
  public String name;

  // This constructor takes the parameters explicitly.
  
  public Ship4(double x, double y, double speed,
               double direction, String name) {
    this.x = x;
    this.y = y;
    this.speed = speed;
    this.direction = direction;
    this.name = name;
  }

  // This constructor requires a name but lets you accept
  // the default values for x, y, speed, and direction.

  public Ship4(String name) {
    this.name = name;
  }
  
  private double degreesToRadians(double degrees) {
    return(degrees * Math.PI / 180.0);
  }

  // Move one step.
  
  public void move() {
    move(1);
  }

  // Move N steps.

 public void move(int steps) {
    double angle = degreesToRadians(direction);
    x = x + (double)steps * speed * Math.cos(angle);
    y = y + (double)steps * speed * Math.sin(angle);
  }

  public void printLocation() {
    System.out.println(name + " is at (" + x + "," + y + ").");
  }
}

public class Test4 {
  public static void main(String[] args) {
    Ship4 s1 = new Ship4("Ship1"); 
    Ship4 s2 = new Ship4(0.0, 0.0, 2.0, 135.0, "Ship2");
    s1.move();
    s2.move(3);
    s1.printLocation();
    s2.printLocation();
  }
}
************************

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10390
Categories:Programming Code Examples, Java/J2EE/J2ME, Object Oriented Programming
Tags:Java/J2EE/J2MEObject Oriented Programming
Post Data:2017-01-02 16:04:39

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Accesses instance variables in a Ship object. #Programming Code Examples #Java/J2EE/J2ME #Object Oriented Programming

Test1.java Accesses instance variables in a Ship object. 
********************************************************

// Create a class with five instance variables (fields):
// x, y, speed, direction, and name. Note that Ship1 is 
// not declared "public", so it can be in the same file as
// Test1. A Java file can only contain one "public" class
// definition.

class Ship1 {
  public double x, y, speed, direction;
  public String name;
}

// The "driver" class containing "main".

public class Test1 {
  public static void main(String[] args) {
    Ship1 s1 = new Ship1();
    s1.x = 0.0;
    s1.y = 0.0;
    s1.speed = 1.0;
    s1.direction = 0.0;   // East
    s1.name = "Ship1";
    Ship1 s2 = new Ship1();
    s2.x = 0.0;
    s2.y = 0.0;
    s2.speed = 2.0;
    s2.direction = 135.0; // Northwest
    s2.name = "Ship2";
    s1.x = s1.x + s1.speed
           * Math.cos(s1.direction * Math.PI / 180.0);
    s1.y = s1.y + s1.speed
           * Math.sin(s1.direction * Math.PI / 180.0);
    s2.x = s2.x + s2.speed
           * Math.cos(s2.direction * Math.PI / 180.0);
    s2.y = s2.y + s2.speed
           * Math.sin(s2.direction * Math.PI / 180.0);
    System.out.println(s1.name + " is at ("
                       + s1.x + "," + s1.y + ").");
    System.out.println(s2.name + " is at ("
                       + s2.x + "," + s2.y + ").");
  }
}
**********************

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10387
Categories:Programming Code Examples, Java/J2EE/J2ME, Object Oriented Programming
Tags:Java/J2EE/J2MEObject Oriented Programming
Post Data:2017-01-02 16:04:39

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

ShowSession.java Servlet that uses session tracking to determine if the client is a repeat visitor. Uses the ServletUtilities class to simplify the DOCTYPE and HEAD output. #Programming Code Examples #Java/J2EE/J2ME #Servlet

ShowSession.java  Servlet that uses session tracking to determine if the client is a repeat visitor. Uses the ServletUtilities  class to simplify the DOCTYPE and HEAD output.


package cwp;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.util.*;

/** Simple example of session tracking.
 *  

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class ShowSession extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Session Tracking Example"; HttpSession session = request.getSession(true); String heading; Integer accessCount = (Integer)session.getAttribute("accessCount"); if (accessCount == null) { accessCount = new Integer(0); heading = "Welcome, Newcomer"; } else { heading = "Welcome Back"; accessCount = new Integer(accessCount.intValue() + 1); } // Use setAttribute instead of putValue in version 2.2. session.setAttribute("accessCount", accessCount); out.println(ServletUtilities.headWithTitle(title) + "n" + "

" + heading + "

n" + "

Information on Your Session:

n" + "n" + "n" + " n" + " n" + " n" + " n" + "
Info TypeValuen" + "
IDn" + " " + session.getId() + "n" + "
Creation Timen" + " " + new Date(session.getCreationTime()) + "n" + "
Time of Last Accessn" + " " + new Date(session.getLastAccessedTime()) + "n" + "
Number of Previous Accessesn" + " " + accessCount + "n" + "
n" + ""); } /** Handle GET and POST requests identically. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10255
Categories:Programming Code Examples, Java/J2EE/J2ME, Servlet
Tags:Java/J2EE/J2MEServlet
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

LongLivedCookie.java Subclass of Cookie that automatically sets the max age to one year. #Programming Code Examples #Java/J2EE/J2ME #Servlet

LongLivedCookie.java  Subclass of Cookie that automatically sets the max age to one year. 

package cwp;

import javax.servlet.http.*;

/** Cookie that persists 1 year. Default Cookie doesn't
 *  persist past current session.
 *  

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class LongLivedCookie extends Cookie { public static final int SECONDS_PER_YEAR = 60*60*24*365; public LongLivedCookie(String name, String value) { super(name, value); setMaxAge(SECONDS_PER_YEAR); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10254
Categories:Programming Code Examples, Java/J2EE/J2ME, Servlet
Tags:Java/J2EE/J2MEServlet
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

ShowCookies.java Servlet that displays all cookies that arrived in current request. Uses the ServletUtilities class. #Programming Code Examples #Java/J2EE/J2ME #Servlet


ShowCookies.java  Servlet that displays all cookies that arrived in current request. Uses the ServletUtilities  class. 

package cwp;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/** Sets six cookies: three that apply only to the current
 *  session (regardless of how long that session lasts)
 *  and three that persist for an hour (regardless of
 *  whether the browser is restarted).
 *  

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class SetCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { for(int i=0; i<3; i++) { // Default maxAge is -1, indicating cookie // applies only to current browsing session. Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-S" + i); response.addCookie(cookie); cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i); // Cookie is valid for an hour, regardless of whether // user quits browser, reboots computer, or whatever. cookie.setMaxAge(3600); response.addCookie(cookie); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Setting Cookies"; out.println (ServletUtilities.headWithTitle(title) + "n" + "

" + title + "

n" + "There are six cookies associated with this page.n" + "To see them, visit then" + "n" + "ShowCookies servlet.n" + "

n" + "Three of the cookies are associated only with then" + "current session, while three are persistent.n" + "Quit the browser, restart, and return to then" + "ShowCookies servlet to verify thatn" + "the three long-lived ones persist across sessions.n" + "

"); } } ServletUtilities.java package cwp; import javax.servlet.*; import javax.servlet.http.*; /** Some simple time savers. Note that most are static methods. *

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class ServletUtilities { public static final String DOCTYPE = ""; public static String headWithTitle(String title) { return(DOCTYPE + "n" + "n" + "" + title + "n"); } /** Read a parameter with the specified name, convert it * to an int, and return it. Return the designated default * value if the parameter doesn't exist or if it is an * illegal integer format. */ public static int getIntParameter(HttpServletRequest request, String paramName, int defaultValue) { String paramString = request.getParameter(paramName); int paramValue; try { paramValue = Integer.parseInt(paramString); } catch(NumberFormatException nfe) { // null or bad format paramValue = defaultValue; } return(paramValue); } /** Given an array of Cookies, a name, and a default value, * this method tries to find the value of the cookie with * the given name. If there is no cookie matching the name * in the array, then the default value is returned instead. */ public static String getCookieValue(Cookie[] cookies, String cookieName, String defaultValue) { if (cookies != null) { for(int i=0; i<cookies .length; i++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) return(cookie.getValue()); } } return(defaultValue); } /** Given an array of cookies and a name, this method tries * to find and return the cookie from the array that has * the given name. If there is no cookie matching the name * in the array, null is returned. */ public static Cookie getCookie(Cookie[] cookies, String cookieName) { if (cookies != null) { for(int i=0; i<cookies.length; i++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) return(cookie); } } return(null); } /** Given a string, this method replaces all occurrences of * '' with * '>', and (to handle cases that occur inside attribute * values), all occurrences of double quotes with * '"' and all occurrences of '&' with '&'. * Without such filtering, an arbitrary string * could not safely be inserted in a Web page. */ public static String filter(String input) { StringBuffer filtered = new StringBuffer(input.length()); char c; for(int i=0; i<input .length(); i++) { c = input.charAt(i); if (c == '') { filtered.append(">"); } else if (c == '"') { filtered.append("""); } else if (c == '&') { filtered.append("&"); } else { filtered.append(c); } } return(filtered.toString()); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10253
Categories:Programming Code Examples, Java/J2EE/J2ME, Servlet
Tags:Java/J2EE/J2MEServlet
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

SetCookies.java Servlet that sets a few persistent and session cookies. Uses the ServletUtilities class to simplify the DOCTYPE and HEAD output. #Programming Code Examples #Java/J2EE/J2ME #Servlet

SetCookies.java  Servlet that sets a few persistent and session cookies. Uses the ServletUtilities  class to simplify the DOCTYPE and HEAD output. 


package cwp;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/** Sets six cookies: three that apply only to the current
 *  session (regardless of how long that session lasts)
 *  and three that persist for an hour (regardless of
 *  whether the browser is restarted).
 *  

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class SetCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { for(int i=0; i<3; i++) { // Default maxAge is -1, indicating cookie // applies only to current browsing session. Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-S" + i); response.addCookie(cookie); cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i); // Cookie is valid for an hour, regardless of whether // user quits browser, reboots computer, or whatever. cookie.setMaxAge(3600); response.addCookie(cookie); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Setting Cookies"; out.println (ServletUtilities.headWithTitle(title) + "n" + "

" + title + "

n" + "There are six cookies associated with this page.n" + "To see them, visit then" + "n" + "ShowCookies servlet.n" + "

n" + "Three of the cookies are associated only with then" + "current session, while three are persistent.n" + "Quit the browser, restart, and return to then" + "ShowCookies servlet to verify thatn" + "the three long-lived ones persist across sessions.n" + "

"); } } ServletUtilities.java package cwp; import javax.servlet.*; import javax.servlet.http.*; /** Some simple time savers. Note that most are static methods. *

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class ServletUtilities { public static final String DOCTYPE = ""; public static String headWithTitle(String title) { return(DOCTYPE + "n" + "n" + "" + title + "n"); } /** Read a parameter with the specified name, convert it * to an int, and return it. Return the designated default * value if the parameter doesn't exist or if it is an * illegal integer format. */ public static int getIntParameter(HttpServletRequest request, String paramName, int defaultValue) { String paramString = request.getParameter(paramName); int paramValue; try { paramValue = Integer.parseInt(paramString); } catch(NumberFormatException nfe) { // null or bad format paramValue = defaultValue; } return(paramValue); } /** Given an array of Cookies, a name, and a default value, * this method tries to find the value of the cookie with * the given name. If there is no cookie matching the name * in the array, then the default value is returned instead. */ public static String getCookieValue(Cookie[] cookies, String cookieName, String defaultValue) { if (cookies != null) { for(int i=0; i<cookies .length; i++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) return(cookie.getValue()); } } return(defaultValue); } /** Given an array of cookies and a name, this method tries * to find and return the cookie from the array that has * the given name. If there is no cookie matching the name * in the array, null is returned. */ public static Cookie getCookie(Cookie[] cookies, String cookieName) { if (cookies != null) { for(int i=0; i<cookies.length; i++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) return(cookie); } } return(null); } /** Given a string, this method replaces all occurrences of * '' with * '>', and (to handle cases that occur inside attribute * values), all occurrences of double quotes with * '"' and all occurrences of '&' with '&'. * Without such filtering, an arbitrary string * could not safely be inserted in a Web page. */ public static String filter(String input) { StringBuffer filtered = new StringBuffer(input.length()); char c; for(int i=0; i<input .length(); i++) { c = input.charAt(i); if (c == '') { filtered.append(">"); } else if (c == '"') { filtered.append("""); } else if (c == '&') { filtered.append("&"); } else { filtered.append(c); } } return(filtered.toString()); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10252
Categories:Programming Code Examples, Java/J2EE/J2ME, Servlet
Tags:Java/J2EE/J2MEServlet
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

PrimeNumbers.java Servlet that processes a request to generate n prime numbers, each with at least m digits. If these results are not complete, it sends a Refresh header instructing the browser to ask for new results a little while later. Uses the Primes #Programming Code Examples #Java/J2EE/J2ME #Servlet

PrimeNumbers.java  Servlet that processes a request to generate n prime numbers, each with at least m digits. If these results are not complete, it sends a Refresh header instructing the browser to ask for new results a little while later. Uses the Primes, PrimeList, and ServletUtilities  classes.

package cwp;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

/** Servlet that processes a request to generate n
 *  prime numbers, each with at least m digits.
 *  It performs the calculations in a low-priority background
 *  thread, returning only the results it has found so far.
 *  If these results are not complete, it sends a Refresh
 *  header instructing the browser to ask for new results a
 *  little while later. It also maintains a list of a
 *  small number of previously calculated prime lists
 *  to return immediately to anyone who supplies the
 *  same n and m as a recent completed computation.
 *  

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class PrimeNumbers extends HttpServlet { private Vector primeListVector = new Vector(); private int maxPrimeLists = 30; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int numPrimes = ServletUtilities.getIntParameter(request, "numPrimes", 50); int numDigits = ServletUtilities.getIntParameter(request, "numDigits", 120); PrimeList primeList = findPrimeList(primeListVector, numPrimes, numDigits); if (primeList == null) { primeList = new PrimeList(numPrimes, numDigits, true); // Multiple servlet request threads share the instance // variables (fields) of PrimeNumbers. So // synchronize all access to servlet fields. synchronized(primeListVector) { if (primeListVector.size() >= maxPrimeLists) primeListVector.removeElementAt(0); primeListVector.addElement(primeList); } } Vector currentPrimes = primeList.getPrimes(); int numCurrentPrimes = currentPrimes.size(); int numPrimesRemaining = (numPrimes - numCurrentPrimes); boolean isLastResult = (numPrimesRemaining == 0); if (!isLastResult) { response.setHeader("Refresh", "5"); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Some " + numDigits + "-Digit Prime Numbers"; out.println(ServletUtilities.headWithTitle(title) + "n" + "

" + title + "

n" + "

Primes found with " + numDigits + " or more digits: " + numCurrentPrimes + ".

"); if (isLastResult) out.println("Done searching."); else out.println("Still looking for " + numPrimesRemaining + " more..."); out.println("
    "); for(int i=0; i<numcurrentprimes ; i++) { out.println("
  1. " + currentPrimes.elementAt(i)); } out.println("
"); out.println(""); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } // See if there is an existing ongoing or completed // calculation with the same number of primes and number // of digits per prime. If so, return those results instead // of starting a new background thread. Keep this list // small so that the Web server doesn't use too much memory. // Synchronize access to the list since there may be // multiple simultaneous requests. private PrimeList findPrimeList(Vector primeListVector, int numPrimes, int numDigits) { synchronized(primeListVector) { for(int i=0; i<primelistvector .size(); i++) { PrimeList primes = (PrimeList)primeListVector.elementAt(i); if ((numPrimes == primes.numPrimes()) && (numDigits == primes.numDigits())) return(primes); } return(null); } } } Primes.java package cwp; import java.math.BigInteger; /** A few utilities to generate a large random BigInteger, * and find the next prime number above a given BigInteger. *

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class Primes { // Note that BigInteger.ZERO was new in JDK 1.2, and 1.1 // code is being used to support the most servlet engines. private static final BigInteger ZERO = new BigInteger("0"); private static final BigInteger ONE = new BigInteger("1"); private static final BigInteger TWO = new BigInteger("2"); // Likelihood of false prime is less than 1/2^ERR_VAL // Assumedly BigInteger uses the Miller-Rabin test or // equivalent, and thus is NOT fooled by Carmichael numbers. // See section 33.8 of Cormen et al's Introduction to // Algorithms for details. private static final int ERR_VAL = 100; public static BigInteger nextPrime(BigInteger start) { if (isEven(start)) start = start.add(ONE); else start = start.add(TWO); if (start.isProbablePrime(ERR_VAL)) return(start); else return(nextPrime(start)); } private static boolean isEven(BigInteger n) { return(n.mod(TWO).equals(ZERO)); } private static StringBuffer[] digits = { new StringBuffer("0"), new StringBuffer("1"), new StringBuffer("2"), new StringBuffer("3"), new StringBuffer("4"), new StringBuffer("5"), new StringBuffer("6"), new StringBuffer("7"), new StringBuffer("8"), new StringBuffer("9") }; private static StringBuffer randomDigit() { int index = (int)Math.floor(Math.random() * 10); return(digits[index]); } public static BigInteger random(int numDigits) { StringBuffer s = new StringBuffer(""); for(int i=0; i 0) numDigits = Integer.parseInt(args[0]); else numDigits = 150; BigInteger start = random(numDigits); for(int i=0; i<50; i++) { start = nextPrime(start); System.out.println("Prime " + i + " = " + start); } } } PrimeList.java package cwp; import java.util.*; import java.math.BigInteger; /** Creates a Vector of large prime numbers, usually in * a low-priority background thread. Provides a few small * thread-safe access methods. *

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class PrimeList implements Runnable { private Vector primesFound; private int numPrimes, numDigits; /** Finds numPrimes prime numbers, each of which are * numDigits long or longer. You can set it to only * return when done, or have it return immediately, * and you can later poll it to see how far it * has gotten. */ public PrimeList(int numPrimes, int numDigits, boolean runInBackground) { // Using Vector instead of ArrayList // to support JDK 1.1 servlet engines primesFound = new Vector(numPrimes); this.numPrimes = numPrimes; this.numDigits = numDigits; if (runInBackground) { Thread t = new Thread(this); // Use low priority so you don't slow down server. t.setPriority(Thread.MIN_PRIORITY); t.start(); } else { run(); } } public void run() { BigInteger start = Primes.random(numDigits); for(int i=0; i<numprimes ; i++) { start = Primes.nextPrime(start); synchronized(this) { primesFound.addElement(start); } } } public synchronized boolean isDone() { return(primesFound.size() == numPrimes); } public synchronized Vector getPrimes() { if (isDone()) return(primesFound); else return((Vector)primesFound.clone()); } public int numDigits() { return(numDigits); } public int numPrimes() { return(numPrimes); } public synchronized int numCalculatedPrimes() { return(primesFound.size()); } } ServerUtilities.java package cwp; import javax.servlet.*; import javax.servlet.http.*; /** Some simple time savers. Note that most are static methods. *

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class ServletUtilities { public static final String DOCTYPE = ""; public static String headWithTitle(String title) { return(DOCTYPE + "n" + "n" + "" + title + "n"); } /** Read a parameter with the specified name, convert it * to an int, and return it. Return the designated default * value if the parameter doesn't exist or if it is an * illegal integer format. */ public static int getIntParameter(HttpServletRequest request, String paramName, int defaultValue) { String paramString = request.getParameter(paramName); int paramValue; try { paramValue = Integer.parseInt(paramString); } catch(NumberFormatException nfe) { // null or bad format paramValue = defaultValue; } return(paramValue); } /** Given an array of Cookies, a name, and a default value, * this method tries to find the value of the cookie with * the given name. If there is no cookie matching the name * in the array, then the default value is returned instead. */ public static String getCookieValue(Cookie[] cookies, String cookieName, String defaultValue) { if (cookies != null) { for(int i=0; i<cookies .length; i++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) return(cookie.getValue()); } } return(defaultValue); } /** Given an array of cookies and a name, this method tries * to find and return the cookie from the array that has * the given name. If there is no cookie matching the name * in the array, null is returned. */ public static Cookie getCookie(Cookie[] cookies, String cookieName) { if (cookies != null) { for(int i=0; i<cookies.length; i++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) return(cookie); } } return(null); } /** Given a string, this method replaces all occurrences of * '' with * '>', and (to handle cases that occur inside attribute * values), all occurrences of double quotes with * '"' and all occurrences of '&' with '&'. * Without such filtering, an arbitrary string * could not safely be inserted in a Web page. */ public static String filter(String input) { StringBuffer filtered = new StringBuffer(input.length()); char c; for(int i=0; i<input .length(); i++) { c = input.charAt(i); if (c == '') { filtered.append(">"); } else if (c == '"') { filtered.append("""); } else if (c == '&') { filtered.append("&"); } else { filtered.append(c); } } return(filtered.toString()); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10251
Categories:Programming Code Examples, Java/J2EE/J2ME, Servlet
Tags:Java/J2EE/J2MEServlet
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada