]> git.basschouten.com Git - openhab-addons.git/blob
a66e3c2d3bc818c8e846f46a6ef8e33a5a96a74f
[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.ClosedChannelException;
19 import java.nio.channels.SeekableByteChannel;
20
21 /**
22  * Simple wrapper around a byte array to provide a SeekableByteChannel for consumption
23  *
24  * @author Dan Cunningham - Initial contribution
25  */
26 public class ReadOnlySeekableByteArrayChannel implements SeekableByteChannel {
27     private byte[] data;
28     private int position;
29     private boolean closed;
30
31     public ReadOnlySeekableByteArrayChannel(byte[] data) {
32         this.data = data;
33     }
34
35     @Override
36     public long position() {
37         return position;
38     }
39
40     @Override
41     public SeekableByteChannel position(long newPosition) throws IOException {
42         ensureOpen();
43         position = (int) Math.max(0, Math.min(newPosition, size()));
44         return this;
45     }
46
47     @Override
48     public long size() {
49         return data.length;
50     }
51
52     @Override
53     public int read(ByteBuffer buf) throws IOException {
54         ensureOpen();
55         int remaining = (int) size() - position;
56         if (remaining <= 0) {
57             return -1;
58         }
59         int readBytes = buf.remaining();
60         if (readBytes > remaining) {
61             readBytes = remaining;
62         }
63         buf.put(data, position, readBytes);
64         position += readBytes;
65         return readBytes;
66     }
67
68     @Override
69     public void close() {
70         closed = true;
71     }
72
73     @Override
74     public boolean isOpen() {
75         return !closed;
76     }
77
78     @Override
79     public int write(ByteBuffer b) throws IOException {
80         throw new UnsupportedOperationException();
81     }
82
83     @Override
84     public SeekableByteChannel truncate(long newSize) {
85         throw new UnsupportedOperationException();
86     }
87
88     private void ensureOpen() throws ClosedChannelException {
89         if (!isOpen()) {
90             throw new ClosedChannelException();
91         }
92     }
93 }