-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Transferable.java
96 lines (79 loc) · 2.53 KB
/
Transferable.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package org.testcontainers.images.builder;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.Checksum;
public interface Transferable {
int DEFAULT_FILE_MODE = 0100644;
int DEFAULT_DIR_MODE = 040755;
static Transferable of(String string) {
return of(string.getBytes(StandardCharsets.UTF_8));
}
static Transferable of(byte[] bytes) {
return of(bytes, DEFAULT_FILE_MODE);
}
static Transferable of(byte[] bytes, int fileMode) {
return new Transferable() {
@Override
public long getSize() {
return bytes.length;
}
@Override
public byte[] getBytes() {
return bytes;
}
@Override
public void updateChecksum(Checksum checksum) {
checksum.update(bytes, 0, bytes.length);
}
@Override
public int getFileMode() {
return fileMode;
}
};
}
/**
* Get file mode. Default is 0100644.
*
* @return file mode
* @see Transferable#DEFAULT_FILE_MODE
*/
default int getFileMode() {
return DEFAULT_FILE_MODE;
}
/**
* Size of an object.
*
* @return size in bytes
*/
long getSize();
/**
* transfer content of this Transferable to the output stream. <b>Must not</b> close the stream.
*
* @param tarArchiveOutputStream stream to output
* @param destination
*/
default void transferTo(TarArchiveOutputStream tarArchiveOutputStream, final String destination) {
TarArchiveEntry tarEntry = new TarArchiveEntry(destination);
tarEntry.setSize(getSize());
tarEntry.setMode(getFileMode());
try {
tarArchiveOutputStream.putArchiveEntry(tarEntry);
IOUtils.write(getBytes(), tarArchiveOutputStream);
tarArchiveOutputStream.closeArchiveEntry();
} catch (IOException e) {
throw new RuntimeException("Can't transfer " + getDescription(), e);
}
}
default byte[] getBytes() {
return new byte[0];
}
default String getDescription() {
return "";
}
default void updateChecksum(Checksum checksum) {
throw new UnsupportedOperationException("Provide implementation in subclass");
}
}