Pointers #Programming Code Examples #Java/J2EE/J2ME #Ajax

/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
#include <algorithm>
#include <iostream>

using namespace std;

/* function that compares two pointers by comparing the values to which they po
int
 */
bool int_ptr_less (int* a, int* b)
{
    return *a < *b;
}

int main()
{
    int x = 17;
    int y = 42;
    int* px = &x;
    int* py = &y;
    int* pmax;

    // call max() with special comparison function
    pmax = max (px, py, int_ptr_less);
    cout << *pmax;
    //...
}

 /* 
42
 */       
    

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

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

C++ Template Example #Programming Code Examples #Java/J2EE/J2ME #Ajax

/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */

#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <string>
#include <algorithm>
#include <iterator>
#include <functional>
#include <numeric>

using namespace std;

/* PRINT_ELEMENTS()
 * - prints optional C-string optcstr followed by
 * - all elements of the collection coll
 * - separated by spaces
 */
template <class T>
inline void PRINT_ELEMENTS (const T& coll, const char* optcstr="")
{
    typename T::const_iterator pos;

    std::cout << optcstr;
    for (pos=coll.begin(); pos!=coll.end(); ++pos) {
        std::cout << *pos << ' ';
    }
    std::cout << std::endl;
}

/* INSERT_ELEMENTS (collection, first, last)
 * - fill values from first to last into the collection
 * - NOTE: NO half-open range
 */
template <class T>
inline void INSERT_ELEMENTS (T& coll, int first, int last)
{
    for (int i=first; i<=last; ++i) {
        coll.insert(coll.end(),i);
    }
}



// return whether the second object has double the value of the first
bool doubled (int elem1, int elem2)
{
   return elem1 * 2 == elem2;
}

int main()
{
   vector<int> coll;

   coll.push_back(1);
   coll.push_back(3);
   coll.push_back(2);
   coll.push_back(4);
   coll.push_back(5);
   coll.push_back(5);
   coll.push_back(0);

   PRINT_ELEMENTS(coll,"coll: ");

   // search first two elements with equal value
   vector<int>::iterator pos;
   pos = adjacent_find (coll.begin(), coll.end());

   if (pos != coll.end()) {
       cout << "first two elements with equal value have position "
            << distance(coll.begin(),pos) + 1
            << endl;
   }

}

/*
coll: 1 3 2 4 5 5 0
first two elements with equal value have position 5

 */

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

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

Valarray Example #Programming Code Examples #Java/J2EE/J2ME #Ajax

/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
#include <iostream>
#include <valarray>
using namespace std;

// print valarray
template <class T>
void printValarray (const valarray<T>& va)
{
    for (int i=0; i<va.size(); i++) {
        cout << va[i] << ' ';
    }
    cout << endl;
}

int main()
{
    // create and initialize valarray with nine elements
    valarray<double> va(9);
    for (int i=0; i<va.size(); i++) {
        va[i] = i * 1.1;
    }

    // print valarray
    printValarray(va);

    // double values in the valarray
    va *= 2.0;

    // print valarray again
    printValarray(va);

    // create second valarray initialized by the values of the first plus 10
    valarray<double> vb(va+10.0);

    // print second valarray
    printValarray(vb);

    // create third valarray as a result of processing both existing valarrays

    valarray<double> vc;
    vc = sqrt(va) + vb/2.0 - 1.0;

    // print third valarray
    printValarray(vc);
}

/*
0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8
0 2.2 4.4 6.6 8.8 11 13.2 15.4 17.6
10 12.2 14.4 16.6 18.8 21 23.2 25.4 27.6


 */

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

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

Javascript : Miscellaneous Code #Programming Code Examples #Java/J2EE/J2ME #Ajax

                var browser=navigator.appName;
                var b_version=navigator.appVersion;


<a href="http://www.justetc.net" target="_blank">
<img border="0" alt="hello" src="b_pink.gif" id="b1" width="26" height="26" onmouseover="mouseOver()" onmouseout="mouseOut()" />


Place the following code under script tag/in a javascript file function mouseOver() { document.getElementById("b1").src ="b_blue.gif"; } function mouseOut() { document.getElementById("b1").src ="b_pink.gif"; }

<map name="planetmap">

<area shape ="rect" coords ="0,0,82,126"
onMouseOver="writeText('You are over the target area')"
href ="target.htm" target ="_blank" alt="target" />
var t1=setTimeout("document.getElementById('id1').value='2 seconds!'",2000);
var t2=setTimeout("document.getElementById('id1').value='4 seconds!'",4000);
var t3=setTimeout("document.getElementById('id1').value='6 seconds!'",6000);
Direct Instance: 

pObj=new Object();
pObj.firstname="John";
pObj.lastname="Doe";
pObj.age=50;
pObj.eyecolor="blue";

document.write(pObj.firstname + " is " + pObj.age + " years 

function car(brand,make,model)
{
this.brand=brand;
this.make=make;
this.model=model;
}
var myCar=new car("Honda","2009","Accord");
document.write(myCar.brand +  myCar.make + myCar.model );
try
{
}
catch(err)
{
}

Under script tag/javascript file:

onerror=handleErr;
var alertTxt = "" 

function handleErr(msg, url, l)
{
   alertTxt = "Error Information:.nn";
   alertTxt += msg + "n";
   alertTxt += url + "n";
   alertTxt += l + "nn";
   alertTxt += "Click OK to continue.nn";
   alert(alertTxt);
   return true;
}


var x;
var myFriends= new Array();
myFriends[0] = "Shafiq";
myFriends[1] = "Rafiq";
myFriends[2] = "Abba";
myFriends[3] = "Amma";

for (x in myFriends)
{
   document.write(myFriends[x] + "
"); }
var d = new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
  document.write("Friday");
  break;
case 6:
  document.write("Saturday");
  break;
case 0:
  document.write("Sunday");
  break;
}
   var pattern = new RegExp("e","g");
   do
   {
     result=pattern .exec("This is the line where the regular expression will be searched on");
     document.write(result);
   }
   while (result!=null) 

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

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

Controlling Image Loading #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics

~~~~~~~~~~~~~~~~~~~
ImageBox.java A class that incorrectly tries to load an image and draw an outline around it. The problem is that the size of the image is requested before the image is completely loaded, thus, returning a width and height of -1.
~~~~~~~~~~~~~~~~~~~
import java.applet.Applet;
import java.awt.*;

/** A class that incorrectly tries to load an image and draw an
 *  outline around it. Don't try this at home.
 *
 ********************

public class ImageBox extends Applet {
  private int imageWidth, imageHeight;
  private Image image;

  public void init() {
    String imageName = getParameter("IMAGE");
    if (imageName != null) {
      image = getImage(getDocumentBase(), imageName);
    } else {
      image = getImage(getDocumentBase(), "error.gif");
    }
    setBackground(Color.white);

    // The following is wrong, since the image won't be done
    // loading, and -1 will be returned.
    imageWidth = image.getWidth(this);
    imageHeight = image.getHeight(this);
  }

  public void paint(Graphics g) {
    g.drawImage(image, 0, 0, this);
    g.drawRect(0, 0, imageWidth, imageHeight);
  }
}
>>>>>>>>>>>>>>>>>>
BetterImageBox.java An improved version of ImageBox.java. Here a MediaTracker is used to block (wait till the image is completely loaded) before preceding to determine the image size.
>>>>>>>>>>>>>>>>>>
import java.applet.Applet;
import java.awt.*;

/** This version fixes the problems associated with ImageBox by
 *  using a MediaTracker to be sure the image is loaded before
 *  you try to get its dimensions.
 *
 *********************************

public class BetterImageBox extends Applet {
  private int imageWidth, imageHeight;
  private Image image;

  public void init() {
    String imageName = getParameter("IMAGE");
    if (imageName != null) {
      image = getImage(getDocumentBase(), imageName);
    } else {
      image = getImage(getDocumentBase(), "error.gif");
    }
    setBackground(Color.white);
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(image, 0);
    try {
      tracker.waitForAll();
    } catch(InterruptedException ie) {}
    if (tracker.isErrorAny()) {
      System.out.println("Error while loading image");
    }

    // This is safe: image is fully loaded
    imageWidth = image.getWidth(this);
    imageHeight = image.getHeight(this);
  }

  public void paint(Graphics g) {
    g.drawImage(image, 0, 0, this);
    g.drawRect(0, 0, imageWidth, imageHeight);
  }
}
>>>>>>>>>>>>>>>>>
TrackerUtil.java A utility class that lets you load and wait for an image in a single swoop.
>>>>>>>>>>>>>>>>>
import java.awt.*;

/** A utility class that lets you load and wait for an image or
 *  images in one fell swoop. If you are loading multiple
 *  images, only use multiple calls to waitForImage if you
 *  need loading to be done serially. Otherwise, use
 *  waitForImages, which loads concurrently, which can be
 *  much faster.
 *
 *******************

public class TrackerUtil {
  public static boolean waitForImage(Image image, Component c) {
    MediaTracker tracker = new MediaTracker(c);
    tracker.addImage(image, 0);
    try {
      tracker.waitForAll();
    } catch(InterruptedException ie) {}
    if (tracker.isErrorAny()) {
      return(false);
    } else {
      return(true);
    }
  }

  public static boolean waitForImages(Image[] images,
                                      Component c) {
    MediaTracker tracker = new MediaTracker(c);
    for(int i=0; i>>>>>>>>>>>>>>>>>>>>>

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10385
Categories:Programming Code Examples, Java/J2EE/J2ME, Applets and Basic Graphics
Tags:Java/J2EE/J2MEApplets and Basic Graphics
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

Loading Images #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics

JavaMan1.java Applet that loads an image from a relative URL.
*************************************************************
import java.applet.Applet;
import java.awt.*;

/** An applet that loads an image from a relative URL. 
 *
>>>>>>>>>>>>>>>>>>>

public class JavaMan1 extends Applet {
  private Image javaMan;

  public void init() {
    javaMan = getImage(getCodeBase(),"images/Java-Man.gif");
  }

  public void paint(Graphics g) {
    g.drawImage(javaMan, 0, 0, this);
  }
}
>>>>>>>>>>>>>>>>>>>>
JavaMan2.java Illustrates loading an image from an absolute URL.
********************
import java.applet.Applet;
import java.awt.*;
import java.net.*;

/** An applet that loads an image from an absolute
 *  URL on the same machine that the applet came from.
 *
***********************

public class JavaMan2 extends Applet {
  private Image javaMan;

  public void init() {
    try {
      URL imageFile = new URL("http://www.corewebprogramming.com" +
                              "/images/Java-Man.gif");
      javaMan = getImage(imageFile);
    } catch(MalformedURLException mue) {
      showStatus("Bogus image URL.");
      System.out.println("Bogus URL");
    }
  }

  public void paint(Graphics g) {
    g.drawImage(javaMan, 0, 0, this);
  }
}
>>>>>>>>>>>>>>>>>>>>>
# JavaMan3.java An application that loads an image from a local file. Uses the following image and two files:

    * Java-Man.gif which should be placed in images subdirectory.
    * WindowUtilities.java Simplifies the setting of native look and feel.
    * ExitListener.java WindowListener to support terminating the application.
*******************
JavaMan3.java
*******************
import java.awt.*;
import javax.swing.*;

/** An application that loads an image from a local file. 
 *  Applets are not permitted to do this.
 *
**********************

class JavaMan3 extends JPanel {
  private Image javaMan;

  public JavaMan3() {
    String imageFile = System.getProperty("user.dir") +
                       "/images/Java-Man.gif";
    javaMan = getToolkit().getImage(imageFile);
    setBackground(Color.white);
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(javaMan, 0, 0, this);
  }
  
  public static void main(String[] args) {
    JPanel panel = new JavaMan3();
    WindowUtilities.setNativeLookAndFeel();
    WindowUtilities.openInJFrame(panel, 380, 390);
  }   
}
>>>>>>>>>>>>>>>>>>
Preload.java An application that demonstrates the effect of preloading an image before drawing. Specify -preload as a command-line argument to preload the image. In this case, the prepareImage method is called to immediately start a thread to load the image. Thus, the image is ready to display when the user later selects the Display Image button. 
>>>>>>>>>>>>>>>>>>>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;

/** A class that compares the time to draw an image preloaded
 *  (getImage, prepareImage, and drawImage) vs. regularly
 *  (getImage and drawImage).
 *  

* The answer you get the regular way is dependent on the * network speed and the size of the image, but if you assume * you load the applet "long" (compared to the time the image * loading requires) before pressing the button, the drawing * time in the preloaded version depends only on the speed of * the local machine. * ********************** public class Preload extends JPanel implements ActionListener { private JTextField timeField; private long start = 0; private boolean draw = false; private JButton button; private Image plate; public Preload(String imageFile, boolean preload) { setLayout(new BorderLayout()); button = new JButton("Display Image"); button.setFont(new Font("SansSerif", Font.BOLD, 24)); button.addActionListener(this); JPanel buttonPanel = new JPanel(); buttonPanel.add(button); timeField = new JTextField(25); timeField.setEditable(false); timeField.setFont(new Font("SansSerif", Font.BOLD, 24)); buttonPanel.add(timeField); add(buttonPanel, BorderLayout.SOUTH); registerImage(imageFile, preload); } /** No need to check which object caused this, * since the button is the only possibility. */ public void actionPerformed(ActionEvent event) { draw = true; start = System.currentTimeMillis(); repaint(); } // Do getImage, optionally starting the loading. private void registerImage(String imageFile, boolean preload) { try { plate = getToolkit().getImage(new URL(imageFile)); if (preload) { prepareImage(plate, this); } } catch(MalformedURLException mue) { System.out.println("Bad URL: " + mue); } } /** If button has been clicked, draw image and * show elapsed time. Otherwise, do nothing. */ public void paintComponent(Graphics g) { super.paintComponent(g); if (draw) { g.drawImage(plate, 0, 0, this); showTime(); } } // Show elapsed time in textfield. private void showTime() { timeField.setText("Elapsed Time: " + elapsedTime() + " seconds."); } // Time in seconds since button was clicked. private double elapsedTime() { double delta = (double)(System.currentTimeMillis() - start); return(delta/1000.0); } public static void main(String[] args) { JPanel preload; if (args.length == 0) { System.out.println("Must provide URL"); System.exit(0); } if (args.length == 2 && args[1].equals("-preload")) { preload = new Preload(args[0], true); } else { preload = new Preload(args[0], false); } WindowUtilities.setNativeLookAndFeel(); WindowUtilities.openInJFrame(preload, 1000, 750); } } < <<<<<<<<<<<<<<<<<

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10384
Categories:Programming Code Examples, Java/J2EE/J2ME, Applets and Basic Graphics
Tags:Java/J2EE/J2MEApplets and Basic Graphics
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

HelloWWW2.java Illustrates the ability of an applet to read parameters contained in the HTML document #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics

HelloWWW2.java Illustrates the ability of an applet to read parameters contained in the HTML document (PARAM element containing a NAME-VALUE pair).
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
import java.applet.Applet;
import java.awt.*;

*************************

public class HelloWWW2 extends Applet {
  public void init() {
    setFont(new Font("SansSerif", Font.BOLD, 30));
    Color background = Color.gray;
    Color foreground = Color.darkGray;
    String backgroundType = getParameter("BACKGROUND");
    if (backgroundType != null) {
      if (backgroundType.equalsIgnoreCase("LIGHT")) {
        background = Color.white;
        foreground = Color.black;
      } else if (backgroundType.equalsIgnoreCase("DARK")) {
        background = Color.black;
        foreground = Color.white;
      }
    }
    setBackground(background);
    setForeground(foreground);
  }

  public void paint(Graphics g) {
    g.drawString("Hello, World Wide Web.", 5, 35);
  }
}
>>>>>>>>>>>>>>>>>>>>>>>

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10383
Categories:Programming Code Examples, Java/J2EE/J2ME, Applets and Basic Graphics
Tags:Java/J2EE/J2MEApplets and Basic Graphics
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

Basic template for a Java applet #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics

AppletTemplate.java
>>>>>>>>>>>>>>>>>>>>
import java.applet.Applet;
import java.awt.*;

********************

public class AppletTemplate extends Applet {

  // Variable declarations.

  public void init() {
    // Variable initializations, image loading, etc.
  }

  public void paint(Graphics g) {
    // Drawing operations.
  }
}
>>>>>>>>>>>>>>>>>>>>>

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10382
Categories:Programming Code Examples, Java/J2EE/J2ME, Applets and Basic Graphics
Tags:Java/J2EE/J2MEApplets and Basic Graphics
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

An example Travel Site #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics


quick-search.html Front end to travel site

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Front end to travel servlet.

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
  <TITLE>Online Travel Quick Search</TITLE>
  <LINK REL=STYLESHEET
        HREF="travel-styles.css"
        TYPE="text/css">
</HEAD>
<BODY>
<BR>
<H1>Online Travel Quick Search</H1>
<FORM ACTION="/servlet/cwp.Travel" METHOD="POST">
<CENTER>
Email address: <INPUT TYPE="TEXT" NAME="emailAddress"><BR>
Password: <INPUT TYPE="PASSWORD" NAME="password" SIZE=10><BR>
Origin: <INPUT TYPE="TEXT" NAME="origin"><BR>
Destination: <INPUT TYPE="TEXT" NAME="destination"><BR>
Start date (MM/DD/YY):
  <INPUT TYPE="TEXT" NAME="startDate" SIZE=8><BR>
End date (MM/DD/YY):
  <INPUT TYPE="TEXT" NAME="endDate" SIZE=8><BR>
<P>
<TABLE CELLSPACING=1>
<TR>
  <TH> <IMG SRC="airplane.gif" WIDTH=100 HEIGHT=29
                 ALIGN="TOP" ALT="Book Flight"> 
  <TH> <IMG SRC="car.gif" WIDTH=100 HEIGHT=31
                 ALIGN="MIDDLE" ALT="Rent Car"> 
  <TH> <IMG SRC="bed.gif" WIDTH=100 HEIGHT=85
                 ALIGN="MIDDLE" ALT="Find Hotel"> 
  <TH> <IMG SRC="passport.gif" WIDTH=71 HEIGHT=100
                 ALIGN="MIDDLE" ALT="Edit Account"> 
<TR>
  <TH><SMALL>
      <INPUT TYPE="SUBMIT" NAME="flights" VALUE="Book Flight">
      </SMALL>
  <TH><SMALL>
      <INPUT TYPE="SUBMIT" NAME="cars" VALUE="Rent Car">
      </SMALL>
  <TH><SMALL>
      <INPUT TYPE="SUBMIT" NAME="hotels" VALUE="Find Hotel">
      </SMALL>
  <TH><SMALL>
      <INPUT TYPE="SUBMIT" NAME="account" VALUE="Edit Account">
      </SMALL>
</TABLE>
</CENTER>
</FORM>
<BR>
<P ALIGN="CENTER">
<B>Not yet a member? Get a free account
<A HREF="accounts.jsp">here</A>.</B></P>
</BODY>
</HTML>


Travel.java  Servlet used by travel site. Uses the MVC architecture in that servlet just does computation; all presentation done by JSP. Uses the TravelCustomer bean.




package cwp;

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

/** Top-level travel-processing servlet. This servlet sets up
 *  the customer data as a bean, then forwards the request
 *  to the airline booking page, the rental car reservation
 *  page, the hotel page, the existing account modification
 *  page, or the new account page.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class Travel extends HttpServlet {
  private TravelCustomer[] travelData;

  public void init() {
    travelData = TravelData.getTravelData();
  }

  /** Since password is being sent, use POST only. However,
   *  the use of POST means that you cannot forward
   *  the request to a static HTML page, since the forwarded
   *  request uses the same request method as the original
   *  one, and static pages cannot handle POST. Solution:
   *  have the "static" page be a JSP file that contains
   *  HTML only. That's what accounts.jsp is. The other
   *  JSP files really need to be dynamically generated,
   *  since they make use of the customer data.
   */

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    String emailAddress = request.getParameter("emailAddress");
    String password = request.getParameter("password");
    TravelCustomer customer =
      TravelCustomer.findCustomer(emailAddress, travelData);
    if ((customer == null) || (password == null) ||
        (!password.equals(customer.getPassword()))) {
      gotoPage("/travel/accounts.jsp", request, response);
    }
    // The methods that use the following parameters will
    // check for missing or malformed values.
    customer.setStartDate(request.getParameter("startDate"));
    customer.setEndDate(request.getParameter("endDate"));
    customer.setOrigin(request.getParameter("origin"));
    customer.setDestination(request.getParameter
                              ("destination"));
    HttpSession session = request.getSession(true);
    session.setAttribute("customer", customer);
    if (request.getParameter("flights") != null) {
      gotoPage("/travel/BookFlights.jsp",
               request, response);
    } else if (request.getParameter("cars") != null) {
      gotoPage("/travel/RentCars.jsp",
               request, response);
    } else if (request.getParameter("hotels") != null) {
      gotoPage("/travel/FindHotels.jsp",
               request, response);
    } else if (request.getParameter("cars") != null) {
      gotoPage("/travel/EditAccounts.jsp",
               request, response);
    } else {
      gotoPage("/travel/IllegalRequest.jsp",
               request, response);
    }
  }

  private void gotoPage(String address,
                        HttpServletRequest request,
                        HttpServletResponse response)
      throws ServletException, IOException {
    RequestDispatcher dispatcher =
      getServletContext().getRequestDispatcher(address);
    dispatcher.forward(request, response);
  }
}






TravelCustomer Bean

package cwp;

import java.util.*;
import java.text.*;

/** Describes a travel services customer. Implemented
 *  as a bean with some methods that return data in HTML
 *  format, suitable for access from JSP.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class TravelCustomer {
  private String emailAddress, password, firstName, lastName;
  private String creditCardName, creditCardNumber;
  private String phoneNumber, homeAddress;
  private String startDate, endDate;
  private String origin, destination;
  private FrequentFlyerInfo[] frequentFlyerData;
  private RentalCarInfo[] rentalCarData;
  private HotelInfo[] hotelData;

  public TravelCustomer(String emailAddress,
                        String password,
                        String firstName,
                        String lastName,
                        String creditCardName,
                        String creditCardNumber,
                        String phoneNumber,
                        String homeAddress,
                        FrequentFlyerInfo[] frequentFlyerData,
                        RentalCarInfo[] rentalCarData,
                        HotelInfo[] hotelData) {
    setEmailAddress(emailAddress);
    setPassword(password);
    setFirstName(firstName);
    setLastName(lastName);
    setCreditCardName(creditCardName);
    setCreditCardNumber(creditCardNumber);
    setPhoneNumber(phoneNumber);
    setHomeAddress(homeAddress);
    setStartDate(startDate);
    setEndDate(endDate);
    setFrequentFlyerData(frequentFlyerData);
    setRentalCarData(rentalCarData);
    setHotelData(hotelData);
  }

  public String getEmailAddress() {
    return(emailAddress);
  }

  public void setEmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
  }

  public String getPassword() {
    return(password);
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getFirstName() {
    return(firstName);
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return(lastName);
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getFullName() {
    return(getFirstName() + " " + getLastName());
  }

  public String getCreditCardName() {
    return(creditCardName);
  }

  public void setCreditCardName(String creditCardName) {
    this.creditCardName = creditCardName;
  }

  public String getCreditCardNumber() {
    return(creditCardNumber);
  }

  public void setCreditCardNumber(String creditCardNumber) {
    this.creditCardNumber = creditCardNumber;
  }

  public String getCreditCard() {
    String cardName = getCreditCardName();
    String cardNum = getCreditCardNumber();
    cardNum = cardNum.substring(cardNum.length() - 4);
    return(cardName + " (XXXX-XXXX-XXXX-" + cardNum + ")");
  }

  public String getPhoneNumber() {
    return(phoneNumber);
  }

  public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
  }

  public String getHomeAddress() {
    return(homeAddress);
  }

  public void setHomeAddress(String homeAddress) {
    this.homeAddress = homeAddress;
  }

  public String getStartDate() {
    return(startDate);
  }

  public void setStartDate(String startDate) {
    this.startDate = startDate;
  }

  public String getEndDate() {
    return(endDate);
  }

  public void setEndDate(String endDate) {
    this.endDate = endDate;
  }

  public String getOrigin() {
    return(origin);
  }

  public void setOrigin(String origin) {
    this.origin = origin;
  }

  public String getDestination() {
    return(destination);
  }

  public void setDestination(String destination) {
    this.destination = destination;
  }

  public FrequentFlyerInfo[] getFrequentFlyerData() {
    return(frequentFlyerData);
  }

  public void setFrequentFlyerData(FrequentFlyerInfo[]
                                   frequentFlyerData) {
    this.frequentFlyerData = frequentFlyerData;
  }

  public String getFrequentFlyerTable() {
    FrequentFlyerInfo[] frequentFlyerData =
      getFrequentFlyerData();
    if (frequentFlyerData.length == 0) {
      return("<I>No frequent flyer data recorded.</I>");
    } else {
      String table =
        "<TABLE>n" +
        "  <TR><TH>Airline<TH>Frequent Flyer Numbern";
      for(int i=0; i<frequentFlyerData.length; i++) {
        FrequentFlyerInfo info = frequentFlyerData[i];
        table = table +
                "<TR ALIGN="CENTER">" +
                "<TD>" + info.getAirlineName() +
                "<TD>" + info.getFrequentFlyerNumber() + "n";
      }
      table = table + "</TABLE>n";
      return(table);
    }
  }

  public RentalCarInfo[] getRentalCarData() {
    return(rentalCarData);
  }

  public void setRentalCarData(RentalCarInfo[] rentalCarData) {
    this.rentalCarData = rentalCarData;
  }

  public HotelInfo[] getHotelData() {
    return(hotelData);
  }

  public void setHotelData(HotelInfo[] hotelData) {
    this.hotelData = hotelData;
  }

  // This would be replaced by a database lookup
  // in a real application.

  public String getFlights() {
    String flightOrigin =
      replaceIfMissing(getOrigin(), "Nowhere");
    String flightDestination =
      replaceIfMissing(getDestination(), "Nowhere");
    Date today = new Date();
    DateFormat formatter =
      DateFormat.getDateInstance(DateFormat.MEDIUM);
    String dateString = formatter.format(today);
    String flightStartDate =
      replaceIfMissing(getStartDate(), dateString);
    String flightEndDate =
      replaceIfMissing(getEndDate(), dateString);
    String [][] flights =
      { { "Java Airways", "1522", "455.95", "Java, Indonesia",
          "Sun Microsystems", "9:00", "3:15" },
        { "Servlet Express", "2622", "505.95", "New Atlanta",
          "New Atlanta", "9:30", "4:15" },
        { "Geek Airlines", "3.14159", "675.00", "JHU",
          "MIT", "10:02:37", "2:22:19" } };
    String flightString = "";
    for(int i=0; i<flights.length; i++) {
      String[] flightInfo = flights[i];
      flightString =
        flightString + getFlightDescription(flightInfo[0],
                                            flightInfo[1],
                                            flightInfo[2],
                                            flightInfo[3],
                                            flightInfo[4],
                                            flightInfo[5],
                                            flightInfo[6],
                                            flightOrigin,
                                            flightDestination,
                                            flightStartDate,
                                            flightEndDate);
    }
    return(flightString);
  }

  private String getFlightDescription(String airline,
                                      String flightNum,
                                      String price,
                                      String stop1,
                                      String stop2,
                                      String time1,
                                      String time2,
                                      String flightOrigin,
                                      String flightDestination,
                                      String flightStartDate,
                                      String flightEndDate) {
    String flight =
      "<P><BR>n" +
      "<TABLE WIDTH="100%"><TR><TH CLASS="COLORED">n" +
      "<B>" + airline + " Flight " + flightNum +
      " ($" + price + ")</B></TABLE><BR>n" +
      "<B>Outgoing:</B> Leaves " + flightOrigin +
      " at " + time1 + " AM on " + flightStartDate +
      ", arriving in " + flightDestination +
      " at " + time2 + " PM (1 stop -- " + stop1 + ").n" +
      "<BR>n" +
      "<B>Return:</B> Leaves " + flightDestination +
      " at " + time1 + " AM on " + flightEndDate +
      ", arriving in " + flightOrigin +
      " at " + time2 + " PM (1 stop -- " + stop2 + ").n";
    return(flight);
  }

  private String replaceIfMissing(String value,
                                  String defaultValue) {
    if ((value != null) && (value.length() > 0)) {
      return(value);
    } else {
      return(defaultValue);
    }
  }

  public static TravelCustomer findCustomer
                                 (String emailAddress,
                                  TravelCustomer[] customers) {
    if (emailAddress == null) {
      return(null);
    }
    for(int i=0; i<customers.length; i++) {
      String custEmail = customers[i].getEmailAddress();
      if (emailAddress.equalsIgnoreCase(custEmail)) {
        return(customers[i]);
      }
    }
    return(null);
  }
}



BookFlights.jsp, RentCars.jsp, FindHotels.jsp, EditAccounts.jsp, and IllegalRequest.jsp Pages used by the Travel servlet to do its presentation.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Flight-finding page for travel example.

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
  <TITLE>Best Available Flights</TITLE>
  <LINK REL=STYLESHEET
        HREF="/travel/travel-styles.css"
        TYPE="text/css">
</HEAD>
<BODY>
<H1>Best Available Flights</H1>
<CENTER>
<jsp:useBean id="customer"
             class="cwp.TravelCustomer" 
             scope="session" />
Finding flights for
<jsp:getProperty name="customer" property="fullName" />
<P>
<jsp:getProperty name="customer" property="flights" />
<P><BR><HR><BR>
<FORM ACTION="/servlet/BookFlight">
<jsp:getProperty name="customer" 
                 property="frequentFlyerTable" />
<P>
<B>Credit Card:</B>
<jsp:getProperty name="customer" property="creditCard" />
<P>
<INPUT TYPE="SUBMIT" NAME="holdButton" VALUE="Hold for 24 Hrs">
<P>
<INPUT TYPE="SUBMIT" NAME="bookItButton" VALUE="Book It!">
</FORM>
</CENTER>
</BODY>
</HTML>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Car rental page not implemented -- see airline booking page.

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
  <TITLE>Not Implemented</TITLE>
  <LINK REL=STYLESHEET
        HREF="/travel/travel-styles.css"
        TYPE="text/css">
</HEAD>
<BODY>
<H1>Car Rental Page Not Implemented</H1>
<CENTER>
Hey, this is only an example. See the airline booking page.
</CENTER>
</BODY>
</HTML>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Hotel page not implemented -- see airline booking page.

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
  <TITLE>Not Implemented</TITLE>
  <LINK REL=STYLESHEET
        HREF="/travel/travel-styles.css"
        TYPE="text/css">
</HEAD>
<BODY>
<H1>Hotel Page Not Implemented</H1>
<CENTER>
Hey, this is only an example. See the airline booking page.
</CENTER>
</BODY>
</HTML>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Account page not implemented -- see airline booking page.

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
  <TITLE>Not Implemented</TITLE>
  <LINK REL=STYLESHEET
        HREF="/travel/travel-styles.css"
        TYPE="text/css">
</HEAD>
<BODY>
<H1>Accounts Page Not Implemented</H1>
<CENTER>
Hey, this is only an example. See the airline booking page.
</CENTER>
</BODY>
</HTML>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Illegal request at Travel Quick Search page.

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
  <TITLE>Illegal Request</TITLE>
  <LINK REL=STYLESHEET
        HREF="/travel/travel-styles.css"
        TYPE="text/css">
</HEAD>
<BODY>
<H1>Illegal Request</H1>
<CENTER>Please try again.</CENTER>
</BODY>
</HTML>


Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10289
Categories:Programming Code Examples, Java/J2EE/J2ME, Applets and Basic Graphics
Tags:Java/J2EE/J2MEApplets and Basic Graphics
Post Data:2017-01-02 16:04:31

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

ForwardSnippet.java Partial servlet illustrating how to use a RequestDispatcher to forward requests #Programming Code Examples #Java/J2EE/J2ME #Applets and Basic Graphics

ForwardSnippet.java Partial servlet illustrating how to use a RequestDispatcher to forward requests

public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
    throws ServletException, IOException {
  String operation = request.getParameter("operation");
  if (operation == null) {
    operation = "unknown";
  }
  if (operation.equals("operation1")) {
    gotoPage("/operations/presentation1.jsp",
             request, response);
  } else if (operation.equals("operation2")) {
    gotoPage("/operations/presentation2.jsp",
             request, response);
  } else {
    gotoPage("/operations/unknownRequestHandler.jsp",
             request, response);
  }
}

private void gotoPage(String address,
                      HttpServletRequest request,
                      HttpServletResponse response)
    throws ServletException, IOException {
  RequestDispatcher dispatcher =
    getServletContext().getRequestDispatcher(address);
  dispatcher.forward(request, response);
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10288
Categories:Programming Code Examples, Java/J2EE/J2ME, Applets and Basic Graphics
Tags:Java/J2EE/J2MEApplets and Basic Graphics
Post Data:2017-01-02 16:04:31

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