Debian Codegraph @

src/tools/org/h2/dev/fs/ArchiveTool.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.dev.fs;
7
8 import java.io.BufferedInputStream;
9 import java.io.BufferedOutputStream;
10 import java.io.ByteArrayInputStream;
11 import java.io.ByteArrayOutputStream;
12 import java.io.DataInputStream;
13 import java.io.DataOutputStream;
14 import java.io.EOFException;
15 import java.io.File;
16 import java.io.FileInputStream;
17 import java.io.FileOutputStream;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.OutputStream;
21 import java.nio.ByteBuffer;
22 import java.nio.channels.FileChannel;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.TreeMap;
28 import java.util.TreeSet;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.atomic.AtomicBoolean;
31 import java.util.zip.Deflater;
32 import java.util.zip.DeflaterOutputStream;
33 import java.util.zip.Inflater;
34 import java.util.zip.InflaterInputStream;
35
36 /**
37 * A standalone archive tool to compress directories. It does not have any
38 * dependencies except for the Java libraries.
39 * <p>
40 * Unlike other compression tools, it splits the data into chunks and sorts the
41 * chunks, so that large directories or files that contain duplicate data are
42 * compressed much better.
43 */
44 public class ArchiveTool {
45
46 /**
47 * The file header.
48 */
49 private static final byte[] HEADER = {'H', '2', 'A', '1'};
50
51 /**
52 * The number of bytes per megabyte (used for the output).
53 */
54 private static final int MB = 1000 * 1000;
55
56 /**
57 * Run the tool.
58 *
59 * @param args the command line arguments
60 */
61 public static void main(String... args) throws Exception {
62 Log log = new Log();
63 int level = Integer.getInteger("level", Deflater.BEST_SPEED);
64 if (args.length == 1) {
65 File f = new File(args[0]);
66 if (f.exists()) {
67 if (f.isDirectory()) {
68 String fromDir = f.getAbsolutePath();
69 String toFile = fromDir + ".at";
70 compress(fromDir, toFile, level);
71 return;
72 }
73 String fromFile = f.getAbsolutePath();
74 int dot = fromFile.lastIndexOf('.');
75 if (dot > 0 && dot > fromFile.replace('\\', '/').lastIndexOf('/')) {
76 String toDir = fromFile.substring(0, dot);
77 extract(fromFile, toDir);
78 return;
79 }
80 }
81 }
82 String arg = args.length != 3 ? null : args[0];
83 if ("-compress".equals(arg)) {
84 String toFile = args[1];
85 String fromDir = args[2];
86 compress(fromDir, toFile, level);
87 } else if ("-extract".equals(arg)) {
88 String fromFile = args[1];
89 String toDir = args[2];
90 extract(fromFile, toDir);
91 } else {
92 log.println("An archive tool to efficiently compress large directories");
93 log.println("Command line options:");
94 log.println("<sourceDir>");
95 log.println("<compressedFile>");
96 log.println("-compress <compressedFile> <sourceDir>");
97 log.println("-extract <compressedFile> <targetDir>");
98 }
99 }
100
101 private static void compress(String fromDir, String toFile, int level) throws IOException {
102 final Log log = new Log();
103 final long start = System.nanoTime();
104 final long startMs = System.currentTimeMillis();
105 final AtomicBoolean title = new AtomicBoolean();
106 long size = getSize(new File(fromDir), new Runnable() {
107 int count;
108 long lastTime = start;
109 @Override
110 public void run() {
111 count++;
112 if (count % 1000 == 0) {
113 long now = System.nanoTime();
114 if (now - lastTime > TimeUnit.SECONDS.toNanos(3)) {
115 if (!title.getAndSet(true)) {
116 log.println("Counting files");
117 }
118 log.print(count + " ");
119 lastTime = now;
120 }
121 }
122 }
123 });
124 if (title.get()) {
125 log.println();
126 }
127 log.println("Compressing " + size / MB + " MB at " +
128 new java.sql.Time(startMs).toString());
129 InputStream in = getDirectoryInputStream(fromDir);
130 String temp = toFile + ".temp";
131 OutputStream out =
132 new BufferedOutputStream(
133 new FileOutputStream(toFile), 1024 * 1024);
134 Deflater def = new Deflater();
135 def.setLevel(level);
136 out = new BufferedOutputStream(
137 new DeflaterOutputStream(out, def), 1024 * 1024);
138 sort(log, in, out, temp, size);
139 in.close();
140 out.close();
141 log.println();
142 log.println("Compressed to " +
143 new File(toFile).length() / MB + " MB in " +
144 TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start) +
145 " seconds");
146 log.println();
147 }
148
149 private static void extract(String fromFile, String toDir) throws IOException {
150 Log log = new Log();
151 long start = System.nanoTime();
152 long startMs = System.currentTimeMillis();
153 long size = new File(fromFile).length();
154 log.println("Extracting " + size / MB + " MB at " + new java.sql.Time(startMs).toString());
155 InputStream in =
156 new BufferedInputStream(
157 new FileInputStream(fromFile), 1024 * 1024);
158 String temp = fromFile + ".temp";
159 Inflater inflater = new Inflater();
160 in = new InflaterInputStream(in, inflater, 1024 * 1024);
161 OutputStream out = getDirectoryOutputStream(toDir);
162 combine(log, in, out, temp);
163 inflater.end();
164 in.close();
165 out.close();
166 log.println();
167 log.println("Extracted in " +
168 TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start) +
169 " seconds");
170 }
171
172 private static long getSize(File f, Runnable r) {
173 // assume a metadata entry is 40 bytes
174 long size = 40;
175 if (f.isDirectory()) {
176 File[] list = f.listFiles();
177 if (list != null) {
178 for (File c : list) {
179 size += getSize(c, r);
180 }
181 }
182 } else {
183 size += f.length();
184 }
185 r.run();
186 return size;
187 }
188
189 private static InputStream getDirectoryInputStream(final String dir) {
190
191 File f = new File(dir);
192 if (!f.isDirectory() || !f.exists()) {
193 throw new IllegalArgumentException("Not an existing directory: " + dir);
194 }
195
196 return new InputStream() {
197
198 private final String baseDir;
199 private final ArrayList<String> files = new ArrayList<>();
200 private String current;
201 private ByteArrayInputStream meta;
202 private DataInputStream fileIn;
203 private long remaining;
204
205 {
206 File f = new File(dir);
207 baseDir = f.getAbsolutePath();
208 addDirectory(f);
209 }
210
211 private void addDirectory(File f) {
212 File[] list = f.listFiles();
213 if (list != null) {
214 // first all directories, then all files
215 for (File c : list) {
216 if (c.isDirectory()) {
217 files.add(c.getAbsolutePath());
218 }
219 }
220 for (File c : list) {
221 if (c.isFile()) {
222 files.add(c.getAbsolutePath());
223 }
224 }
225 }
226 }
227
228 // int: metadata length
229 // byte: 0: directory, 1: file
230 // varLong: lastModified
231 // byte: 0: read-write, 1: read-only
232 // (file only) varLong: file length
233 // utf-8: file name
234
235 @Override
236 public int read() throws IOException {
237 if (meta != null) {
238 // read from the metadata
239 int x = meta.read();
240 if (x >= 0) {
241 return x;
242 }
243 meta = null;
244 }
245 if (fileIn != null) {
246 if (remaining > 0) {
247 // read from the file
248 int x = fileIn.read();
249 remaining--;
250 if (x < 0) {
251 throw new EOFException();
252 }
253 return x;
254 }
255 fileIn.close();
256 fileIn = null;
257 }
258 if (files.isEmpty()) {
259 // EOF
260 return -1;
261 }
262 // breadth-first traversal
263 // first all files, then all directories
264 current = files.remove(files.size() - 1);
265 File f = new File(current);
266 if (f.isDirectory()) {
267 addDirectory(f);
268 }
269 ByteArrayOutputStream metaOut = new ByteArrayOutputStream();
270 DataOutputStream out = new DataOutputStream(metaOut);
271 boolean isFile = f.isFile();
272 out.writeInt(0);
273 out.write(isFile ? 1 : 0);
274 out.write(!f.canWrite() ? 1 : 0);
275 writeVarLong(out, f.lastModified());
276 if (isFile) {
277 remaining = f.length();
278 writeVarLong(out, remaining);
279 fileIn = new DataInputStream(new BufferedInputStream(
280 new FileInputStream(current), 1024 * 1024));
281 }
282 if (!current.startsWith(baseDir)) {
283 throw new IOException("File " + current + " does not start with " + baseDir);
284 }
285 String n = current.substring(baseDir.length() + 1);
286 out.writeUTF(n);
287 out.writeInt(metaOut.size());
288 out.flush();
289 byte[] bytes = metaOut.toByteArray();
290 // copy metadata length to beginning
291 System.arraycopy(bytes, bytes.length - 4, bytes, 0, 4);
292 // cut the length
293 bytes = Arrays.copyOf(bytes, bytes.length - 4);
294 meta = new ByteArrayInputStream(bytes);
295 return meta.read();
296 }
297
298 @Override
299 public int read(byte[] buff, int offset, int length) throws IOException {
300 if (meta != null || fileIn == null || remaining == 0) {
301 return super.read(buff, offset, length);
302 }
303 int l = (int) Math.min(length, remaining);
304 fileIn.readFully(buff, offset, l);
305 remaining -= l;
306 return l;
307 }
308
309 };
310
311 }
312
313 private static OutputStream getDirectoryOutputStream(final String dir) {
314 new File(dir).mkdirs();
315 return new OutputStream() {
316
317 private ByteArrayOutputStream meta = new ByteArrayOutputStream();
318 private OutputStream fileOut;
319 private File file;
320 private long remaining = 4;
321 private long modified;
322 private boolean readOnly;
323
324 @Override
325 public void write(byte[] buff, int offset, int length) throws IOException {
326 while (length > 0) {
327 if (fileOut == null || remaining <= 1) {
328 write(buff[offset] & 255);
329 offset++;
330 length--;
331 } else {
332 int l = (int) Math.min(length, remaining - 1);
333 fileOut.write(buff, offset, l);
334 remaining -= l;
335 offset += l;
336 length -= l;
337 }
338 }
339 }
340
341 @Override
342 public void write(int b) throws IOException {
343 if (fileOut != null) {
344 fileOut.write(b);
345 if (--remaining > 0) {
346 return;
347 }
348 // this can be slow, but I don't know a way to avoid it
349 fileOut.close();
350 fileOut = null;
351 file.setLastModified(modified);
352 if (readOnly) {
353 file.setReadOnly();
354 }
355 remaining = 4;
356 return;
357 }
358 meta.write(b);
359 if (--remaining > 0) {
360 return;
361 }
362 DataInputStream in = new DataInputStream(
363 new ByteArrayInputStream(meta.toByteArray()));
364 if (meta.size() == 4) {
365 // metadata is next
366 remaining = in.readInt() - 4;
367 if (remaining > 16 * 1024) {
368 throw new IOException("Illegal directory stream");
369 }
370 return;
371 }
372 // read and ignore the length
373 in.readInt();
374 boolean isFile = in.read() == 1;
375 readOnly = in.read() == 1;
376 modified = readVarLong(in);
377 if (isFile) {
378 remaining = readVarLong(in);
379 } else {
380 remaining = 4;
381 }
382 String name = dir + "/" + in.readUTF();
383 file = new File(name);
384 if (isFile) {
385 if (remaining == 0) {
386 new File(name).createNewFile();
387 remaining = 4;
388 } else {
389 fileOut = new BufferedOutputStream(
390 new FileOutputStream(name), 1024 * 1024);
391 }
392 } else {
393 file.mkdirs();
394 file.setLastModified(modified);
395 if (readOnly) {
396 file.setReadOnly();
397 }
398 }
399 meta.reset();
400 }
401 };
402 }
403
404 private static void sort(Log log, InputStream in, OutputStream out,
405 String tempFileName, long size) throws IOException {
406 int bufferSize = 32 * 1024 * 1024;
407 DataOutputStream tempOut = new DataOutputStream(new BufferedOutputStream(
408 new FileOutputStream(tempFileName), 1024 * 1024));
409 byte[] bytes = new byte[bufferSize];
410 List<Long> segmentStart = new ArrayList<>();
411 long outPos = 0;
412 long id = 1;
413
414 // Temp file: segment* 0
415 // Segment: chunk* 0
416 // Chunk: pos* 0 sortKey data
417
418 log.setRange(0, 30, size);
419 while (true) {
420 int len = readFully(in, bytes, bytes.length);
421 if (len == 0) {
422 break;
423 }
424 log.printProgress(len);
425 TreeMap<Chunk, Chunk> map = new TreeMap<>();
426 for (int pos = 0; pos < len;) {
427 int[] key = getKey(bytes, pos, len);
428 int l = key[3];
429 byte[] buff = Arrays.copyOfRange(bytes, pos, pos + l);
430 pos += l;
431 Chunk c = new Chunk(null, key, buff);
432 Chunk old = map.get(c);
433 if (old == null) {
434 // new entry
435 c.idList = new ArrayList<>();
436 c.idList.add(id);
437 map.put(c, c);
438 } else {
439 old.idList.add(id);
440 }
441 id++;
442 }
443 segmentStart.add(outPos);
444 for (Chunk c : map.keySet()) {
445 outPos += c.write(tempOut, true);
446 }
447 // end of segment
448 outPos += writeVarLong(tempOut, 0);
449 }
450 tempOut.close();
451 long tempSize = new File(tempFileName).length();
452
453 // merge blocks if needed
454 int blockSize = 64;
455 boolean merge = false;
456 while (segmentStart.size() > blockSize) {
457 merge = true;
458 log.setRange(30, 50, tempSize);
459 log.println();
460 log.println("Merging " + segmentStart.size() + " segments " + blockSize + ":1");
461 ArrayList<Long> segmentStart2 = new ArrayList<>();
462 outPos = 0;
463 DataOutputStream tempOut2 = new DataOutputStream(new BufferedOutputStream(
464 new FileOutputStream(tempFileName + ".b"), 1024 * 1024));
465 while (segmentStart.size() > 0) {
466 segmentStart2.add(outPos);
467 int s = Math.min(segmentStart.size(), blockSize);
468 List<Long> start = segmentStart.subList(0, s);
469 TreeSet<ChunkStream> segmentIn = new TreeSet<>();
470 long read = openSegments(start, segmentIn, tempFileName, true);
471 log.printProgress(read);
472 Chunk last = null;
473 Iterator<Chunk> it = merge(segmentIn, log);
474 while (it.hasNext()) {
475 Chunk c = it.next();
476 if (last == null) {
477 last = c;
478 } else if (last.compareTo(c) == 0) {
479 last.idList.addAll(c.idList);
480 } else {
481 outPos += last.write(tempOut2, true);
482 last = c;
483 }
484 }
485 if (last != null) {
486 outPos += last.write(tempOut2, true);
487 }
488 // end of segment
489 outPos += writeVarLong(tempOut2, 0);
490 segmentStart = segmentStart.subList(s, segmentStart.size());
491 }
492 segmentStart = segmentStart2;
493 tempOut2.close();
494 tempSize = new File(tempFileName).length();
495 new File(tempFileName).delete();
496 tempFileName += ".b";
497 }
498 if (merge) {
499 log.println();
500 log.println("Combining " + segmentStart.size() + " segments");
501 }
502
503 TreeSet<ChunkStream> segmentIn = new TreeSet<>();
504 long read = openSegments(segmentStart, segmentIn, tempFileName, true);
505 log.printProgress(read);
506
507 DataOutputStream dataOut = new DataOutputStream(out);
508 dataOut.write(HEADER);
509 writeVarLong(dataOut, size);
510
511 // File: header length chunk* 0
512 // chunk: pos* 0 data
513 log.setRange(50, 100, tempSize);
514 Chunk last = null;
515 Iterator<Chunk> it = merge(segmentIn, log);
516 while (it.hasNext()) {
517 Chunk c = it.next();
518 if (last == null) {
519 last = c;
520 } else if (last.compareTo(c) == 0) {
521 last.idList.addAll(c.idList);
522 } else {
523 last.write(dataOut, false);
524 last = c;
525 }
526 }
527 if (last != null) {
528 last.write(dataOut, false);
529 }
530 new File(tempFileName).delete();
531 writeVarLong(dataOut, 0);
532 dataOut.flush();
533 }
534
535 private static long openSegments(List<Long> segmentStart, TreeSet<ChunkStream> segmentIn,
536 String tempFileName, boolean readKey) throws IOException {
537 long inPos = 0;
538 int bufferTotal = 64 * 1024 * 1024;
539 int bufferPerStream = bufferTotal / segmentStart.size();
540 // FileChannel fc = new RandomAccessFile(tempFileName, "r").
541 // getChannel();
542 for (int i = 0; i < segmentStart.size(); i++) {
543 // long end = i < segmentStart.size() - 1 ?
544 // segmentStart.get(i+1) : fc.size();
545 // InputStream in =
546 // new SharedInputStream(fc, segmentStart.get(i), end);
547 InputStream in = new FileInputStream(tempFileName);
548 in.skip(segmentStart.get(i));
549 ChunkStream s = new ChunkStream(i);
550 s.readKey = readKey;
551 s.in = new DataInputStream(new BufferedInputStream(in, bufferPerStream));
552 inPos += s.readNext();
553 if (s.current != null) {
554 segmentIn.add(s);
555 }
556 }
557 return inPos;
558 }
559
560 private static Iterator<Chunk> merge(final TreeSet<ChunkStream> segmentIn, final Log log) {
561 return new Iterator<Chunk>() {
562
563 @Override
564 public boolean hasNext() {
565 return !segmentIn.isEmpty();
566 }
567
568 @Override
569 public Chunk next() {
570 ChunkStream s = segmentIn.first();
571 segmentIn.remove(s);
572 Chunk c = s.current;
573 int len = s.readNext();
574 log.printProgress(len);
575 if (s.current != null) {
576 segmentIn.add(s);
577 }
578 return c;
579 }
580
581 };
582 }
583
584 /**
585 * Read a number of bytes. This method repeats reading until
586 * either the bytes have been read, or EOF.
587 *
588 * @param in the input stream
589 * @param buffer the target buffer
590 * @param max the number of bytes to read
591 * @return the number of bytes read (max unless EOF has been reached)
592 */
593 private static int readFully(InputStream in, byte[] buffer, int max)
594 throws IOException {
595 int result = 0, len = Math.min(max, buffer.length);
596 while (len > 0) {
597 int l = in.read(buffer, result, len);
598 if (l < 0) {
599 break;
600 }
601 result += l;
602 len -= l;
603 }
604 return result;
605 }
606
607 /**
608 * Get the sort key and length of a chunk.
609 */
610 private static int[] getKey(byte[] data, int start, int maxPos) {
611 int minLen = 4 * 1024;
612 int mask = 4 * 1024 - 1;
613 long min = Long.MAX_VALUE;
614 int pos = start;
615 for (int j = 0; pos < maxPos; pos++, j++) {
616 if (pos <= start + 10) {
617 continue;
618 }
619 long hash = getSipHash24(data, pos - 10, pos, 111, 11224);
620 if (hash < min) {
621 min = hash;
622 }
623 if (j > minLen) {
624 if ((hash & mask) == 1) {
625 break;
626 }
627 if (j > minLen * 4 && (hash & (mask >> 1)) == 1) {
628 break;
629 }
630 if (j > minLen * 16) {
631 break;
632 }
633 }
634 }
635 int len = pos - start;
636 int[] counts = new int[8];
637 for (int i = start; i < pos; i++) {
638 int x = data[i] & 0xff;
639 counts[x >> 5]++;
640 }
641 int cs = 0;
642 for (int i = 0; i < 8; i++) {
643 cs *= 2;
644 if (counts[i] > (len / 32)) {
645 cs += 1;
646 }
647 }
648 int[] key = new int[4];
649 // TODO test if cs makes a difference
650 key[0] = (int) (min >>> 32);
651 key[1] = (int) min;
652 key[2] = cs;
653 key[3] = len;
654 return key;
655 }
656
657 private static long getSipHash24(byte[] b, int start, int end, long k0,
658 long k1) {
659 long v0 = k0 ^ 0x736f6d6570736575L;
660 long v1 = k1 ^ 0x646f72616e646f6dL;
661 long v2 = k0 ^ 0x6c7967656e657261L;
662 long v3 = k1 ^ 0x7465646279746573L;
663 int repeat;
664 for (int off = start; off <= end + 8; off += 8) {
665 long m;
666 if (off <= end) {
667 m = 0;
668 int i = 0;
669 for (; i < 8 && off + i < end; i++) {
670 m |= ((long) b[off + i] & 255) << (8 * i);
671 }
672 if (i < 8) {
673 m |= ((long) end - start) << 56;
674 }
675 v3 ^= m;
676 repeat = 2;
677 } else {
678 m = 0;
679 v2 ^= 0xff;
680 repeat = 4;
681 }
682 for (int i = 0; i < repeat; i++) {
683 v0 += v1;
684 v2 += v3;
685 v1 = Long.rotateLeft(v1, 13);
686 v3 = Long.rotateLeft(v3, 16);
687 v1 ^= v0;
688 v3 ^= v2;
689 v0 = Long.rotateLeft(v0, 32);
690 v2 += v1;
691 v0 += v3;
692 v1 = Long.rotateLeft(v1, 17);
693 v3 = Long.rotateLeft(v3, 21);
694 v1 ^= v2;
695 v3 ^= v0;
696 v2 = Long.rotateLeft(v2, 32);
697 }
698 v0 ^= m;
699 }
700 return v0 ^ v1 ^ v2 ^ v3;
701 }
702
703 /**
704 * Get the sort key and length of a chunk.
705 */
706 private static int[] getKeyOld(byte[] data, int start, int maxPos) {
707 int minLen = 4 * 1024;
708 int mask = 4 * 1024 - 1;
709 int min = Integer.MAX_VALUE;
710 int max = Integer.MIN_VALUE;
711 int pos = start;
712 long bytes = 0;
713 for (int j = 0; pos < maxPos; pos++, j++) {
714 bytes = (bytes << 8) | (data[pos] & 255);
715 int hash = getHash(bytes);
716 if (hash < min) {
717 min = hash;
718 }
719 if (hash > max) {
720 max = hash;
721 }
722 if (j > minLen) {
723 if ((hash & mask) == 1) {
724 break;
725 }
726 if (j > minLen * 4 && (hash & (mask >> 1)) == 1) {
727 break;
728 }
729 if (j > minLen * 16) {
730 break;
731 }
732 }
733 }
734 int len = pos - start;
735 int[] counts = new int[8];
736 for (int i = start; i < pos; i++) {
737 int x = data[i] & 0xff;
738 counts[x >> 5]++;
739 }
740 int cs = 0;
741 for (int i = 0; i < 8; i++) {
742 cs *= 2;
743 if (counts[i] > (len / 32)) {
744 cs += 1;
745 }
746 }
747 int[] key = new int[4];
748 key[0] = cs;
749 key[1] = min;
750 key[2] = max;
751 key[3] = len;
752 return key;
753 }
754
755 private static int getHash(long key) {
756 int hash = (int) ((key >>> 32) ^ key);
757 hash = ((hash >>> 16) ^ hash) * 0x45d9f3b;
758 hash = ((hash >>> 16) ^ hash) * 0x45d9f3b;
759 hash = (hash >>> 16) ^ hash;
760 return hash;
761 }
762
763 private static void combine(Log log, InputStream in, OutputStream out,
764 String tempFileName) throws IOException {
765 int bufferSize = 16 * 1024 * 1024;
766 DataOutputStream tempOut =
767 new DataOutputStream(
768 new BufferedOutputStream(
769 new FileOutputStream(tempFileName), 1024 * 1024));
770
771 // File: header length chunk* 0
772 // chunk: pos* 0 data
773
774 DataInputStream dataIn = new DataInputStream(in);
775 byte[] header = new byte[4];
776 dataIn.readFully(header);
777 if (!Arrays.equals(header, HEADER)) {
778 tempOut.close();
779 throw new IOException("Invalid header");
780 }
781 long size = readVarLong(dataIn);
782 long outPos = 0;
783 List<Long> segmentStart = new ArrayList<>();
784 boolean end = false;
785
786 // Temp file: segment* 0
787 // Segment: chunk* 0
788 // Chunk: pos* 0 data
789 log.setRange(0, 30, size);
790 while (!end) {
791 int segmentSize = 0;
792 TreeMap<Long, byte[]> map = new TreeMap<>();
793 while (segmentSize < bufferSize) {
794 Chunk c = Chunk.read(dataIn, false);
795 if (c == null) {
796 end = true;
797 break;
798 }
799 int length = c.value.length;
800 log.printProgress(length);
801 segmentSize += length;
802 for (long x : c.idList) {
803 map.put(x, c.value);
804 }
805 }
806 if (map.size() == 0) {
807 break;
808 }
809 segmentStart.add(outPos);
810 for (Long x : map.keySet()) {
811 outPos += writeVarLong(tempOut, x);
812 outPos += writeVarLong(tempOut, 0);
813 byte[] v = map.get(x);
814 outPos += writeVarLong(tempOut, v.length);
815 tempOut.write(v);
816 outPos += v.length;
817 }
818 outPos += writeVarLong(tempOut, 0);
819 }
820 tempOut.close();
821 long tempSize = new File(tempFileName).length();
822 size = outPos;
823
824 // merge blocks if needed
825 int blockSize = 64;
826 boolean merge = false;
827 while (segmentStart.size() > blockSize) {
828 merge = true;
829 log.setRange(30, 50, tempSize);
830 log.println();
831 log.println("Merging " + segmentStart.size() + " segments " + blockSize + ":1");
832 ArrayList<Long> segmentStart2 = new ArrayList<>();
833 outPos = 0;
834 DataOutputStream tempOut2 = new DataOutputStream(new BufferedOutputStream(
835 new FileOutputStream(tempFileName + ".b"), 1024 * 1024));
836 while (segmentStart.size() > 0) {
837 segmentStart2.add(outPos);
838 int s = Math.min(segmentStart.size(), blockSize);
839 List<Long> start = segmentStart.subList(0, s);
840 TreeSet<ChunkStream> segmentIn = new TreeSet<>();
841 long read = openSegments(start, segmentIn, tempFileName, false);
842 log.printProgress(read);
843
844 Iterator<Chunk> it = merge(segmentIn, log);
845 while (it.hasNext()) {
846 Chunk c = it.next();
847 outPos += writeVarLong(tempOut2, c.idList.get(0));
848 outPos += writeVarLong(tempOut2, 0);
849 outPos += writeVarLong(tempOut2, c.value.length);
850 tempOut2.write(c.value);
851 outPos += c.value.length;
852 }
853 outPos += writeVarLong(tempOut2, 0);
854
855 segmentStart = segmentStart.subList(s, segmentStart.size());
856 }
857 segmentStart = segmentStart2;
858 tempOut2.close();
859 tempSize = new File(tempFileName).length();
860 new File(tempFileName).delete();
861 tempFileName += ".b";
862 }
863 if (merge) {
864 log.println();
865 log.println("Combining " + segmentStart.size() + " segments");
866 }
867
868 TreeSet<ChunkStream> segmentIn = new TreeSet<>();
869 DataOutputStream dataOut = new DataOutputStream(out);
870 log.setRange(50, 100, size);
871
872 long read = openSegments(segmentStart, segmentIn, tempFileName, false);
873 log.printProgress(read);
874
875 Iterator<Chunk> it = merge(segmentIn, log);
876 while (it.hasNext()) {
877 dataOut.write(it.next().value);
878 }
879 new File(tempFileName).delete();
880 dataOut.flush();
881 }
882
883 /**
884 * A stream of chunks.
885 */
886 static class ChunkStream implements Comparable<ChunkStream> {
887 final int id;
888 Chunk current;
889 DataInputStream in;
890 boolean readKey;
891
892 ChunkStream(int id) {
893 this.id = id;
894 }
895
896 /**
897 * Read the next chunk.
898 *
899 * @return the number of bytes read
900 */
901 int readNext() {
902 current = null;
903 current = Chunk.read(in, readKey);
904 if (current == null) {
905 return 0;
906 }
907 return current.value.length;
908 }
909
910 @Override
911 public int compareTo(ChunkStream o) {
912 int comp = current.compareTo(o.current);
913 if (comp != 0) {
914 return comp;
915 }
916 return Integer.signum(id - o.id);
917 }
918 }
919
920 /**
921 * A chunk of data.
922 */
923 static class Chunk implements Comparable<Chunk> {
924 ArrayList<Long> idList;
925 final byte[] value;
926 private final int[] sortKey;
927
928 Chunk(ArrayList<Long> idList, int[] sortKey, byte[] value) {
929 this.idList = idList;
930 this.sortKey = sortKey;
931 this.value = value;
932 }
933
934 /**
935 * Read a chunk.
936 *
937 * @param in the input stream
938 * @param readKey whether to read the sort key
939 * @return the chunk, or null if 0 has been read
940 */
941 public static Chunk read(DataInputStream in, boolean readKey) {
942 try {
943 ArrayList<Long> idList = new ArrayList<>();
944 while (true) {
945 long x = readVarLong(in);
946 if (x == 0) {
947 break;
948 }
949 idList.add(x);
950 }
951 if (idList.isEmpty()) {
952 // eof
953 in.close();
954 return null;
955 }
956 int[] key = null;
957 if (readKey) {
958 key = new int[4];
959 for (int i = 0; i < key.length; i++) {
960 key[i] = in.readInt();
961 }
962 }
963 int len = (int) readVarLong(in);
964 byte[] value = new byte[len];
965 in.readFully(value);
966 return new Chunk(idList, key, value);
967 } catch (IOException e) {
968 throw new RuntimeException(e);
969 }
970 }
971
972 /**
973 * Write a chunk.
974 *
975 * @param out the output stream
976 * @param writeKey whether to write the sort key
977 * @return the number of bytes written
978 */
979 int write(DataOutputStream out, boolean writeKey) throws IOException {
980 int len = 0;
981 for (long x : idList) {
982 len += writeVarLong(out, x);
983 }
984 len += writeVarLong(out, 0);
985 if (writeKey) {
986 for (int i = 0; i < sortKey.length; i++) {
987 out.writeInt(sortKey[i]);
988 len += 4;
989 }
990 }
991 len += writeVarLong(out, value.length);
992 out.write(value);
993 len += value.length;
994 return len;
995 }
996
997 @Override
998 public int compareTo(Chunk o) {
999 if (sortKey == null) {
1000 // sort by id
1001 long a = idList.get(0);
1002 long b = o.idList.get(0);
1003 if (a < b) {
1004 return -1;
1005 } else if (a > b) {
1006 return 1;
1007 }
1008 return 0;
1009 }
1010 for (int i = 0; i < sortKey.length; i++) {
1011 if (sortKey[i] < o.sortKey[i]) {
1012 return -1;
1013 } else if (sortKey[i] > o.sortKey[i]) {
1014 return 1;
1015 }
1016 }
1017 if (value.length < o.value.length) {
1018 return -1;
1019 } else if (value.length > o.value.length) {
1020 return 1;
1021 }
1022 for (int i = 0; i < value.length; i++) {
1023 int a = value[i] & 255;
1024 int b = o.value[i] & 255;
1025 if (a < b) {
1026 return -1;
1027 } else if (a > b) {
1028 return 1;
1029 }
1030 }
1031 return 0;
1032 }
1033 }
1034
1035 /**
1036 * A logger, including context.
1037 */
1038 static class Log {
1039
1040 private long lastTime;
1041 private long current;
1042 private int pos;
1043 private int low;
1044 private int high;
1045 private long total;
1046
1047 /**
1048 * Print an empty line.
1049 */
1050 void println() {
1051 System.out.println();
1052 pos = 0;
1053 }
1054
1055 /**
1056 * Print a message.
1057 *
1058 * @param msg the message
1059 */
1060 void print(String msg) {
1061 System.out.print(msg);
1062 }
1063
1064 /**
1065 * Print a message.
1066 *
1067 * @param msg the message
1068 */
1069 void println(String msg) {
1070 System.out.println(msg);
1071 pos = 0;
1072 }
1073
1074 /**
1075 * Set the range.
1076 *
1077 * @param low the percent value if current = 0
1078 * @param high the percent value if current = total
1079 * @param total the maximum value
1080 */
1081 void setRange(int low, int high, long total) {
1082 this.low = low;
1083 this.high = high;
1084 this.current = 0;
1085 this.total = total;
1086 }
1087
1088 /**
1089 * Print the progress.
1090 *
1091 * @param offset the offset since the last operation
1092 */
1093 void printProgress(long offset) {
1094 current += offset;
1095 long now = System.nanoTime();
1096 if (now - lastTime > TimeUnit.SECONDS.toNanos(3)) {
1097 String msg = (low + (high - low) * current / total) + "% ";
1098 if (pos > 80) {
1099 System.out.println();
1100 pos = 0;
1101 }
1102 System.out.print(msg);
1103 pos += msg.length();
1104 lastTime = now;
1105 }
1106 }
1107
1108 }
1109
1110 /**
1111 * Write a variable size long value.
1112 *
1113 * @param out the output stream
1114 * @param x the value
1115 * @return the number of bytes written
1116 */
1117 static int writeVarLong(OutputStream out, long x)
1118 throws IOException {
1119 int len = 0;
1120 while ((x & ~0x7f) != 0) {
1121 out.write((byte) (0x80 | (x & 0x7f)));
1122 x >>>= 7;
1123 len++;
1124 }
1125 out.write((byte) x);
1126 return ++len;
1127 }
1128
1129 /**
1130 * Read a variable size long value.
1131 *
1132 * @param in the input stream
1133 * @return the value
1134 */
1135 static long readVarLong(InputStream in) throws IOException {
1136 long x = in.read();
1137 if (x < 0) {
1138 throw new EOFException();
1139 }
1140 x = (byte) x;
1141 if (x >= 0) {
1142 return x;
1143 }
1144 x &= 0x7f;
1145 for (int s = 7; s < 64; s += 7) {
1146 long b = in.read();
1147 if (b < 0) {
1148 throw new EOFException();
1149 }
1150 b = (byte) b;
1151 x |= (b & 0x7f) << s;
1152 if (b >= 0) {
1153 break;
1154 }
1155 }
1156 return x;
1157 }
1158
1159 /**
1160 * An input stream that uses a shared file channel.
1161 */
1162 static class SharedInputStream extends InputStream {
1163 private final FileChannel channel;
1164 private final long endPosition;
1165 private long position;
1166
1167 SharedInputStream(FileChannel channel, long position, long endPosition) {
1168 this.channel = channel;
1169 this.position = position;
1170 this.endPosition = endPosition;
1171 }
1172
1173 @Override
1174 public int read() {
1175 throw new UnsupportedOperationException();
1176 }
1177
1178 @Override
1179 public int read(byte[] b, int off, int len) throws IOException {
1180 if (len == 0) {
1181 return 0;
1182 }
1183 len = (int) Math.min(len, endPosition - position);
1184 if (len <= 0) {
1185 return -1;
1186 }
1187 ByteBuffer buff = ByteBuffer.wrap(b, off, len);
1188 len = channel.read(buff, position);
1189 position += len;
1190 return len;
1191 }
1192
1193 }
1194
1195 }