6036b7e48ca6f7a59da0d8a420264cd4a6fb5443
[netconf.git] / restconf / restconf-openapi / src / main / java / org / opendaylight / restconf / openapi / impl / SchemaStream.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.charset.StandardCharsets;
17 import java.util.Deque;
18 import org.opendaylight.restconf.openapi.jaxrs.OpenApiBodyWriter;
19 import org.opendaylight.restconf.openapi.model.OpenApiEntity;
20 import org.opendaylight.restconf.openapi.model.SchemaEntity;
21
22 public final class SchemaStream extends InputStream {
23     private final Deque<SchemaEntity> stack;
24     private final OpenApiBodyWriter writer;
25
26     private Reader reader;
27
28     public SchemaStream(final Deque<SchemaEntity> schemas, final OpenApiBodyWriter writer) {
29         this.stack = schemas;
30         this.writer = writer;
31     }
32
33     @Override
34     public int read() throws IOException {
35         if (reader == null) {
36             if (stack.isEmpty()) {
37                 return -1;
38             }
39             reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(writeNextEntity(stack.pop())),
40                 StandardCharsets.UTF_8));
41         }
42
43         var read = reader.read();
44         while (read == -1) {
45             if (stack.isEmpty()) {
46                 return -1;
47             }
48             reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(writeNextEntity(stack.pop())),
49                 StandardCharsets.UTF_8));
50             read = reader.read();
51         }
52
53         return read;
54     }
55
56     @Override
57     public int read(final byte[] array, final int off, final int len) throws IOException {
58         return super.read(array, off, len);
59     }
60
61     private byte[] writeNextEntity(final OpenApiEntity entity) throws IOException {
62         writer.writeTo(entity, null, null, null, null, null, null);
63         return writer.readFrom();
64     }
65 }