aboutsummaryrefslogtreecommitdiff
path: root/basebuilder-3.6.2/org.eclipse.releng.basebuilder/plugins/org.eclipse.test.performance.ui/src/org/eclipse/test/performance/ui/Utils.java
blob: b4feffdbda3bb21a73ca55a31e393fd2656f5f61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/*******************************************************************************
 * Copyright (c) 2000, 2009 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.test.performance.ui;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.test.internal.performance.PerformanceTestPlugin;
import org.eclipse.test.internal.performance.db.Variations;
import org.eclipse.test.internal.performance.results.utils.Util;
import org.osgi.framework.Bundle;


public class Utils {

	public final static double STANDARD_ERROR_THRESHOLD = 0.03; // 3%
	static final NumberFormat PERCENT_FORMAT = NumberFormat.getPercentInstance();
	static {
		PERCENT_FORMAT.setMaximumFractionDigits(1);
	}
	static final DecimalFormat DEVIATION_FORMAT = (DecimalFormat) NumberFormat.getPercentInstance();
	static {
		DEVIATION_FORMAT.setMaximumFractionDigits(1);
		DEVIATION_FORMAT.setMinimumFractionDigits(1);
		DEVIATION_FORMAT.setPositivePrefix("+");
		DEVIATION_FORMAT.setNegativePrefix("- ");
	}
	static final DecimalFormat STDERR_FORMAT = (DecimalFormat) NumberFormat.getNumberInstance();
	static {
		STDERR_FORMAT.setMaximumFractionDigits(1);
		STDERR_FORMAT.setMinimumFractionDigits(1);
		STDERR_FORMAT.setMultiplier(100);
	}
	public final static String STANDARD_ERROR_THRESHOLD_STRING = PERCENT_FORMAT.format(STANDARD_ERROR_THRESHOLD);

	// Image files
	public final static String UNKNOWN_IMAGE="images/Unknown.gif";
	public final static String OK_IMAGE="images/OK.gif";
	public final static String OK_IMAGE_WARN="images/OK_caution.gif";
	public final static String FAIL_IMAGE="images/FAIL.gif";
	public final static String FAIL_IMAGE_WARN="images/FAIL_caution.gif";
	public final static String FAIL_IMAGE_EXPLAINED="images/FAIL_greyed.gif";
	public final static String LIGHT="images/light.gif";
	public final static String WARNING_OBJ="images/warning_obj.gif";

	// Java script files
	public final static String TOOLTIP_SCRIPT = "scripts/ToolTip.js";
	public final static String TOOLTIP_STYLE = "scripts/ToolTip.css";
	public final static String FINGERPRINT_SCRIPT = "scripts/Fingerprints.js";

	// Doc files
	public final static String HELP = "doc/help.html";

	// Status
	public final static int OK = 0;
	public final static int NAN = 0x1;
	public final static int ERR = 0x2;

	/**
	 * Return <html><head><meta http-equiv="Content-Type"
	 *         content="text/html; charset=iso-8859-1">
	 */
	public final static String HTML_OPEN = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n";

	/**
	 * Return "&lt;/html&gt;".
	 */
	public final static String HTML_CLOSE = "</html>\n";

	/**
	 * Default style-sheet used on eclipse.org
	 */
	public final static String HTML_DEFAULT_CSS = "<style type=\"text/css\">" + "p, table, td, th {  font-family: arial, helvetica, geneva; font-size: 10pt}\n"
			+ "pre {  font-family: \"Courier New\", Courier, mono; font-size: 10pt}\n" + "h2 { font-family: arial, helvetica, geneva; font-size: 18pt; font-weight: bold ; line-height: 14px}\n"
			+ "code {  font-family: \"Courier New\", Courier, mono; font-size: 10pt}\n" + "sup {  font-family: arial,helvetica,geneva; font-size: 10px}\n"
			+ "h3 {  font-family: arial, helvetica, geneva; font-size: 14pt; font-weight: bold}\n" + "li {  font-family: arial, helvetica, geneva; font-size: 10pt}\n"
			+ "h1 {  font-family: arial, helvetica, geneva; font-size: 28px; font-weight: bold}\n"
			+ "body {  font-family: arial, helvetica, geneva; font-size: 10pt; clip:   rect(   ); margin-top: 5mm; margin-left: 3mm}\n"
			+ ".indextop { font-size: x-large;; font-family: Verdana, Arial, Helvetica, sans-serif; font-weight: bold}\n"
			+ ".indexsub { font-size: xx-small;; font-family: Arial, Helvetica, sans-serif; color: #8080FF}\n" + "</style>\n\n";

	/**
	 * Creates a Variations object using build id pattern, config and jvm.
	 *
	 * @param buildIdPattern
	 * @param config
	 * @param jvm
	 */
	public static Variations getVariations(String buildIdPattern, String config, String jvm) {
		String buildIdPatterns = buildIdPattern.replace(',', '%');
		Variations variations = new Variations();
		variations.put(PerformanceTestPlugin.CONFIG, config);
		variations.put(PerformanceTestPlugin.BUILD, buildIdPatterns);
		variations.put("jvm", jvm);
		return variations;
	}

	/**
	 * Copy all bundle files contained in the given path
	 */
	public static void copyBundleFiles(Bundle bundle, String path, String pattern, File output) {
		Enumeration imageFiles = bundle.findEntries(path, pattern, false);
		while (imageFiles.hasMoreElements()) {
			URL url = (URL) imageFiles.nextElement();
			try {
				File outputFile = new File(output, url.getFile());
				if (!outputFile.getParentFile().exists()) {
					outputFile.getParentFile().mkdirs();
				}
				Util.copyStream(url.openStream(), outputFile);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * Downsample Image to 8 bit depth format so that the resulting image data
	 * can be saved to GIF. Note. If the source image contains photo quality
	 * content with more than 256 colours, resulting data will look very poor.
	 */
	static int closest(RGB[] rgbs, int n, RGB rgb) {
		int minDist = 256 * 256 * 3;
		int minIndex = 0;
		for (int i = 0; i < n; ++i) {
			RGB rgb2 = rgbs[i];
			int da = rgb2.red - rgb.red;
			int dg = rgb2.green - rgb.green;
			int db = rgb2.blue - rgb.blue;
			int dist = da * da + dg * dg + db * db;
			if (dist < minDist) {
				minDist = dist;
				minIndex = i;
			}
		}
		return minIndex;
	}

	static class ColorCounter implements Comparable {
		RGB rgb;

		int count;

		public int compareTo(Object o) {
			return ((ColorCounter) o).count - this.count;
		}
	}

	public static ImageData downSample(Image image) {
		ImageData data = image.getImageData();
		if (!data.palette.isDirect && data.depth <= 8)
			return data;

		// compute a histogram of color frequencies
		HashMap freq = new HashMap();
		int width = data.width;
		int[] pixels = new int[width];
		int[] maskPixels = new int[width];
		for (int y = 0, height = data.height; y < height; ++y) {
			data.getPixels(0, y, width, pixels, 0);
			for (int x = 0; x < width; ++x) {
				RGB rgb = data.palette.getRGB(pixels[x]);
				ColorCounter counter = (ColorCounter) freq.get(rgb);
				if (counter == null) {
					counter = new ColorCounter();
					counter.rgb = rgb;
					freq.put(rgb, counter);
				}
				counter.count++;
			}
		}

		// sort colors by most frequently used
		ColorCounter[] counters = new ColorCounter[freq.size()];
		freq.values().toArray(counters);
		Arrays.sort(counters);

		// pick the most frequently used 256 (or fewer), and make a palette
		ImageData mask = null;
		if (data.transparentPixel != -1 || data.maskData != null) {
			mask = data.getTransparencyMask();
		}
		int n = Math.min(256, freq.size());
		RGB[] rgbs = new RGB[n + (mask != null ? 1 : 0)];
		for (int i = 0; i < n; ++i)
			rgbs[i] = counters[i].rgb;
		if (mask != null) {
			rgbs[rgbs.length - 1] = data.transparentPixel != -1 ? data.palette.getRGB(data.transparentPixel) : new RGB(255, 255, 255);
		}
		PaletteData palette = new PaletteData(rgbs);

		// create a new image using the new palette:
		// for each pixel in the old image, look up the best matching
		// index in the new palette
		ImageData newData = new ImageData(width, data.height, 8, palette);
		if (mask != null)
			newData.transparentPixel = rgbs.length - 1;
		for (int y = 0, height = data.height; y < height; ++y) {
			data.getPixels(0, y, width, pixels, 0);
			if (mask != null)
				mask.getPixels(0, y, width, maskPixels, 0);
			for (int x = 0; x < width; ++x) {
				if (mask != null && maskPixels[x] == 0) {
					pixels[x] = rgbs.length - 1;
				} else {
					RGB rgb = data.palette.getRGB(pixels[x]);
					pixels[x] = closest(rgbs, n, rgb);
				}
			}
			newData.setPixels(0, y, width, pixels, 0);
		}
		return newData;
	}

	/**
	 * Returns the date/time from the build id in format yyyymmddhm
	 *
	 * @param buildId
	 * @return date/time in format YYYYMMDDHHMM, ie. 200504060010
	 */
	public static long getDateFromBuildID(String buildId) {
		return getDateFromBuildID(buildId, false);
	}

	public static long getDateFromBuildID(String buildId, boolean matchLast) {
		Calendar calendar = Calendar.getInstance();

		if (buildId.indexOf('_') != -1) {
			String[] buildIdParts = buildId.split("_");

			int buildIdSegment = 1;
			if (matchLast)
				buildIdSegment = buildIdParts.length - 1;
			// if release build, expect <release>_<release date and
			// timestamp>_<date and timestamp test ran>
			// use test date and time for plotting
			int year = Integer.parseInt(buildIdParts[buildIdSegment].substring(0, 4));
			int month = Integer.parseInt(buildIdParts[buildIdSegment].substring(4, 6)) - 1;
			int date = Integer.parseInt(buildIdParts[buildIdSegment].substring(6, 8));
			int hours = Integer.parseInt(buildIdParts[buildIdSegment].substring(8, 10));
			int min = Integer.parseInt(buildIdParts[buildIdSegment].substring(10, 12));

			calendar.set(year, month, date, hours, min);
			return calendar.getTimeInMillis();

		} else if (buildId.indexOf('-') != -1) {
			// if regular build, expect <buildType><date>-<time> format
			String[] buildIdParts = buildId.split("-");
			int year = Integer.parseInt(buildIdParts[0].substring(1, 5));
			int month = Integer.parseInt(buildIdParts[0].substring(5, 7)) - 1;
			int date = Integer.parseInt(buildIdParts[0].substring(7, 9));
			int hours = Integer.parseInt(buildIdParts[1].substring(0, 2));
			int min = Integer.parseInt(buildIdParts[1].substring(2, 4));
			calendar.set(year, month, date, hours, min);

			return calendar.getTimeInMillis();
		}

		return -1;
	}

	/**
	 * Returns a message corresponding to given statistics.
	 *
	 * @param resultStats The value with its standard error
	 * @param full
	 * @return The failure message. May be empty if stats are good...
	 */
	public static String failureMessage(double[] resultStats, boolean full) {
		StringBuffer buffer = new StringBuffer();
		int level = confidenceLevel(resultStats);
//		boolean isWarn = (level & WARN) != 0;
		boolean isErr = (level & ERR) != 0;
		if (full) {
			if (isErr) {
				buffer.append("*** WARNING ***  ");
	 			buffer.append(Messages.bind(Messages.standardError, PERCENT_FORMAT.format(resultStats[1]), STANDARD_ERROR_THRESHOLD_STRING));
			}
			return buffer.toString();
		}
		if (resultStats != null) {
			double deviation = resultStats[0];
			buffer.append("<font color=\"#0000FF\" size=\"1\">");
			if (Double.isNaN(deviation) || Double.isInfinite(deviation)) {
	 			buffer.append(" [n/a]");
 			} else {
				double stderr = resultStats[1];
				deviation = Math.abs(deviation)<0.001 ? 0 : -deviation;
	 			if (Double.isNaN(stderr) || Double.isInfinite(stderr)) {
		 			buffer.append(DEVIATION_FORMAT.format(deviation));
					buffer.append("</font><font color=\"#DDDD00\" size=\"1\"> ");
		 			buffer.append(" [n/a]");
	 			} else {
		 			buffer.append(DEVIATION_FORMAT.format(deviation));
	 				buffer.append(" [&#177;");
	 				buffer.append(STDERR_FORMAT.format(Math.abs(stderr)));
	 				buffer.append(']');
	 			}
 			}
			buffer.append("</font>");
		}
		return buffer.toString();
	}

	/**
	 * Returns the confidence level for given statistics:
	 * <ul>
	 * <li>{@link #NAN}: if the value is infinite or not a number</li>
	 * <li>{@link #ERR}: if the standard error is over the expected threshold ({@link #STANDARD_ERROR_THRESHOLD})</li>
	 * <li>{@link #OK}: in all other cases</li>
	 * </ul>
	 *
	 * @param resultStats array of 2 doubles, the former is the average value and
	 * 	the latter is the standard error made while computing the average.
	 * @return a value telling caller the level of confidence of the provided value
	 */
	public static int confidenceLevel(double[] resultStats) {
		int level = OK;
 		if (resultStats != null){
			if (Double.isNaN(resultStats[0]) || Double.isInfinite(resultStats[0])) {
				level = NAN;
 			} else {
//	 			if (resultStats[1] >= (STANDARD_ERROR_THRESHOLD/2)) { // warns standard error higher than the half of authorized threshold
//	 				level |= WARN;
//	 			}
	 			if (resultStats[1] >= STANDARD_ERROR_THRESHOLD) { // standard error higher than the authorized threshold
	 				level = ERR;
	 			}
 			}
 		}
		return level;
	}

	/**
	 * Get an icon image corresponding to a given level of confidence and explanation.
	 *
	 * @param confidence the confiden level
	 * @param hasExplanation flags indicates whether the confidence may be tempered by an explanation
	 * @return Corresponding image
	 */
	public static String getImage(int confidence, boolean scenarioFailed, boolean hasExplanation) {
	    String image = null;

	    if (scenarioFailed) {
	    	if (hasExplanation) {
		    	image = FAIL_IMAGE_EXPLAINED;
		    } else if ((confidence & ERR) != 0) {
    			image = FAIL_IMAGE_WARN;
		    } else {
    			image = FAIL_IMAGE;
		    }
	    } else if ((confidence & NAN) != 0) {
			image = UNKNOWN_IMAGE;
	    } else if ((confidence & ERR) != 0) {
	   		image = OK_IMAGE_WARN;
	    } else {
   			image = OK_IMAGE;
	    }
	    return image;
    }

/**
 * @param outputFile
 * @param image
 */
public static void saveImage(File outputFile, Image image) {
	// Save image
	ImageData data = downSample(image);
	ImageLoader imageLoader = new ImageLoader();
	imageLoader.data = new ImageData[] { data };

	OutputStream out = null;
	try {
		out = new BufferedOutputStream(new FileOutputStream(outputFile));
		imageLoader.save(out, SWT.IMAGE_GIF);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} finally {
		image.dispose();
		if (out != null) {
			try {
				out.close();
			} catch (IOException e1) {
				// silently ignored
			}
		}
	}
}

}