0

Наметки rest api

- задействован SpringMVC;
- определены обработчики 404-й и 500-й ошибок.
This commit is contained in:
2019-01-06 03:01:43 +03:00
parent 407a91c435
commit 21306e1c8d
7 changed files with 234 additions and 12 deletions

View File

@@ -1,10 +0,0 @@
package ks.server;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Main {
public static void main(String[] args) {
log.info("KinoSearch - Server");
}
}

View File

@@ -0,0 +1,20 @@
package ks.server;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
@ComponentScan({ "ks.server.controllers" })
@EnableWebMvc
public class SpringConfigMVC implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new GsonHttpMessageConverter());
}
}

View File

@@ -0,0 +1,100 @@
package ks.server;
import ks.server.controllers.ErrorPageController;
import ks.server.controllers.WebController;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jetty.server.ConnectionFactory;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Slf4jLog;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import java.net.InetSocketAddress;
@Slf4j
@RequiredArgsConstructor
public class WebApplication {
private final String host;
private final int port;
private DispatcherServlet getDispatcherServlet(WebApplicationContext context) {
DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
return dispatcherServlet;
}
private ErrorPageErrorHandler getErrorHandler() {
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorHandler.addErrorPage(500, "/err500");
return errorHandler;
}
/**
* Подготавливаем обработчик запросов
*
* @param context Spring-контекст веб-приложения {@link WebApplicationContext}
* @return {@link ServletContextHandler}
*/
private ServletContextHandler getServletContextHandler(WebApplicationContext context) {
ServletContextHandler contextHandler = new ServletContextHandler();
contextHandler.setContextPath("/");
contextHandler.setErrorHandler(getErrorHandler());
contextHandler.addServlet(new ServletHolder(getDispatcherServlet(context)), "/*");
contextHandler.addEventListener(new ContextLoaderListener(context));
return contextHandler;
}
/**
* Создаем Spring-контекст
*
* @return {@link WebApplicationContext}
*/
private WebApplicationContext getWebApplicationContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(SpringConfigMVC.class);
return context;
}
/**
* Запуск встроенного веб-сервера
*/
private void start() {
Log.setLog(new Slf4jLog("Jetty.Logger"));
Server jettyServer = new Server(new InetSocketAddress(host, port));
for (Connector connector : jettyServer.getConnectors()) {
for (ConnectionFactory factory : connector.getConnectionFactories()) {
if (factory instanceof HttpConnectionFactory) {
((HttpConnectionFactory)factory).getHttpConfiguration().setSendServerVersion(false);
}
}
}
jettyServer.setHandler(getServletContextHandler(getWebApplicationContext()));
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
log.error("Error start server", e);
}
}
public static void main(String[] args) {
final String host = System.getProperty("host", "127.0.0.1");
final int port = Integer.parseInt(System.getProperty("port", "8080"));
log.info("Server listen {}:{}", host, port);
WebApplication webApplication = new WebApplication(host, port);
webApplication.start();
}
}

View File

@@ -0,0 +1,47 @@
package ks.server.controllers;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.ServletException;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public class ErrorPageController {
private Map<String, String> createErrorMap(HttpStatus httpStatus) {
return createErrorMap(httpStatus.value(), httpStatus.getReasonPhrase());
}
private Map<String, String> createErrorMap(int code, String message) {
Map<String, String> map = new HashMap<>();
map.put("error", String.valueOf(code));
map.put("errorMessage", message);
return map;
}
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String, String> handleNotFound() {
return createErrorMap(HttpStatus.NOT_FOUND);
}
@ExceptionHandler(ServletException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, String> handleUnexceptedError() {
return createErrorMap(-1, "Unexcepted error");
}
@RequestMapping(path = "/err500", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, String> handleInternalError() {
return createErrorMap(HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@@ -0,0 +1,21 @@
package ks.server.controllers;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Collections;
import java.util.Map;
@Controller
@RequestMapping(path = "/", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public class WebController {
@RequestMapping(method = RequestMethod.GET)
public Map<String, String> index() {
return Collections.singletonMap("message", "hello?");
}
}

View File

@@ -6,8 +6,10 @@
</Console>
</Appenders>
<Loggers>
<Root level="all">
<Root level="warn">
<AppenderRef ref="Console"/>
</Root>
<Logger name="ks.server" level="info"/>
<Logger name="org.springframework.web.servlet.PageNotFound" level="error"/>
</Loggers>
</Configuration>