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

SearchEngines.java Servlet that redirects requests to various search engines. Uses the SearchSpec helper class. Accessed by means of SearchEngines.html. #Programming Code Examples #Java/J2EE/J2ME #Servlet

SearchEngines.java  Servlet that redirects requests to various search engines. Uses the SearchSpec  helper class. Accessed by means of SearchEngines.html. 

package cwp;

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

/** Servlet that takes a search string, number of results per
 *  page, and a search engine name, sending the query to
 *  that search engine. Illustrates manipulating
 *  the response status line. It sends a 302 response
 *  (via sendRedirect) if it gets a known search engine,
 *  and sends a 404 response (via sendError) otherwise.
 *  

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class SearchEngines extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String searchString = request.getParameter("searchString"); if ((searchString == null) || (searchString.length() == 0)) { reportProblem(response, "Missing search string."); return; } // The URLEncoder changes spaces to "+" signs and other // non-alphanumeric characters to "%XY", where XY is the // hex value of the ASCII (or ISO Latin-1) character. // Browsers always URL-encode form values, so the // getParameter method decodes automatically. But since // we're just passing this on to another server, we need to // re-encode it. searchString = URLEncoder.encode(searchString); String numResults = request.getParameter("numResults"); if ((numResults == null) || (numResults.equals("0")) || (numResults.length() == 0)) { numResults = "10"; } String searchEngine = request.getParameter("searchEngine"); if (searchEngine == null) { reportProblem(response, "Missing search engine name."); return; } SearchSpec[] commonSpecs = SearchSpec.getCommonSpecs(); for(int i=0; i<commonspecs .length; i++) { SearchSpec searchSpec = commonSpecs[i]; if (searchSpec.getName().equals(searchEngine)) { String url = searchSpec.makeURL(searchString, numResults); response.sendRedirect(url); return; } } reportProblem(response, "Unrecognized search engine."); } private void reportProblem(HttpServletResponse response, String message) throws IOException { response.sendError(response.SC_NOT_FOUND, "

" + message + ""); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } SearchSpec.java package cwp; /** Small class that encapsulates how to construct a * search string for a particular search engine. *

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * May be freely used or adapted. */ public class SearchSpec { private String name, baseURL, numResultsSuffix; private static SearchSpec[] commonSpecs = { new SearchSpec("google", "http://www.google.com/search?q=", "&num="), new SearchSpec("infoseek", "http://infoseek.go.com/Titles?qt=", "&nh="), new SearchSpec("lycos", "http://lycospro.lycos.com/cgi-bin/" + "pursuit?query=", "&maxhits="), new SearchSpec("hotbot", "http://www.hotbot.com/?MT=", "&DC=") }; public SearchSpec(String name, String baseURL, String numResultsSuffix) { this.name = name; this.baseURL = baseURL; this.numResultsSuffix = numResultsSuffix; } public String makeURL(String searchString, String numResults) { return(baseURL + searchString + numResultsSuffix + numResults); } public String getName() { return(name); } public static SearchSpec[] getCommonSpecs() { return(commonSpecs); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10250
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

EncodedPage.java Servlet that shows the bandwidth benefits of gzipping pages to browsers that can handle gzip. Uses the ServletUtilities class to simplify the DOCTYPE and HEAD output. #Programming Code Examples #Java/J2EE/J2ME #Servlet

EncodedPage.java  Servlet that shows the bandwidth benefits of gzipping pages to browsers that can handle gzip. 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.util.zip.*;

/** Example showing benefits of gzipping pages to browsers
 *  that can handle gzip.
 *  

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class EncodedPage extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String encodings = request.getHeader("Accept-Encoding"); String encodeFlag = request.getParameter("encoding"); PrintWriter out; String title; if ((encodings != null) && (encodings.indexOf("gzip") != -1) && !"none".equals(encodeFlag)) { title = "Page Encoded with GZip"; OutputStream out1 = response.getOutputStream(); out = new PrintWriter(new GZIPOutputStream(out1), false); response.setHeader("Content-Encoding", "gzip"); } else { title = "Unencoded Page"; out = response.getWriter(); } out.println(ServletUtilities.headWithTitle(title) + "n" + "

" + title + "

n"); String line = "Blah, blah, blah, blah, blah. " + "Yadda, yadda, yadda, yadda."; for(int i=0; i<10000; i++) { out.println(line); } out.println(""); out.close(); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10249
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

ShowRequestHeaders.java Servlet that shows all request headers sent by browser in current request. #Programming Code Examples #Java/J2EE/J2ME #Servlet

ShowRequestHeaders.java  Servlet that shows all request headers sent by browser in current request. 

package cwp;

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

/** Shows all the request headers sent on this request.
 *  

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class ShowRequestHeaders extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Servlet Example: Showing Request Headers"; out.println(ServletUtilities.headWithTitle(title) + "n" + "

" + title + "

n" + "Request Method: " + request.getMethod() + "
n" + "Request URI: " + request.getRequestURI() + "
n" + "Request Protocol: " + request.getProtocol() + "

n" + "n" + "n" + "
Header NameHeader Value"); Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String headerName = (String)headerNames.nextElement(); out.println("
" + headerName); out.println(" " + request.getHeader(headerName)); } out.println("
n"); } /** Let the same servlet handle both GET and POST. */ 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=10248
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