1 package org.simantics.db.javacore;
3 import java.io.ByteArrayInputStream;
4 import java.io.IOException;
5 import java.io.ObjectInputStream;
6 import java.io.Serializable;
7 import java.nio.file.Files;
8 import java.nio.file.Path;
9 import java.security.MessageDigest;
10 import java.security.NoSuchAlgorithmException;
11 import java.util.ArrayList;
12 import java.util.Arrays;
14 import org.simantics.acorn.exception.InvalidHeadStateException;
16 public class HeadState implements Serializable {
18 private static final long serialVersionUID = -4135031566499790077L;
20 public int headChangeSetId = 0;
21 public long transactionId = 1;
22 public long reservedIds = 3;
24 public ArrayList<String> clusters = new ArrayList<>();
25 public ArrayList<String> files = new ArrayList<>();
26 public ArrayList<String> stream = new ArrayList<>();
27 public ArrayList<String> cs = new ArrayList<>();
28 // public ArrayList<String> ccs = new ArrayList<String>();
30 public static HeadState load(Path directory) throws InvalidHeadStateException {
31 Path f = directory.resolve("head.state");
33 byte[] bytes = Files.readAllBytes(f);
34 MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
35 int digestLength = sha1.getDigestLength();
36 sha1.update(bytes, digestLength, bytes.length - digestLength);
37 byte[] newChecksum = sha1.digest();
38 if (!Arrays.equals(newChecksum, Arrays.copyOfRange(bytes, 0, digestLength))) {
39 throw new InvalidHeadStateException(
40 "Checksum " + Arrays.toString(newChecksum) + " does not match excpected "
41 + Arrays.toString(Arrays.copyOfRange(bytes, 0, digestLength)) + " for " + f.toAbsolutePath());
43 try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes, digestLength, bytes.length - digestLength))) {
44 HeadState state = (HeadState) ois.readObject();
47 } catch (IOException i) {
48 return new HeadState();
49 } catch (ClassNotFoundException c) {
50 // throw new Error("HeadState class not found", c);
51 return new HeadState();
52 } catch (NoSuchAlgorithmException e) {
53 throw new Error("SHA-1 Algorithm not found", e);
57 public static void validateHeadStateIntegrity(Path headState) throws InvalidHeadStateException, IOException {
59 byte[] bytes = Files.readAllBytes(headState);
60 MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
61 int digestLength = sha1.getDigestLength();
62 sha1.update(bytes, digestLength, bytes.length - digestLength);
63 byte[] newChecksum = sha1.digest();
64 if (!Arrays.equals(newChecksum, Arrays.copyOfRange(bytes, 0, digestLength))) {
65 throw new InvalidHeadStateException(
66 "Checksum " + Arrays.toString(newChecksum) + " does not match excpected "
67 + Arrays.toString(Arrays.copyOfRange(bytes, 0, digestLength)) + " for " + headState.toAbsolutePath());
69 } catch (NoSuchAlgorithmException e) {
70 throw new Error("SHA-1 digest not found, should not happen", e);