3 import java.io.IOException;
4 import java.nio.file.Files;
5 import java.nio.file.Path;
6 import java.nio.file.Paths;
7 import java.time.Instant;
8 import java.time.ZoneId;
9 import java.time.format.DateTimeFormatter;
10 import java.util.List;
11 import java.util.stream.Collectors;
12 import java.util.zip.ZipEntry;
13 import java.util.zip.ZipFile;
14 import java.util.zip.ZipOutputStream;
16 import org.eclipse.core.runtime.Platform;
17 import org.simantics.utils.FileUtils;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
22 * @author Tuukka Lehtonen
25 public class DatabaseBaselines {
27 private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseBaselines.class);
29 private static final boolean REQUIRE_INDEX_IN_BASELINE = false;
31 private static final String DB_DIRECTORY = "db"; //$NON-NLS-1$
32 private static final String INDEX_DIRECTORY = ".metadata/.plugins/org.simantics.db.indexing"; //$NON-NLS-1$
34 private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter.ofPattern("d. MMM yyyy HH:mm:ss");
36 public static boolean handleBaselineDatabase(Path installLocation, boolean databaseExists) throws PlatformException {
37 Path workspaceLocation = Platform.getLocation().toFile().toPath();
38 Path baselineIndicatorFile = workspaceLocation.resolve(".baselined");
39 if (Files.isRegularFile(baselineIndicatorFile)) {
40 // This means that the workspace has already been initialized from
41 // a database baseline and further initialization is not necessary.
45 Path baseline = resolveBaselineFile(installLocation);
46 if (baseline == null) {
47 baseline = getAutomaticBaselinePath();
52 if(!existsAutomaticBaseline())
56 DatabaseBaselines.validateBaselineFile(baseline);
57 DatabaseBaselines.validateWorkspaceForBaselineInitialization(workspaceLocation);
58 DatabaseBaselines.initializeWorkspaceWithBaseline(baseline, workspaceLocation, baselineIndicatorFile);
63 private static Path resolveBaselineFile(Path installLocation) throws PlatformException {
64 String dbBaselineArchive = System.getProperty("org.simantics.db.baseline", null);
65 if (dbBaselineArchive == null)
68 Path baseline = Paths.get(dbBaselineArchive);
69 if (baseline.isAbsolute()) {
70 if (!Files.isRegularFile(baseline))
71 throw new PlatformException("Specified database baseline archive " + baseline
72 + " does not exist. Cannot initialize workspace database from baseline.");
76 // Relative path resolution order:
77 // 1. from the platform "install location"
78 // 2. from working directory
79 //Path installLocation = tryGetInstallLocation();
80 if (installLocation != null) {
81 Path installedBaseline = installLocation.resolve(dbBaselineArchive);
82 if (Files.isRegularFile(installedBaseline))
83 return installedBaseline;
85 if (!Files.isRegularFile(baseline))
86 throw new PlatformException("Specified database baseline archive " + baseline
87 + " does not exist in either the install location (" + installLocation
88 + ") or the working directory (" + Paths.get(".").toAbsolutePath()
89 + "). Cannot initialize workspace database.");
93 private static boolean useAutomaticBaseline() {
94 return getAutomaticBaselinePath() != null;
97 private static Path getAutomaticBaselinePath() {
98 if("true".equals(System.getProperty("org.simantics.db.baseline.automatic")))
99 return Paths.get("automatic_baseline", "baseline.zip");
104 private static boolean existsAutomaticBaseline() {
105 Path baselineFile = getAutomaticBaselinePath();
106 if(baselineFile == null)
108 return Files.exists(baselineFile);
111 public static boolean shouldCreateAutomaticBaseline(boolean existsDatabase) throws PlatformException {
112 if(!useAutomaticBaseline()) {
113 // Are we using this feature?
117 // Baseline can only be created after db initialization
120 if(existsAutomaticBaseline()) {
121 // Existing baselines should not be automatically overridden
127 public static void createAutomaticBaseline(Path dbLocation) throws PlatformException {
129 if(existsAutomaticBaseline())
133 DatabaseBaselines.packageBaseline(dbLocation.getParent(), getAutomaticBaselinePath());
134 } catch (IOException e) {
135 LOGGER.error("Error while creating automatic baseline", e);
140 public static Path packageBaseline(Path fromWorkspace, Path packageFilePath) throws IOException {
141 Files.createDirectories(packageFilePath.getParent());
142 return compressZip(fromWorkspace, collectBaselinePaths(fromWorkspace), packageFilePath);
145 private static List<Path> collectBaselinePaths(Path workspace) throws IOException {
146 Path dbPath = workspace.resolve(DB_DIRECTORY);
147 Path indexPath = workspace.resolve(INDEX_DIRECTORY);
149 if (!Files.isDirectory(dbPath))
150 throw new IllegalArgumentException("workspace database directory " + dbPath + " does not exist");
152 List<Path> paths = Files.walk(dbPath).collect(Collectors.toList());
153 if (Files.isDirectory(indexPath)) {
154 List<Path> indexPaths = Files.walk(indexPath).collect(Collectors.toList());
155 paths.addAll(indexPaths);
157 if (REQUIRE_INDEX_IN_BASELINE)
158 throw new IllegalArgumentException("workspace database index directory " + indexPath + " does not exist");
163 private static Path compressZip(Path relativeRoot, List<Path> paths, Path zipFile) throws IOException {
164 if (LOGGER.isDebugEnabled())
165 LOGGER.debug("Compressing " + paths.size() + " path entries into ZIP file " + zipFile);
166 try (ZipOutputStream zout = new ZipOutputStream(Files.newOutputStream(zipFile))) {
167 compressZip(relativeRoot, zout, paths);
170 if (LOGGER.isDebugEnabled())
171 LOGGER.debug("Compressed " + paths.size() + " entries into " + zipFile);
175 private static void compressZip(Path relativeRoot, ZipOutputStream zout, List<Path> paths) throws IOException {
176 for (Path p : paths) {
177 Path rp = relativeRoot.relativize(p);
178 String name = rp.toString();
179 if (Files.isDirectory(p)) {
180 name = name.endsWith("/") ? name : name + "/";
181 zout.putNextEntry(new ZipEntry(name));
183 zout.putNextEntry(new ZipEntry(name));
184 FileUtils.copy(p.toFile(), zout);
190 public static byte[] baselineIndicatorContents(Path path) throws IOException {
191 return String.format("%s%n%s%n",
193 Instant.now().atZone(ZoneId.systemDefault()).format(TIMESTAMP_FORMAT))
197 public static void validateWorkspaceForBaselineInitialization(Path workspaceLocation) throws PlatformException {
199 Path db = workspaceLocation.resolve(DB_DIRECTORY);
200 if (Files.exists(db))
201 throw new PlatformException("Database location " + db + " already exists. Cannot re-initialize workspace from baseline.");
202 if (REQUIRE_INDEX_IN_BASELINE) {
203 Path index = workspaceLocation.resolve(INDEX_DIRECTORY);
204 if (Files.exists(index) || !isEmptyDirectory(index))
205 throw new PlatformException("Index location " + index + " already exists. Cannot re-initialize workspace from baseline.");
207 } catch (IOException e) {
208 throw new PlatformException("Failed to validate workspace for baseline initialization", e);
212 private static boolean isEmptyDirectory(Path dir) throws IOException {
213 return Files.walk(dir).count() == 1;
216 public static void validateBaselineFile(Path baseline) throws PlatformException {
217 try (ZipFile zip = new ZipFile(baseline.toFile())) {
218 ZipEntry db = zip.getEntry(DB_DIRECTORY);
220 throw new PlatformException("Baseline archive does not contain database directory '" + DB_DIRECTORY + "'");
222 if (REQUIRE_INDEX_IN_BASELINE) {
223 ZipEntry index = zip.getEntry(INDEX_DIRECTORY);
225 throw new PlatformException("Baseline archive does not contain database index directory '" + INDEX_DIRECTORY + "'");
227 } catch (IOException e) {
228 throw new PlatformException("Failed to validate baseline archive " + baseline, e);
232 public static void initializeWorkspaceWithBaseline(Path baseline, Path workspaceLocation, Path indicatorPath) throws PlatformException {
234 Files.createDirectories(workspaceLocation);
235 FileUtils.extractZip(baseline.toFile(), workspaceLocation.toFile());
236 if (indicatorPath != null)
237 Files.write(indicatorPath, DatabaseBaselines.baselineIndicatorContents(indicatorPath));
238 } catch (IOException e) {
239 throw new PlatformException(e);
243 public static void main(String[] args) throws IOException {
244 packageBaseline(Paths.get("D:/temp/desktop/workspace"), Paths.get("d:/temp/desktop/workspace/baseline.zip"));