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.apache.commons.io.IOUtils;
28 import org.junit.Before;
29 import org.owasp.dependencycheck.data.nvdcve.DatabaseManager;
30 import org.owasp.dependencycheck.utils.WriteLock;
31 import org.owasp.dependencycheck.utils.Settings;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35
36
37
38
39
40
41 public abstract class BaseDBTestCase extends BaseTest {
42
43 protected final static int BUFFER_SIZE = 2048;
44
45 private final static Logger LOGGER = LoggerFactory.getLogger(BaseDBTestCase.class);
46
47 @Before
48 @Override
49 public void setUp() throws Exception {
50 super.setUp();
51 synchronized (this) {
52 ensureDBExists();
53 }
54 }
55
56 public void ensureDBExists() throws Exception {
57 try (WriteLock dblock = new WriteLock(getSettings(), DatabaseManager.isH2Connection(getSettings()))) {
58 File f = new File("./target/data/odc.mv.db");
59 if (f.exists() && f.isFile() && f.length() < 71680) {
60 f.delete();
61 }
62 File dataPath = getSettings().getH2DataDirectory();
63 String fileName = getSettings().getString(Settings.KEYS.DB_FILE_NAME);
64 LOGGER.trace("DB file name {}", fileName);
65 File dataFile = new File(dataPath, fileName);
66 LOGGER.trace("Ensuring {} exists", dataFile);
67 if (!dataPath.exists() || !dataFile.exists()) {
68 LOGGER.trace("Extracting database to {}", dataPath);
69 dataPath.mkdirs();
70 File path = new File(BaseDBTestCase.class.getClassLoader().getResource("data.zip").toURI().getPath());
71 try (FileInputStream fis = new FileInputStream(path);
72 ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis))) {
73 ZipEntry entry;
74 while ((entry = zin.getNextEntry()) != null) {
75 if (entry.isDirectory()) {
76 final File d = new File(dataPath, entry.getName());
77 d.mkdir();
78 continue;
79 }
80
81
82 dataFile.createNewFile();
83 try (FileOutputStream fos = new FileOutputStream(dataFile, false);
84 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) {
85 IOUtils.copy(zin, dest);
86 } catch (Throwable ex) {
87 LOGGER.error("", ex);
88 }
89 }
90 }
91
92 DatabaseManager factory = new DatabaseManager(getSettings());
93 }
94 }
95 }
96 }