1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.owasp.dependencycheck;
19
20 import java.io.BufferedInputStream;
21 import java.io.BufferedOutputStream;
22 import java.io.File;
23 import java.io.FileInputStream;
24 import java.io.FileOutputStream;
25 import java.util.zip.ZipEntry;
26 import java.util.zip.ZipInputStream;
27 import org.junit.Before;
28 import org.owasp.dependencycheck.BaseTest;
29 import org.owasp.dependencycheck.utils.Settings;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33
34
35
36
37
38
39 public abstract class BaseDBTestCase extends BaseTest {
40
41 protected final static int BUFFER_SIZE = 2048;
42
43 private final static Logger LOGGER = LoggerFactory.getLogger(BaseDBTestCase.class);
44
45 @Before
46 public void setUp() throws Exception {
47 ensureDBExists();
48 }
49
50 public static void ensureDBExists() throws Exception {
51
52 File f = new File("./target/data/dc.h2.db");
53 if (f.exists() && f.isFile() && f.length() < 71680) {
54 f.delete();
55 }
56
57 java.io.File dataPath = Settings.getDataDirectory();
58 String fileName = Settings.getString(Settings.KEYS.DB_FILE_NAME);
59 LOGGER.trace("DB file name {}", fileName);
60 java.io.File dataFile = new File(dataPath, fileName);
61 LOGGER.trace("Ensuring {} exists", dataFile.toString());
62 if (!dataPath.exists() || !dataFile.exists()) {
63 LOGGER.trace("Extracting database to {}", dataPath.toString());
64 dataPath.mkdirs();
65 FileInputStream fis = null;
66 ZipInputStream zin = null;
67 try {
68 File path = new File(BaseDBTestCase.class.getClassLoader().getResource("data.zip").toURI().getPath());
69 fis = new FileInputStream(path);
70 zin = new ZipInputStream(new BufferedInputStream(fis));
71 ZipEntry entry;
72 while ((entry = zin.getNextEntry()) != null) {
73 if (entry.isDirectory()) {
74 final File d = new File(dataPath, entry.getName());
75 d.mkdir();
76 continue;
77 }
78 FileOutputStream fos = null;
79 BufferedOutputStream dest = null;
80 try {
81 File o = new File(dataPath, entry.getName());
82 o.createNewFile();
83 fos = new FileOutputStream(o, false);
84 dest = new BufferedOutputStream(fos, BUFFER_SIZE);
85 byte data[] = new byte[BUFFER_SIZE];
86 int count;
87 while ((count = zin.read(data, 0, BUFFER_SIZE)) != -1) {
88 dest.write(data, 0, count);
89 }
90 } catch (Throwable ex) {
91 LOGGER.error("", ex);
92 } finally {
93 try {
94 if (dest != null) {
95 dest.flush();
96 dest.close();
97 }
98 } catch (Throwable ex) {
99 LOGGER.trace("", ex);
100 }
101 try {
102 if (fos != null) {
103 fos.close();
104 }
105 } catch (Throwable ex) {
106 LOGGER.trace("", ex);
107 }
108 }
109 }
110 } finally {
111 try {
112 if (zin != null) {
113 zin.close();
114 }
115 } catch (Throwable ex) {
116 LOGGER.trace("", ex);
117 }
118 try {
119 if (fis != null) {
120 fis.close();
121 }
122 } catch (Throwable ex) {
123 LOGGER.trace("", ex);
124 }
125 }
126 }
127 }
128 }