2 * Copyright (c) 2023 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.restconf.openapi.impl;
10 import com.fasterxml.jackson.core.JsonFactoryBuilder;
11 import com.fasterxml.jackson.core.JsonGenerator;
12 import java.io.ByteArrayInputStream;
13 import java.io.ByteArrayOutputStream;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.io.InputStreamReader;
17 import java.io.Reader;
18 import java.nio.charset.StandardCharsets;
19 import java.util.ArrayDeque;
20 import java.util.Deque;
21 import java.util.List;
23 import org.opendaylight.restconf.openapi.jaxrs.OpenApiBodyWriter;
24 import org.opendaylight.restconf.openapi.model.Info;
25 import org.opendaylight.restconf.openapi.model.InfoEntity;
26 import org.opendaylight.restconf.openapi.model.OpenApiVersionEntity;
27 import org.opendaylight.restconf.openapi.model.Server;
28 import org.opendaylight.restconf.openapi.model.ServerEntity;
29 import org.opendaylight.restconf.openapi.model.ServersEntity;
30 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
32 public final class OpenApiInputStream extends InputStream {
33 private final ByteArrayOutputStream stream = new ByteArrayOutputStream();
34 private final JsonGenerator generator = new JsonFactoryBuilder().build().createGenerator(stream);
35 private final Deque<InputStream> stack = new ArrayDeque<>();
37 private Reader reader;
41 public OpenApiInputStream(final EffectiveModelContext context, final String openApiVersion, final Info info,
42 final List<Server> servers, final List<Map<String, List<String>>> security) throws IOException {
43 final OpenApiBodyWriter writer = new OpenApiBodyWriter(generator, stream);
44 stack.add(new OpenApiVersionStream(new OpenApiVersionEntity(), writer));
45 stack.add(new InfoStream(new InfoEntity(info.version(), info.title(), info.description()), writer));
46 stack.add(new ServersStream(new ServersEntity(
47 List.of(new ServerEntity(servers.iterator().next().url()))), writer));
48 stack.add(new PathsSteam(context, writer, generator, stream));
49 stack.add(new SchemasStream(context, writer, generator, stream));
50 stack.add(new SecurityStream(writer));
54 public int read() throws IOException {
59 generator.writeStartObject();
61 reader = new InputStreamReader(new ByteArrayInputStream(stream.toByteArray()), StandardCharsets.UTF_8);
65 var read = reader.read();
67 if (stack.isEmpty()) {
68 generator.writeEndObject();
70 reader = new InputStreamReader(new ByteArrayInputStream(stream.toByteArray()), StandardCharsets.UTF_8);
75 reader = new InputStreamReader(stack.pop(), StandardCharsets.UTF_8);
83 public int read(final byte[] array, final int off, final int len) throws IOException {
84 return super.read(array, off, len);