Use nio Channels in OpenAPI read
[netconf.git] / restconf / restconf-openapi / src / main / java / org / opendaylight / restconf / openapi / impl / SecuritySchemesStream.java
1 /*
2  * Copyright (c) 2023 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.restconf.openapi.impl;
9
10 import java.io.BufferedReader;
11 import java.io.ByteArrayInputStream;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.io.InputStreamReader;
15 import java.io.Reader;
16 import java.nio.ByteBuffer;
17 import java.nio.channels.Channels;
18 import java.nio.channels.ReadableByteChannel;
19 import java.nio.charset.StandardCharsets;
20 import java.util.Map;
21 import org.opendaylight.restconf.openapi.jaxrs.OpenApiBodyWriter;
22 import org.opendaylight.restconf.openapi.model.OpenApiEntity;
23 import org.opendaylight.restconf.openapi.model.SecuritySchemesEntity;
24 import org.opendaylight.restconf.openapi.model.security.SecuritySchemeObject;
25
26 public final class SecuritySchemesStream extends InputStream {
27     private final OpenApiBodyWriter writer;
28     private final SecuritySchemesEntity securitySchemesEntity;
29
30     private Reader reader;
31     private ReadableByteChannel channel;
32
33     public SecuritySchemesStream(final OpenApiBodyWriter writer,
34             final Map<String, SecuritySchemeObject> securitySchemes) {
35         this.writer = writer;
36         this.securitySchemesEntity = new SecuritySchemesEntity(securitySchemes);
37     }
38
39     @Override
40     public int read() throws IOException {
41         if (reader == null) {
42             reader = new BufferedReader(
43                 new InputStreamReader(new ByteArrayInputStream(writeNextEntity(securitySchemesEntity)),
44                     StandardCharsets.UTF_8));
45         }
46         return reader.read();
47     }
48
49     @Override
50     public int read(final byte[] array, final int off, final int len) throws IOException {
51         if (channel == null) {
52             final var stream = new ByteArrayInputStream(writeNextEntity(securitySchemesEntity));
53             channel = Channels.newChannel(stream);
54         }
55         return channel.read(ByteBuffer.wrap(array, off, len));
56     }
57
58     private byte[] writeNextEntity(final OpenApiEntity next) throws IOException {
59         writer.writeTo(next, null, null, null, null, null, null);
60         return writer.readFrom();
61     }
62 }