org.pipservices3.swagger.services.SwaggerService Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pip-services3-swagger Show documentation
Show all versions of pip-services3-swagger Show documentation
The swagger module provides a Swagger UI that can be added into microservices
and seamlessly integrated with existing REST and Commandable HTTP services.
The newest version!
package org.pipservices3.swagger.services;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.ws.rs.HttpMethod;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.pipservices3.commons.convert.JsonConverter;
import org.pipservices3.rpc.services.ISwaggerService;
import org.pipservices3.rpc.services.RestService;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
public class SwaggerService extends RestService implements ISwaggerService {
private final HashMap _routes = new HashMap<>();
public SwaggerService() {
this._baseRoute = "swagger";
}
private InputStreamReader getFileStream(String fileName) {
return new InputStreamReader(Objects.requireNonNull(SwaggerService.class.getClassLoader().getResourceAsStream(fileName)));
}
private String calculateContentType(String fileName) {
var ext = Optional.of(fileName)
.filter(f -> f.contains("."))
.map(f -> f.substring(fileName.lastIndexOf(".") + 1)).get();
return switch (ext) {
case "html" -> "text/html";
case "css" -> "text/css";
case "js" -> "application/javascript";
case "png" -> "image/png";
default -> "text/plain";
};
}
private boolean checkFileExist(String fileName) {
return SwaggerService.class.getClassLoader().getResource(fileName) != null;
}
private String loadFileContent(String fileName) {
StringBuilder resultStringBuilder = new StringBuilder();
try (BufferedReader br
= new BufferedReader(this.getFileStream(fileName))) {
String line;
while ((line = br.readLine()) != null) {
resultStringBuilder.append(line).append("\n");
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return resultStringBuilder.toString();
}
private Response getSwaggerFile(ContainerRequestContext req) {
var fileName = req.getUriInfo().getPathParameters().get("file_name").get(0).toLowerCase();
//req.params.file_name.toLowerCase();
if (!this.checkFileExist(fileName))
return Response.status(404).build();
return Response
.status(200)
.entity(this.loadFileContent(fileName))
.header("Content-Type", this.calculateContentType(fileName))
.build();
}
private Response getIndex(ContainerRequestContext req) {
var content = this.loadFileContent("index.html");
// Inject urls
var urls = new ArrayList
© 2015 - 2025 Weber Informatics LLC | Privacy Policy