1 package com.stateofflow.eclipse.metrics.export.html;
2
3 import java.io.BufferedOutputStream;
4 import java.io.File;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.OutputStream;
9 import java.net.URL;
10 import java.util.Enumeration;
11
12 import org.eclipse.core.runtime.IProgressMonitor;
13
14 import com.stateofflow.eclipse.metrics.MetricsPlugin;
15
16 final class MetricsDescriptionWriter {
17 private final File directory;
18
19 public MetricsDescriptionWriter(final File directory) {
20 this.directory = directory;
21 }
22
23 public void write(final IProgressMonitor monitor) {
24 monitor.subTask("Copying metric descriptions");
25
26 final Enumeration<String> enumeration = getDescriptionEntryPaths();
27 while (enumeration.hasMoreElements()) {
28 final String entryPath = enumeration.nextElement();
29 copyToDescriptionsDirectory(entryPath);
30 }
31
32 monitor.worked(1);
33 }
34
35 @SuppressWarnings("unchecked")
36 private Enumeration<String> getDescriptionEntryPaths() {
37 return MetricsPlugin.getDefault().getBundle().getEntryPaths("/docs/descriptions/");
38 }
39
40 private void copyToDescriptionsDirectory(final String entryPath) {
41 final URL entry = MetricsPlugin.getDefault().getBundle().getEntry(entryPath);
42 try {
43 copyToDescriptionsDirectory(entry);
44 } catch (final IOException e) {
45 MetricsPlugin.log(e);
46 }
47 }
48
49 private void copyToDescriptionsDirectory(final URL entry) throws IOException {
50 final String file = new File(entry.getFile()).getName();
51 InputStream inputStream = null;
52 try {
53 inputStream = entry.openStream();
54 copyToDirectory(inputStream, file);
55 } finally {
56 if (inputStream != null) {
57 inputStream.close();
58 }
59 }
60 }
61
62 private void copyToDirectory(final InputStream inputStream, final String name) throws IOException {
63 BufferedOutputStream outputStream = null;
64 final File destination = new File(directory, name);
65 try {
66 outputStream = new BufferedOutputStream(new FileOutputStream(destination), 16384);
67 copyContents(inputStream, outputStream);
68 } finally {
69 if (outputStream != null) {
70 outputStream.close();
71 }
72 }
73 }
74
75 private void copyContents(final InputStream inputStream, final OutputStream outputStream) throws IOException {
76 final byte[] bytes = new byte[2048];
77 int bytesRead;
78 while ((bytesRead = inputStream.read(bytes)) > 0) {
79 outputStream.write(bytes, 0, bytesRead);
80 }
81 }
82 }
83