Category Archives: Java/J2EE/J2ME

Your first struts application #47

  • Check: http://www.coreservlets.com/Apache-Struts-Tutorial/Installing-Struts.html
  • Spring: Struts to spring migration with Hibernate and Unit testing support: Start with equinox application from http://sourcebeat.com/downloads/

From: http://sitestree.com/?p=4912
Categories:47
Tags:
Post Data:2013-06-13 10:32:35

    Shop Online: <a href='https://www.ShopForSoul.com/' target='new' rel="noopener">https://www.ShopForSoul.com/</a>
    (Big Data, Cloud, Security, Machine Learning): Courses: <a href='http://Training.SitesTree.com' target='new' rel="noopener"> http://Training.SitesTree.com</a> 
    In Bengali: <a href='http://Bangla.SaLearningSchool.com' target='new' rel="noopener">http://Bangla.SaLearningSchool.com</a>
    <a href='http://SitesTree.com' target='new' rel="noopener">http://SitesTree.com</a>
    8112223 Canada Inc./JustEtc: <a href='http://JustEtc.net' target='new' rel="noopener">http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning) </a>
    Shop Online: <a href='https://www.ShopForSoul.com'> https://www.ShopForSoul.com/</a>
    Medium: <a href='https://medium.com/@SayedAhmedCanada' target='new' rel="noopener"> https://medium.com/@SayedAhmedCanada </a>

A good resource for learning Struts #47

From: http://sitestree.com/?p=4960
Categories:47
Tags:
Post Data:2006-08-04 21:50:24

    Shop Online: <a href='https://www.ShopForSoul.com/' target='new' rel="noopener">https://www.ShopForSoul.com/</a>
    (Big Data, Cloud, Security, Machine Learning): Courses: <a href='http://Training.SitesTree.com' target='new' rel="noopener"> http://Training.SitesTree.com</a> 
    In Bengali: <a href='http://Bangla.SaLearningSchool.com' target='new' rel="noopener">http://Bangla.SaLearningSchool.com</a>
    <a href='http://SitesTree.com' target='new' rel="noopener">http://SitesTree.com</a>
    8112223 Canada Inc./JustEtc: <a href='http://JustEtc.net' target='new' rel="noopener">http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning) </a>
    Shop Online: <a href='https://www.ShopForSoul.com'> https://www.ShopForSoul.com/</a>
    Medium: <a href='https://medium.com/@SayedAhmedCanada' target='new' rel="noopener"> https://medium.com/@SayedAhmedCanada </a>

Struts: Radio Button : Form Bean:JSP #47

Once, I was having some issues with Struts: Radio Button : Form Bean:JSP. The following information helped me.

You usually specify the name of the form/form-bean when you declare a form bean in your struts-config.xml file like:

You can use a variable to point to this form using:

extract specific properties:

print them:

From: http://sitestree.com/?p=4842
Categories:47
Tags:
Post Data:2007-02-09 03:15:47

    Shop Online: <a href='https://www.ShopForSoul.com/' target='new' rel="noopener">https://www.ShopForSoul.com/</a>
    (Big Data, Cloud, Security, Machine Learning): Courses: <a href='http://Training.SitesTree.com' target='new' rel="noopener"> http://Training.SitesTree.com</a> 
    In Bengali: <a href='http://Bangla.SaLearningSchool.com' target='new' rel="noopener">http://Bangla.SaLearningSchool.com</a>
    <a href='http://SitesTree.com' target='new' rel="noopener">http://SitesTree.com</a>
    8112223 Canada Inc./JustEtc: <a href='http://JustEtc.net' target='new' rel="noopener">http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning) </a>
    Shop Online: <a href='https://www.ShopForSoul.com'> https://www.ShopForSoul.com/</a>
    Medium: <a href='https://medium.com/@SayedAhmedCanada' target='new' rel="noopener"> https://medium.com/@SayedAhmedCanada </a>

Struts: Application Development Approaches #47

Struts: Application Development Approaches

From: http://sitestree.com/?p=4825
Categories:47
Tags:
Post Data:2008-06-16 17:55:16

    Shop Online: <a href='https://www.ShopForSoul.com/' target='new' rel="noopener">https://www.ShopForSoul.com/</a>
    (Big Data, Cloud, Security, Machine Learning): Courses: <a href='http://Training.SitesTree.com' target='new' rel="noopener"> http://Training.SitesTree.com</a> 
    In Bengali: <a href='http://Bangla.SaLearningSchool.com' target='new' rel="noopener">http://Bangla.SaLearningSchool.com</a>
    <a href='http://SitesTree.com' target='new' rel="noopener">http://SitesTree.com</a>
    8112223 Canada Inc./JustEtc: <a href='http://JustEtc.net' target='new' rel="noopener">http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning) </a>
    Shop Online: <a href='https://www.ShopForSoul.com'> https://www.ShopForSoul.com/</a>
    Medium: <a href='https://medium.com/@SayedAhmedCanada' target='new' rel="noopener"> https://medium.com/@SayedAhmedCanada </a>

struts lesson 7 advanced struts actions #By Sayed Ahmed

From: http://sitestree.com/?p=2734
Categories:By Sayed Ahmed
Tags:
Post Data:2015-11-01 00:27:44

    Shop Online: <a href='https://www.ShopForSoul.com/' target='new' rel="noopener">https://www.ShopForSoul.com/</a>
    (Big Data, Cloud, Security, Machine Learning): Courses: <a href='http://Training.SitesTree.com' target='new' rel="noopener"> http://Training.SitesTree.com</a> 
    In Bengali: <a href='http://Bangla.SaLearningSchool.com' target='new' rel="noopener">http://Bangla.SaLearningSchool.com</a>
    <a href='http://SitesTree.com' target='new' rel="noopener">http://SitesTree.com</a>
    8112223 Canada Inc./JustEtc: <a href='http://JustEtc.net' target='new' rel="noopener">http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning) </a>
    Shop Online: <a href='https://www.ShopForSoul.com'> https://www.ShopForSoul.com/</a>
    Medium: <a href='https://medium.com/@SayedAhmedCanada' target='new' rel="noopener"> https://medium.com/@SayedAhmedCanada </a>

struts lesson 8 how to use properties file for internationalization and flexible message display #By Sayed Ahmed

From: http://sitestree.com/?p=2738
Categories:By Sayed Ahmed
Tags:
Post Data:2015-11-01 06:12:11

    Shop Online: <a href='https://www.ShopForSoul.com/' target='new' rel="noopener">https://www.ShopForSoul.com/</a>
    (Big Data, Cloud, Security, Machine Learning): Courses: <a href='http://Training.SitesTree.com' target='new' rel="noopener"> http://Training.SitesTree.com</a> 
    In Bengali: <a href='http://Bangla.SaLearningSchool.com' target='new' rel="noopener">http://Bangla.SaLearningSchool.com</a>
    <a href='http://SitesTree.com' target='new' rel="noopener">http://SitesTree.com</a>
    8112223 Canada Inc./JustEtc: <a href='http://JustEtc.net' target='new' rel="noopener">http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning) </a>
    Shop Online: <a href='https://www.ShopForSoul.com'> https://www.ShopForSoul.com/</a>
    Medium: <a href='https://medium.com/@SayedAhmedCanada' target='new' rel="noopener"> https://medium.com/@SayedAhmedCanada </a>

struts2 struts1 eclipse ant #By Sayed Ahmed

From: http://sitestree.com/?p=2740
Categories:By Sayed Ahmed
Tags:
Post Data:2015-11-01 12:13:30

    Shop Online: <a href='https://www.ShopForSoul.com/' target='new' rel="noopener">https://www.ShopForSoul.com/</a>
    (Big Data, Cloud, Security, Machine Learning): Courses: <a href='http://Training.SitesTree.com' target='new' rel="noopener"> http://Training.SitesTree.com</a> 
    In Bengali: <a href='http://Bangla.SaLearningSchool.com' target='new' rel="noopener">http://Bangla.SaLearningSchool.com</a>
    <a href='http://SitesTree.com' target='new' rel="noopener">http://SitesTree.com</a>
    8112223 Canada Inc./JustEtc: <a href='http://JustEtc.net' target='new' rel="noopener">http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning) </a>
    Shop Online: <a href='https://www.ShopForSoul.com'> https://www.ShopForSoul.com/</a>
    Medium: <a href='https://medium.com/@SayedAhmedCanada' target='new' rel="noopener"> https://medium.com/@SayedAhmedCanada </a>

struts2 struts1 eclipse ant 2 #By Sayed Ahmed

From: http://sitestree.com/?p=2742
Categories:By Sayed Ahmed
Tags:
Post Data:2015-11-01 18:15:10

    Shop Online: <a href='https://www.ShopForSoul.com/' target='new' rel="noopener">https://www.ShopForSoul.com/</a>
    (Big Data, Cloud, Security, Machine Learning): Courses: <a href='http://Training.SitesTree.com' target='new' rel="noopener"> http://Training.SitesTree.com</a> 
    In Bengali: <a href='http://Bangla.SaLearningSchool.com' target='new' rel="noopener">http://Bangla.SaLearningSchool.com</a>
    <a href='http://SitesTree.com' target='new' rel="noopener">http://SitesTree.com</a>
    8112223 Canada Inc./JustEtc: <a href='http://JustEtc.net' target='new' rel="noopener">http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning) </a>
    Shop Online: <a href='https://www.ShopForSoul.com'> https://www.ShopForSoul.com/</a>
    Medium: <a href='https://medium.com/@SayedAhmedCanada' target='new' rel="noopener"> https://medium.com/@SayedAhmedCanada </a>

Java spring application demo #By Sayed Ahmed

From: http://sitestree.com/?p=2414
Categories:By Sayed Ahmed
Tags:application, Java, spring, demo
Post Data:2015-10-09 08:30:54

    Shop Online: <a href='https://www.ShopForSoul.com/' target='new' rel="noopener">https://www.ShopForSoul.com/</a>
    (Big Data, Cloud, Security, Machine Learning): Courses: <a href='http://Training.SitesTree.com' target='new' rel="noopener"> http://Training.SitesTree.com</a> 
    In Bengali: <a href='http://Bangla.SaLearningSchool.com' target='new' rel="noopener">http://Bangla.SaLearningSchool.com</a>
    <a href='http://SitesTree.com' target='new' rel="noopener">http://SitesTree.com</a>
    8112223 Canada Inc./JustEtc: <a href='http://JustEtc.net' target='new' rel="noopener">http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning) </a>
    Shop Online: <a href='https://www.ShopForSoul.com'> https://www.ShopForSoul.com/</a>
    Medium: <a href='https://medium.com/@SayedAhmedCanada' target='new' rel="noopener"> https://medium.com/@SayedAhmedCanada </a>

Spring and iBatis: Some Notes [Will be updated later] #Java Short Notes

Implementing the data access layer of a Spring application using iBATIS.
Spring Framework and IBATIS

You can use JDBC with Spring for sure. Spring also simplifies the use of JDBC. iBATIS can provide one more step in simplification. Using iBATIS, you can mapdata and Java objects, also make use of simplified database operations.

Using iBatis with Spring involves three steps
Configuration: Configure various files at Data layer to be able to use iBatis
Mapping files: The mapping of the selected rows to the properties of the domain objects.
CRUD Operations: Learn how to use iBatis for select, delete, and update operations.

iBatis Notes:
allows the developer to write the custom SQL code they need to populate the bean properties
In a Spring iBATIS application, you need to configure the reference file and the mapping files.
org.springframework.orm.ibatis.SqlMapClientFactoryBean takes care of loading the configuration files.
You should not create and manage database transactions manually in the iBATIS mapping files. Always delegate the transaction management to Spring
In reference configuration file, you can list the sqlmap files.
You also need to use spring context file (applicationContext.xml ) that will link all configuration file together
it is a good idea to create a separate sqlMap file for each domain object.
Domain objects are POJOs
Mapping files for domains:

                                                         select * from Test     

Configuring iBATIS and Spring
Define the TestDao interface for example and its iBATIS implementation and then add the familiar dataSource bean.
Use the applicationContext.xml file to link the beans together.

usage in a sample application:
context = new ClassPathXmlApplicationContext("applicationContext.xml");
TestDao testDao = (TestDao)context.getBean("testDao");

Use select operation:
Add methods in the DAo as follows:
public List getAll() {
return getSqlMapClientTemplate().queryForList("getAllTests", null);
}

From: http://sitestree.com/?p=5154
Categories:Java Short Notes
Tags:
Post Data:2012-08-13 08:19:19

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

Topics to Learn in Java Spring framework #Java Short Notes

Why Spring Framework?

  • What's wrong with Java EE (EJB)
  • Light-weight vs. heavy-weight containers
  • Motivation for Spring
  • Spring Background

Spring Framework Overview

  • Spring features
  • Spring light-weight container architecture
  • Spring application context
  • Inversion of Control (IoC) design pattern
  • Dependency Injection (DI)
  • Advantages of IoC/DI
    • Design for testability
    • Low coupling
    • Code re-use
    • Consistent architecture and configuration
    • Easy-to-follow design
    • Good OOP

Spring Installation and Configuration

  • Spring libraries and dependancies
  • XML configuration files
  • Annotations

Spring IDE

  • Overview
  • Features
  • Installation
  • Editors, Wizards, Graphs, Views, Validators

Spring Persistence/DAO Support

  • Overview
  • JDBC
    • DataSources via JNDI
    • Templates
    • Exception Translators
    • Queries and updates
  • Hibernate ORM
    • Resource management and SessionFactory
    • Templates
    • Exception Translators
    • Transactions (intro to AOP)
    • API

Spring JMS

  • Overview
  • Templates
  • Connection, Destination, Transaction management
  • Sending and Receiving Messages (sync/async)
  • Listeners
  • Message-driven POJOs

Spring Testing

  • Unit Testing
  • Integration Testing
  • Mocks, Stubs, Fixtures
  • jUnit Integration
  • Spring TestContext Framework

Spring MVC and WebFlow

  • Overview
  • The DispatcherServlet
  • Configuration
  • Controllers: simple, form, multi-action
  • Views and view resolution: JSP/JSTL
  • Forms with Spring tag libraries
  • Data-binding, Property Editors, and Validation
  • I18N
  • Exception handling
  • Convention over configuration with annotation-driven controllers
  • Overview of Spring WebFlow
  • Integration with other frameworks - e.g. Sturts, JSF, Tapestry, WebWork (as requested)

Spring AOP

  • Overview
  • Concepts
  • Proxies
  • @AspectJ vs Spring AOP
  • API
  • Built-in aspects
  • Defining and using aspects

Spring Security (Acegi) Framework

  • Overview
  • Installation
  • Architecture
  • Configuration
  • Web Security
  • AOP-based security
  • Integration

Final Thoughts

  • Overview of Spring JMX
  • Overview of Spring Remoting
  • New features in Spring 2.5
  • Annotation vs. XML configuration (wiring)
  • Direction of Spring Framework
  • Best practices and architectural/design patterns

From: http://sitestree.com/?p=5119
Categories:Java Short Notes
Tags:
Post Data:2012-05-19 07:47:35

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

Java/J2EE:Important Resources: Struts, Spring, Hibernate, JPA #Java Short Notes

Java/J2EE:Important Resources: Struts, Spring, Hibernate, JPA ...... .... ..... .... ... ... ... ... ... ... .. ..
Struts

Spring, Hibernate, JPA

JSF

Servlets & JSP

Ajax, GWT, JavaScript

From: http://sitestree.com/?p=5116
Categories:Java Short Notes
Tags:
Post Data:2009-10-06 10:41:14

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

Java Spring: Web-application Development: Video Training: Step by Step #Java Short Notes

Code for this Tutorial

From: http://sitestree.com/?p=5069
Categories:Java Short Notes
Tags:
Post Data:2011-01-30 15:35:36

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

Lesson 7: Advanced Action Handling in Struts #Java Short Notes

From: http://sitestree.com/?p=5045
Categories:Java Short Notes
Tags:
Post Data:2011-04-21 13:19:47

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

What is Java Spring Framework? #Java Short Notes

According to the Spring Framework Reference Documentation (springframework.org):

"...Spring provides a light-weight solution for building enterprise-ready applications, while still supporting the possibility of using declarative transaction management, remote access to your logic using RMI or web services, mailing facilities and various options in persisting your data to a database. Spring provides an MVC framework, transparent ways of integrating AOP into your software and a well-structured exception hierarchy including automatic mapping from proprietary exception hierarchies.

Spring could potentially be a one-stop shop for all your enterprise applications, however, Spring is modular, allowing you to use parts of it, without having to bring in the rest..."

From: http://sitestree.com/?p=5020
Categories:Java Short Notes
Tags:
Post Data:2011-03-17 06:38:10

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

Struts 2 vs. Struts 1 #Java Short Notes

Please check the following resources:

From: http://sitestree.com/?p=4987
Categories:Java Short Notes
Tags:
Post Data:2008-11-22 05:09:37

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

Step By Step Video Tutorial: Struts-based Java Web Application Development #Java Short Notes

Please follow the link to see a list of training videos on Struts. And watch them.

From: http://sitestree.com/?p=4986
Categories:Java Short Notes
Tags:
Post Data:2010-06-21 20:35:21

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

Creating Java Development Environment with Struts for Your Home PC #Java Short Notes

Creating Java Development Environment with Struts for Your Home PC..........................

From: http://sitestree.com/?p=4985
Categories:Java Short Notes
Tags:
Post Data:2012-12-06 03:06: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

Java: Struts: Lesson 5: Processing Requests with Action Objects #Java Short Notes

Corresponding Video Tutorial
Code Example for this article

  • What happens? When a form is submitted?
  • Flow:
    1. Refer to a x.do from form action
    2. Check struts-config.xml for action named 'x'
    3. Check the corresponding type (class) of the action, execute the execute method of that action type (really a class where execute is the class method)
    4. The method will usually return a string using mapping.findForward("string"),
    5. Then the string will be matched in struts-config.xml file in the global forwards section or as part of the actions.
    6. In forwards a string is mapped to a destination web-page/action
  • Steps to write a simple application [one programmer]:
    1. Create the first web-page with the form [html/jsp]
    2. Create an action for the action string of this form in struts-config.xml file [mention the type/class, and corresponding forwards and specify the destination]
    3. The destination of a forward can be another action, forwards can be part of the action or can be placed in the global forwards section,
    4. Write the class and the corresponding execute method
    5. In the execute method you may require to collect the user supplied values/inputs, process the data and return a string using mapping.findForward based() on your logic/requirements.
    6. Create the destination pages.

From: http://sitestree.com/?p=4972
Categories:Java Short Notes
Tags:
Post Data:2013-03-27 11:44: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

A simple EJB 3.0 application: Explanation of EJB 3.0 technology: EJB => Spring Framework #Java Short Notes

A simple EJB 3.0 application: Explanation of EJB 3.0 technology: EJB => Spring Framework ....... .... ...

From: http://sitestree.com/?p=4933
Categories:Java Short Notes
Tags:
Post Data:2008-05-07 18:54: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

Writing your first Spring application #Java Short Notes

  • Requirements: JDK 1.4.2 (or above), Tomcat 5.0+, Ant 1.6.1+
  • Also, you can use cygwin in windows to emulate linux like commands
  • set JAVA_HOME, ANT_HOME, CATALINA_HOME environment variables - paths to the installed software
  • Add to PATH: JAVA_HOME/bin, ANT_HOME/bin, CATALINA_HOME/bin
  • You can start with the minimal application like struts-blanke.war or webapp-minimal that contains the basic files for struts and spring frameworks respectively. Or start with a equinox download from https://equinox.dev.java.net/files/documents/1901/5728/equinox-1.0.zip that will simplify strut-spring integration/switching. Download and unzip
  • Make sure that the environment variables are set properly. Take a look at build.xml file. Check different sections like compile, distribution, ant-tomcat, help, database
  • run ant new -Dapp.name=users from windows/linux/cygwin command prompt. It will create a new application with name users.
  • Check the directory structure. It should look like as follows:
  • under newly created users directory run commands like ant and check output. In build.xml, change default="help" to default="compile", run ant again, run ant deploy, play with different ant commands
  • if ant command shows error messages then you may need to change build.xml file as indicated. With equinox, you may face path error like {...}/common/lib or {...} lib
  • If things don't work right, check build.properties and modify the options if required. Play again
  • Also, check tomcatTasks.properties file to see what classes are used for different ant commands (used in the build.xml file)
  • Run ant list to check the services running. if the command fails, check that build.properties file contains right information. Make sure tomcat-users.xml file under the Tomcat installation directory has an entry for users as provided in the build.properties file
  • Make sure, you are under the users directory
  • run: ant deploy : the users application will be deployed under Tomcat. Check target name=deploy section in your build.xml file. You will see what actually happens in deployment (mostly copy)
  • Using your browser, go to: http://localhost:8080/users/, you will see the interface of the users application
  • Unit Test Persistence Layer
  • Hibernate for persistence
  • Hibernate relates Java Objects to database tables, makes CRUD (Create, Read, Update, Delete) very easy
  • Spring + Hibernate: 75% code reduction than Hibernate alone: [ref:Internet, sourcebeat.com]
  • Spring + Hibernate: removal of a ServiceLocator, removal of several DAOFactory classes, replace Hibernate's checked exceptions with Spring's runtime exceptions
  • Before proceeding further, you may want to open the application using Eclipse. You can also use any editor to create Java files.
  • Eclipse 3.3.2: How to open the project: File->new->project->java->java project->create project from existing source->identify the location and provide project name as users->you may want to switch to java perspectives.
  • Click on build.xml file. Right click -> run as -> 2 Ant Build. If compilation fails: change basedir to the application directory. If it fails again check, tomcat directories and the directories mentioned in the build.xml files are the same. [you may not need /server in build.xml for tomcat 6.o]
  • Check: build.xml -> right click -> Run As -> 3. Ant Build -> check that you selected the operation you want. If you want to deploy your application after compilation you need to select compile, deploy. Check what else apply. Or you can use the ant command [with options] from the command prompt
  • Now Hibernate and Persistence again:

From: http://sitestree.com/?p=4924
Categories:Java Short Notes
Tags:
Post Data:2006-12-25 08:52:32

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

Your First Spring+Hibernate Application in IntelliJ #Java Short Notes

From: http://sitestree.com/?p=4926
Categories:Java Short Notes
Tags:
Post Data:2006-08-17 07:59:04

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

Java Spring Topics: What spring framework brings to the table #Java Short Notes

Java Spring Topics
Knowing the buzzwords does not make anyone a good developer. However, it helps. Being expert in a technology like Spring in one day is not possible, but initially getting familiar with all the aspects is helpful as you will know which Spring feature is required to solve the current problem/situation. Then you can just explore and use that feature. It can always help the software engineers/software architects/project managers/product managers - as it will help to select technologies to use.

  • Traditional way of resolving dependencies - binding interfaces to implementations using a Factory Pattern: Spring does it all using XML.
  • How to write a simple Spring web application: Struts MVC as the front-end, Spring as the middle-tier, Hibernate for the back-end.
  • BeanFactory: the heart of Spring. Topics to learn: BeanFactory Life Cycle, bean definitions, bean properties, dependencies, autowiring, making singleton beans versus prototypes, inversion of control
  • Spring MVC framework: DispatcherServlet, various controllers, handler mappings, view resolvers, validation and internationalization, Spring's JSP tags
  • Advanced MVC: validation and page decoration, Tiles and SiteMesh to decorate a web application, handling validation and using it in the web business layers, handling exceptions in the control layers, upload files, and send emails
  • View Options: JSP, Velocity, FreeMarker, XSLT, PDF and Excel
  • JasperReports: open source Java reporting tool, excellent tool for rendering printable pages. Supports: PDF, HTML, XLS, CSV, XML
  • Persistence Strategies: Hibernate, JDBC or iBATIS (if database or pre-written sqls are already there)
  • Testing Spring Applications: test-driven spring development. Tools: Easy-Mock, jMock, DBUnit. Controller testing: Cactus for in-container testing, Spring Mocks for Out of container testing. jWebUnit and Canoo's WebTest for testing web interface
  • AOP: Aspect Oriented Programming
  • Transactions: How spring simplifies declarative and programmatic transactions
  • How to integrate other web-framework into Spring. Web-frameworks: JSF, Struts, Tapestry, WebWork
  • Security: Authentication and authorization using traditional container managed J2EE security features and Acegi Security Framework for Spring. Acegi: protect and prevent method invocations on Spring managed beans, configure Access Control Lists (ACLs)
  • Advanced Form Processing: Using forms and handling common issues (handling non-String types like Integer, Date, and Boolean, drop down lists, check boxes, editing nested objects). Multi-page forms: AbstractWizardFormController, Spring Web Flow

From: http://sitestree.com/?p=4921
Categories:Java Short Notes
Tags:
Post Data:2010-05-08 00:57:04

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

Introduction to Spring #Java Short Notes

  • Open-sourced on February, 2003
  • Layered J2EE application framework
  • Inversion of Control (IoC): A Data Access Object (DAO) depends on a DataSource.
  • Allows: code to interfaces
  • Spring has classes to support Hibernate, Struts, and other frameworks
  • According to many Java developers [ref:internet], J2EE patterns are sometimes cumbersome. Spring uses patterns but made everything simpler
  • ServiceLocator -> to lookup Hibernate sessions. Spring Alternative: configure a SessionFactory
  • Spring provides/supports good programming practices such as, coding to interfaces, reducing coupling, easy testability.
  • But EJBs require to run EJB containers (WebLogic, JBoss, Websphere) to test them [testability problems inherent in EJBs] [as of 2005]
  • Over the time EJB [EJB 3.0 ] has recovered some of the issues like testability, portability [ 1. EJB 2.0 has deployment descriptors but EJB 3.0 has no deployment descriptor, 2. In EJB 2.0 you have to write Home and Remote Interfaces But in EJB3.0 you do not need to write Home interfaces, 3. In EJB 3.0, all entities are identified with '@', 4. In EJB 3.0 methods like ejbPassivate, ejbActivate, ejbLoad, ejbStore, etc. are not required, 5. EJB 3.0 is totally newly designed including the entity manager, 6. EJB 3.0 entity beans are just POJO, 7. No EJB container required to run, 8. EJB 3.0 supports Java Persistence API for all of its data needs, 9. No XMLDeployment Descriptors but annotations, 10. EJB 3.0 entity beans/JPA becomes local, 11. Queries are very flexible. Multiple levels of joins are enabled, 12. EJB 3.0 pluggable, security enabled ]
  • Spring Criticisms [as of 2005]: It's not an standard like EJBs, too heavyweight (though custom selection of modules/jars will help)
  • How Spring works: Spring can configure applications using JavaBeans. A class can expose it's dependency through setters, Spring can configure that dependency.
  • Inversion of Control/Dependency Injection: Wiring dependent objects together through a container
  • Spring Modules: Spring AOP (source level metadata), ORM (Hibernate, iBATIS, JDO support), Spring Web (WebApplicationContext, MultipartResolver, Web Utilities), DAO (Transaction Infrastructure, JDBC, DAO support), Context (ApplicationContext, UI Support, Validation, JNDI, EJB, Remoting support, Mail), MVC (Web Framework, Web Views, JSP, Velocity, Freemarker, PDF, Excel, XML/XSL)
  • Spring advantage over J2EE: Reducing Coupling: It's better not to tightly couple any application to a specific resource. In J2EE, for database operations typically an abstract Factory class (DAOFactory) is defined and a class is written for each specific implementation (DAOFactoryOracle). [J2EE Factory Pattern]. It creates additional issues such as managing dependencies of these factoried objects, handling Hibernate Session
  • Spring approach: bind interfaces to implementations, configure everything in an XML file, and modify the XML file as required for switching, unit tests can be written without the knowledge of the implementation [great with Hibernate and iBATIS] p30. Define the bean in the applicationContext.xml file, and use it from your code through ClassPathXmlApplicationContext, get a reference to the bean using ClassPathXmlApplicationContext.getBean. You can change the class property in the bean definition to use a different implementation
  • You can use Hibernate from Spring (ORM support). If you go through wrapping classes of Spring to provide Hibernate functionalities, you will not require to worry about (try, catch) checked exceptions that Hibernate usually throws

From: http://sitestree.com/?p=4923
Categories:Java Short Notes
Tags:
Post Data:2006-10-26 16:03:22

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

Spring Applications: Examples #Java Short Notes

From: http://sitestree.com/?p=4913
Categories:Java Short Notes
Tags:
Post Data:2006-11-11 03:02:48

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

Spring Resources #Java Short Notes

From: http://sitestree.com/?p=4914
Categories:Java Short Notes
Tags:
Post Data:2009-04-21 06:03:06

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

What is Spring Framework? What does it mean to J2EE developers #Java Short Notes

What is Spring Framework? What does it mean to J2EE developers?

Spring is a light-weight framework, very often referred as an alternative/competitor to EJB, for the development of enterprise-type applications.

Spring provides many features such as declarative transaction management, access to remote logic using RMI or web services, mailing facilities and

database abstraction.

Features of Spring Framework

  1. Transaction Management: A generic abstraction layer for transaction management that removes low-level interactions
  2. JDBC Exception Handling: An exception hierarchy to simplify the error handling strategy
  3. Integration with Hibernate, JDO, and iBATIS
  4. AOP Framework: Aspect Oriented Programming Framework
  5. MVC Framework: Spring provides MVC web application framework built on core Spring functionality

Spring Architecture

  1. Spring AOP: Provides declarative enterprise services such as declarative transaction management
  2. Spring ORM: Provides integration layers for object-relational mapping APIs, including JDO, Hibernate and iBatis for database access.
  3. Spring Web: Provides web application development stack that includes Spring MVC.
  4. Spring DAO: Provides standardization to data access using the technologies like JDBC, Hibernate or JDO.
  5. Spring Context: Provides support for using message sources, and resources. It is based on Java bean.
  6. Spring Web MVC: Provides MVC for web applications.
  7. Spring Core: Provides Dependency Injection features

From: http://sitestree.com/?p=4828
Categories:Java Short Notes
Tags:
Post Data:2007-09-08 00:28:07

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

MVC : Struts : Java : Industry Web Application #Java Short Notes

Industries use frameworks for application development quite often. For example: Java concepts like JSP, Servlet, Swing, Bean, JDBC can be used directly to create web-applications but when such applications become big, it becomes difficult to maintain and develop them further. Hence, frameworks like struts are used to develop large web-based Java applications. This makes maintenance and further development easier. If you need to write a very simple web application with a few pages, then you might consider using JSP/Servlet directly otherwise Struts like frameworks are better options.Struts-1 uses the concept Model View Architecture (MVC) and provides the controller. In MVC model, Model represents business logic, View represents user interfaces, and Controller represents/controls control flow of the application. Struts' control layer is based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Apache Commons  packages, like BeanUtils and Chain of Responsibility. For the Model,  struts-1 framework can interact with standard data access technologies, like JDBC  and EJB,  as well as most any third-party packages, like Hibernate,  iBATIS,  or Object Relational Bridge.  For the View,  the framework works well with JavaServer Pages,  including JSTL and JSF,  as well as  Velocity Templates,  XSLT,  and other presentation systems.The framework's Controller acts as a bridge between the application's Model and the web View. When a request is received, the Controller invokes an Action  class. The Action class consults with the Model to examine or update the application's state. The framework provides an ActionForm  class to help transfer data between Model and View.Struts-1 Configuration-----------------------web.xml is one of the configuration files. It is an XML-formatted file that works as a deployment descriptor. struts-config.xml is another resource file to initialize the applications resources. These resources include  ActionForms  to collect input from users,  ActionMappings  to direct input to server-side  Actions,  and ActionForwards to select output pages.Sample struts-config.xml file.                                                                                                                                                                                        Other resources like Validators can be initialized here.

From: http://sitestree.com/?p=4787
Categories:Java Short Notes
Tags:
Post Data:2010-03-13 02:59:40

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

Lesson 1: Java Spring Step by Step #Java Short Notes #Java Spring

Lesson 1: Java Spring Step by Step .... .... ... ... ... ... ... ... ... ... .... .... .... .... .... ....

From: http://sitestree.com/?p=5023
Categories:Java Short Notes, Java Spring
Tags:
Post Data:2010-09-07 19:59:49

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

Java Spring: Components for Web #Java #Spring #Spring Framework and Hibernate #Spring #Spring Framework and Hibernate

Java Spring: Components for Web

Full-stack web development with Tomcat and Spring MVC
Reactive web development with Netty and Spring WebFlux: requires Spring Boot >=2.0.0.M1
Websocket development with SockJS and STOMP
Contract-first SOAP service development with Spring Web Services
RESTful Web Services framework with support of JAX-RS
RESTful Web Services framework with support of JAX-RS
Spring Boot integration for the Ratpack framework
Vaadin java web application framework
Exposing Spring Data repositories over REST via spring-data-rest-webmvc
HATEOAS-based RESTful services
Browsing Spring Data REST repositories in your browser
Simplify the development of mobile web applications with spring-mobile
Document RESTful services by combining hand-written and auto-generated documentation
Stormpath default starter including Spring MVC, Thymeleaf and Spring Security: requires Spring Boot >=1.5.0.RC1 and <2.0.0.M1
Keycloak integration, an open source Identity and Access Management solution.: requires Spring Boot >=1.5.3.RELEASE and <2.0.0.M1

From: http://sitestree.com/?p=10914
Categories:Java, Spring, Spring Framework and Hibernate, Spring, Spring Framework and Hibernate
Tags:
Post Data:2017-07-28 21:58:25

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

Java Spring: Use Cases #Java #Java Frameworks #Spring #Spring Framework and Hibernate

Reference: https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/overview.html

 

Typical full-fledged Spring web application

 

 

Spring middle-tier using a third-party web framework

 

Remoting usage scenario

 

EJBs - Wrapping existing POJOs

 

 

  From: http://sitestree.com/?p=10900
Categories:Java, Java Frameworks, Spring, Spring Framework and Hibernate
Tags:
Post Data:2017-07-28 20:42: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

Placement of buttons in a BoxLayout using rigid areas, struts, and glue #Programming Code Examples #Java/J2EE/J2ME #Layout Managers

###############
InvisibleComponentTest.java Placement of buttons in a BoxLayout using rigid areas, struts, and glue
###############
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

/** Example of using rigid areas, struts, and glue to
 *  produce the effect of invisible components.
 *
 ******************

public class InvisibleComponentTest extends JPanel {
  Component spacer;

  public InvisibleComponentTest() {
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    // Place a rigid invisible component 25 pixels wide and
    // 75 pixels tall between the two buttons
    JPanel p1= new JPanel();
    spacer = Box.createRigidArea(new Dimension(20,75));
    setUpPanel(p1, "Rigid Area - 20x75 pixels", spacer);

    // Separate two buttons by a 60-pixel horizontal strut
    JPanel p2= new JPanel();
    spacer = Box.createHorizontalStrut(60);
    setUpPanel(p2, "Horizontal Strut - 60 pixels", spacer);

    // Horizontal glue in FlowLayout - not useful
    JPanel p3= new JPanel();
    spacer = Box.createHorizontalGlue();
    setUpPanel(p3, "Horizontal Glue - FlowLayout", spacer);

    // Add glue to fill all remaining horizontal space between
    // the two buttons. Glue not supported by default FlowLayout
    // of JPanel.  Change layout of JPanel to BoxLayout.
    JPanel p4= new JPanel();
    p4.setLayout(new BoxLayout(p4,BoxLayout.X_AXIS));
    spacer = Box.createHorizontalGlue();
    setUpPanel(p4, "Horizontal Glue - BoxLayout", spacer);

    add(p1);
    add(p2);
    add(p3);
    add(p4);
  }

  // Helper to set the border and add components
  private void setUpPanel(JPanel p, String title,
                          Component spacer) {
    p.setBorder(BorderFactory.createTitledBorder(
                       BorderFactory.createEtchedBorder(),title,
                       TitledBorder.TOP,TitledBorder.CENTER));
    p.setBackground(Color.white);
    p.add(new JButton("Left"));
    p.add(spacer);
    p.add(new JButton("Right"));
  }

  public static void main(String[] args) {
    String title = "Using Invisible Components";
    WindowUtilities.setNativeLookAndFeel();
    WindowUtilities.openInJFrame(new InvisibleComponentTest(),
                                 350, 325, title);
  }
}

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

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

Java Spring and I/O #Root

Java Spring and I/O

Spring Batch including HSQLDB database
Common spring-integration modules
Schedule jobs using Quartz: requires Spring Boot >=2.0.0.M2
Activiti BPMN workflow engine
Integration using Apache Camel
Java Message Service API via Apache ActiveMQ
Java Message Service API via Apache Artemis
Java Message Service API via HornetQ: requires Spring Boot >=1.1.0.RELEASE and <1.4.0.RC1
Advanced Message Queuing Protocol via spring-rabbit
Kafka messaging support using Spring Kafka: requires Spring Boot >=1.5.0.RC1

From: http://sitestree.com/?p=10920
Categories:Root
Tags:
Post Data:2017-07-28 23:30:14

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

Java Spring and Social #Root

Java Spring and Social

Social

spring-social-facebook
spring-social-linkedin
spring-social-twitter

From: http://sitestree.com/?p=10922
Categories:Root
Tags:
Post Data:2017-07-28 22:30:46

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

Java Spring and AWS Cloud #Root

Java Spring and AWS Cloud

 

AWS native services from spring-cloud-aws
Relational databases on AWS with RDS and spring-cloud-aws-jdbc
Messaging on AWS with SQS and spring-cloud-aws-messaging

From: http://sitestree.com/?p=10924
Categories:Root
Tags:
Post Data:2017-07-28 23:45:04

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

Java Spring: Template Engine #Root

Java Spring: Template Engines

FreeMarker templating engine
Velocity templating engine: requires Spring Boot >=1.1.6.RELEASE and <1.4.0.M2
Groovy templating engine
Thymeleaf templating engine, including integration with Spring
Mustache templating engine

From: http://sitestree.com/?p=10912
Categories:Root
Tags:
Post Data:2017-07-28 21:53:16

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

Java Spring: Components to Deal with Database (SQL Aspect) #Root

Java Spring: Components to Deal with Database (SQL Aspect)

Java Persistence API including spring-data-jpa, spring-orm and Hibernate
Persistence support using Java Object Oriented Querying
Persistence support using MyBatis
JDBC databases
H2 database (with embedded support)
HSQLDB database (with embedded support)
Apache Derby database (with embedded support)
MySQL jdbc driver
PostgreSQL jdbc driver
Microsoft SQL Server jdbc driver: requires Spring Boot >=1.5.0.RC1
Flyway Database Migrations library
Liquibase Database Migrations library

From: http://sitestree.com/?p=10916
Categories:Root
Tags:
Post Data:2017-07-28 23:08:44

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

struts leson 5 action object process request #Root

From: http://sitestree.com/?p=2824
Categories:Root
Tags:
Post Data:2015-10-26 07:34:22

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

struts leson 6 handling request parameters with form beans #Root

From: http://sitestree.com/?p=2826
Categories:Root
Tags:
Post Data:2015-10-26 07:35:52

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

step by step spring inventory management #Spring #Spring Framework and Hibernate #Spring #Spring Framework and Hibernate

From: http://sitestree.com/?p=2746
Categories:Spring, Spring Framework and Hibernate, Spring, Spring Framework and Hibernate
Tags:spring, inventory management
Post Data:2015-11-01 18:17:34

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

Print three-dimensional valarray line-by-line

/* 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 three-dimensional valarray line-by-line
template<class T>
void printValarray3D (const valarray<T>& va, int dim1, int dim2)
{
    for (int i=0; i<va.size()/(dim1*dim2); ++i) {
        for (int j=0; j<dim2; ++j) {
            for (int k=0; k<dim1; ++k) {
                cout << va[i*dim1*dim2+j*dim1+k] << ' ';
            }
            cout << '\n';
        }
        cout << '\n';
    }
    cout << endl;
}

int main()
{
    /* valarray with 24 elements
     * - two groups
     * - four rows
     * - three columns
     */
    valarray<double> va(24);

    // fill valarray with values
    for (int i=0; i<24; i++) {
        va[i] = i;
    }

    // print valarray
    printValarray3D (va, 3, 4);

    // we need two two-dimensional subsets of three times 3 values
    // in two 12-element arrays
    size_t lengthvalues[] = {  2, 3 };
    size_t stridevalues[] = { 12, 3 };
    valarray<size_t> length(lengthvalues,2);
    valarray<size_t> stride(stridevalues,2);

    // assign the second column of the first three rows
    // to the first column of the first three rows
    va[gslice(0,length,stride)]
        = valarray<double>(va[gslice(1,length,stride)]);

    // add and assign the third of the first three rows
    // to the first of the first three rows
    va[gslice(0,length,stride)]
        += valarray<double>(va[gslice(2,length,stride)]);

    // print valarray
    printValarray3D (va, 3, 4);
}

/*
0 1 2
3 4 5
6 7 8
9 10 11

12 13 14
15 16 17
18 19 20
21 22 23


3 1 2
9 4 5
15 7 8
9 10 11

27 13 14
33 16 17
39 19 20
21 22 23



 */

Example demonstrating the use of packages

&&&&&&&&&&&&&&&&&&&
Example demonstrating the use of packages.

    * Class1.java defined in package1.
    * Class2.java defined in package2.
    * Class3.java defined in package2.package3.
    * Class1.java defined in package4.
    * PackageExample.java Driver for package example
&&&&&&&&&&&&&&&&&&&&&
~~~~~~~~~~~~~~~~~~~~~
Class1.java defined in package1.
~~~~~~~~~~~~~~~~~~~~~
package package1;

*****************
 
public class Class1 {
  public static void printInfo() {
    System.out.println("This is Class1 in package1.");
  }
}
&&&&&&&&&&&&&&&&&&&&&
~~~~~~~~~~~~~~~~~~~~~
Class2.java defined in package2. 
~~~~~~~~~~~~~~~~~~~~~
package package2;
$$$$$$$$$$$$$$$$

public class Class2 {
  public static void printInfo() {
    System.out.println("This is Class2 in package2.");
  }
}
&&&&&&&&&&&&&&&&&&&&&&
~~~~~~~~~~~~~~~~~~~~~~
Class3.java defined in package2.package3
~~~~~~~~~~~~~~~~~~~~~~
package package2.package3;

@@@@@@@@@@@@@@@@@@@@@@@@@

public class Class3 {
  public static void printInfo() {
    System.out.println("This is Class3 in " +
                       "package2.package3.");
  }
}
&&&&&&&&&&&&&&&&&&&&&&&&&
~~~~~~~~~~~~~~~~~~~~~~~~~
Class1.java defined in package4.
~~~~~~~~~~~~~~~~~~~~~~~~~
package package4;

@@@@@@@@@@@@@@@@

public class Class1 {
  public static void printInfo() {
    System.out.println("This is Class1 in package4.");
  }
}
&&&&&&&&&&&&&&&&&&&&&&&&&&
~~~~~~~~~~~~~~~~~~~~~~~~~~
PackageExample.java Driver for package example.
~~~~~~~~~~~~~~~~~~~~~~~~~~
import package1.*;
import package2.Class2;
import package2.package3.*;

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

public class PackageExample {
  public static void main(String[] args) {
    Class1.printInfo();
    Class2.printInfo();
    Class3.printInfo();
    package4.Class1.printInfo();
  }
}
****************************

Code examples for interfaces

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

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

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

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

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

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

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

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

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

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

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

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

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

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

A Ship class illustrating object-oriented programming concepts

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

public class Ship {
  // Instance variables

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

  // Constructors

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

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

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

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

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

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

  /** Move N steps. */

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

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

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

  /** Report location to standard output. */

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

  /** Get current X location. */

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

  /** Set current X location. */

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

  /** Get current Y location. */

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

  /** Set current Y location. */

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

  /** Get current speed. */

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

  /** Set current speed. */

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

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

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

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

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

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

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

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

Accesses instance variables in a Ship object.

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 + ").");
  }
}
**********************

DropBall.java Uses a while loop to determine how long it takes a ball to fall from the top of the Washington Monument to the ground

DropBall.java Uses a while loop to determine how long it takes a ball to fall from the top of the Washington Monument to the ground
************************************************************
/** Simulating dropping a ball from the top of the Washington
 *  Monument. The program outputs the height of the ball each
 *  second until the ball hits the ground.
 *
 *****************************************

public class DropBall {
  public static void main(String[] args) {
    int time = 0;
    double start = 550.0, drop = 0.0;
    double height = start;
    while (height > 0) {
      System.out.println("After " + time + 
                   (time==1 ? " second, " : " seconds,") + 
                   "the ball is at " + height + " feet.");
      time++;                   
      drop = freeFall(time);
      height = start - drop;
    }
    System.out.println("Before " + time + " seconds could " +
                       "expire, the ball hit the ground!");
  }
  
  /** Calculate the distance in feet for an object in 
   *  free fall. 
   */

  public static double freeFall (float time) {
    // Gravitational constant is 32 feet per second squared
    return(16.0 * time * time); // 1/2 gt^2
  }
}
@@@@@@@@@@@@@@@@@@@@

NumFormat.java Formats real numbers with DecimalFormat.

import java.text.*;

/** Formatting real numbers with DecimalFormat.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class NumFormat {
  public static void main (String[] args) {
    DecimalFormat science = new DecimalFormat("0.000E0");
    DecimalFormat plain = new DecimalFormat("0.0000");

    for(double d=100.0; d<140.0; d*=1.10) {
      System.out.println("Scientific: " + science.format(d) +
                         " and Plain: " + plain.format(d));
    }
  }
}

ModificationTest.java Demonstrates changing fields of an object. Inherits from ReferenceTest.java.

/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

import java.awt.Point;

public class ModificationTest extends ReferenceTest {
  public static void main(String[] args) {
    Point p1 = new Point(1, 2); // Assign Point to p1
    Point p2 = p1; // p2 is new reference to *same* Point
    print("p1", p1); // (1, 2)
    print("p2", p2); // (1, 2)
    munge(p2); // Changes fields of the *single* Point
    print("p1", p1); // (5, 10)
    print("p2", p2); // (5, 10)
  }

  public static void munge(Point p) {
    p.x = 5;
    p.y = 10;
  }
}


/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

import java.awt.Point;

public class ReferenceTest {
  public static void main(String[] args) {
    Point p1 = new Point(1, 2); // Assign Point to p1
    Point p2 = p1; // p2 is new reference to *same* Point
    print("p1", p1); // (1, 2)
    print("p2", p2); // (1, 2)
    triple(p2); // Doesn?t change p2
    print("p2", p2); // (1, 2)
    p2 = triple(p2); // Have p2 point to *new* Point
    print("p2", p2); // (3, 6)
    print("p1", p1); // p1 unchanged: (1, 2)
  }

  public static Point triple(Point p) {
    p = new Point(p.x * 3, p.y * 3); // Redirect p
    return(p);
  }

  public static void print(String name, Point p) {
    System.out.println("Point " + name + "= (" +
                       p.x + ", " + p.y + ").");
  }
}

Tests the class type of an object using the isInstance method (preferred over instanceof operator).

/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

interface Barking {}

class Mammal {}

class Canine extends Mammal {}

class Dog extends Canine implements Barking {}

class Retriever extends Dog {}

public class InstanceOf {
  public static void main(String[] args) {
    Canine wolf = new Canine();
    Retriever rover = new Retriever();

    System.out.println("Testing instanceof:");
    report(wolf, "wolf");
    System.out.println();
    report(rover, "rover");

    System.out.println("\nTesting isInstance:");
    Class barkingClass = Barking.class;
    Class dogClass = Dog.class;
    Class retrieverClass = Retriever.class;
    System.out.println("  Does a retriever bark? " +
                       barkingClass.isInstance(rover));
    System.out.println("  Is a retriever a dog? " +
                       dogClass.isInstance(rover));
    System.out.println("  Is a dog necessarily a retriever? " +
                       retrieverClass.isInstance(new Dog()));
  }

  public static void report(Object object, String name) {
    System.out.println("  " + name + " is a mammal: " +
                       (object instanceof Mammal));
    System.out.println("  " + name + " is a canine: " +
                       (object instanceof Canine));
    System.out.println("  " + name + " is a dog: " +
                       (object instanceof Dog));
    System.out.println("  " + name + " is a retriever: " +
                       (object instanceof Retriever));
  }
}

URLTest.java Demonstrates try/catch blocks.

/** Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.  
 */
 
 // Further simplified getURL method. 
 
 public URL getURL() {
    if (url != null) {
      return(url);
    }
    System.out.print("Enter URL: ");
    System.out.flush();
    BufferedReader in = new BufferedReader(
                          new InputStreamReader(System.in));
    String urlString = null;
    try {
      urlString = in.readLine();
      url = new URL(urlString);
    } catch(MalformedURLException mue) {
      System.out.println(urlString + " is not valid.\n" +
                                 "Try again.");
      getURL();
    } catch(IOException ioe) {
      System.out.println("IOError when reading input: " + ioe);
      ioe.printStackTrace(); // Can skip return(null) now
    } finally {
      return(url);
    }
  }

import java.net.*; // For URL, MalformedURLException
import java.io.*;  // For BufferedReader

/** A small class to demonstrate try/catch blocks.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class URLTest {
  public static void main(String[] args) {
    URLTest test = new URLTest();
    test.getURL();
    test.printURL();
  }

  private URL url = null;

  /** Read a string from user and create a URL from it. If
   *  reading fails, give up and report error. If reading
   *  succeeds but URL is illegal, try again.
   */

  public URL getURL() {
    if (url != null) {
      return(url);
    }
    System.out.print("Enter URL: ");
    System.out.flush();
    BufferedReader in = new BufferedReader(
                          new InputStreamReader(System.in));
    String urlString;
    try {
      urlString = in.readLine();
    } catch(IOException ioe) {
      System.out.println("IOError when reading input: " + ioe);
      ioe.printStackTrace(); // Show stack dump.
      return(null);
    }
    try {
      url = new URL(urlString);
    } catch(MalformedURLException mue) {
      System.out.println(urlString + " is not valid.\n" +
                         "Try again.");
      getURL();
    }
    return(url);
  }

  /** Print info on URL. */

  public void printURL() {
    if (url == null) {
      System.out.println("No URL.");
    } else {
      String protocol = url.getProtocol();
      String host = url.getHost();
      int port = url.getPort();
      if (protocol.equals("http") && (port == -1)) {
        port = 80;
      }
      String file = url.getFile();
      System.out.println("Protocol: " + protocol +
                         "\nHost: " + host +
                         "\nPort: " + port +
                         "\nFile: " + file);
    }
  }
}

/** Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.  
 */
 
  // Simplified getURL method.
  
  public URL getURL() {
    if (url != null) {
      return(url);
    }
    System.out.print("Enter URL: ");
    System.out.flush();
    BufferedReader in = new BufferedReader(
                          new InputStreamReader(System.in));
    String urlString = null;
    try {
      urlString = in.readLine();
      url = new URL(urlString);
    } catch(MalformedURLException mue) {
      System.out.println(urlString + " is not valid.\n" +
                                    "Try again.");
      getURL();
    } catch(IOException ioe) {
      System.out.println("IOError when reading input: " + ioe);
      ioe.printStackTrace(); // Show stack dump
      return(null);
    }
    return(url);
  }

ExecTest.java illustrates use of the Exec class.

/** A test of the Exec class.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class ExecTest {
  public static void main(String[] args) {
    // Note: no trailing "&" -- special shell chars not
    // understood, since no shell started. Besides, exec
    // doesn?t wait, so the program continues along even
    // before Netscape pops up.
    Exec.exec("/usr/local/bin/netscape");

    // Run commands, printing results.
    Exec.execPrint("/usr/bin/ls");
    Exec.execPrint("/usr/bin/cat Test.java");

    // Don?t print results, but wait until this finishes.
    Exec.execWait("/usr/java1.3/bin/javac Test.java");

    // Now Test.class should exist.
    Exec.execPrint("/usr/bin/ls");
  }
}

DropBall.java Uses a while loop to determine how long it takes a ball to fall from the top of the Washington Monument to the ground.

/** Simulating dropping a ball from the top of the Washington
 *  Monument. The program outputs the height of the ball each
 *  second until the ball hits the ground.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class DropBall {
  public static void main(String[] args) {
    int time = 0;
    double start = 550.0, drop = 0.0;
    double height = start;
    while (height > 0) {
      System.out.println("After " + time +
                   (time==1 ? " second, " : " seconds,") +
                   "the ball is at " + height + " feet.");
      time++;
      drop = freeFall(time);
      height = start - drop;
    }
    System.out.println("Before " + time + " seconds could " +
                       "expire, the ball hit the ground!");
  }

  /** Calculate the distance in feet for an object in
   *  free fall.
   */

  public static double freeFall (float time) {
    // Gravitational constant is 32 feet per second squared
    return(16.0 * time * time); // 1/2 gt^2
  }
}

Loading Images

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);
  }
}
<<<<<<<<<<<<<<<<<<

Basic template for a Java applet

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.
  }
}
>>>>>>>>>>>>>>>>>>>>>

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

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);
}

Example illustrating inheritance and abstract classes

***********************************
# Example illustrating inheritance and abstract classes.

    * Shape.java The parent class (abstract) for all closed, open, curved, and straight-edged shapes.
    * Curve.java An (abstract) curved Shape (open or closed).
    * StraightEdgedShape.java A Shape with straight edges (open or closed).
    * Measurable.java Interface defining classes with measurable areas.
    * Circle.java A circle that extends Shape and implements Measurable.
    * MeasureUtil.java Operates on Measurable instances.
    * Polygon.java A closed Shape with straight edges; extends StraightEdgedShape and implements Measurable.
    * Rectangle.java A rectangle that satisfies the Measurable interface; extends Polygon.
    * MeasureTest.java Driver for example.
**************************************
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Shape.java 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** The parent class for all closed, open, curved, and 
 *  straight-edged shapes.
 *
 ############################
public abstract class Shape {
  protected int x, y;

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

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

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

  public void setY(int y) {
    this.y = y;
  }
}
#############################
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Curve.java An (abstract) curved Shape (open or closed)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** A curved shape (open or closed). Subclasses will include
 *  arcs and circles.
 *
***********************

public abstract class Curve extends Shape {}
##############################
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
StraightEdgedShape.java A Shape with straight edges (open or closed). 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** A Shape with straight edges (open or closed). Subclasses
 *  will include Line, LineSegment, LinkedLineSegments,
 *  and Polygon.
 *
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public abstract class StraightEdgedShape extends Shape {}
################################
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Measurable.java Interface defining classes with measurable areas
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** Used in classes with measurable areas. 
 *
 **************

public interface Measurable {
  double getArea();
}
#################################
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Circle.java A circle that extends Shape and implements Measurable.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** A circle. Since you can calculate the area of
 *  circles, class implements the Measurable interface.
 *
***********************************
public class Circle extends Curve implements Measurable {
  private double radius;

  public Circle(int x, int y, double radius) {
    setX(x);
    setY(y);
    setRadius(radius);
  }

  public double getRadius() {
    return(radius);
  }

  public void setRadius(double radius) {
    this.radius = radius;
  }

  /** Required for Measurable interface. */

  public double getArea() {
    return(Math.PI * radius * radius);
  }
}
############################
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MeasureUtil.java Operates on Measurable instances
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** Some operations on Measurable instances. 
 *

************************
public class MeasureUtil {
  public static double maxArea(Measurable m1,
                               Measurable m2) {
    return(Math.max(m1.getArea(), m2.getArea()));
  }

  public static double totalArea(Measurable[] mArray) {
    double total = 0;
    for(int i=0; i
~~~~~~~~~~~~~~~~~~~~~~

Speedboat.java Illustrates inheritance from Ship class

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

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

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

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

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

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

Demonstrates overloading methods in class Ship4

*********************
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();
  }
}
************************

HelloWWW.java Basic Hello World (Wide Web) Applet

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

*********************
 
public class HelloWWW extends Applet {
  private int fontSize = 40;
  
  public void init() {
    setBackground(Color.black);
    setForeground(Color.white);
    setFont(new Font("SansSerif", Font.BOLD, fontSize));
  }
  
  public void paint(Graphics g) {
    g.drawString("Hello, World Wide Web.", 5, fontSize+5);
  }
}
<<<<<<<<<<<<<<<<<<<<<

StringTest.java Demonstrates various methods of the String class.

/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */


  public class StringTest {
  public static void main (String[] args) {
    String str = "";
    if (args.length > 0) {
        str = args[0];
    }
    if (str.length()>8) {
      System.out.println("String is \"" + str + "\"\n");
      System.out.println("  charAt(3) ------------------ " +
                         str.charAt(3));
      System.out.println("  compareTo(Moscow) ---------- " +
                         str.compareTo("Moscow"));
      System.out.println("  concat(SuFFiX) ------------- " +
                         str.concat("SuFFiX"));
      System.out.println("  endsWith(hic) -------------- " +
                         str.endsWith("hic"));
      System.out.println("  == Geographic -------------- " +
                         (str == "Geographic"));
      System.out.println("  equals(geographic) --------- " +
                         str.equals("geographic"));
      System.out.println("  equalsIgnoreCase(geographic) " +
                         str.equalsIgnoreCase("geographic"));
      System.out.println("  indexOf('o') --------------- " +
                         str.indexOf('o'));
      System.out.println("  indexOf('i',5) ------------- " +
                         str.indexOf('i',5));
      System.out.println("  indexOf('o',5) ------------- " +
                         str.indexOf('o',5));
      System.out.println("  indexOf(rap) --------------- " +
                         str.indexOf("rap"));
      System.out.println("  indexOf(rap, 5) ------------ " +
                         str.indexOf("rap", 5));
      System.out.println("  lastIndexOf('o') ----------- " +
                         str.lastIndexOf('o'));
      System.out.println("  lastIndexOf('i',5) --------- " +
                         str.lastIndexOf('i',5));
      System.out.println("  lastIndexOf('o',5) --------- " +
                         str.lastIndexOf('o',5));
      System.out.println("  lastIndexOf(rap) ----------- " +
                         str.lastIndexOf("rap"));
      System.out.println("  lastIndexOf(rap, 5) -------- " +
                         str.lastIndexOf("rap", 5));
      System.out.println("  length() ------------------- " +
                         str.length());
      System.out.println("  replace('c','k') ----------- " +
                         str.replace('c','k'));
      System.out.println("  startsWith(eog,1) ---------- " +
                         str.startsWith("eog",1));
      System.out.println("  startsWith(eog) ------------ " +
                         str.startsWith("eog"));
      System.out.println("  substring(3) --------------- " +
                         str.substring(3));
      System.out.println("  substring(3,8) ------------- " +
                         str.substring(3,8));
      System.out.println("  toLowerCase() -------------- " +
                         str.toLowerCase());
      System.out.println("  toUpperCase() -------------- " +
                         str.toUpperCase());
      System.out.println("  trim() --------------------- " +
                         str.trim());
      System.out.println("\nString is still \"" + str + "\"\n");
    }
  }
}

NegativeLengthException.java Illustrates defining and throwing your own exceptions.

import java.io.*;

/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class NegativeLengthException extends Exception {

  /** Test NegativeLengthException */

  public static void main(String[] args) {
    try {
      int lineLength = readLength();
      for(int i=0; i

TreeTest.java Builds a binary tree and prints the contents of the nodes. Uses the following classes:

Treetest.java
/** A NodeOperator that prints each node.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

class PrintOperator implements NodeOperator {
  public void operateOn(Node node) {
    System.out.println(node.getNodeValue());
  }
}

/** A sample tree representing a parse tree of
 *  the sentence "Java hackers hack Java", using
 *  some simple context-free grammar.
 */

public class TreeTest {
  public static void main(String[] args) {
    Node adjective =
      new Node("  Adjective", new Leaf("   Java"));
    Node noun1 =
      new Node("  Noun", new Leaf("   hackers"));
    Node verb =
      new Node("  TransitiveVerb", new Leaf("   hack"));
    Node noun2 =
      new Node("  Noun", new Leaf("   Java"));
    Node np = new Node(" NounPhrase", adjective, noun1);
    Node vp = new Node(" VerbPhrase", verb, noun2);
    Node sentence = new Node("Sentence", np, vp);
    PrintOperator printOp = new PrintOperator();
    System.out.println("Depth first traversal:");
    sentence.depthFirstSearch(printOp);
    System.out.println("\nBreadth first traversal:");
    sentence.breadthFirstSearch(printOp);
  }
}

Leaf.java
A leaf node with no children.
/** Leaf node: a node with no subtrees.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class Leaf extends Node {
  public Leaf(Object value) {
    super(value, null, null);
  }
}

Node.java A data structure representing a node in a binary tree. 


import java.util.Vector;

/** A data structure representing a node in a binary tree.
 *  It contains a node value and a reference (pointer) to
 *  the left and right subtrees.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class Node {
  private Object nodeValue;
  private Node leftChild, rightChild;

 /** Build Node with specified value and subtrees. */

  public Node(Object nodeValue, Node leftChild,
              Node rightChild) {
    this.nodeValue = nodeValue;
    this.leftChild = leftChild;
    this.rightChild = rightChild;
  }

  /** Build Node with specified value and L subtree. R child
   *  will be null. If you want both children to be null, use
   *  the Leaf constructor.
   */

  public Node(Object nodeValue, Node leftChild) {
    this(nodeValue, leftChild, null);
  }

  /** Return the value of this node. */

  public Object getNodeValue() {
    return(nodeValue);
  }

  /** Specify the value of this node. */

  public void setNodeValue(Object nodeValue) {
    this.nodeValue = nodeValue;
  }

 /** Return the L subtree. */

  public Node getLeftChild() {
    return(leftChild);
  }

  /** Specify the L subtree. */

  public void setLeftChild(Node leftChild) {
    this.leftChild = leftChild;
  }

  /** Return the R subtree. */

  public Node getRightChild() {
    return(rightChild);
  }

  /** Specify the R subtree. */

  public void setRightChild(Node rightChild) {
    this.rightChild = rightChild;
  }

  /** Traverse the tree in depth-first order, applying
   *  the specified operation to each node along the way.
   */

  public void depthFirstSearch(NodeOperator op) {
    op.operateOn(this);
    if (leftChild != null) {
      leftChild.depthFirstSearch(op);
    }
    if (rightChild != null) {
      rightChild.depthFirstSearch(op);
    }
  }

  /** Traverse the tree in breadth-first order, applying the
   *  specified operation to each node along the way.
   */

  public void breadthFirstSearch(NodeOperator op) {
    Vector nodeQueue = new Vector();
    nodeQueue.addElement(this);
    Node node;
    while(!nodeQueue.isEmpty()) {
      node = (Node)nodeQueue.elementAt(0);
      nodeQueue.removeElementAt(0);
      op.operateOn(node);
      if (node.getLeftChild() != null) {
        nodeQueue.addElement(node.getLeftChild());
      }
      if (node.getRightChild() != null) {
        nodeQueue.addElement(node.getRightChild());
      }
    }
  }
}

NodeOperator.java An interface used in the Node class to ensure that an object has an operateOn method. 

/** An interface used in the Node class to ensure that
 *  an object has an operateOn method.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public interface NodeOperator {
  void operateOn(Node node);
}

Illustrates the use of arrays

/** Report on a round of golf at St. Andy?s.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class Golf {
  public static void main(String[] args) {
    int[] pars   = { 4,5,3,4,5,4,4,3,4 };
    int[] scores = { 5,6,3,4,5,3,2,4,3 };
    report(pars, scores);
  }

  /** Reports on a short round of golf. */

  public static void report(int[] pars, int[] scores) {
    for(int i=0; i

Factorial.java Computes an exact factorial, n!, using a BigInteger

import java.math.BigInteger;

/** Computes an exact factorial, using a BigInteger.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class Factorial {
  public static void main(String[] args) {
    for(int i=1; i<=256; i*=2) {
      System.out.println(i + "!=" + factorial(i));
    }
  }

  public static BigInteger factorial(int n) {
    if (n <= 1) {
      return(new BigInteger("1"));
    } else {
      BigInteger bigN = new BigInteger(String.valueOf(n));
      return(bigN.multiply(factorial(n - 1)));
    }
  }
}

Exec.java Provides static methods for running external processes from applications.

import java.io.*;

/** A class that eases the pain of running external processes
 *  from applications. Lets you run a program three ways:
 *  


     *     
    exec: Execute the command, returning
     *         immediately even if the command is still running.
     *         This would be appropriate for printing a file.
     *     
    execWait: Execute the command, but don?t
     *         return until the command finishes. This would be
     *         appropriate for sequential commands where the first
     *         depends on the second having finished (e.g.,
     *         javac followed by java).
     *     
    execPrint: Execute the command and print the
     *          output. This would be appropriate for the Unix
     *          command ls.
     *  


 *  Note that the PATH is not taken into account, so you must
 *  specify the full pathname to the command, and shell
 *  built-in commands will not work. For instance, on Unix the
 *  above three examples might look like:
 *  


     *    

    Exec.exec("/usr/ucb/lpr Some-File");


     *    

    Exec.execWait("/usr/local/bin/javac Foo.java");
     *        Exec.execWait("/usr/local/bin/java Foo");


     *    

    Exec.execPrint("/usr/bin/ls -al");


     *  


 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class Exec {

  private static boolean verbose = true;

  /** Determines if the Exec class should print which commands
    * are being executed, and prints error messages if a problem
    * is found. Default is true.
    *
    * @param verboseFlag true: print messages, false: don?t.
    */

  public static void setVerbose(boolean verboseFlag) {
    verbose = verboseFlag;
  }

  /** Will Exec print status messages? */

  public static boolean getVerbose() {
    return(verbose);
  }

  /** Starts a process to execute the command. Returns
    * immediately, even if the new process is still running.
    *
    * @param command The full pathname of the command to
    * be executed. No shell built-ins (e.g., "cd") or shell
    * meta-chars (e.g. ">") are allowed.
    * @return false if a problem is known to occur, but since
    * this returns immediately, problems aren?t usually found
    * in time. Returns true otherwise.
    */

  public static boolean exec(String command) {
    return(exec(command, false, false));
  }

  /** Starts a process to execute the command. Waits for the
    * process to finish before returning.
    *
    * @param command The full pathname of the command to
    * be executed. No shell built-ins or shell metachars are
    * allowed.
    * @return false if a problem is known to occur, either due
    * to an exception or from the subprocess returning a
    * nonzero value. Returns true otherwise.
    */

  public static boolean execWait(String command) {
    return(exec(command, false, true));
  }

  /** Starts a process to execute the command. Prints any output
    * the command produces.
    *
    * @param command The full pathname of the command to
    * be executed. No shell built-ins or shell meta-chars are
    * allowed.
    * @return false if a problem is known to occur, either due
    * to an exception or from the subprocess returning a
    * nonzero value. Returns true otherwise.
    */

  public static boolean execPrint(String command) {
    return(exec(command, true, false));
  }

  /** This creates a Process object via Runtime.getRuntime.exec()
    * Depending on the flags, it may call waitFor on the process
    * to avoid continuing until the process terminates, and open
    * an input stream from the process to read the results.
    */

  private static boolean exec(String command,
                              boolean printResults,
                              boolean wait) {
    if (verbose) {
      printSeparator();
      System.out.println("Executing '" + command + "'.");
    }
    try {
      // Start running command, returning immediately.
      Process p  = Runtime.getRuntime().exec(command);

      // Print the output. Since we read until there is no more
      // input, this causes us to wait until the process is
      // completed.
      if(printResults) {
        BufferedReader buffer = new BufferedReader(
          new InputStreamReader(p.getInputStream()));
        String s = null;
        try {
          while ((s = buffer.readLine()) != null) {
            System.out.println("Output: " + s);
          }
          buffer.close();
          if (p.exitValue() != 0) {
            if (verbose) {
              printError(command + " -- p.exitValue() != 0");
            }
            return(false);
          }
        } catch (Exception e) {
          // Ignore read errors; they mean the process is done.
        }

      // If not printing the results, then we should call waitFor
      // to stop until the process is completed.
      } else if (wait) {
        try {
          System.out.println(" ");
          int returnVal = p.waitFor();
          if (returnVal != 0) {
            if (verbose) {
              printError(command);
            }
            return(false);
          }
        } catch (Exception e) {
          if (verbose) {
            printError(command, e);
          }
          return(false);
        }
      }
    } catch (Exception e) {
      if (verbose) {
        printError(command, e);
      }
      return(false);
    }
    return(true);
  }

  private static void printError(String command,
                                 Exception e) {
    System.out.println("Error doing exec(" + command + "): " +
                        e.getMessage());
    System.out.println("Did you specify the full " +
                       "pathname?");
  }

  private static void printError(String command) {
    System.out.println("Error executing ?" + command + "?.");
  }

  private static void printSeparator() {
    System.out.println
      ("==============================================");
  }
}

Controlling Image Loading

~~~~~~~~~~~~~~~~~~~
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>>>>>>>>>>>>>>>>>>>>>

HelloWWW2.java Illustrates the ability of an applet to read parameters contained in the HTML document

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);
  }
}
>>>>>>>>>>>>>>>>>>>>>>>

An example Travel Site

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 Number\n";
      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>

IfExample.jsp Page that uses the custom nested tags

IfExample.jsp Page that uses the custom nested tags


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Illustration of IfTag tag. 

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted. 
-->
<HTML>
<HEAD>
<TITLE>If Tag Example</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>
<BODY>
<H1>If Tag Example</H1>
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<cwp:if>
  <cwp:condition>true</cwp:condition>
  <cwp:then>Condition is true</cwp:then>
  <cwp:else>Condition is false</cwp:else>
</cwp:if>
<P>
<cwp:if>
  <cwp:condition><%= request.isSecure() %></cwp:condition>
  <cwp:then>Request is using SSL (https)</cwp:then>
  <cwp:else>Request is not using SSL</cwp:else>
</cwp:if>
<P>
Some coin tosses:<BR>
<cwp:repeat reps="10">
  <cwp:if>
    <cwp:condition><%= Math.random() < 0.5 %></cwp:condition>
    <cwp:then><B>Heads</B><BR></cwp:then>
    <cwp:else><B>Tails</B><BR></cwp:else>
  </cwp:if>
</cwp:repeat>
</BODY>
</HTML>

Statics.java Demonstrates static and non-static methods.

*/

public class Statics {
 public static void main(String[] args) {
    staticMethod();
    Statics s1 = new Statics();
    s1.regularMethod();
  }

  public static void staticMethod() {
    System.out.println("This is a static method.");
  }

  public void regularMethod() {
    System.out.println("This is a regular method.");
  }
}

Batton’s java

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

/././././././

public class Buttons extends Applet {
  private Button button1, button2, button3;
  
  public void init() {
    button1 = new Button("Button One");
    button2 = new Button("Button Two");
    button3 = new Button("Button Three");
    add(button1);
    add(button2);
    add(button3);
  }
}
/././././././././.

IfTag.java, IfConditionTag.java, IfThenTag.java, and IfElseTag.java, Custom tags that make use of tag nesting

IfTag.java, IfConditionTag.java, IfThenTag.java, and IfElseTag.java, Custom tags that make use of tag nesting


IfTag.java

package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.servlet.*;

/** A tag that acts like an if/then/else.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class IfTag extends TagSupport {
  private boolean condition;
  private boolean hasCondition = false;

  public void setCondition(boolean condition) {
    this.condition = condition;
    hasCondition = true;
  }

  public boolean getCondition() {
    return(condition);
  }

  public void setHasCondition(boolean flag) {
    this.hasCondition = flag;
  }

  /** Has the condition field been explicitly set? */

  public boolean hasCondition() {
    return(hasCondition);
  }

  public int doStartTag() {
    return(EVAL_BODY_INCLUDE);
  }
}


package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.servlet.*;

/** The condition part of an if tag.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class IfConditionTag extends BodyTagSupport {
  public int doStartTag() throws JspTagException {
    IfTag parent =
      (IfTag)findAncestorWithClass(this, IfTag.class);
    if (parent == null) {
      throw new JspTagException("condition not inside if");
    }
    return(EVAL_BODY_TAG);
  }

  public int doAfterBody() {
    IfTag parent =
      (IfTag)findAncestorWithClass(this, IfTag.class);
    String bodyString = getBodyContent().getString();
    if (bodyString.trim().equals("true")) {
      parent.setCondition(true);
    } else {
      parent.setCondition(false);
    }
    return(SKIP_BODY);
  }
}

package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.servlet.*;

/** The else part of an if tag.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class IfElseTag extends BodyTagSupport {
  public int doStartTag() throws JspTagException {
    IfTag parent =
      (IfTag)findAncestorWithClass(this, IfTag.class);
    if (parent == null) {
      throw new JspTagException("else not inside if");
    } else if (!parent.hasCondition()) {
      String warning =
        "condition tag must come before else tag";
      throw new JspTagException(warning);
    }
    return(EVAL_BODY_TAG);
  }

  public int doAfterBody() {
    IfTag parent =
      (IfTag)findAncestorWithClass(this, IfTag.class);
    if (!parent.getCondition()) {
      try {
        BodyContent body = getBodyContent();
        JspWriter out = body.getEnclosingWriter();
        out.print(body.getString());
      } catch(IOException ioe) {
        System.out.println("Error in IfElseTag: " + ioe);
      }
    }
    return(SKIP_BODY);
  }
}

package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.servlet.*;

/** The then part of an if tag.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class IfThenTag extends BodyTagSupport {
  public int doStartTag() throws JspTagException {
    IfTag parent =
      (IfTag)findAncestorWithClass(this, IfTag.class);
    if (parent == null) {
      throw new JspTagException("then not inside if");
    } else if (!parent.hasCondition()) {
      String warning =
        "condition tag must come before then tag";
      throw new JspTagException(warning);
    }
    return(EVAL_BODY_TAG);
  }

  public int doAfterBody() {
    IfTag parent =
      (IfTag)findAncestorWithClass(this, IfTag.class);
    if (parent.getCondition()) {
      try {
        BodyContent body = getBodyContent();
        JspWriter out = body.getEnclosingWriter();
        out.print(body.getString());
      } catch(IOException ioe) {
        System.out.println("Error in IfThenTag: " + ioe);
      }
    }
    return(SKIP_BODY);
  }
}

FilterExample.jsp Page that uses the FilterTag custom tag

FilterExample.jsp Page that uses the FilterTag custom tag

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Illustration of FilterTag tag. 

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>HTML Logical Character Styles</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>
<BODY>
<H1>HTML Logical Character Styles</H1>
Physical character styles (B, I, etc.) are rendered consistently
in different browsers. Logical character styles, however,
may be rendered differently by different browsers.
Here's how your browser 
(<%= request.getHeader("User-Agent") %>) 
renders the HTML 4.0 logical character styles:
<P>
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<TABLE BORDER=1 ALIGN="CENTER">
<TR CLASS="COLORED"><TH>Example<TH>Result
<TR>
<TD><PRE><cwp:filter>
<EM>Some emphasized text.</EM><BR>
<STRONG>Some strongly emphasized text.</STRONG><BR>
<CODE>Some code.</CODE><BR>
<SAMP>Some sample text.</SAMP><BR>
<KBD>Some keyboard text.</KBD><BR>
<DFN>A term being defined.</DFN><BR>
<VAR>A variable.</VAR><BR>
<CITE>A citation or reference.</CITE>
</cwp:filter></PRE>
<TD>
<EM>Some emphasized text.</EM><BR>
<STRONG>Some strongly emphasized text.</STRONG><BR>
<CODE>Some code.</CODE><BR>
<SAMP>Some sample text.</SAMP><BR>
<KBD>Some keyboard text.</KBD><BR>
<DFN>A term being defined.</DFN><BR>
<VAR>A variable.</VAR><BR>
<CITE>A citation or reference.</CITE>
</TABLE>
</BODY>
</HTML>


package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import cwp.*;

/** A tag that replaces <, >, ", and & with their HTML
 *  character entities (<, >, ", and &).
 *  After filtering, arbitrary strings can be placed
 *  in either the page body or in HTML attributes.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class FilterTag extends BodyTagSupport {
  public int doAfterBody() {
    BodyContent body = getBodyContent();
    String filteredBody =
      ServletUtilities.filter(body.getString());
    try {
      JspWriter out = body.getEnclosingWriter();
      out.print(filteredBody);
    } catch(IOException ioe) {
      System.out.println("Error in FilterTag: " + ioe);
    }
    // SKIP_BODY means we're done. If we wanted to evaluate
    // and handle the body again, we'd return EVAL_BODY_TAG.
    return(SKIP_BODY);
  }
}

Demonstrates using a TexturePaint to fill an shape with a tiled image

^^^^^^^^^^^^^^^^^
TiledImages.java Demonstrates using a TexturePaint to fill an shape with a tiled image. Uses the following class and images:

    * ImageUtilities.java Simplifies creating a BufferedImage from an image file. 
~~~~~~~~~~~~~~~~~~
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;

/** An example of using TexturePaint to fill objects with tiled
 *  images. Uses the getBufferedImage method of ImageUtilities 
 *  to load an Image from a file and turn that into a 
 *  BufferedImage.
 *
 ****************

public class TiledImages extends JPanel {
  private String dir = System.getProperty("user.dir");
  private String imageFile1 = dir + "/images/marty.jpg";
  private TexturePaint imagePaint1;
  private Rectangle imageRect;
  private String imageFile2 = dir + "/images/bluedrop.gif";
  private TexturePaint imagePaint2;
  private int[] xPoints = { 30, 700, 400 };
  private int[] yPoints = { 30, 30, 600 };
  private Polygon imageTriangle =
                    new Polygon(xPoints, yPoints, 3);
  public TiledImages() {
    BufferedImage image =
      ImageUtilities.getBufferedImage(imageFile1, this);
    imageRect = new Rectangle(235, 70, image.getWidth(),
                              image.getHeight());
    imagePaint1 = new TexturePaint(image, imageRect);
    image = ImageUtilities.getBufferedImage(imageFile2, this);
    imagePaint2 =
      new TexturePaint(image, new Rectangle(0, 0, 32, 32));
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;
    g2d.setPaint(imagePaint2);
    g2d.fill(imageTriangle);
    g2d.setPaint(Color.blue);
    g2d.setStroke(new BasicStroke(5));
    g2d.draw(imageTriangle);
    g2d.setPaint(imagePaint1);
    g2d.fill(imageRect);
    g2d.setPaint(Color.black);
    g2d.draw(imageRect);
  }

  public static void main(String[] args) {
    WindowUtilities.openInJFrame(new TiledImages(), 750, 650);
  }
}
>>>>>>>>>>>>>>
ImageUtilities.java Simplifies creating a BufferedImage from an image file.
>>>>>>>>>>>>>>>
import java.awt.*;
import java.awt.image.*;

/** A class that simplifies a few common image operations, in
 *  particular, creating a BufferedImage from an image file and
 *  using MediaTracker to wait until an image or several images
 *  are done loading.
 *
 ********************

public class ImageUtilities {
  
  /** Create Image from a file, then turn that into a
   *  BufferedImage.
   */

  public static BufferedImage getBufferedImage(String imageFile,
                                               Component c) {
    Image image = c.getToolkit().getImage(imageFile);
    waitForImage(image, c);

    BufferedImage bufferedImage =
      new BufferedImage(image.getWidth(c), image.getHeight(c),
                        BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bufferedImage.createGraphics();
    g2d.drawImage(image, 0, 0, c);
    return(bufferedImage);
  }

  /** Take an Image associated with a file, and wait until it is
   *  done loading (just a simple application of MediaTracker).
   *  If you are loading multiple images, don't use this
   *  consecutive times; instead, use the version that takes
   *  an array of images.
   */

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

  /** Take some Images associated with files, and wait until they
   *  are done loading (just a simple application of
   *  MediaTracker).
   */

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

Draws a filled ellipse

import javax.swing.*;   // For JPanel, etc.
import java.awt.*;      // For Graphics, etc.
import java.awt.geom.*; // For Ellipse2D, etc.

/** An example of drawing/filling shapes with Java 2D in
 *  Java 1.2 and later.
 *
**************************
public class ShapeExample extends JPanel {
  private Ellipse2D.Double circle =
    new Ellipse2D.Double(10, 10, 350, 350);
  private Rectangle2D.Double square =
    new Rectangle2D.Double(10, 10, 350, 350);

  public void paintComponent(Graphics g) {
    clear(g);
    Graphics2D g2d = (Graphics2D)g;
    g2d.fill(circle);
    g2d.draw(square);
  }

  // super.paintComponent clears off screen pixmap,
  // since we're using double buffering by default.
  protected void clear(Graphics g) {
    super.paintComponent(g);
  }

  protected Ellipse2D.Double getCircle() {
    return(circle);
  }

public static void main(String[] args) {
    WindowUtilities.openInJFrame(new ShapeExample(), 380, 400);
  }
}

JavaTextField.java

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

/** Lets the user enter the name of any
 *  good programming language. Or does it?
 *  


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

public class JavaTextField extends Applet {
  public void init() {
    setFont(new Font("Serif", Font.BOLD, 14));
    setLayout(new GridLayout(2, 1));
    add(new Label("Enter a Good Programming Language",
                  Label.CENTER));
    LanguageField langField = new LanguageField();
    Font langFont = new Font("SansSerif", Font.BOLD, 18);
    langField.setFont(langFont);
    add(langField);
  }
}

Applet that uses processXxx methods to print detailed reports on mouse events. Illustrates low-level alternative to handling events with listeners.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*; 

/** Prints non-detailed reports of mouse events.
 *  Uses the low-level processXxxEvent methods instead
 *  of the usual event listeners.
 *  


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

public class MouseReporter extends Applet {
  public void init() {
    setBackground(Color.blue); // So you can see applet in page
    enableEvents(AWTEvent.MOUSE_EVENT_MASK |
                 AWTEvent.MOUSE_MOTION_EVENT_MASK);
  }

  public void processMouseEvent(MouseEvent event) {
    System.out.println("Mouse enter/exit or click at (" +
                       event.getX() + "," +
                       event.getY() + ").");
    // In case there are MouseListeners attached:
    super.processMouseEvent(event); 
  }

  
  public void processMouseMotionEvent(MouseEvent event) {
    System.out.println("Mouse move/drag at (" +
                       event.getX() + "," +
                       event.getY() + ").");
    // In case there are MouseMotionListeners attached:
    super.processMouseMotionEvent(event);
  }
}

HeadingExample.jsp Page that uses the HeadingTag custom tag

HeadingExample.jsp Page that uses the HeadingTag custom tag


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Illustration of HeadingTag tag. 

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted. 
-->
<HTML>
<HEAD>
<TITLE>Some Tag-Generated Headings</TITLE>
</HEAD>
<BODY>
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<cwp:heading bgColor="#C0C0C0">
Default Heading
</cwp:heading>
<P>
<cwp:heading bgColor="BLACK" color="WHITE">
White on Black Heading
</cwp:heading>
<P>
<cwp:heading bgColor="#EF8429" fontSize="60" border="5">
Large Bordered Heading
</cwp:heading>
<P>
<cwp:heading bgColor="CYAN" width="100%">
Heading with Full-Width Background
</cwp:heading>
<P>
<cwp:heading bgColor="CYAN" fontSize="60"
                fontList="Brush Script MT, Times, serif">
Heading with Non-Standard Font
</cwp:heading>
</BODY>
</HTML>

package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

/** Generates an HTML heading with the specified background
 *  color, foreground color, alignment, font, and font size.
 *  You can also turn on a border around it, which normally
 *  just barely encloses the heading, but which can also
 *  stretch wider. All attributes except the background
 *  color are optional.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class HeadingTag extends TagSupport {
  private String bgColor; // The one required attribute
  private String color = null;
  private String align="CENTER";
  private String fontSize="36";
  private String fontList="Arial, Helvetica, sans-serif";
  private String border="0";
  private String width=null;

  public void setBgColor(String bgColor) {
    this.bgColor = bgColor;
  }

  public void setColor(String color) {
    this.color = color;
  }

  public void setAlign(String align) {
    this.align = align;
  }

  public void setFontSize(String fontSize) {
    this.fontSize = fontSize;
  }

  public void setFontList(String fontList) {
    this.fontList = fontList;
  }

  public void setBorder(String border) {
    this.border = border;
  }

  public void setWidth(String width) {
    this.width = width;
  }

  public int doStartTag() {
    try {
      JspWriter out = pageContext.getOut();
      out.print("<TABLE BORDER=" + border +
                " BGCOLOR=\"" + bgColor + "\"" +
                " ALIGN=\"" + align + "\"");
      if (width != null) {
        out.print(" WIDTH=\"" + width + "\"");
      }
      out.print("><TR><TH>");
      out.print("<SPAN STYLE=\"" +
                "font-size: " + fontSize + "px; " +
                "font-family: " + fontList + "; ");
      if (color != null) {
        out.println("color: " + color + ";");
      }
      out.print("\"> "); // End of <SPAN ...>
    } catch(IOException ioe) {
      System.out.println("Error in HeadingTag: " + ioe);
    }
    return(EVAL_BODY_INCLUDE); // Include tag body
  }

  public int doEndTag() {
    try {
      JspWriter out = pageContext.getOut();
      out.print("</SPAN></TABLE>");
    } catch(IOException ioe) {
      System.out.println("Error in HeadingTag: " + ioe);
    }
    return(EVAL_PAGE); // Continue with rest of JSP page
  }
}

PrimeExample.jsp Page that uses the PrimeTag custom tag

PrimeExample.jsp Page that uses the PrimeTag custom tag


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Illustration of PrimeTag tag. 

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted. 
-->
<HTML>
<HEAD>
<TITLE>Some N-Digit Primes</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>
<BODY>
<H1>Some N-Digit Primes</H1>
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<UL>
  <LI>20-digit: <cwp:prime length="20" />
  <LI>40-digit: <cwp:prime length="40" />
  <LI>80-digit: <cwp:prime length="80" />
  <LI>Default (50-digit): <cwp:prime />
</UL>
</BODY>
</HTML>



package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

/** Generates an N-digit random prime (default N = 50).
 *  Extends SimplePrimeTag, adding a length attribute
 *  to set the size of the prime. The doStartTag
 *  method of the parent class uses the len field
 *  to determine the approximate length of the prime.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class PrimeTag extends SimplePrimeTag {
  public void setLength(String length) {
    try {
      len = Integer.parseInt(length);
    } catch(NumberFormatException nfe) {
      len = 50;
    }
  }
}

SimplePrimeExample.jsp Page that uses the SimplePrimeTag custom tag

SimplePrimeExample.jsp Page that uses the SimplePrimeTag custom tag

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Illustration of SimplePrimeTag tag. 

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted. 
-->
<HTML>
<HEAD>
<TITLE>Some 50-Digit Primes</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>
<BODY>
<H1>Some 50-Digit Primes</H1>
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<UL>
  <LI><cwp:simplePrime />
  <LI><cwp:simplePrime />
  <LI><cwp:simplePrime />
  <LI><cwp:simplePrime />
</UL>
</BODY>
</HTML>

SimpleExample.jsp Page that uses the ExampleTag custom tag.

SimpleExample.jsp Page that uses the ExampleTag custom tag.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Illustration of very simple JSP custom tag. 

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted. 
-->
<HTML>
<HEAD>
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<TITLE><cwp:example /></TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>
<BODY>
<H1><cwp:example /></H1>
<cwp:example />
</BODY>
</HTML>


ExampleTag

package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

/** Very simple JSP tag that just inserts a string
 *  ("Custom tag example...") into the output.
 *  The actual name of the tag is not defined here;
 *  that is given by the Tag Library Descriptor (TLD)
 *  file that is referenced by the taglib directive
 *  in the JSP file.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ExampleTag extends TagSupport {
  public int doStartTag() {
    try {
      JspWriter out = pageContext.getOut();
      out.print("Custom tag example " +
                "(cwp.tags.ExampleTag)");
    } catch(IOException ioe) {
      System.out.println("Error in ExampleTag: " + ioe);
    }
    return(SKIP_BODY);
  }
}

ExampleTag.java Very simple custom tag. Remember to install it in the WEB-INF/classes/cwp/tags directory.

ExampleTag.java Very simple custom tag. Remember to install it in the WEB-INF/classes/cwp/tags directory. 


package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

/** Very simple JSP tag that just inserts a string
 *  ("Custom tag example...") into the output.
 *  The actual name of the tag is not defined here;
 *  that is given by the Tag Library Descriptor (TLD)
 *  file that is referenced by the taglib directive
 *  in the JSP file.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class ExampleTag extends TagSupport {
  public int doStartTag() {
    try {
      JspWriter out = pageContext.getOut();
      out.print("Custom tag example " +
                "(cwp.tags.ExampleTag)");
    } catch(IOException ioe) {
      System.out.println("Error in ExampleTag: " + ioe);
    }
    return(SKIP_BODY);
  }
}

AccessCountBean.java Bean used to illustrate the difference between running jsp:setProperty for every request vs. only when the object is created

AccessCountBean.java Bean used to illustrate the difference between running jsp:setProperty for every request vs. only when the object is created

package cwp;

/** Simple bean to illustrate sharing beans through
 *  use of the scope attribute of jsp:useBean.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class AccessCountBean {
  private String firstPage;
  private int accessCount = 1;

  public String getFirstPage() {
    return(firstPage);
  }

  public void setFirstPage(String firstPage) {
    this.firstPage = firstPage;
  }

  public int getAccessCount() {
    return(accessCount++);
  }
}

SaleEntry2.jsp Page that uses the SaleEntry bean, using the param attribute to read request parameters and assign them to bean properties

SaleEntry2.jsp Page that uses the SaleEntry bean, using the param attribute to read request parameters and assign them to bean properties

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Example of using jsp:setProperty and an explicity association
with an input parameter. See SaleEntry1.jsp
and SaleEntry3.jsp for alternatives. 
   
Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>Using jsp:setProperty</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>

<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
  <TR><TH CLASS="TITLE">
      Using jsp:setProperty</TABLE>
<jsp:useBean id="entry" class="cwp.SaleEntry" />
<jsp:setProperty 
    name="entry"
    property="itemID"
    param="itemID" />
<jsp:setProperty 
    name="entry"
    property="numItems"
    param="numItems" />
<%-- WARNING! Both the JSWDK 1.0.1 and the Java Web Server
              have a bug that makes them fail on double
              type conversions of the following sort.
--%>
<jsp:setProperty 
    name="entry"
    property="discountCode"
    param="discountCode" />
<BR>
<TABLE ALIGN="CENTER" BORDER=1>
<TR CLASS="COLORED">
  <TH>Item ID<TH>Unit Price<TH>Number Ordered<TH>Total Price
<TR ALIGN="RIGHT">
  <TD><jsp:getProperty name="entry" property="itemID" />
  <TD>$<jsp:getProperty name="entry" property="itemCost" />
  <TD><jsp:getProperty name="entry" property="numItems" />
  <TD>$<jsp:getProperty name="entry" property="totalCost" />
</TABLE>     
</BODY>
</HTML>


SaleEntry.java //SaleEntry Bean

package cwp;

/** Simple bean to illustrate the various forms
 *  of jsp:setProperty.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class SaleEntry {
  private String itemID = "unknown";
  private double discountCode = 1.0;
  private int numItems = 0;

  public String getItemID() {
    return(itemID);
  }

  public void setItemID(String itemID) {
    if (itemID != null) {
      this.itemID = itemID;
    } else {
      this.itemID = "unknown";
    }
  }

  public double getDiscountCode() {
    return(discountCode);
  }

  public void setDiscountCode(double discountCode) {
    this.discountCode = discountCode;
  }

  public int getNumItems() {
    return(numItems);
  }

  public void setNumItems(int numItems) {
    this.numItems = numItems;
  }

  // In real life, replace this with database lookup.

  public double getItemCost() {
    double cost;
    if (itemID.equals("a1234")) {
      cost = 12.99*getDiscountCode();
    } else {
      cost = -9999;
    }
    return(roundToPennies(cost));
  }

  private double roundToPennies(double cost) {
    return(Math.floor(cost*100)/100.0);
  }

  public double getTotalCost() {
    return(getItemCost() * getNumItems());
  }
}

SaleEntry.java Bean used to demonstrate the various approaches to reading request parameters and stuffing them into Java objects.

package cwp;

/** Simple bean to illustrate the various forms
 *  of jsp:setProperty.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class SaleEntry {
  private String itemID = "unknown";
  private double discountCode = 1.0;
  private int numItems = 0;

  public String getItemID() {
    return(itemID);
  }

  public void setItemID(String itemID) {
    if (itemID != null) {
      this.itemID = itemID;
    } else {
      this.itemID = "unknown";
    }
  }

  public double getDiscountCode() {
    return(discountCode);
  }

  public void setDiscountCode(double discountCode) {
    this.discountCode = discountCode;
  }

  public int getNumItems() {
    return(numItems);
  }

  public void setNumItems(int numItems) {
    this.numItems = numItems;
  }

  // In real life, replace this with database lookup.

  public double getItemCost() {
    double cost;
    if (itemID.equals("a1234")) {
      cost = 12.99*getDiscountCode();
    } else {
      cost = -9999;
    }
    return(roundToPennies(cost));
  }

  private double roundToPennies(double cost) {
    return(Math.floor(cost*100)/100.0);
  }

  public double getTotalCost() {
    return(getItemCost() * getNumItems());
  }
}

The class that actually gets the strings over the network by means of an ObjectInputStream via HTTP tunneling.

import java.net.*;
import java.io.*;

/** When this class is built, it returns a value
 *  immediately, but this value returns false for isDone
 *  and null for getQueries. Meanwhile, it starts a Thread
 *  to request an array of query strings from the server,
 *  reading them in one fell swoop by means of an
 *  ObjectInputStream. Once they've all arrived, they
 *  are placed in the location getQueries returns,
 *  and the isDone flag is switched to true.
 *  Used by the ShowQueries applet.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
  *  May be freely used or adapted.
 */

public class QueryCollection implements Runnable {
  private String[] queries;
  private String[] tempQueries;
  private boolean isDone = false;
  private URL dataURL;

  public QueryCollection(String urlSuffix, URL currentPage) {
    try {
      // Only the URL suffix need be supplied, since
      // the rest of the URL is derived from the current page.
      String protocol = currentPage.getProtocol();
      String host = currentPage.getHost();
      int port = currentPage.getPort();
      dataURL = new URL(protocol, host, port, urlSuffix);
      Thread queryRetriever = new Thread(this);
      queryRetriever.start();
    } catch(MalformedURLException mfe) {
      isDone = true;
    }
  }

  public void run() {
    try {
      tempQueries = retrieveQueries();
      queries = tempQueries;
    } catch(IOException ioe) {
      tempQueries = null;
      queries = null;
    }
    isDone = true;
  }

  public String[] getQueries() {
    return(queries);
  }

  public boolean isDone() {
    return(isDone);
  }

  private String[] retrieveQueries() throws IOException {
    URLConnection connection = dataURL.openConnection();
    // Make sure browser doesn't cache this URL, since
    // I want different queries for each request.
    connection.setUseCaches(false);
    // Use ObjectInputStream so I can read a String[]
    // all at once.
    ObjectInputStream in =
      new ObjectInputStream(connection.getInputStream());
    try {
      // The return type of readObject is Object, so
      // I need a typecast to the actual type.
      String[] queryStrings = (String[])in.readObject();
      return(queryStrings);
    } catch(ClassNotFoundException cnfe) {
      return(null);
    }
  }
}

A class the encapsulates the URLs used by various search engines.

SearchSpec.java
*******************
/** 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);
  }
}

DebugExample.jsp Page that uses the DebugTag custom tag

# DebugExample.jsp Page that uses the DebugTag custom tag

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Illustration of SimplePrimeTag tag. 

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted. 
-->
<HTML>
<HEAD>
<TITLE>Using the Debug Tag</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>
<BODY>
<H1>Using the Debug Tag</H1>
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
Top of regular page. Blah, blah, blah. Yadda, yadda, yadda.
<P>
<cwp:debug>
<B>Debug:</B>
<UL>
  <LI>Current time: <%= new java.util.Date() %>
  <LI>Requesting hostname: <%= request.getRemoteHost() %>
  <LI>Session ID: <%= session.getId() %>
</UL>
</cwp:debug>
<P>
Bottom of regular page. Blah, blah, blah. Yadda, yadda, yadda.
</BODY>
</HTML>

package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.servlet.*;

/** A tag that includes the body content only if
 *  the "debug" request parameter is set.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class DebugTag extends TagSupport {
  public int doStartTag() {
    ServletRequest request = pageContext.getRequest();
    String debugFlag = request.getParameter("debug");
    if ((debugFlag != null) &&
        (!debugFlag.equalsIgnoreCase("false"))) {
      return(EVAL_BODY_INCLUDE);
    } else {
      return(SKIP_BODY);
    }
  }
}

ShearExample.java. Illustrates the effect of applying a shear transformation prior to drawing a square

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

/** An example of shear transformations on a rectangle. 
 *
 ***********************

public class ShearExample extends JPanel {
  private static int gap=10, width=100;
  private Rectangle rect = new Rectangle(gap, gap, 100, 100);

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;
    for (int i=0; i<5; i++) {
      g2d.setPaint(Color.red);
      g2d.fill(rect);
      // Each new square gets 0.2 more x shear.
      g2d.shear(0.2, 0.0);
      g2d.translate(2*gap + width, 0);
    }
  }

  public static void main(String[] args) {
    String title =
      "Shear: x shear ranges from 0.0 for the leftmost" +
      "'square' to 0.8 for the rightmost one.";
    WindowUtilities.openInJFrame(new ShearExample(),
                                 20*gap + 5*width, 
                                 5*gap + width,
                                 title);
  }
}

LineStyles.java Provides examples of the available styles for joining line segments

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

/** A demonstration of different controls when joining two line
 *  segments. The style of the line end point is controlled
 *  through the capStyle parameter.
 *
 ************************************

public class LineStyles extends JPanel {
  private GeneralPath path;
  private static int x = 30, deltaX = 150, y = 300,
                     deltaY = 250, thickness = 40;
  private Circle p1Large, p1Small, p2Large, p2Small,
                 p3Large, p3Small;
  private int compositeType = AlphaComposite.SRC_OVER;
  private AlphaComposite transparentComposite =
    AlphaComposite.getInstance(compositeType, 0.4F);
  private int[] caps =
    { BasicStroke.CAP_SQUARE, BasicStroke.CAP_BUTT,
      BasicStroke.CAP_ROUND };
  private String[] capNames =
    { "CAP_SQUARE", "CAP_BUTT", "CAP_ROUND" };
  private int[] joins =
    { BasicStroke.JOIN_MITER, BasicStroke.JOIN_BEVEL,
      BasicStroke.JOIN_ROUND };
  private String[] joinNames =
    { "JOIN_MITER", "JOIN_BEVEL", "JOIN_ROUND" };

  public LineStyles() {
    path = new GeneralPath();
    path.moveTo(x, y);
    p1Large = new Circle(x, y, thickness/2);
    p1Small = new Circle(x, y, 2);
    path.lineTo(x + deltaX, y - deltaY);
    p2Large = new Circle(x + deltaX, y - deltaY, thickness/2);
    p2Small = new Circle(x + deltaX, y - deltaY, 2);
    path.lineTo(x + 2*deltaX, y);
    p3Large = new Circle(x + 2*deltaX, y, thickness/2);
    p3Small = new Circle(x + 2*deltaX, y, 2);
    setFont(new Font("SansSerif", Font.BOLD, 20));
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;
    g2d.setColor(Color.lightGray);
    for(int i=0; i

Illustrates using a local font (Goudy Handtooled BT) to perform drawing in Java 2D

import java.awt.*;

/** An example of using local fonts to perform drawing in
 *  Java 2D.
 *
 **********************

public class FontExample extends GradientPaintExample {
  public FontExample() {
    GraphicsEnvironment env =
      GraphicsEnvironment.getLocalGraphicsEnvironment();
    env.getAvailableFontFamilyNames();
    setFont(new Font("Goudy Handtooled BT", Font.PLAIN, 100));
  }

  protected void drawBigString(Graphics2D g2d) {
    g2d.setPaint(Color.black);
    g2d.drawString("Java 2D", 25, 215);
  }

  public void paintComponent(Graphics g) {
    clear(g);
    Graphics2D g2d = (Graphics2D)g;
    drawGradientCircle(g2d);
    drawBigString(g2d);
  }

  public static void main(String[] args) {
    WindowUtilities.openInJFrame(new FontExample(), 380, 400);
  }
}

Draws a circle with a gradient fill

GradientPaintExample.java Draws a circle with a gradient fill. Inherits from ShapeExample.java. 
**************************************
import java.awt.*;

/** An example of applying a gradient fill to a circle. The
 *  color definition starts with red at (0,0), gradually
 *  changing to yellow at (175,175).
 *
 **********************************

public class GradientPaintExample extends ShapeExample {
  private GradientPaint gradient =
    new GradientPaint(0, 0, Color.red, 175, 175, Color.yellow,
                      true); // true means to repeat pattern

  public void paintComponent(Graphics g) {
    clear(g);
    Graphics2D g2d = (Graphics2D)g;
    drawGradientCircle(g2d);
  }

  protected void drawGradientCircle(Graphics2D g2d) {
    g2d.setPaint(gradient);
    g2d.fill(getCircle());
    g2d.setPaint(Color.black);
    g2d.draw(getCircle());
  }

  public static void main(String[] args) {
    WindowUtilities.openInJFrame(new GradientPaintExample(),
                                 380, 400);
  }
}

An applet that permits freehand drawing

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/** An applet that lets you perform freehand drawing.
 *  


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

public class SimpleWhiteboard extends Applet {
  protected int lastX=0, lastY=0;

  public void init() {
    setBackground(Color.white);
    setForeground(Color.blue);
    addMouseListener(new PositionRecorder());
    addMouseMotionListener(new LineDrawer());
  }

  protected void record(int x, int y) {
    lastX = x;
    lastY = y;
  }

  // Record position that mouse entered window or
  // where user pressed mouse button.
  
  private class PositionRecorder extends MouseAdapter {
    public void mouseEntered(MouseEvent event) {
      requestFocus(); // Plan ahead for typing
      record(event.getX(), event.getY());
    }

    public void mousePressed(MouseEvent event) {
      record(event.getX(), event.getY());
    }
  }

  // As user drags mouse, connect subsequent positions
  // with short line segments.
  
  private class LineDrawer extends MouseMotionAdapter {
    public void mouseDragged(MouseEvent event) {
      int x = event.getX();
      int y = event.getY();
      Graphics g = getGraphics();
      g.drawLine(lastX, lastY, x, y);
      record(x, y);
    }
  }
}

A TextField that uses key events to correct the spelling of the names of computer languages entered into it

import java.awt.*;
import java.awt.event.*;

/** A spelling-correcting TextField for entering
 *  a language name.
 *  


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

public class LanguageField extends TextField {
  private String[] substrings =
    { "", "J", "Ja", "Jav", "Java" };

  public LanguageField() {
    addKeyListener(new SpellingCorrector());
    addActionListener(new WordCompleter());
    addFocusListener(new SubliminalAdvertiser());
  }

  // Put caret at end of field.
  
  private void setCaret() {
    setCaretPosition(5);
  }
  
  // Listener to monitor/correct spelling as user types.
  
  private class SpellingCorrector extends KeyAdapter {
    public void keyTyped(KeyEvent event) {
      setLanguage();
      setCaret();
    }

    // Enter partial name of good programming language that
    // most closely matches what they've typed so far.
    
    private void setLanguage() {
      int length = getText().length();
      if (length <= 4) {
        setText(substrings[length]);
      } else {
        setText("Java");
      }
      setCaret();
    }
  }

  // Listener to replace current partial name with
  // most closely-matching name of good language.
  
  private class WordCompleter implements ActionListener {

    // When they hit RETURN, fill in the right answer.
    
    public void actionPerformed(ActionEvent event) {
      setText("Java");
      setCaret();
    }
  }

  // Listener to give the user a hint.
  
  private class SubliminalAdvertiser extends FocusAdapter {
    public void focusGained(FocusEvent event) {
      String text = getText();
      for(int i=0; i<10; i++) {
        setText("Hint: Java");
        setText(text);
      }
    }
  }
}

DebugTag.java Custom tag that optionally makes use of a tag body

DebugTag.java Custom tag that optionally makes use of a tag body

package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.servlet.*;

/** A tag that includes the body content only if
 *  the "debug" request parameter is set.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class DebugTag extends TagSupport {
  public int doStartTag() {
    ServletRequest request = pageContext.getRequest();
    String debugFlag = request.getParameter("debug");
    if ((debugFlag != null) &&
        (!debugFlag.equalsIgnoreCase("false"))) {
      return(EVAL_BODY_INCLUDE);
    } else {
      return(SKIP_BODY);
    }
  }
}

HeadingTag.java Custom tag that makes use of a tag body

HeadingTag.java Custom tag that makes use of a tag body


package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

/** Generates an HTML heading with the specified background
 *  color, foreground color, alignment, font, and font size.
 *  You can also turn on a border around it, which normally
 *  just barely encloses the heading, but which can also
 *  stretch wider. All attributes except the background
 *  color are optional.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class HeadingTag extends TagSupport {
  private String bgColor; // The one required attribute
  private String color = null;
  private String align="CENTER";
  private String fontSize="36";
  private String fontList="Arial, Helvetica, sans-serif";
  private String border="0";
  private String width=null;

  public void setBgColor(String bgColor) {
    this.bgColor = bgColor;
  }

  public void setColor(String color) {
    this.color = color;
  }

  public void setAlign(String align) {
    this.align = align;
  }

  public void setFontSize(String fontSize) {
    this.fontSize = fontSize;
  }

  public void setFontList(String fontList) {
    this.fontList = fontList;
  }

  public void setBorder(String border) {
    this.border = border;
  }

  public void setWidth(String width) {
    this.width = width;
  }

  public int doStartTag() {
    try {
      JspWriter out = pageContext.getOut();
      out.print("<TABLE BORDER=" + border +
                " BGCOLOR=\"" + bgColor + "\"" +
                " ALIGN=\"" + align + "\"");
      if (width != null) {
        out.print(" WIDTH=\"" + width + "\"");
      }
      out.print("><TR><TH>");
      out.print("<SPAN STYLE=\"" +
                "font-size: " + fontSize + "px; " +
                "font-family: " + fontList + "; ");
      if (color != null) {
        out.println("color: " + color + ";");
      }
      out.print("\"> "); // End of <SPAN ...>
    } catch(IOException ioe) {
      System.out.println("Error in HeadingTag: " + ioe);
    }
    return(EVAL_BODY_INCLUDE); // Include tag body
  }

  public int doEndTag() {
    try {
      JspWriter out = pageContext.getOut();
      out.print("</SPAN></TABLE>");
    } catch(IOException ioe) {
      System.out.println("Error in HeadingTag: " + ioe);
    }
    return(EVAL_PAGE); // Continue with rest of JSP page
  }
}

PrimeTag.java Custom tag that outputs a random prime number of a user-specifiable approximate length

PrimeTag.java Custom tag that outputs a random prime number of a user-specifiable approximate length

package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

/** Generates an N-digit random prime (default N = 50).
 *  Extends SimplePrimeTag, adding a length attribute
 *  to set the size of the prime. The doStartTag
 *  method of the parent class uses the len field
 *  to determine the approximate length of the prime.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class PrimeTag extends SimplePrimeTag {
  public void setLength(String length) {
    try {
      len = Integer.parseInt(length);
    } catch(NumberFormatException nfe) {
      len = 50;
    }
  }
}

SimplePrimeTag.java Custom tag that outputs a random prime number of a fixed approximate length

SimplePrimeTag.java Custom tag that outputs a random prime number of a fixed approximate length


package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.math.*;
import cwp.*;

/** Generates a prime of approximately 50 digits.
 *  (50 is actually the length of the random number
 *  generated -- the first prime above that number will
 *  be returned.)
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class SimplePrimeTag extends TagSupport {
  protected int len = 50;

  public int doStartTag() {
    try {
      JspWriter out = pageContext.getOut();
      BigInteger prime = Primes.nextPrime(Primes.random(len));
      out.print(prime);
    } catch(IOException ioe) {
      System.out.println("Error generating prime: " + ioe);
    }
    return(SKIP_BODY);
  }
}