]> git.basschouten.com Git - openhab-addons.git/blob
a8544d8e70baa7e64afbdff2945b9dd18d35f1c3
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13
14 package org.openhab.automation.jsscripting.internal.fs;
15
16 import java.io.IOException;
17 import java.nio.ByteBuffer;
18 import java.nio.channels.SeekableByteChannel;
19 import java.util.Arrays;
20
21 /**
22  * Wrapper for a {@link SeekableByteChannel} allowing prefixing the stream with a fixed array of bytes
23  *
24  * @author Jonathan Gilbert - Initial contribution
25  */
26 public class PrefixedSeekableByteChannel implements SeekableByteChannel {
27
28     private byte[] prefix;
29     private SeekableByteChannel source;
30     private long position;
31
32     public PrefixedSeekableByteChannel(byte[] prefix, SeekableByteChannel source) {
33         this.prefix = prefix;
34         this.source = source;
35     }
36
37     @Override
38     public int read(ByteBuffer dst) throws IOException {
39         int read = 0;
40
41         if (position < prefix.length) {
42             dst.put(Arrays.copyOfRange(prefix, (int) position, prefix.length));
43             read += prefix.length - position;
44         }
45
46         read += source.read(dst);
47
48         position += read;
49
50         return read;
51     }
52
53     @Override
54     public int write(ByteBuffer src) throws IOException {
55         throw new IOException("Read only!");
56     }
57
58     @Override
59     public long position() throws IOException {
60         return position;
61     }
62
63     @Override
64     public SeekableByteChannel position(long newPosition) throws IOException {
65         this.position = newPosition;
66
67         if (newPosition > prefix.length) {
68             source.position(newPosition - prefix.length);
69         }
70
71         return this;
72     }
73
74     @Override
75     public long size() throws IOException {
76         return source.size() + prefix.length;
77     }
78
79     @Override
80     public SeekableByteChannel truncate(long size) throws IOException {
81         throw new IOException("Read only!");
82     }
83
84     @Override
85     public boolean isOpen() {
86         return source.isOpen();
87     }
88
89     @Override
90     public void close() throws IOException {
91         source.close();
92     }
93 }