net.sf.aguacate.swagger.AguacateSwaggerServlet Maven / Gradle / Ivy
package net.sf.aguacate.swagger;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.sf.aguacate.AguacateServlet;
import net.sf.aguacate.swagger.configuration.SwaggerConfigurationCoupling;
import net.sf.aguacate.util.meta.Meta;
import net.sf.aguacate.util.meta.MetaCoupling;
public class AguacateSwaggerServlet extends HttpServlet {
private static final long serialVersionUID = 3534985525342204442L;
private static final Logger LOGGER = LogManager.getLogger(AguacateSwaggerServlet.class);
private static final Logger LOGGER2 = LogManager.getLogger("aguacate.init");
private static final String EXTENSION = ".yaml";
private static final int EXTENSION_LENGTH = 5;
static {
assert EXTENSION_LENGTH == EXTENSION.length();
}
@Override
public void init() throws ServletException {
super.init();
String group = "net.sf.aguacate.swagger";
String artifact = "aguacate-servlet-swagger";
Meta meta = MetaCoupling.get(AguacateServlet.class, group, artifact);
String message = group + " & " + artifact + " & " + meta.getVersion();
log(message);
LOGGER2.info(message);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
String originalName = request.getServletPath().substring(1);
if (originalName.indexOf('/') < 0 && originalName.endsWith(EXTENSION)) {
String name = originalName.substring(0, originalName.length() - EXTENSION_LENGTH);
LOGGER.trace("{} -> {}", originalName, name);
String configuration = SwaggerConfigurationCoupling.getConfiguration(name);
if (configuration == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
} else {
response.setStatus(HttpServletResponse.SC_OK);
writeSingleString(response, configuration);
}
} else {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
} catch (IOException | RuntimeException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
LOGGER.error("on servlet", e);
}
}
void writeSingleString(HttpServletResponse response, String configuration) throws IOException {
response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
response.setContentType("text/x-yaml");
Writer writer = response.getWriter();
try {
writer.write(configuration);
} finally {
try {
writer.close();
} catch (IOException e) {
LOGGER.warn("on close resource", e);
}
}
}
}