KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jmanage > webui > applets > GraphApplet


1 /**
2  * Copyright 2004-2005 jManage.org
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.jmanage.webui.applets;
17
18 import org.jfree.data.time.TimeSeries;
19 import org.jfree.data.time.TimeSeriesCollection;
20 import org.jfree.data.time.Second;
21 import org.jfree.chart.ChartFactory;
22 import org.jfree.chart.JFreeChart;
23 import org.jfree.chart.ChartPanel;
24 import org.jfree.chart.title.Title;
25
26 import javax.swing.*;
27 import java.applet.Applet JavaDoc;
28 import java.awt.*;
29 import java.util.Date JavaDoc;
30 import java.util.Properties JavaDoc;
31 import java.util.LinkedList JavaDoc;
32 import java.util.StringTokenizer JavaDoc;
33 import java.net.*;
34 import java.io.*;
35
36 /**
37  *
38  * Date: May 27, 2005
39  * @author Rakesh Kalra
40  */

41 public class GraphApplet extends JApplet implements GraphAppletParameters {
42
43     private JFreeChart chart;
44     private String JavaDoc graphTitle;
45     // polling interval in seconds
46
private long pollingInterval;
47     // attributes to be graphed
48
private String JavaDoc attributes;
49     // attribute display names
50
private String JavaDoc displayNames;
51     // remoteURL to get the data from
52
private URL remoteURL;
53     // yAxisLabel
54
private String JavaDoc yAxisLabel;
55     // scale factor
56
private double scaleFactor = 1;
57     // scale up or down
58
private boolean scaleUp = true;
59
60     public void init() {
61         // read parameters
62
graphTitle = getParameter(GRAPH_TITLE);
63         pollingInterval = Long.parseLong(getParameter(POLLING_INTERVAL));
64         attributes = getParameter(ATTRIBUTES);
65         displayNames = getParameter(ATTRIBUTE_DISPLAY_NAMES);
66         yAxisLabel = getParameter(Y_AXIS_LABEL);
67         if(yAxisLabel == null) yAxisLabel = "";
68
69         try {
70             remoteURL = new URL(getParameter(REMOTE_URL));
71         } catch (MalformedURLException e) {
72             throw new RuntimeException JavaDoc(e);
73         }
74         String JavaDoc temp = getParameter(SCALE_FACTOR);
75         if(temp != null){
76             scaleFactor = Double.parseDouble(temp);
77         }
78         temp = getParameter(SCALE_UP);
79         if(temp != null){
80             scaleUp = temp.equals("true");
81         }
82
83         /* get initial set of values for the graph */
84         poll();
85
86         /* create the chart */
87         chart = ChartFactory.createTimeSeriesChart(
88                         graphTitle, // chart title
89
"Time", // domain axis label
90
yAxisLabel, // range axis label
91
dataset, // data
92
true, // include legend
93
true, // tooltips
94
false // urls. would be a pretty good extension so that you could click on a task line to open the document in notes
95
);
96         chart.setBackgroundPaint(Color.WHITE);
97         chart.setBorderVisible(false);
98         chart.setBorderPaint(Color.WHITE);
99
100         stopThread = false;
101         new MyThread().start();
102     }
103
104     public void start(){
105         final ChartPanel chartPanel = new ChartPanel(chart);
106         this.setContentPane(chartPanel);
107     }
108
109     private boolean stopThread = false;
110
111     public void stop(){
112         stopThread = true;
113     }
114
115     private class MyThread extends Thread JavaDoc{
116         public void run(){
117             while(!stopThread){
118                 try {
119                     Thread.sleep(pollingInterval * 1000);
120                 } catch (InterruptedException JavaDoc e) {
121                 }
122                 /* get new data */
123                 poll();
124             }
125         }
126     }
127
128     private TimeSeriesCollection dataset;
129     private TimeSeries[] series;
130
131     private void poll() {
132         Properties JavaDoc properties = getNewValues();
133         if(properties == null) return;
134         long timestamp = Long.parseLong(properties.getProperty("timestamp"));
135         // todo: this is not used
136
String JavaDoc attributes = properties.getProperty("attributes");
137         String JavaDoc values = properties.getProperty("values");
138
139         if(dataset == null){
140             dataset = new TimeSeriesCollection();
141             dataset.setDomainIsPointsInTime(false);
142             StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(displayNames, "|");
143             series = new TimeSeries[tokenizer.countTokens()];
144             for(int i=0; tokenizer.hasMoreTokens(); i++){
145                 series[i] = new TimeSeries(tokenizer.nextToken(), Second.class);
146                 series[i].setMaximumItemCount(100);// todo: this should somehow be configurable
147
dataset.addSeries(series[i]);
148             }
149         }
150
151         /* set the next set of values */
152         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(values, "|");
153         assert series.length == tokenizer.countTokens();
154         Second second = new Second(new Date JavaDoc(timestamp));
155         for(int i=0; i<series.length; i++){
156             double attrValue = Double.parseDouble(tokenizer.nextToken());
157             attrValue = scaleUp?attrValue * scaleFactor: attrValue/scaleFactor;
158             series[i].add(second, attrValue);
159         }
160     }
161
162     private Properties JavaDoc getNewValues(){
163
164         String JavaDoc output = doHttpPost();
165         if(output == null) return null;
166         Properties JavaDoc properties = new Properties JavaDoc();
167         try {
168             properties.load(new ByteArrayInputStream(output.getBytes()));
169         } catch (IOException e) {
170             throw new RuntimeException JavaDoc(e);
171         }
172         return properties;
173     }
174
175
176     private String JavaDoc doHttpPost(){
177
178         try {
179             String JavaDoc queryString="attributes=" +
180                     URLEncoder.encode(attributes, "UTF-8");
181             HttpURLConnection conn = (HttpURLConnection) remoteURL.openConnection();
182             conn.setDoInput(true);
183             conn.setDoOutput(true);
184             conn.setRequestMethod("POST");
185             // Sets the default Content-type and content lenght for POST requests
186
conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
187             conn.setRequestProperty("Content-length", Integer.toString(queryString.length()));
188             // Gets the output stream and POSTs data
189
OutputStream postStream = conn.getOutputStream();
190             OutputStreamWriter postWriter = new OutputStreamWriter(postStream);
191             postWriter.write(queryString);
192             postWriter.flush();
193             postWriter.close();
194
195             // check the response code
196
int responseCode = conn.getResponseCode();
197             if (responseCode != HttpURLConnection.HTTP_OK) {
198                 // todo: what should the user see?
199
return null;
200             }
201
202             BufferedReader reader = new BufferedReader(
203                     new InputStreamReader(conn.getInputStream()));
204             StringBuffer JavaDoc output = new StringBuffer JavaDoc();
205             String JavaDoc outputLine = reader.readLine();
206             while(outputLine != null){
207                 output.append(outputLine + "\n");
208                 outputLine = reader.readLine();
209             }
210
211             return output.toString();
212
213         } catch (UnsupportedEncodingException e) {
214             throw new RuntimeException JavaDoc(e);
215         } catch (ProtocolException e) {
216             throw new RuntimeException JavaDoc(e);
217         } catch (IOException e) {
218             throw new RuntimeException JavaDoc(e);
219         }
220     }
221 }
222
Popular Tags