Home > Articles > Programming > Java

This chapter is from the book

RCX Bean

Now we need to create a JSP to interact with the bean. Don't worry if you are not familiar with JSP technology. In a nutshell, a JSP contains code that is executed on the server machine. The JSP code determines what the HTML code that is eventually sent to the client's browser looks like. JSP code can access Java classes on the server, just like regular Java, as long as it can access them somewhere in the CLASSPATH. In our example, we will be using the RCXBean class for communications with the RCX.

The bean uses no constructor, so all properties are set using methods. This includes the COM port the bean will use. If this method is not called before the bean is used, then the bean throws an exception from the JSP code (and the users see an exception on their Web page).

pc.irtower.comm.RCXBean 
  • public String getComPort()
    Returns a String representing the name of the COM port used by the bean.

  • public void setComPort(String value) throws IOException
    Change or set which COM port should be used for communication with the RCX.

    Parameters:

    value

    A String representing the COM port (e.g., COM1, /dev/ttyS0, or USB.

  • public void sendInt(int v) throws IOException
    Sends an int value as four bytes.

    Parameters:

    v

    The data.

  • public void send(byte b) throws IOException
    Sends a single byte value.

    Parameters:

    v

    The data.

  • public void send(byte[] b) throws IOException
    Sends an array of byte values.

    Parameters:

    v

    The data in the form of an array of bytes.

  • public byte receive() throws IOException
    Receives a single byte of data, will wait until one appears in the buffer.

  • public int receiveInt() throws IOException
    Receives an int value composed of four bytes.

  • public byte[] receive(int n) throws IOException
    Receive n bytes from the RCX.

    Parameters:

    n

    The number of bytes to receive, also determines the size of the array.

  • public synchronized void lock(Object o) throws IOException
    The lock() method creates a lock on the RCX bean. The RCX bean cannot be locked by another object before the free() method has been run. If lock() is called while it is already locked then the bean throws an IOException.

    Parameters:

    o

    The lock is bound to this object. It should therefore be unique for the thread.


    NOTE

    The lock() method does not prevent other threads from using the RCX bean!

  • public synchronized void free(Object o)
    Make the RCX bean available for other threads.

    Parameters:

    o

    The object that has the lock.

  • public void close()
    Close this RCX bean.

    WARNING

    For RCXBean to work with a JSP page, the CLASSPATH setting for leJOS must be accessible to the environment the Web server is running in. If you have set up CLASSPATH as a system variable, this is probably already working.

Because a Web page can be accessed simultaneously by many people on the Web, it is necessary to restrict access to the IR tower so only one person will access it at a time. The RCXBean uses two methods for restricting the use of the RCX bean: lock() and free(). The lock() method blocks other users from accessing the bean until free() is called. The rest of the JSP page is pretty standard, and is used for displaying an HTML page for the user to interact with (Figure 11–11). The following code can be entered in a simple text editor, or even in an IDE like JCreator. Keep in mind you should not attempt to compile it. Let's have a look at the code:

 1.  <%@ page contentType="text/html" language='java' import='pc.irtower.comm.*'%>
 2.  <jsp:useBean id='rcx' class='pc.irtower.comm.RCXBean' scope='application'>
 3.    <jsp:setProperty name='rcx' property='comPort' value='COM2'/>
 4.  </jsp:useBean>
 5.  <HTML>
 6.  <HEAD><TITLE>Russian Roulette</TITLE></HEAD>
 7.  <BODY>
 8.  Select the amount of time to spin the wheel.
 9.  Less than 800 means you are safe,
10.  greater than 800 means you have lost.
11.  <FORM>
12.    <SELECT name='SpinTime'>
13.      <OPTION value='1'>1 second
14.      <OPTION value='3'>3 seconds
15.      <OPTION value='5'>5 seconds
16.    </SELECT>
17.    <INPUT type='SUBMIT'>
18.  </FORM><BR>   
19.  <%   
20.    try {   
21.      String sensorIDString = request.getParameter("SpinTime");   
22.      if (sensorIDString != null) {
23.        int time = Integer.decode(sensorIDString).intValue();
24.        rcx.lock(request);   
25.        rcx.send((byte)time);
26.        int value = rcx.receiveInt();
27.        if(value < 800)   
28.        out.println("<b>"+value+"</b>"+"...click.");
29.        else   
30.          out.println("<b>"+value+"... BANG!</b>");
31.      }   
32.    } catch (NumberFormatException e) {
33.      out.println("The value of <code>time</code> is invalid.");   
34.    } finally {   
35.    rcx.free(request);   
36.    }   
37.  %>
38.  </body>
39.  </html>

Figure 11-11 The JSP page displayed in a browser.

Save this file with the name roulette.jsp. The file should be saved to the Resin doc directory, which is used to store the Web pages on the server. The very first line of code imports the packages used by the code—in this case pc.irtower.comm. The second and third lines define the JavaBean being used by the JSP, which is RCXBean. The bean is designated with a variable of rcx in the code. This is the variable name it is referred to by the JSP code. Because this is a bean, various parameters can be set, including the communications port (make sure this is set to the COM port your computer is using). The body of the HTML page contains a drop-down menu to select one of three options (Figure 11–11). Next comes the Java code, enclosed in the <% %> braces. As you can see, this is just regular Java code so it should be easy to understand what is happening in it. Now we just need one final component to run the project—a LEGO model.

NOTE

The root HTML directory for Resin can be changed in the resin.conf file located in the conf directory. The default setting is <app-dir>doc</app-dir>.

Step 1 The motor must be mounted on its back. Attach a wire brick to the motor with the wire facing downward. Attach a 2 _ 4 brick to the bottom of the motor.

Step 2 Attach the light sensor to the 2 __4 brick and add a 1 __2 brick with a hole to shield the sensor.

Step 3 Secure the sensor in place by placing two 1 __2 plates and 1 __2 bricks on each side of the sensor, then cap it off with a gray 2 __4 plate.

Step 4 Attach the green 3 ´ 6 plate without corners to a green 2 ´ 8 plate as shown in the diagram. Attach the 2 ´ 8 plate to a 40-tooth gear by placing the plate studs into the holes on the gear. Attach the gear to the motor axle.

Step 5 Place a black friction pin in the center hole of a 1 _ 8 beam and attach it to another 1 _ 8 beam. Attach the double beam to the back of the motor.

Step 6 Attach two gray 2 __2 plates to the double beam and attach two 1 __2 bricks with holes to the plate as shown.

Step 7 Insert black friction pins into the bottom holes of the double beam. Attach two more black friction pins in the 1 ´ 2 brick holes. Now attach the two 1 ´ 12 beams by clipping them onto friction pins.

Step 8 Attach support legs to the base as shown.

We're all ready to test out the project now. First, upload the Roulette class to the RCX brick and press the Run button. The brick should be in front of the IR tower, with the IR port facing the tower. Next, make sure the Resin Server is running and go to the following Web address in your browser:

      http://localhost/roulette.jsp
.

You should be presented with a Web page displaying an option to choose the delay time (Figure 11–11). Choose one and click Submit Query. At this point the green light should appear on the IR tower, and the arm will begin spinning. When the arm stops a sensor reading is sent back to the computer, and the Web page displays the sensor value as well as a win–lose message.

NOTE

If the Web page seems to freeze when you submit the value and the green light does not go on, this is almost a sure sign the COM port is not properly set. Edit the third line in the roulette.jsp file so the value is equal to the correct port.

NOTE

If the Web page returns an error message, it might indicate it was not able to access certain classes. Make sure your CLASSPATH environment variable is set to include jdk1.3.1\lib\comm.jar and lejos\lib\classes.jar.

Now that we know the Web page is working locally, why not try to get others to browse to it? First you'll need to connect to the Internet and find your IP address. Windows users can find this by going to a command prompt and typing

ipconfig 

Linux users can use a similar program in the super-user directory:

/sbin/ifconfig 

These commands bring up data that includes the IP Address. Record this number and call a friend. Have your friend go to your IP address and make sure he or she types the prefix http:// in the address line; for example:

http://255.255.255.255/roulette.jsp 

NOTE

If your computer is behind a firewall there may be problems contacting it. Also, some Internet connections use nonroutable or dynamic IPs that can cause connection problems.

NOTE

Not all code in the JSP file Roulette.jsp is sent to the client's Web browser. Only the HTML code (including scripting languages like JavaScript) makes it to the client. The JSP-related code is executed by the server, and it produces an HTML document to return to the client. Any code enclosed in <% %> braces, or using the JSP tag <jsp: .. /jsp: ..> will never be seen by a client. To view this, try going to View Source in your browser.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020