001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.activemq.web;
018    
019    import java.io.IOException;
020    import java.io.PrintWriter;
021    import java.util.Hashtable;
022    import java.util.Map;
023    
024    import javax.jms.Destination;
025    import javax.jms.JMSException;
026    import javax.jms.Message;
027    import javax.jms.Session;
028    import javax.servlet.ServletException;
029    import javax.servlet.http.HttpServletRequest;
030    import javax.servlet.http.HttpServletResponse;
031    
032    /**
033     * A servlet which will publish dummy market data prices
034     * 
035     * 
036     */
037    public class PortfolioPublishServlet extends MessageServletSupport {
038    
039        private static final int MAX_DELTA_PERCENT = 1;
040        private static final Map<String, Double> LAST_PRICES = new Hashtable<String, Double>();
041    
042        public void init() throws ServletException {
043            super.init();
044        }
045    
046        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
047            PrintWriter out = response.getWriter();
048            String[] stocks = request.getParameterValues("stocks");
049            if (stocks == null || stocks.length == 0) {
050                out.println("<html><body>No <b>stocks</b> query parameter specified. Cannot publish market data</body></html>");
051            } else {
052                Integer total = (Integer)request.getSession(true).getAttribute("total");
053                if (total == null) {
054                    total = Integer.valueOf(0);
055                }
056    
057                int count = getNumberOfMessages(request);
058                total = Integer.valueOf(total.intValue() + count);
059                request.getSession().setAttribute("total", total);
060    
061                try {
062                    WebClient client = WebClient.getWebClient(request);
063                    for (int i = 0; i < count; i++) {
064                        sendMessage(client, stocks);
065                    }
066                    out.print("<html><head><meta http-equiv='refresh' content='");
067                    String refreshRate = request.getParameter("refresh");
068                    if (refreshRate == null || refreshRate.length() == 0) {
069                        refreshRate = "1";
070                    }
071                    out.print(refreshRate);
072                    out.println("'/></head>");
073                    out.println("<body>Published <b>" + escape(Integer.toString(count)) + "</b> of " + escape(Integer.toString(total))
074                            + " price messages.  Refresh = " + escape(refreshRate) + "s");
075                    out.println("</body></html>");
076    
077                } catch (JMSException e) {
078                    out.println("<html><body>Failed sending price messages due to <b>" + e + "</b></body></html>");
079                    log("Failed to send message: " + e, e);
080                }
081            }
082        }
083    
084        protected void sendMessage(WebClient client, String[] stocks) throws JMSException {
085            Session session = client.getSession();
086    
087            int idx = 0;
088            while (true) {
089                idx = (int)Math.round(stocks.length * Math.random());
090                if (idx < stocks.length) {
091                    break;
092                }
093            }
094            String stock = stocks[idx];
095            Destination destination = session.createTopic("STOCKS." + stock);
096            String stockText = createStockText(stock);
097            log("Sending: " + stockText + " on destination: " + destination);
098            Message message = session.createTextMessage(stockText);
099            client.send(destination, message);
100        }
101    
102        protected String createStockText(String stock) {
103            Double value = LAST_PRICES.get(stock);
104            if (value == null) {
105                value = new Double(Math.random() * 100);
106            }
107    
108            // lets mutate the value by some percentage
109            double oldPrice = value.doubleValue();
110            value = new Double(mutatePrice(oldPrice));
111            LAST_PRICES.put(stock, value);
112            double price = value.doubleValue();
113    
114            double offer = price * 1.001;
115    
116            String movement = (price > oldPrice) ? "up" : "down";
117            return "<price stock='" + stock + "' bid='" + price + "' offer='" + offer + "' movement='" + movement + "'/>";
118        }
119    
120        protected double mutatePrice(double price) {
121            double percentChange = (2 * Math.random() * MAX_DELTA_PERCENT) - MAX_DELTA_PERCENT;
122    
123            return price * (100 + percentChange) / 100;
124        }
125    
126        protected int getNumberOfMessages(HttpServletRequest request) {
127            String name = request.getParameter("count");
128            if (name != null) {
129                return Integer.parseInt(name);
130            }
131            return 1;
132        }
133    
134        protected String escape(String text) throws IOException {
135            return java.net.URLEncoder.encode(text, "UTF-8");
136        }
137    }