jazz/ActiveMQ/08-10-27: PortfolioPublishServlet.java

File PortfolioPublishServlet.java, 5.1 KB (added by jazz, 17 years ago)
Line 
1/**
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17package org.apache.activemq.web;
18
19import java.io.IOException;
20import java.io.PrintWriter;
21import java.util.Hashtable;
22import java.util.Map;
23
24import javax.jms.Destination;
25import javax.jms.JMSException;
26import javax.jms.Message;
27import javax.jms.Session;
28import javax.servlet.ServletException;
29import javax.servlet.http.HttpServletRequest;
30import javax.servlet.http.HttpServletResponse;
31
32/**
33 * A servlet which will publish dummy market data prices
34 *
35 * @version $Revision: 1.1.1.1 $
36 */
37public class PortfolioPublishServlet extends MessageServletSupport {
38
39    private static final int MAX_DELTA_PERCENT = 1;
40    private static final Map<String, Double> LAST_PRICES = new Hashtable<String, Double>();
41
42    public void init() throws ServletException {
43        super.init();
44    }
45
46    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
47        PrintWriter out = response.getWriter();
48        String[] stocks = request.getParameterValues("stocks");
49        if (stocks == null || stocks.length == 0) {
50            out.println("<html><body>No <b>stocks</b> query parameter specified. Cannot publish market data</body></html>");
51        } else {
52            Integer total = (Integer)request.getSession(true).getAttribute("total");
53            if (total == null) {
54                total = Integer.valueOf(0);
55            }
56
57            int count = getNumberOfMessages(request);
58            total = Integer.valueOf(total.intValue() + count);
59            request.getSession().setAttribute("total", total);
60
61            try {
62                WebClient client = WebClient.getWebClient(request);
63                for (int i = 0; i < count; i++) {
64                    sendMessage(client, stocks);
65                }
66                out.print("<html><head><meta http-equiv='refresh' content='");
67                String refreshRate = request.getParameter("refresh");
68                if (refreshRate == null || refreshRate.length() == 0) {
69                    refreshRate = "1";
70                }
71                out.print(refreshRate);
72                out.println("'/></head>");
73                out.println("<body>Published <b>" + count + "</b> of " + total + " price messages.  Refresh = " + refreshRate + "s");
74                out.println("</body></html>");
75
76            } catch (JMSException e) {
77                out.println("<html><body>Failed sending price messages due to <b>" + e + "</b></body></html>");
78                log("Failed to send message: " + e, e);
79            }
80        }
81    }
82
83    protected void sendMessage(WebClient client, String[] stocks) throws JMSException {
84        Session session = client.getSession();
85
86        int idx = 0;
87        while (true) {
88            idx = (int)Math.round(stocks.length * Math.random());
89            if (idx < stocks.length) {
90                break;
91            }
92        }
93        String stock = stocks[idx];
94        Destination destination = session.createTopic("STOCKS." + stock);
95        String stockText = createStockText(stock);
96        log("Sending: " + stockText + " on destination: " + destination);
97        Message message = session.createTextMessage(stockText);
98        client.send(destination, message);
99    }
100
101    protected String createStockText(String stock) {
102        Double value = LAST_PRICES.get(stock);
103        if (value == null) {
104            value = new Double(Math.random() * 100);
105        }
106
107        // lets mutate the value by some percentage
108        double oldPrice = value.doubleValue();
109        value = new Double(mutatePrice(oldPrice));
110        LAST_PRICES.put(stock, value);
111        double price = value.doubleValue();
112
113        double offer = price * 1.001;
114
115        String movement = (price > oldPrice) ? "up" : "down";
116        return "<price stock='" + stock + "' bid='" + price + "' offer='" + offer + "' movement='" + movement + "'/>";
117    }
118
119    protected double mutatePrice(double price) {
120        double percentChange = (2 * Math.random() * MAX_DELTA_PERCENT) - MAX_DELTA_PERCENT;
121
122        return price * (100 + percentChange) / 100;
123    }
124
125    protected int getNumberOfMessages(HttpServletRequest request) {
126        String name = request.getParameter("count");
127        if (name != null) {
128            return Integer.parseInt(name);
129        }
130        return 1;
131    }
132}