]> git.basschouten.com Git - openhab-addons.git/blob
2bd98ca8580425f565936b53456f6fb2b91208c0
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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
40         int read = 0;
41
42         if (position < prefix.length) {
43             dst.put(Arrays.copyOfRange(prefix, (int) position, prefix.length));
44             read += prefix.length - position;
45         }
46
47         read += source.read(dst);
48
49         position += read;
50
51         return read;
52     }
53
54     @Override
55     public int write(ByteBuffer src) throws IOException {
56         throw new IOException("Read only!");
57     }
58
59     @Override
60     public long position() throws IOException {
61         return position;
62     }
63
64     @Override
65     public SeekableByteChannel position(long newPosition) throws IOException {
66
67         this.position = newPosition;
68
69         if (newPosition > prefix.length) {
70             source.position(newPosition - prefix.length);
71         }
72
73         return this;
74     }
75
76     @Override
77     public long size() throws IOException {
78         return source.size() + prefix.length;
79     }
80
81     @Override
82     public SeekableByteChannel truncate(long size) throws IOException {
83         throw new IOException("Read only!");
84     }
85
86     @Override
87     public boolean isOpen() {
88         return source.isOpen();
89     }
90
91     @Override
92     public void close() throws IOException {
93         source.close();
94     }
95 }