1 package fi.vtt.simantics.procore.internal;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.io.OutputStream;
9 import java.nio.ByteBuffer;
11 import org.simantics.db.common.utils.Logger;
12 import org.simantics.db.exception.DatabaseException;
13 import org.simantics.db.exception.RuntimeDatabaseException;
16 public class ReservedIds {
17 private File file = null;
18 private boolean loaded = false;
19 private Data data = new Data();
20 public static class Data {
24 ReservedIds(File workDir, String id) {
25 if (!workDir.isDirectory()) {
27 throw new RuntimeDatabaseException("Work directory not correct: " + workDir.getPath());
29 String name = workDir.getPath() + File.separator + "reservedIds." + id;
30 file = new File(name);
32 public boolean loaded() {
37 if(file == null || !file.exists())
41 } catch (IOException e) {
43 Logger.defaultLogError("Failed to load reserved ids.", e);
48 public void create(int idCount, long nextId) {
49 data.idCount = idCount;
51 saveNoThrow(idCount, nextId);
54 public void saveNoThrow(int idCount, long nextId) {
56 save(idCount, nextId);
57 } catch (IOException e) {
59 Logger.defaultLogError("Failed to load reserved ids.", e);
62 public void save(int idCount, long nextId)
64 data.idCount = idCount;
66 OutputStream stream = new FileOutputStream(file);
68 byte[] bytes = new byte[12];
69 ByteBuffer bb = ByteBuffer.wrap(bytes);
72 stream.write(bb.array());
79 public void mergeToFile(File toFile)
80 throws DatabaseException {
83 long next = data.nextId + data.idCount;
84 if (toFile.isDirectory()) {
85 toFile = new File(toFile, file.getName());
86 }else if (toFile.exists()) {
88 InputStream is = null;
90 is = new FileInputStream(toFile);
91 byte[] bytes = new byte[8];
92 int n = is.read(bytes);
94 ByteBuffer bb = ByteBuffer.wrap(bytes);
95 long oldNext = bb.getLong();
102 } catch (IOException e) {
103 String msg = "Could not open file " + toFile.getAbsolutePath() + ".";
104 Logger.defaultLogError(msg, e);
105 throw new DatabaseException(msg, e);
109 OutputStream stream = new FileOutputStream(toFile);
111 byte[] bytes = new byte[8];
112 ByteBuffer bb = ByteBuffer.wrap(bytes);
114 stream.write(bb.array());
119 } catch (IOException e) {
120 String msg = "Could not save file " + toFile.getAbsolutePath() + ".";
121 Logger.defaultLogError(msg, e);
122 throw new DatabaseException(msg, e);
125 private void loadInternal()
127 InputStream is = new FileInputStream(file);
129 byte[] bytes = new byte[12];
130 int n = is.read(bytes);
133 ByteBuffer bb = ByteBuffer.wrap(bytes);
134 data.idCount = bb.getInt();
135 data.nextId = bb.getLong();