KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > components > flow > apples > samples > GuessGameApple


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon.components.flow.apples.samples;
17
18 import java.util.HashMap JavaDoc;
19 import java.util.Map JavaDoc;
20 import java.util.Random JavaDoc;
21
22 import org.apache.avalon.framework.logger.AbstractLogEnabled;
23 import org.apache.cocoon.ProcessingException;
24 import org.apache.cocoon.components.flow.apples.AppleController;
25 import org.apache.cocoon.components.flow.apples.AppleRequest;
26 import org.apache.cocoon.components.flow.apples.AppleResponse;
27
28 /**
29  * GuessGameApple shows an easy Apples implementation for a number guessing game.
30  */

31 public class GuessGameApple extends AbstractLogEnabled implements AppleController {
32
33     private final int random = (new Random JavaDoc()).nextInt(10) + 1;
34     private int guesses = 0;
35
36     public String JavaDoc toString() {
37         return "GuessGameApple[ random=" + this.random + " | guesses=" + this.guesses + "]";
38     }
39
40     public void process(AppleRequest req, AppleResponse res) throws ProcessingException {
41         
42         String JavaDoc hint = "No hints yet.";
43         String JavaDoc targetURI = "guess/guess.jx";
44         
45         int newGuess = -1;
46         String JavaDoc newGuessString = req.getCocoonRequest().getParameter("guess");
47         
48         if (newGuessString != null) {
49             newGuess = Integer.parseInt(newGuessString);
50             this.guesses++;
51
52             if (this.random == newGuess) {
53                 targetURI = "guess/success.jx";
54             } else {
55                 if (this.random < newGuess) {
56                     hint = "Try lower.";
57                 } else {
58                     hint = "Try higher.";
59                 }
60             }
61         }
62
63         getLogger().debug(toString());
64
65         Map JavaDoc bizdata = new HashMap JavaDoc();
66         bizdata.put("random" , "" + this.random);
67         bizdata.put("guesses", "" + this.guesses);
68         bizdata.put("hint" , hint);
69
70         res.sendPage(targetURI, bizdata);
71     }
72     
73 }
74
Popular Tags