기본 골격

This commit is contained in:
현성필
2023-05-08 10:16:00 +09:00
parent 169ba6448c
commit 2412d289c3
606 changed files with 214162 additions and 114780 deletions
+22 -9
View File
@@ -1,5 +1,5 @@
plugins {
id 'org.springframework.boot' version '2.4.4'
id 'org.springframework.boot' version '2.5.14'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id 'war'
@@ -17,33 +17,46 @@ group = 'com.eactive'
version = '1.0.1'
sourceCompatibility = '1.8'
compileJava.options.encoding = 'UTF-8'
configurations {
annotationProcessor
}
compileJava {
options.annotationProcessorPath = configurations.annotationProcessor
options.encoding = 'UTF-8'
}
repositories {
mavenCentral()
}
dependencies {
annotationProcessor "org.mapstruct:mapstruct-processor:1.5.3.Final"
implementation 'org.mapstruct:mapstruct:1.5.3.Final'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.data:spring-data-envers'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
implementation 'com.navercorp.lucy:lucy-xss-servlet:2.0.1'
// implementation 'com.github.darrachequesne:spring-data-jpa-datatables:5.1.0'
// implementation 'com.google.jimfs:jimfs:1.2'
implementation 'io.springfox:springfox-boot-starter:3.0.0'
implementation 'org.apache.httpcomponents:httpclient:4.5.13'
implementation 'org.apache.httpcomponents:httpclient:4.5.14'
implementation 'org.apache.commons:commons-lang3:3.12.0'
implementation 'commons-io:commons-io:2.11.0'
implementation 'com.jayway.jsonpath:json-path:2.7.0'
implementation 'io.netty:netty-transport-native-kqueue:4.1.79.Final'
implementation 'io.netty:netty-resolver-dns-native-macos:4.1.79.Final'
implementation ('io.netty:netty-all:4.1.79.Final') {
exclude group: "io.netty", module: "netty-transport-native-kqueue"
exclude group: "io.netty", module: "netty-resolver-dns-native-macos"
implementation 'com.jayway.jsonpath:json-path:2.8.0'
implementation 'io.netty:netty-all:4.1.92.Final'
implementation ('commons-beanutils:commons-beanutils:1.9.4') {
exclude group: 'commons-collections', module: 'commons-collections'
}
runtimeOnly 'com.h2database:h2'
implementation 'org.mdkt.compiler:InMemoryJavaCompiler:1.3.0'
@@ -2,8 +2,13 @@ package com.eactive.httpmockserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@SpringBootApplication(exclude = {
UserDetailsServiceAutoConfiguration.class,
})
@ComponentScan("com.eactive")
public class HttpMockServerApplication {
public static void main(String[] args) {
@@ -1,36 +0,0 @@
package com.eactive.httpmockserver;
public class HttpResponseInfo {
private String statusCode;
private String headers;
private String body;
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getHeaders() {
return headers;
}
public void setHeaders(String headers) {
this.headers = headers;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
@Override
public String toString() {
return "HttpResponseInfo [statusCode=" + statusCode + ", headers=" + headers + ", body=" + body + "]";
}
}
@@ -1,29 +0,0 @@
package com.eactive.httpmockserver;
import com.eactive.httpmockserver.script.service.ScriptInfoService;
import com.eactive.httpmockserver.script.ScriptLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.net.URISyntaxException;
@Component
public class PostConstructBean {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
public ScriptInfoService scriptInfoService;
@PostConstruct
public void init() throws URISyntaxException {
logger.info("init scripts");
try {
ScriptLoader.getInstance().init(scriptInfoService);
} catch (Exception e) {
logger.error("init scripts failed", e);
}
}
}
@@ -1,221 +0,0 @@
package com.eactive.httpmockserver.api.controller;
import com.eactive.httpmockserver.api.entity.ApiInfo;
import com.eactive.httpmockserver.api.entity.ApiServiceKey;
import com.eactive.httpmockserver.script.Script;
import com.eactive.httpmockserver.script.ScriptLoader;
import com.eactive.httpmockserver.api.service.ApiService;
import com.eactive.httpmockserver.api.service.ApiServiceKeyService;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.server.ResponseStatusException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
@Controller
public class ApiController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private ApiServiceKeyService apiKeyService;
@Autowired
private ApiService apiService;
/** one random instance */
Random random = new Random();
@SuppressWarnings("deprecation")
//@RequestMapping(value = "/mock-api/**")
@RequestMapping(value = "/{_:^(?!swagger-ui|plugins|dist|favicon.ico).*$}/**")
public ResponseEntity<String> mockApi(HttpEntity<String> httpEntity, HttpServletRequest request,
HttpServletResponse response) throws Exception {
logger.info("==================================================");
logger.info("==================================================");
logger.info("request.getProtocol()= {}", request.getProtocol());
logger.info("request.getMethod()= {}", request.getMethod());
logger.info("request.getServletPath()= {}", request.getServletPath());
logger.info("request.getQueryString()= {}", request.getQueryString());
logger.info("--------------------------------------------------");
logger.info("httpEntity.getHeaders().toString()= {}", httpEntity.getHeaders());
logger.info("--------------------------------------------------");
logger.info("httpEntity.getBody()={}", httpEntity.getBody());
logger.info("--------------------------------------------------");
Map<String, String[]> paramMap = request.getParameterMap();
for (Entry<String, String[]> entry : paramMap.entrySet()) {
for (String value : entry.getValue()) {
logger.info("request.getParameter({})={}", entry.getKey(), value);
}
}
logger.info("==================================================");
logger.info("==================================================");
String url = request.getServletPath();
String serviceValue = assignServiceValue(httpEntity, request, url);
if (StringUtils.isNotBlank(serviceValue)) {
logger.info("--------------------------------------------------");
logger.info("serviceCode={}", serviceValue);
logger.info("==================================================");
logger.info("==================================================");
}
ApiInfo api = apiService.findByUrlAndServiceValue(url, serviceValue);
if (api == null) {
logger.info("Not found API(URL={}, ServiceValue={}", url, serviceValue);
throw new ResponseStatusException(HttpStatus.NOT_FOUND,
String.format("Not found API(URL=%s, ServiceValue=%s", url, serviceValue));
}
if (StringUtils.isNotBlank(api.getMethod())) {
if (!api.getMethod().equalsIgnoreCase(request.getMethod())) {
logger.info("Method({}) not allowe", request.getMethod());
throw new ResponseStatusException(HttpStatus.METHOD_NOT_ALLOWED,
String.format("Method(%s) not allowed", request.getMethod()));
}
}
// sleep 적용
if (api.getSleepSeconds() != null) {
int sleepSeconds = api.getSleepSeconds().intValue();
if (sleepSeconds > 0) {
try {
logger.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
logger.info("Start Sleep {} Seconds.", sleepSeconds);
logger.info("...");
Thread.sleep(sleepSeconds * 1000l);
logger.info("......");
logger.info("Finished Sleep {} Seconds.", sleepSeconds);
logger.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
} catch (InterruptedException e) {
logger.error("sleep", e);
}
}
}
HttpHeaders responseHeaders = new HttpHeaders();
if (StringUtils.isNotBlank(api.getResponseContentType())) {
responseHeaders.setContentType(MediaType.parseMediaType(api.getResponseContentType()));
} else {
responseHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
}
assignResponseHeaders(responseHeaders, api.getResponseHeaders());
// status code 적용
int responseStatusCode = 200;
if (api.getResponseStatusCode() != null) {
responseStatusCode = api.getResponseStatusCode().intValue();
logger.info("Response Status Code={}", responseStatusCode);
}
String responseStr = assignResponseBody(api);
String scriptName = api.getScriptName();
if(StringUtils.isNotBlank(scriptName)) {
Script script = ScriptLoader.getInstance().newScript(scriptName);
logger.info("Execute postProcess Script={}", scriptName);
responseStr = script.postProcess(httpEntity.getBody(), responseStr);
}
logger.info("ResponseBody={}", responseStr);
return new ResponseEntity<String>(responseStr, responseHeaders, responseStatusCode);
}
private String assignServiceValue(HttpEntity<String> httpEntity, HttpServletRequest request, String url) {
ApiServiceKey apiServiceKey = apiKeyService.findByUrl(url);
if (apiServiceKey == null || StringUtils.isBlank(apiServiceKey.getServiceType())) {
return "";
}
String serviceType = apiServiceKey.getServiceType();
String serviceKey = apiServiceKey.getServiceKey();
if (StringUtils.isBlank(serviceKey)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND,
String.format("ServiceKey not found(URL=%s, ServiceType=%s)", url, serviceType));
}
if (serviceType.equalsIgnoreCase("header")) {
String serviceValue = request.getHeader(serviceKey);
if (StringUtils.isBlank(serviceValue)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND,
String.format("Header not found(URL=%s, ServiceKey=%s)", url, serviceKey));
}
return serviceValue;
} else if (serviceType.equalsIgnoreCase("parameter")) {
String serviceValue = request.getParameter(serviceKey);
if (StringUtils.isBlank(serviceValue)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND,
String.format("Parameter not found(URL=%s, ServiceKey=%s)", url, serviceKey));
}
return serviceValue;
} else if (serviceType.equalsIgnoreCase("json-body")) {
// ex) $.dataHeader.serviceId
DocumentContext jsonContext = JsonPath.parse(httpEntity.getBody());
String serviceValue = jsonContext.read(serviceKey);
if (StringUtils.isBlank(serviceValue)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND,
String.format("json-key not found(URL=%s, ServiceKey=%s)", url, serviceKey));
}
return serviceValue;
} else if (serviceType.equalsIgnoreCase("flat-data")) {
String msg = httpEntity.getBody();
String[] args = org.springframework.util.StringUtils.tokenizeToStringArray(serviceKey, ",");
int startIdx = NumberUtils.toInt(args[0]);
int length = NumberUtils.toInt(args[1]);
String serviceValue = msg.substring(startIdx, startIdx + length);
if (StringUtils.isBlank(serviceValue)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND,
String.format("sbi-std-servlet not found(URL=%s, ServiceKey=%s)", url, serviceKey));
}
return serviceValue;
} else {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
String.format("Unsuported ServiceType(ServiceType=%s, ServiceKey=%s)", serviceType, serviceKey));
}
}
private String assignResponseBody(ApiInfo api) {
if (api == null) {
return "";
}
if (StringUtils.isBlank(api.getResponseBody2())) {
return api.getResponseBody1();
} else {
if (random.nextInt(2) == 0) {
return api.getResponseBody2();
} else {
return api.getResponseBody1();
}
}
}
private void assignResponseHeaders(HttpHeaders httpHeaders, String headerStr) {
if (StringUtils.isBlank(headerStr)) {
return;
}
// service_code=1234,user_id=james
String[] headerPairs = org.springframework.util.StringUtils.tokenizeToStringArray(headerStr, ",");
for (String headerPair : headerPairs) {
String[] keyValue = org.springframework.util.StringUtils.tokenizeToStringArray(headerPair, "=");
if (keyValue.length == 2 && StringUtils.isNotBlank(keyValue[0]) && StringUtils.isNotBlank(keyValue[1])) {
httpHeaders.add(keyValue[0], keyValue[1]);
}
}
}
}
@@ -1,135 +0,0 @@
package com.eactive.httpmockserver.api.controller;
import com.eactive.httpmockserver.api.entity.ApiInfo;
import com.eactive.httpmockserver.api.entity.ApiServiceKey;
import com.eactive.httpmockserver.script.service.ScriptInfoService;
import com.eactive.httpmockserver.api.service.ApiService;
import com.eactive.httpmockserver.api.service.ApiServiceKeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
import java.util.Optional;
@Controller
public class ApiManageController {
@Autowired
private ApiService apiService;
@Autowired
private ScriptInfoService scriptInfoService;
@Autowired
private ApiServiceKeyService apiKeyService;
@GetMapping("/manage/findAllApis")
public String getAllApis(Pageable pageable, Model model) {
model.addAttribute("apiGroupNameList", apiService.findAllApiGroupName());
return "page/list-api";
}
@SuppressWarnings("deprecation")
@GetMapping(path = { "/manage/getApiForm", "/manage/getApiForm/{id}" })
public String getApiForm(Model model, @PathVariable Optional<Long> id) {
if (id.isPresent()) {
Optional<ApiInfo> optional = apiService.findById(id.get());
if (optional.isPresent()) {
model.addAttribute("apiInfo", optional.get());
} else {
throw new IllegalArgumentException("No data, id: " + id.get());
}
} else {
ApiInfo apiInfo = new ApiInfo();
apiInfo.setMethod(HttpMethod.POST.name());
apiInfo.setResponseContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
model.addAttribute("apiInfo", apiInfo);
}
model.addAttribute("scriptInfos", scriptInfoService.findAllScriptInfos());
return "page/add-edit-api";
}
@PostMapping("/manage/saveApi")
public String saveApi(@Valid ApiInfo apiInfo, BindingResult result, Model model) {
if (result.hasErrors()) {
return "page/add-edit-api";
}
if (apiInfo.getId() == null) {
apiService.save(apiInfo);
} else {
apiService.update(apiInfo);
}
return "redirect:/manage/findAllApis";
}
@RequestMapping("/manage/deleteApi/{id}")
public String deleteApi(@PathVariable Long id) {
if (id == null) {
throw new IllegalArgumentException("No data, id: " + id);
}
apiService.delete(id);
return "redirect:/manage/findAllApis";
}
@GetMapping("/manage/findAllApiKeys")
public String getAllApiServiceKeys(Pageable pageable, Model model) {
model.addAttribute("apiServiceKeyList", apiKeyService.findAllApiServiceKeys(pageable));
return "page/list-api-key";
}
@GetMapping(path = { "/manage/getApiKeyForm", "/manage/getApiKeyForm/{id}" })
public String getApiKeyForm(Model model, @PathVariable Optional<Long> id) {
if (id.isPresent()) {
Optional<ApiServiceKey> optional = apiKeyService.findById(id.get());
if (optional.isPresent()) {
model.addAttribute("apiServiceKey", optional.get());
} else {
throw new IllegalArgumentException("No data, id: " + id.get());
}
} else {
model.addAttribute("apiServiceKey", new ApiServiceKey());
}
return "page/add-edit-api-key";
}
@PostMapping("/manage/saveApiKey")
public String saveApiKey(@Valid ApiServiceKey apiServiceKey, BindingResult result, Model model) {
if (result.hasErrors()) {
return "page/add-edit-api-key";
}
if (apiServiceKey.getId() == null) {
apiKeyService.save(apiServiceKey);
} else {
apiKeyService.update(apiServiceKey);
}
return "redirect:/manage/findAllApiKeys";
}
@RequestMapping("/manage/deleteApiKey/{id}")
public String deleteApiKey(@PathVariable Long id) {
if (id == null) {
throw new IllegalArgumentException("No data, id: " + id);
}
apiKeyService.delete(id);
return "redirect:/manage/findAllApiKeys";
}
}
@@ -1,177 +0,0 @@
package com.eactive.httpmockserver.api.controller;
import com.eactive.httpmockserver.datatables.Column;
import com.eactive.httpmockserver.datatables.DataTablesRequest;
import com.eactive.httpmockserver.datatables.DataTablesResponse;
import com.eactive.httpmockserver.api.entity.ApiInfo;
import com.eactive.httpmockserver.api.entity.ApiServiceKey;
import com.eactive.httpmockserver.api.service.ApiService;
import com.eactive.httpmockserver.api.service.ApiServiceKeyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatcher;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/manage")
public class ApiManageRestController {
@Autowired
private ApiService apiService;
@Autowired
private ApiServiceKeyService apiKeyService;
@PostMapping("/rest/saveApi")
public ApiInfo saveApi(@RequestBody ApiInfo apiInfo) {
return apiService.save(apiInfo);
}
@PostMapping("/rest/updateApi")
public ApiInfo updateApi(@RequestBody ApiInfo apiInfo) {
if (apiInfo.getId() == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "id is null");
}
return apiService.update(apiInfo);
}
@PostMapping("/rest/deleteApi/{id}")
public ResponseEntity<?> deleteApi(@PathVariable Long id) {
if (id == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "id is null");
}
apiService.delete(id);
return ResponseEntity.ok("Entity deleted");
}
@GetMapping("/rest/findAllApis")
public List<ApiInfo> getAllApis(Pageable pageable) {
return apiService.findAllApis(pageable);
}
@PostMapping("/rest/apis")
public DataTablesResponse<ApiInfo> getAllApisForDatatables(@RequestBody DataTablesRequest req) {
Pageable pageable = assignJpaPageable(req);
// // search option
// Example<ApiInfo> example = null;
// if (StringUtils.isNotBlank(req.getSearch().getValue())) {
// ApiInfo apiInfo = new ApiInfo();
// apiInfo.setApiGroupName(req.getSearch().getValue());
// apiInfo.setApiName(req.getSearch().getValue());
// apiInfo.setServiceValue(req.getSearch().getValue());
//
// ExampleMatcher matcher = ExampleMatcher.matchingAny()
// .withMatcher("apiGroupName", new GenericPropertyMatcher().contains().ignoreCase())
// .withMatcher("apiName", new GenericPropertyMatcher().contains().ignoreCase())
// .withMatcher("serviceValue", new GenericPropertyMatcher().startsWith().ignoreCase());
// example = Example.of(apiInfo, matcher);
// }
//
// DataTablesResponse<ApiInfo> res = new DataTablesResponse<ApiInfo>(apiService.findApis(example, pageable));
// res.setRecordsFiltered(apiService.getRecordsCount(example));
String apiGroupName = StringUtils.defaultIfBlank(req.getColumns().get(0).getSearch().getValue(), null);
String searchStr = StringUtils.defaultIfBlank(req.getSearch().getValue(), null);
DataTablesResponse<ApiInfo> res = new DataTablesResponse<ApiInfo>(
apiService.findApis(apiGroupName, searchStr, pageable));
res.setRecordsFiltered(apiService.countApis(apiGroupName, searchStr));
res.setRecordsTotal(apiService.getRecordsCount(null));
res.setDraw(req.getDraw());
return res;
}
public static Pageable assignJpaPageable(DataTablesRequest req) {
int pageSize = req.getLength();
if (pageSize == 0) {
pageSize = 10;
}
int pageNo = req.getStart() / pageSize;
if (req.getOrder() == null || req.getOrder().size() == 0) {
return PageRequest.of(pageNo, pageSize);
}
List<Sort.Order> orderList = new ArrayList<Sort.Order>();
for (com.eactive.httpmockserver.datatables.Order order : req.getOrder()) {
Column column = req.getColumns().get(order.getColumn());
Direction direction = null;
if (order.getDir().equals(com.eactive.httpmockserver.datatables.Direction.desc)) {
direction = Direction.DESC;
} else {
direction = Direction.ASC;
}
orderList.add(new Order(direction, column.getData()));
}
return PageRequest.of(pageNo, pageSize, Sort.by(orderList));
}
@PostMapping("/rest/saveApiServiceKey")
public ApiServiceKey saveApiServiceKey(@RequestBody ApiServiceKey apiServiceKey) {
return apiKeyService.save(apiServiceKey);
}
@PostMapping("/rest/updateApiServiceKey")
public ApiServiceKey updateApiServiceKey(@RequestBody ApiServiceKey apiServiceKey) {
if (apiServiceKey.getId() == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "id is null");
}
return apiKeyService.update(apiServiceKey);
}
@PostMapping("/rest/deleteApiServiceKey/{id}")
public ResponseEntity<?> deleteApiServiceKey(@PathVariable Long id) {
if (id == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "id is null");
}
apiKeyService.delete(id);
return ResponseEntity.ok("Entity deleted");
}
@GetMapping("/rest/findAllApiServiceKeys")
public List<ApiServiceKey> getAllApiServiceKeys(Pageable pageable) {
return apiKeyService.findAllApiServiceKeys(pageable);
}
@PostMapping("/rest/apiKeys")
public DataTablesResponse<ApiServiceKey> getAllApiKeysForDatatables(@RequestBody DataTablesRequest req) {
Pageable pageable = assignJpaPageable(req);
// search option
Example<ApiServiceKey> example = null;
if (StringUtils.isNotBlank(req.getSearch().getValue())) {
ApiServiceKey key = new ApiServiceKey();
key.setUrl(req.getSearch().getValue());
key.setServiceType(req.getSearch().getValue());
key.setServiceKey(req.getSearch().getValue());
ExampleMatcher matcher = ExampleMatcher.matchingAny()
.withMatcher("url", new GenericPropertyMatcher().contains().ignoreCase())
.withMatcher("serviceType", new GenericPropertyMatcher().startsWith().ignoreCase())
.withMatcher("serviceKey", new GenericPropertyMatcher().startsWith().ignoreCase());
example = Example.of(key, matcher);
}
DataTablesResponse<ApiServiceKey> res = new DataTablesResponse<ApiServiceKey>(
apiKeyService.findApiKeys(example, pageable));
res.setRecordsFiltered(apiKeyService.getRecordsCount(example));
res.setRecordsTotal(apiKeyService.getRecordsCount(null));
res.setDraw(req.getDraw());
return res;
}
}
@@ -1,36 +0,0 @@
package com.eactive.httpmockserver.api.controller;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@RestController
@RequestMapping("/echo")
public class EchoServiceController {
Logger logger = LoggerFactory.getLogger(EchoServiceController.class);
@PostMapping
@ResponseStatus(value = HttpStatus.OK)
public byte[] service(HttpServletRequest requestEntity) throws IOException {
String readString = null;
byte[] readByte = null;
try {
readByte = IOUtils.toByteArray(requestEntity.getInputStream());
readString = new String(readByte);
} catch (IOException e) {
e.printStackTrace();
}
logger.debug("echo \n{}", readString);
return readByte;
}
}
@@ -1,293 +0,0 @@
package com.eactive.httpmockserver.api.controller;
import com.eactive.httpmockserver.HttpResponseInfo;
import com.eactive.httpmockserver.datatables.DataTablesRequest;
import com.eactive.httpmockserver.datatables.DataTablesResponse;
import com.eactive.httpmockserver.api.entity.HttpRequestInfo;
import com.eactive.httpmockserver.api.service.HttpRequestInfoService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatcher;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Controller
public class HttpRequestInfoController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private HttpRequestInfoService httpRequestInfoService;
@PostMapping("/manage/executeHttpRequest")
@ResponseBody
public HttpResponseInfo executeHttpRequest(@Valid HttpRequestInfo httpRequestInfo, BindingResult result)
throws IOException, URISyntaxException, KeyManagementException, NoSuchAlgorithmException,
KeyStoreException {
HttpResponseInfo httpResponseInfo = new HttpResponseInfo();
if (result.hasErrors()) {
httpResponseInfo.setBody(result.toString());
return httpResponseInfo;
}
if (logger.isInfoEnabled()) {
logger.info("======================== Request Info ==========================");
logger.info(httpRequestInfo.toString());
logger.info("================================================================");
}
if (StringUtils.isBlank(httpRequestInfo.getEncode())) {
httpRequestInfo.setEncode(StandardCharsets.UTF_8.name());
}
// Method 생성 및 body 셋팅
HttpRequestBase base;
switch (HttpMethod.resolve(StringUtils.upperCase(httpRequestInfo.getMethod()))) {
case GET:
base = new HttpGet(httpRequestInfo.getUrl());
break;
case DELETE:
base = new HttpDelete(httpRequestInfo.getUrl());
break;
case POST:
base = new HttpPost(httpRequestInfo.getUrl());
assignBody(base, httpRequestInfo);
break;
case PUT:
base = new HttpPut(httpRequestInfo.getUrl());
assignBody(base, httpRequestInfo);
break;
default:
base = new HttpGet(httpRequestInfo.getUrl());
break;
}
// queryParams 셋팅
List<NameValuePair> urlParameters = assignQueryParams(httpRequestInfo.getQueryParams());
if (urlParameters != null && urlParameters.size() > 0) {
URI uri = new URIBuilder(base.getURI()).addParameters(urlParameters).build();
base.setURI(uri);
}
// heaser 셋팅
base.setHeader("Connection", "close");
assignRequestHeaders(base, httpRequestInfo);
try (CloseableHttpClient httpClient = assignHttpClient(httpRequestInfo.getUrl());
CloseableHttpResponse response = httpClient.execute(base)) {
httpResponseInfo.setStatusCode(String.valueOf(response.getStatusLine().getStatusCode()));
httpResponseInfo.setHeaders(assignResponseHeaders(response.getAllHeaders()));
HttpEntity entity = response.getEntity();
String responseStr = "";
if (entity != null) {
responseStr = EntityUtils.toString(entity, httpRequestInfo.getEncode());
httpResponseInfo.setBody(responseStr);
}
if (logger.isInfoEnabled()) {
logger.info("======================== Response Info ==========================");
logger.info("= ProtocolVersion = {}", response.getProtocolVersion());
logger.info("= StatusCode = {}", response.getStatusLine().getStatusCode());
logger.info("= Body = {}", responseStr);
logger.info("================================================================");
}
}
return httpResponseInfo;
}
private String assignResponseHeaders(Header[] headers) {
String headerStr = "";
for (Header header : headers) {
headerStr += header.getName() + "=" + header.getValue();
headerStr += ",";
}
return StringUtils.removeEnd(headerStr, ",");
}
private void assignRequestHeaders(HttpRequestBase base, HttpRequestInfo httpRequestInfo) {
if (StringUtils.isBlank(httpRequestInfo.getRequestHeaders())) {
return;
}
// service_code=1234,user_id=james
String[] headerPairs = org.springframework.util.StringUtils
.tokenizeToStringArray(httpRequestInfo.getRequestHeaders(), ",");
for (String headerPair : headerPairs) {
String[] keyValue = org.springframework.util.StringUtils.tokenizeToStringArray(headerPair, "=");
if (keyValue.length == 2 && StringUtils.isNotBlank(keyValue[0]) && StringUtils.isNotBlank(keyValue[1])) {
base.setHeader(keyValue[0], keyValue[1]);
}
}
}
private void assignBody(HttpRequestBase base, HttpRequestInfo httpRequestInfo) throws IOException {
if (StringUtils.isBlank(httpRequestInfo.getRequestBody())) {
return;
}
if (StringUtils.equals(httpRequestInfo.getRequestContentType(), MediaType.APPLICATION_FORM_URLENCODED_VALUE)) {
List<NameValuePair> parameters = assignQueryParams(httpRequestInfo.getRequestBody());
if (parameters != null) {
((HttpEntityEnclosingRequestBase) base)
.setEntity(new UrlEncodedFormEntity(parameters, httpRequestInfo.getEncode()));
}
} else {
ContentType contentType = ContentType.create(
StringUtils.defaultIfBlank(httpRequestInfo.getRequestContentType(), MediaType.TEXT_PLAIN_VALUE),
httpRequestInfo.getEncode());
((HttpEntityEnclosingRequestBase) base)
.setEntity(new StringEntity(httpRequestInfo.getRequestBody(), contentType));
}
}
private List<NameValuePair> assignQueryParams(String queryParams) {
if (StringUtils.isBlank(queryParams)) {
return null;
}
List<NameValuePair> queryParamList = new ArrayList<>();
// service_code=1234,user_id=james
String[] queryPairs = org.springframework.util.StringUtils.tokenizeToStringArray(queryParams, "&");
for (String queryPair : queryPairs) {
String[] keyValue = org.springframework.util.StringUtils.tokenizeToStringArray(queryPair, "=");
if (keyValue.length == 2) {
queryParamList.add(new BasicNameValuePair(keyValue[0], keyValue[1]));
} else if (keyValue.length == 1) {
queryParamList.add(new BasicNameValuePair(keyValue[0], ""));
}
}
return queryParamList;
}
private CloseableHttpClient assignHttpClient(String url)
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
if (StringUtils.startsWith(url, "https")) {
SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(
SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
NoopHostnameVerifier.INSTANCE);
return HttpClients.custom().setSSLSocketFactory(factory).build();
} else {
return HttpClients.createDefault();
}
}
@GetMapping("/manage/findAllHttpRequestInfos")
public String getAllAllHttpRequestInfos(Pageable pageable, Model model) {
return "page/list-http-request-info";
}
@PostMapping("/manage/rest/httpRequestInfos")
@ResponseBody
public DataTablesResponse<HttpRequestInfo> getAllHttpRequestInfosForDatatables(@RequestBody DataTablesRequest req) {
Pageable pageable = ApiManageRestController.assignJpaPageable(req);
// search option
Example<HttpRequestInfo> example = null;
if (StringUtils.isNotBlank(req.getSearch().getValue())) {
HttpRequestInfo info = new HttpRequestInfo();
info.setRequestGroupName(req.getSearch().getValue());
info.setRequestName(req.getSearch().getValue());
info.setUrl(req.getSearch().getValue());
ExampleMatcher matcher = ExampleMatcher.matchingAny()
.withMatcher("requestGroupName", new GenericPropertyMatcher().contains().ignoreCase())
.withMatcher("requestName", new GenericPropertyMatcher().contains().ignoreCase())
.withMatcher("url", new GenericPropertyMatcher().contains().ignoreCase());
example = Example.of(info, matcher);
}
DataTablesResponse<HttpRequestInfo> res = new DataTablesResponse<HttpRequestInfo>(
httpRequestInfoService.findHttpRequestInfos(example, pageable));
res.setRecordsFiltered(httpRequestInfoService.getRecordsCount(example));
res.setRecordsTotal(httpRequestInfoService.getRecordsCount(null));
res.setDraw(req.getDraw());
return res;
}
@GetMapping(path = { "/manage/getHttpRequestInfoForm", "/manage/getHttpRequestInfoForm/{id}" })
public String getgetHttpRequestInfoForm(Model model, @PathVariable Optional<Long> id) {
if (id.isPresent()) {
Optional<HttpRequestInfo> optional = httpRequestInfoService.findById(id.get());
if (optional.isPresent()) {
model.addAttribute("httpRequestInfo", optional.get());
} else {
throw new IllegalArgumentException("No data, id: " + id.get());
}
} else {
HttpRequestInfo httpRequestInfo = new HttpRequestInfo();
httpRequestInfo.setMethod(HttpMethod.POST.name());
httpRequestInfo.setRequestContentType(MediaType.APPLICATION_JSON_VALUE);
httpRequestInfo.setEncode(StandardCharsets.UTF_8.name());
model.addAttribute("httpRequestInfo", httpRequestInfo);
}
return "page/add-edit-http-request-info";
}
@PostMapping("/manage/saveHttpRequestInfo")
public String saveHttpRequestInfo(@Valid HttpRequestInfo httpRequestInfo, BindingResult result, Model model) {
if (result.hasErrors()) {
return "page/add-edit-http-request-info";
}
if (httpRequestInfo.getId() == null) {
httpRequestInfoService.save(httpRequestInfo);
} else {
httpRequestInfoService.update(httpRequestInfo);
}
return "redirect:/manage/findAllHttpRequestInfos";
}
@RequestMapping("/manage/deleteHttpRequestInfo/{id}")
public String deleteHttpRequestInfo(@PathVariable Long id) {
if (id == null) {
throw new IllegalArgumentException("No data, id: " + id);
}
httpRequestInfoService.delete(id);
return "redirect:/manage/findAllHttpRequestInfos";
}
}
@@ -0,0 +1,121 @@
package com.eactive.httpmockserver.api.controller;
import com.eactive.httpmockserver.api.dto.MockConditionDTO;
import com.eactive.httpmockserver.api.dto.MockRequest;
import com.eactive.httpmockserver.api.entity.MockCondition;
import com.eactive.httpmockserver.api.entity.MockResponse;
import com.eactive.httpmockserver.api.entity.MockRoute;
import com.eactive.httpmockserver.api.repository.MockRouteRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
@Controller
public class MockApiController {
@Autowired
private MockRouteRepository mockRouteRepository;
@RequestMapping(value = "/{_:^(?!swagger-ui|mgmt|plugins|dist|css|fonts|js|h2-console|img|pages|favicon.ico).*$}/**")
public ResponseEntity<String> handleRequest(HttpServletRequest httpRequest) {
MockRequest request = new MockRequest(httpRequest);
AntPathMatcher pathMatcher = new AntPathMatcher();
for (MockRoute mockRoute : mockRouteRepository.findAll()) {
if (isRouteMatch(mockRoute, request)) {
Map<String, String> pathVariables = pathMatcher.extractUriTemplateVariables(mockRoute.getPathPattern(), request.getUri());
MockResponse matchingResponse = findMatchingResponse(mockRoute, request, pathVariables);
if (matchingResponse != null) {
if (matchingResponse.getDelay() > 0) {
try {
Thread.sleep(matchingResponse.getDelay());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
HttpHeaders responseHeaders = new HttpHeaders();
matchingResponse.getHeaders().forEach(responseHeaders::set);
request.getParams().putAll(pathVariables);
return new ResponseEntity<>(replaceParams(matchingResponse.getBody(), request.getParams()), responseHeaders, HttpStatus.valueOf(matchingResponse.getStatusCode()));
}
}
}
// If no matching route or response is found, return a 404 Not Found
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Not Found");
}
private String replaceParams(String responseBody, Map<String, String> params) {
for (Map.Entry<String, String> entry : params.entrySet()) {
responseBody = responseBody.replace("{" + entry.getKey() + "}", entry.getValue());
}
return responseBody;
}
private boolean isRouteMatch(MockRoute mockRoute, MockRequest request) {
AntPathMatcher pathMatcher = new AntPathMatcher();
return mockRoute.getMethod().equalsIgnoreCase(request.getMethod()) && pathMatcher.match(mockRoute.getPathPattern(), request.getUri());
}
private MockResponse findMatchingResponse(MockRoute mockRoute, MockRequest mockRequest, Map<String, String> pathVariables) {
for (MockResponse response : mockRoute.getResponses()) {
if (response.getConditions() == null || isRequestMatching(response.getConditions(), mockRequest, pathVariables)) {
return response;
}
}
return null;
}
private boolean isRequestMatching(List<MockCondition> conditions, MockRequest request, Map<String, String> pathVariables) {
if (conditions == null || conditions.size() == 0) {
return true;
}
for (MockCondition condition : conditions) {
if (condition.getType().equalsIgnoreCase("query")) {
if(!condition.getValue().equals(request.getParam(condition.getKey()))){
return false;
}
} else if (condition.getType().equalsIgnoreCase("header")) {
if (!condition.getValue().equals(request.getHeader(condition.getKey()))){
return false;
}
} else if (condition.getType().equalsIgnoreCase("path")) {
if (!condition.getValue().equals(pathVariables.get(condition.getKey()))){
return false;
}
} else if (condition.getType().equalsIgnoreCase("jsonpath")) {
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(request.getBody());
boolean isMatch = JsonPath.parse(jsonNode).read(condition.getKey()+ '=' + condition.getValue());
if (!isMatch) {
return false;
}
} catch (JsonProcessingException e) {
return false;
}
}
}
return true;
}
}
@@ -0,0 +1,111 @@
package com.eactive.httpmockserver.api.controller;
import com.eactive.httpmockserver.api.dto.MockResponseDTO;
import com.eactive.httpmockserver.api.dto.MockRouteDTO;
import com.eactive.httpmockserver.api.dto.MockRouteSearch;
import com.eactive.httpmockserver.api.entity.MockRoute;
import com.eactive.httpmockserver.api.mapper.MockRouteMapper;
import com.eactive.httpmockserver.api.service.MockRouteService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/mgmt/routes")
public class MockRouteMgmtController {
@Autowired
private MockRouteService mockRouteService;
@Autowired
private Validator validator;
@Autowired
private MockRouteMapper mockRouteMapper;
public static final String MOCK_ROUTE_EDIT = "page/routes/mockRouteEdit";
public static final String MOCK_ROUTE_LIST_VIEW = "redirect:/mgmt/routes/list_view.do";
@GetMapping("/list_view.do")
public String listView(@ModelAttribute("mockRouteSearch") MockRouteSearch mockRouteSearch, ModelMap model, Pageable pageable) {
Page<MockRoute> page = mockRouteService.findAll(mockRouteSearch.buildSpecification(), pageable);
model.addAttribute("page", page);
model.addAttribute("pageable", pageable);
model.addAttribute("modelSearch", mockRouteSearch);
return "page/routes/mockRouteList";
}
@GetMapping("/create_view.do")
public String createView(ModelMap model) {
MockRouteDTO defaultRoute = new MockRouteDTO();
defaultRoute.getResponses().add(new MockResponseDTO());
model.addAttribute("mockRoute", defaultRoute);
return MOCK_ROUTE_EDIT;
}
@GetMapping("/update_view.do")
public String updateView(ModelMap model, @RequestParam("id") Long id) {
MockRoute found = mockRouteService.findById(id);
model.addAttribute("mockRoute", found);
return MOCK_ROUTE_EDIT;
}
@PostMapping("/register.do")
public String register(@ModelAttribute("mockRoute") MockRouteDTO dto, BindingResult bindingResult, ModelMap model) {
if (dto == null) {
return "redirect:/mgmt/routes/create_view.do";
}
validator.validate(dto, bindingResult);
if (bindingResult.hasErrors()) {
model.addAttribute("mockRoute", dto);
return MOCK_ROUTE_EDIT;
}
MockRoute mockRoute = mockRouteMapper.map(dto);
mockRouteService.create(mockRoute);
return MOCK_ROUTE_LIST_VIEW;
}
@PostMapping("/update.do")
public String update(@RequestParam("id") String id,
@ModelAttribute("mockRoute") MockRouteDTO dto,
BindingResult bindingResult, ModelMap model) {
if (StringUtils.isEmpty(id)) {
return MOCK_ROUTE_LIST_VIEW;
}
validator.validate(dto, bindingResult);
if (bindingResult.hasErrors()) {
model.addAttribute("mockRoute", dto);
return MOCK_ROUTE_EDIT;
}
MockRoute mockRoute = mockRouteMapper.map(dto);
mockRouteService.update(Long.parseLong(id), mockRoute);
return MOCK_ROUTE_LIST_VIEW;
}
@PostMapping("/delete.do")
public String delete(@ModelAttribute MockRouteSearch modelSearch) {
modelSearch.getCheckedIdForDel().forEach(id -> {
mockRouteService.deleteById(Long.parseLong(id));
});
return MOCK_ROUTE_LIST_VIEW;
}
}
@@ -1,34 +0,0 @@
package com.eactive.httpmockserver.api.dao;
import com.eactive.httpmockserver.api.entity.ApiInfo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ApiDao extends JpaRepository<ApiInfo, Long> {
ApiInfo findByUrlAndServiceValue(String url, String serviceValue);
@Query(value = "SELECT ai FROM ApiInfo ai WHERE (:apiGroupName is null or ai.apiGroupName = :apiGroupName)"
+ "AND ((:searchStr1 is null or ai.apiGroupName LIKE %:searchStr1%)"
+ "OR (:searchStr2 is null or ai.apiName LIKE %:searchStr2%)"
+ "OR (:searchStr3 is null or ai.serviceValue LIKE :searchStr3%))")
Page<ApiInfo> findApisByParameters(@Param("apiGroupName") String apiGroupName,
@Param("searchStr1") String searchStr1, @Param("searchStr2") String searchStr2,
@Param("searchStr3") String searchStr3, Pageable pageable);
@Query(value = "SELECT COUNT(*) FROM ApiInfo ai WHERE (:apiGroupName is null or ai.apiGroupName = :apiGroupName)"
+ "AND ((:searchStr1 is null or ai.apiGroupName LIKE %:searchStr1%)"
+ "OR (:searchStr2 is null or ai.apiName LIKE %:searchStr2%)"
+ "OR (:searchStr3 is null or ai.serviceValue LIKE :searchStr3%))")
long countApisByParameters(@Param("apiGroupName") String apiGroupName, @Param("searchStr1") String searchStr1,
@Param("searchStr2") String searchStr2, @Param("searchStr3") String searchStr3);
@Query(value = "SELECT ai.apiGroupName FROM ApiInfo ai GROUP BY ai.apiGroupName")
List<String> findAllApiGroupName();
}
@@ -1,10 +0,0 @@
package com.eactive.httpmockserver.api.dao;
import com.eactive.httpmockserver.api.entity.ApiServiceKey;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ApiServiceKeyDao extends JpaRepository<ApiServiceKey, Long> {
ApiServiceKey findByUrl(String url);
}
@@ -1,9 +0,0 @@
package com.eactive.httpmockserver.api.dao;
import com.eactive.httpmockserver.api.entity.HttpRequestInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface HttpRequestInfoDao extends JpaRepository<HttpRequestInfo, Long> {
}
@@ -0,0 +1,33 @@
package com.eactive.httpmockserver.api.dto;
public class MockConditionDTO {
private String type;
private String key;
private String value;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@@ -0,0 +1,23 @@
package com.eactive.httpmockserver.api.dto;
public class MockHeaderDTO {
private String key;
private String value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@@ -0,0 +1,100 @@
package com.eactive.httpmockserver.api.dto;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class MockRequest {
public static Map<String, String> parseQueryString(HttpServletRequest request) {
Map<String, String> queryParams = new HashMap<>();
String queryString = request.getQueryString();
if (queryString != null) {
String[] queryParamsArr = queryString.split("&");
for (String queryParam : queryParamsArr) {
String[] pair = queryParam.split("=");
String key = pair[0];
String value = "";
if (pair.length > 1) {
value = pair[1];
}
queryParams.put(key, value);
}
}
return queryParams;
}
public MockRequest(HttpServletRequest request) {
this.method = request.getMethod();
this.uri = request.getRequestURI();
this.headers = Collections.list(request.getHeaderNames()).stream()
.collect(Collectors.toMap(name -> name, request::getHeader));
this.params = parseQueryString(request);
try {
this.body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
} catch (IOException e) {
e.printStackTrace();
}
}
private String uri;
private String method;
private String body;
private Map<String, String> headers;
private Map<String, String> params;
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public String getHeader(String key) {
return this.headers.get(key);
}
public String getParam(String key) {
return this.params.get(key);
}
public Map<String, String> getParams() {
return params;
}
public void setParams(Map<String, String> params) {
this.params = params;
}
}
@@ -0,0 +1,60 @@
package com.eactive.httpmockserver.api.dto;
import javax.validation.constraints.Min;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class MockResponseDTO {
@Min(100)
private int statusCode = 100;
private List<MockHeaderDTO> headers = new ArrayList<>();
private String body;
private long delay = 0; //millisecond
private List<MockConditionDTO> conditions;
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public List<MockHeaderDTO> getHeaders() {
return headers;
}
public void setHeaders(List<MockHeaderDTO> headers) {
this.headers = headers;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public long getDelay() {
return delay;
}
public void setDelay(long delay) {
this.delay = delay;
}
public List<MockConditionDTO> getConditions() {
return conditions;
}
public void setConditions(List<MockConditionDTO> conditions) {
this.conditions = conditions;
}
}
@@ -0,0 +1,73 @@
package com.eactive.httpmockserver.api.dto;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
public class MockRouteDTO {
private Long id;
@NotEmpty
private String method;
@NotEmpty
private String pathPattern;
@NotEmpty
private String name;
private String description;
@Size(min = 1, message = "Response must have at least one item")
private List<MockResponseDTO> responses = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getPathPattern() {
return pathPattern;
}
public void setPathPattern(String pathPattern) {
this.pathPattern = pathPattern;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<MockResponseDTO> getResponses() {
return responses;
}
public void setResponses(List<MockResponseDTO> responses) {
this.responses = responses;
}
}
@@ -0,0 +1,40 @@
package com.eactive.httpmockserver.api.dto;
import com.eactive.httpmockserver.api.entity.MockRoute;
import com.eactive.httpmockserver.common.search.BaseSearch;
import com.eactive.httpmockserver.common.search.ColumnSearchModel;
import com.eactive.httpmockserver.common.search.SearchCondition;
import com.eactive.httpmockserver.common.search.SearchModel;
import java.util.ArrayList;
import java.util.List;
public class MockRouteSearch implements BaseSearch<MockRoute> {
private String name;
private List<String> checkedIdForDel;
@Override
public List<SearchModel> buildSearchCondition() {
List<SearchModel> models = new ArrayList<>();
models.add(new ColumnSearchModel("name", SearchCondition.LIKE, name));
return models;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getCheckedIdForDel() {
return checkedIdForDel;
}
public void setCheckedIdForDel(List<String> checkedIdForDel) {
this.checkedIdForDel = checkedIdForDel;
}
}
@@ -1,195 +0,0 @@
package com.eactive.httpmockserver.api.entity;
import javax.persistence.*;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;
import java.io.Serializable;
@SuppressWarnings("serial")
@Entity
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "url", "serviceValue" }) }, indexes = {
@Index(name = "idxApiInfo01", columnList = "apiGroupName") })
public class ApiInfo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Column(length = 100, nullable = false)
private String apiGroupName;
@NotBlank
@Column(length = 100, nullable = false)
private String apiName;
@NotBlank
@Column(length = 200, nullable = false)
private String url;
@Column(length = 100)
private String serviceValue;
@Column(length = 10)
private String method;
@Column(length = 500)
private String scriptName;
@Column(length = 50)
private String responseContentType;
@Column(length = 5000)
private String responseHeaders;
@Digits(fraction = 0, integer = 3)
private Integer responseStatusCode;
@Positive
private Integer sleepSeconds;
@Column(length = 50)
private String syntaxResponseBody1;
@Column
@Lob
private String responseBody1;
@Column(length = 50)
private String syntaxResponseBody2;
@Column
@Lob
private String responseBody2;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getApiGroupName() {
return apiGroupName;
}
public void setApiGroupName(String apiGroupName) {
this.apiGroupName = apiGroupName;
}
public String getApiName() {
return apiName;
}
public void setApiName(String apiName) {
this.apiName = apiName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getServiceValue() {
return serviceValue;
}
public void setServiceValue(String serviceValue) {
this.serviceValue = serviceValue;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getResponseContentType() {
return responseContentType;
}
public void setResponseContentType(String responseContentType) {
this.responseContentType = responseContentType;
}
public String getResponseHeaders() {
return responseHeaders;
}
public void setResponseHeaders(String responseHeaders) {
this.responseHeaders = responseHeaders;
}
public Integer getResponseStatusCode() {
return responseStatusCode;
}
public void setResponseStatusCode(Integer responseStatusCode) {
this.responseStatusCode = responseStatusCode;
}
public Integer getSleepSeconds() {
return sleepSeconds;
}
public void setSleepSeconds(Integer sleepSeconds) {
this.sleepSeconds = sleepSeconds;
}
public String getResponseBody1() {
return responseBody1;
}
public void setResponseBody1(String responseBody1) {
this.responseBody1 = responseBody1;
}
public String getResponseBody2() {
return responseBody2;
}
public void setResponseBody2(String responseBody2) {
this.responseBody2 = responseBody2;
}
public String getSyntaxResponseBody1() {
return syntaxResponseBody1;
}
public void setSyntaxResponseBody1(String syntaxResponseBody1) {
this.syntaxResponseBody1 = syntaxResponseBody1;
}
public String getSyntaxResponseBody2() {
return syntaxResponseBody2;
}
public void setSyntaxResponseBody2(String syntaxResponseBody2) {
this.syntaxResponseBody2 = syntaxResponseBody2;
}
public String getScriptName() {
return scriptName;
}
public void setScriptName(String scriptName) {
this.scriptName = scriptName;
}
@Override
public String toString() {
return "ApiInfo{" + "id=" + id + ", apiGroupName='" + apiGroupName + '\'' + ", apiName='" + apiName + '\''
+ ", url='" + url + '\'' + ", serviceValue='" + serviceValue + '\'' + ", method='" + method + '\''
+ ", responseContentType='" + responseContentType + '\'' + ", responseHeaders='" + responseHeaders
+ '\'' + ", responseStatusCode=" + responseStatusCode + ", sleepSeconds=" + sleepSeconds
+ ", syntaxResponseBody1='" + syntaxResponseBody1 + '\'' + ", responseBody1='" + responseBody1 + '\''
+ ", syntaxResponseBody2='" + syntaxResponseBody2 + '\'' + ", responseBody2='" + responseBody2 + '\''
+ '}';
}
}
@@ -1,64 +0,0 @@
package com.eactive.httpmockserver.api.entity;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
@SuppressWarnings("serial")
@Entity
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "url" }) })
public class ApiServiceKey implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Column(length = 200, nullable = false)
private String url;
@NotBlank
@Column(length = 20, nullable = false)
private String serviceType;
@NotBlank
@Column(length = 50)
private String serviceKey;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public String getServiceKey() {
return serviceKey;
}
public void setServiceKey(String serviceKey) {
this.serviceKey = serviceKey;
}
@Override
public String toString() {
return "ApiServiceKey [id=" + id + ", url=" + url + ", serviceType=" + serviceType + ", serviceKey="
+ serviceKey + "]";
}
}
@@ -1,134 +0,0 @@
package com.eactive.httpmockserver.api.entity;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
@SuppressWarnings("serial")
@Entity
@Table(indexes = { @Index(name = "idxHttpRequestInfo01", columnList = "requestGroupName, requestName") })
public class HttpRequestInfo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Column(length = 100, nullable = false)
private String requestGroupName;
@NotBlank
@Column(length = 100, nullable = false)
private String requestName;
@NotBlank
@Column(length = 200, nullable = false)
private String url;
@Column(length = 5000)
private String queryParams;
@NotBlank
@Column(length = 10)
private String method;
@Column(length = 50)
private String requestContentType;
@Column(length = 20)
private String encode;
@Column(length = 5000)
private String requestHeaders;
@Column
@Lob
private String requestBody;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRequestGroupName() {
return requestGroupName;
}
public void setRequestGroupName(String requestGroupName) {
this.requestGroupName = requestGroupName;
}
public String getRequestName() {
return requestName;
}
public void setRequestName(String requestName) {
this.requestName = requestName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getQueryParams() {
return queryParams;
}
public void setQueryParams(String queryParams) {
this.queryParams = queryParams;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getRequestContentType() {
return requestContentType;
}
public void setRequestContentType(String requestContentType) {
this.requestContentType = requestContentType;
}
public String getEncode() {
return encode;
}
public void setEncode(String encode) {
this.encode = encode;
}
public String getRequestHeaders() {
return requestHeaders;
}
public void setRequestHeaders(String requestHeaders) {
this.requestHeaders = requestHeaders;
}
public String getRequestBody() {
return requestBody;
}
public void setRequestBody(String requestBody) {
this.requestBody = requestBody;
}
@Override
public String toString() {
return "HttpRequestInfo [id=" + id + ", requestGroupName=" + requestGroupName + ", requestName=" + requestName
+ ", url=" + url + ", queryParams=" + queryParams + ", method=" + method + ", requestContentType="
+ requestContentType + ", encode=" + encode + ", requestHeaders=" + requestHeaders + ", requestBody="
+ requestBody + "]";
}
}
@@ -0,0 +1,63 @@
package com.eactive.httpmockserver.api.entity;
import javax.persistence.*;
@Entity
@Table(name = "MOCK_RESPONSE_CONDITION")
public class MockCondition {
@ManyToOne
@JoinColumn(name = "MOCK_RESPONSE_ID", nullable = false)
private MockResponse mockResponse;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String type;
private String key;
private String value;
public MockResponse getMockResponse() {
return mockResponse;
}
public void setMockResponse(MockResponse mockResponse) {
this.mockResponse = mockResponse;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@@ -0,0 +1,92 @@
package com.eactive.httpmockserver.api.entity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Entity
@Table(name = "MOCK_RESPONSE")
public class MockResponse {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private int statusCode = 200;
@ElementCollection
@CollectionTable(name = "MOCK_RESPONSE_HEADERS", joinColumns = @JoinColumn(name = "RESPONSE_ID"))
@MapKeyColumn(name = "HEADER_KEY")
@Column(name = "HEADER_VALUE")
private Map<String, String> headers = new HashMap<>();
@Lob
private String body;
private long delay = 0; //millisecond
@ManyToOne
@JoinColumn(name = "ROUTE_ID", nullable = false)
private MockRoute route;
@OneToMany(mappedBy = "mockResponse", cascade = CascadeType.ALL, orphanRemoval = true)
private List<MockCondition> conditions = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public long getDelay() {
return delay;
}
public void setDelay(long delay) {
this.delay = delay;
}
public MockRoute getRoute() {
return route;
}
public void setRoute(MockRoute route) {
this.route = route;
}
public List<MockCondition> getConditions() {
return conditions;
}
public void setConditions(List<MockCondition> conditions) {
this.conditions = conditions;
}
}
@@ -0,0 +1,80 @@
package com.eactive.httpmockserver.api.entity;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "MOCK_ROUTE")
public class MockRoute {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String method;
private String pathPattern;
private String name;
private String description;
@OneToMany(mappedBy = "route", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private List<MockResponse> responses = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getPathPattern() {
return pathPattern;
}
public void setPathPattern(String pathPattern) {
this.pathPattern = pathPattern;
}
public List<MockResponse> getResponses() {
return responses;
}
public void setResponses(List<MockResponse> responses) {
this.responses = responses;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void updateFields(MockRoute update) {
}
}
@@ -0,0 +1,59 @@
package com.eactive.httpmockserver.api.mapper;
import com.eactive.httpmockserver.api.dto.MockHeaderDTO;
import com.eactive.httpmockserver.api.dto.MockResponseDTO;
import com.eactive.httpmockserver.api.dto.MockRouteDTO;
import com.eactive.httpmockserver.api.entity.MockResponse;
import com.eactive.httpmockserver.api.entity.MockRoute;
import com.eactive.httpmockserver.common.mapper.CommonMapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.mapstruct.ReportingPolicy;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Mapper(componentModel = "spring",
uses = {CommonMapper.class},
unmappedTargetPolicy = ReportingPolicy.IGNORE)
@Component
public abstract class MockRouteMapper {
public abstract MockRoute map(MockRouteDTO dto);
public abstract MockRouteDTO map(MockRoute entity);
@Mapping(target = "headers", source = "headers", qualifiedByName = "mapHeadersToMap")
public abstract MockResponse map(MockResponseDTO dto);
@Mapping(target = "headers", source = "headers", qualifiedByName = "mapHeadersToList")
public abstract MockResponseDTO map(MockResponse entity);
@Named("mapHeadersToList")
public List<MockHeaderDTO> mapHeadersToList(Map<String, String> headers) {
List<MockHeaderDTO> list = new ArrayList<>();
if (headers != null) {
headers.forEach((key, value) -> {
MockHeaderDTO header = new MockHeaderDTO();
header.setKey(key);
header.setValue(value);
list.add(header);
});
}
return list;
}
@Named("mapHeadersToMap")
public Map<String, String> mapHeadersToMap(List<MockHeaderDTO> headers) {
Map<String, String> map = new HashMap<>();
if (headers != null) {
headers.forEach(header -> {
map.put(header.getKey(), header.getValue());
});
}
return map;
}
}
@@ -0,0 +1,8 @@
package com.eactive.httpmockserver.api.repository;
import com.eactive.httpmockserver.api.entity.MockRoute;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface MockRouteRepository extends JpaRepository<MockRoute, Long>, JpaSpecificationExecutor<MockRoute> {
}
@@ -1,32 +0,0 @@
package com.eactive.httpmockserver.api.service;
import com.eactive.httpmockserver.api.entity.ApiInfo;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Optional;
public interface ApiService {
public Optional<ApiInfo> findById(Long id);
public ApiInfo save(ApiInfo apiInfo);
public List<ApiInfo> findAllApis(Pageable pageable);
public List<ApiInfo> findApis(Example<ApiInfo> example, Pageable pageable);
public List<ApiInfo> findApis(String apiGroupName, String searchStr, Pageable pageable);
public long countApis(String apiGroupName, String searchStr);
public ApiInfo update(ApiInfo apiInfo);
public ApiInfo findByUrlAndServiceValue(String url, String serviceValue);
public void delete(Long id);
public long getRecordsCount(Example<ApiInfo> example);
public List<String> findAllApiGroupName();
}
@@ -1,26 +0,0 @@
package com.eactive.httpmockserver.api.service;
import com.eactive.httpmockserver.api.entity.ApiServiceKey;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Optional;
public interface ApiServiceKeyService {
public ApiServiceKey save(ApiServiceKey apiServiceKey);
public ApiServiceKey update(ApiServiceKey apiServiceKey);
public List<ApiServiceKey> findAllApiServiceKeys(Pageable pageable);
public ApiServiceKey findByUrl(String url);
public void delete(Long id);
public Optional<ApiServiceKey> findById(Long id);
public List<ApiServiceKey> findApiKeys(Example<ApiServiceKey> example, Pageable pageable);
public long getRecordsCount(Example<ApiServiceKey> example);
}
@@ -1,24 +0,0 @@
package com.eactive.httpmockserver.api.service;
import com.eactive.httpmockserver.api.entity.HttpRequestInfo;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Optional;
public interface HttpRequestInfoService {
public Optional<HttpRequestInfo> findById(Long id);
public HttpRequestInfo save(HttpRequestInfo httpRequestInfo);
public List<HttpRequestInfo> findAllHttpRequestInfos(Pageable pageable);
public List<HttpRequestInfo> findHttpRequestInfos(Example<HttpRequestInfo> example, Pageable pageable);
public HttpRequestInfo update(HttpRequestInfo httpRequestInfo);
public void delete(Long id);
public long getRecordsCount(Example<HttpRequestInfo> example);
}
@@ -0,0 +1,70 @@
package com.eactive.httpmockserver.api.service;
import com.eactive.httpmockserver.api.entity.MockCondition;
import com.eactive.httpmockserver.api.entity.MockResponse;
import com.eactive.httpmockserver.api.entity.MockRoute;
import com.eactive.httpmockserver.api.repository.MockRouteRepository;
import com.eactive.httpmockserver.common.exception.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
@Service
public class MockRouteService {
private static final String NOT_FOUND_MESSAGE = "Route Not Found";
@Autowired
MockRouteRepository mockRouteRepository;
public Page<MockRoute> findAll(Specification<MockRoute> mockRouteSpecification, Pageable pageable) {
return mockRouteRepository.findAll(mockRouteSpecification, pageable);
}
public MockRoute findById(Long id) {
return mockRouteRepository.findById(id).orElseThrow(() -> new NotFoundException(NOT_FOUND_MESSAGE));
}
public void create(MockRoute mockRoute) {
for (MockResponse response : mockRoute.getResponses()) {
response.setRoute(mockRoute);
if (response.getConditions() != null) {
for (MockCondition condition : response.getConditions()) {
condition.setMockResponse(response);
}
}
}
mockRouteRepository.save(mockRoute);
}
public void deleteById(long id) {
mockRouteRepository.deleteById(id);
}
public void update(Long id, MockRoute updated) {
MockRoute route = mockRouteRepository.findById(id).orElseThrow(() -> new NotFoundException(NOT_FOUND_MESSAGE));
route.getResponses().clear();
route.setName(updated.getName());
route.setDescription(updated.getDescription());
route.setMethod(updated.getMethod());
route.setPathPattern(updated.getPathPattern());
route.getResponses().addAll(updated.getResponses());
for (MockResponse response : route.getResponses()) {
response.setRoute(route);
if (response.getConditions() != null) {
for (MockCondition condition : response.getConditions()) {
condition.setMockResponse(response);
}
}
}
mockRouteRepository.save(route);
}
}
@@ -1,108 +0,0 @@
package com.eactive.httpmockserver.api.service.impl;
import com.eactive.httpmockserver.api.dao.ApiDao;
import com.eactive.httpmockserver.api.entity.ApiInfo;
import com.eactive.httpmockserver.api.service.ApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class ApiServiceImpl implements ApiService {
@Autowired
private ApiDao apiDao;
@Override
public Optional<ApiInfo> findById(Long id) {
return apiDao.findById(id);
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public ApiInfo save(ApiInfo apiInfo) {
return apiDao.save(apiInfo);
}
public List<ApiInfo> findAllApis(Pageable pageable) {
Page<ApiInfo> pagedResult = apiDao.findAll(pageable);
if (pagedResult.hasContent()) {
return pagedResult.getContent();
} else {
return new ArrayList<>();
}
}
@Override
public List<ApiInfo> findApis(Example<ApiInfo> example, Pageable pageable) {
if (example == null) {
return findAllApis(pageable);
}
Page<ApiInfo> pagedResult = apiDao.findAll(example, pageable);
if (pagedResult.hasContent()) {
return pagedResult.getContent();
} else {
return new ArrayList<ApiInfo>();
}
}
@Override
public List<ApiInfo> findApis(String apiGroupName, String searchStr, Pageable pageable) {
Page<ApiInfo> pagedResult = apiDao.findApisByParameters(apiGroupName, searchStr, searchStr, searchStr,
pageable);
if (pagedResult.hasContent()) {
return pagedResult.getContent();
} else {
return new ArrayList<ApiInfo>();
}
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public ApiInfo update(ApiInfo apiInfo) {
return apiDao.save(apiInfo);
}
@Override
public ApiInfo findByUrlAndServiceValue(String url, String serviceValue) {
return apiDao.findByUrlAndServiceValue(url, serviceValue);
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void delete(Long id) {
apiDao.deleteById(id);
}
@Override
public long getRecordsCount(Example<ApiInfo> example) {
if (example == null) {
return apiDao.count();
} else {
return apiDao.count(example);
}
}
@Override
public long countApis(String apiGroupName, String searchStr) {
if (apiGroupName == null && searchStr == null) {
return apiDao.count();
} else {
return apiDao.countApisByParameters(apiGroupName, searchStr, searchStr, searchStr);
}
}
@Override
public List<String> findAllApiGroupName() {
return apiDao.findAllApiGroupName();
}
}
@@ -1,84 +0,0 @@
package com.eactive.httpmockserver.api.service.impl;
import com.eactive.httpmockserver.api.dao.ApiServiceKeyDao;
import com.eactive.httpmockserver.api.entity.ApiServiceKey;
import com.eactive.httpmockserver.api.service.ApiServiceKeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class ApiServiceKeyServiceImpl implements ApiServiceKeyService {
@Autowired
private ApiServiceKeyDao dao;
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public ApiServiceKey save(ApiServiceKey apiServiceKey) {
return dao.save(apiServiceKey);
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public ApiServiceKey update(ApiServiceKey apiServiceKey) {
return dao.save(apiServiceKey);
}
@Override
public List<ApiServiceKey> findAllApiServiceKeys(Pageable pageable) {
Page<ApiServiceKey> pagedResult = dao.findAll(pageable);
if (pagedResult.hasContent()) {
return pagedResult.getContent();
} else {
return new ArrayList<ApiServiceKey>();
}
}
@Override
public List<ApiServiceKey> findApiKeys(Example<ApiServiceKey> example, Pageable pageable) {
if (example == null) {
return findAllApiServiceKeys(pageable);
}
Page<ApiServiceKey> pagedResult = dao.findAll(example, pageable);
if (pagedResult.hasContent()) {
return pagedResult.getContent();
} else {
return new ArrayList<ApiServiceKey>();
}
}
@Override
public ApiServiceKey findByUrl(String url) {
return dao.findByUrl(url);
}
@Override
public void delete(Long id) {
dao.deleteById(id);
}
@Override
public Optional<ApiServiceKey> findById(Long id) {
return dao.findById(id);
}
@Override
public long getRecordsCount(Example<ApiServiceKey> example) {
if (example == null) {
return dao.count();
} else {
return dao.count(example);
}
}
}
@@ -1,79 +0,0 @@
package com.eactive.httpmockserver.api.service.impl;
import com.eactive.httpmockserver.api.dao.HttpRequestInfoDao;
import com.eactive.httpmockserver.api.entity.HttpRequestInfo;
import com.eactive.httpmockserver.api.service.HttpRequestInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class HttpRequestInfoServiceImpl implements HttpRequestInfoService {
@Autowired
private HttpRequestInfoDao httpRequestInfoDao;
@Override
public Optional<HttpRequestInfo> findById(Long id) {
return httpRequestInfoDao.findById(id);
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public HttpRequestInfo save(HttpRequestInfo httpRequestInfo) {
return httpRequestInfoDao.save(httpRequestInfo);
}
@Override
public List<HttpRequestInfo> findAllHttpRequestInfos(Pageable pageable) {
Page<HttpRequestInfo> pagedResult = httpRequestInfoDao.findAll(pageable);
if (pagedResult.hasContent()) {
return pagedResult.getContent();
} else {
return new ArrayList<HttpRequestInfo>();
}
}
@Override
public List<HttpRequestInfo> findHttpRequestInfos(Example<HttpRequestInfo> example, Pageable pageable) {
if (example == null) {
return findAllHttpRequestInfos(pageable);
}
Page<HttpRequestInfo> pagedResult = httpRequestInfoDao.findAll(example, pageable);
if (pagedResult.hasContent()) {
return pagedResult.getContent();
} else {
return new ArrayList<HttpRequestInfo>();
}
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public HttpRequestInfo update(HttpRequestInfo httpRequestInfo) {
return httpRequestInfoDao.save(httpRequestInfo);
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void delete(Long id) {
httpRequestInfoDao.deleteById(id);
}
@Override
public long getRecordsCount(Example<HttpRequestInfo> example) {
if (example == null) {
return httpRequestInfoDao.count();
} else {
return httpRequestInfoDao.count(example);
}
}
}
@@ -0,0 +1,30 @@
package com.eactive.httpmockserver.client.controller;
import com.eactive.httpmockserver.client.entity.Server;
import com.eactive.httpmockserver.client.repository.ServerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/mgmt")
public class ApiClientController {
@Autowired
ServerRepository serverRepository;
@GetMapping("/api_tester.do")
public String testView(ModelMap model){
List<Server> servers = serverRepository.findAll();
model.addAttribute("servers", servers);
return "page/apiTester";
}
}
@@ -0,0 +1,9 @@
package com.eactive.httpmockserver.client.dto;
public class ApiRequest {
private String uri;
private String method;
private String body;
}
@@ -0,0 +1,4 @@
package com.eactive.httpmockserver.client.dto;
public class ApiResponse {
}
@@ -0,0 +1,65 @@
package com.eactive.httpmockserver.client.entity;
import javax.persistence.*;
@Entity
@Table(name = "SERVER")
public class Server {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String name;
private String scheme;
private String hostname;
private int port;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScheme() {
return scheme;
}
public void setScheme(String scheme) {
this.scheme = scheme;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@Transient
public String getHostAddress() {
return scheme + "://" + hostname + ":" + port;
}
}
@@ -0,0 +1,9 @@
package com.eactive.httpmockserver.client.repository;
import com.eactive.httpmockserver.client.entity.Server;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface ServerRepository extends JpaRepository<Server, Long>, JpaSpecificationExecutor<Server> {
}
@@ -0,0 +1,83 @@
package com.eactive.httpmockserver.common.entity;
import org.hibernate.annotations.Type;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable {
/**
* 최초등록시점
*/
@Column(name = "REGISTERED_ON")
@Type(type = "org.hibernate.type.LocalDateTimeType")
@CreatedDate
private LocalDateTime createdAt;
/**
* 최초등록자ID
*/
@Column(name = "REGISTERED_BY")
@CreatedBy
private String createdBy;
/**
* 최종수정시점
*/
@Column(name = "LAST_MODIFIED_ON")
@Type(type = "org.hibernate.type.LocalDateTimeType")
@LastModifiedDate
private LocalDateTime updatedAt;
/**
* 최종수정자ID
*/
@Column(name = "LAST_MODIFIED_BY")
@LastModifiedBy
private String updatedBy;
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
@@ -0,0 +1,12 @@
package com.eactive.httpmockserver.common.entity;
public enum EnabledStatus {
Y("사용"),
N("미사용");
private String description;
EnabledStatus(String description) {
this.description = description;
}
}
@@ -0,0 +1,7 @@
package com.eactive.httpmockserver.common.exception;
public class NotFoundException extends IllegalArgumentException {
public NotFoundException(String message) {
super(message);
}
}
@@ -0,0 +1,26 @@
package com.eactive.httpmockserver.common.exception;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
@Controller
public class PortalErrorController implements ErrorController {
@GetMapping("/error")
public String handleError(HttpServletRequest request, ModelMap model) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (status != null) {
model.addAttribute("status", status);
return "/error";
}
return "redirect:/";
}
}
@@ -0,0 +1,31 @@
package com.eactive.httpmockserver.common.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class PortalGlobalExceptionHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
@ExceptionHandler(value = NotFoundException.class)
public ModelAndView handleIllegalArgumentException(HttpServletRequest request, NotFoundException ex) {
log.error(ex.getMessage());
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("common/error/notFoundError");
modelAndView.addObject("exception", ex);
return modelAndView;
}
@ExceptionHandler(value = UserNotLoginException.class)
public ModelAndView handleIllegalArgumentException(HttpServletRequest request, UserNotLoginException ex) {
return new ModelAndView("redirect:/login");
}
}
@@ -0,0 +1,7 @@
package com.eactive.httpmockserver.common.exception;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
@@ -0,0 +1,8 @@
package com.eactive.httpmockserver.common.exception;
public class UserNotLoginException extends RuntimeException {
public UserNotLoginException() {
super("User not login");
}
}
@@ -0,0 +1,8 @@
package com.eactive.httpmockserver.common.exception;
public class UserPasswordResetException extends RuntimeException {
public UserPasswordResetException(String message) {
super(message);
}
}
@@ -0,0 +1,78 @@
package com.eactive.httpmockserver.common.interceptor;
import com.eactive.httpmockserver.common.util.SecurityUtil;
import com.eactive.httpmockserver.user.entity.AnonymousUser;
import com.eactive.httpmockserver.user.entity.User;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 인증여부 체크 인터셉터
*
* @author
* @version 1.0
*/
public class AuthenticInterceptor implements AsyncHandlerInterceptor {
/**
* 관리자 접근 권한 패턴 목록
*/
private List<String> adminAuthPatternList;
private static AntPathMatcher pathMatcher = new AntPathMatcher();
public List<String> getAdminAuthPatternList() {
return adminAuthPatternList;
}
public void setAdminAuthPatternList(List<String> adminAuthPatternList) {
this.adminAuthPatternList = adminAuthPatternList;
}
/**
* 인증된 사용자 여부로 인증 여부를 체크한다.
* 관리자 권한에 따라 접근 페이지 권한을 체크한다.
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//인증된사용자 여부
User currentUser = SecurityUtil.getCurrentUser();
if (currentUser == null || currentUser instanceof AnonymousUser) {
ModelAndView redirectLoginView = new ModelAndView("redirect:/login");
throw new ModelAndViewDefiningException(redirectLoginView);
}
boolean found = findPattern(request.getRequestURI());
if (found) {
if (currentUser.getUserSecurity() != null && "ROLE_ADMIN".equals(currentUser.getUserSecurity().getAuthorCode())) {
return true;
} else {
ModelAndView redirectLoginView = new ModelAndView("redirect:/");
throw new ModelAndViewDefiningException(redirectLoginView);
}
}
return true;
}
boolean findPattern(String path) {
for (String pattern : adminAuthPatternList) {
if (pathMatcher.match(pattern, path)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,44 @@
package com.eactive.httpmockserver.common.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Named;
import org.mapstruct.ReportingPolicy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@Mapper(componentModel = "spring",
unmappedTargetPolicy = ReportingPolicy.IGNORE)
public class CommonMapper {
public String map(boolean value) {
return value ? "Y" : "N";
}
public boolean map(String value) {
if (value == null) return false;
return value.equals("Y");
}
public String map(List<String> values) {
if (values == null) return "";
return String.join(",", values);
}
public List<String> toList(String value) {
if (StringUtils.hasLength(value)) return new ArrayList<>();
return Arrays.asList(value.split(","));
}
@Named("authorities")
public List<String> authorities(Collection<? extends GrantedAuthority> grantedAuthorities) {
return grantedAuthorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
}
}
@@ -0,0 +1,56 @@
package com.eactive.httpmockserver.common.message;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PortalReloadableResourceBundleMessageSource extends org.springframework.context.support.ReloadableResourceBundleMessageSource {
private static final String CLASSPATH_PREFIX = "classpath:";
private static final String PROPERTIES_EXTENSION = ".properties";
private final ResourcePatternResolver resourcePatternResolver;
public PortalReloadableResourceBundleMessageSource() {
this.resourcePatternResolver = new PathMatchingResourcePatternResolver();
}
public void setEgovBaseNames(String... basenames) {
List<String> resolvedBasenames = new ArrayList<>();
for (String basename : basenames) {
String trimmedBasename = StringUtils.trimToEmpty(basename);
if (trimmedBasename.startsWith(CLASSPATH_PREFIX)) {
resolvedBasenames.add(trimmedBasename);
} else if (StringUtils.isNotBlank(trimmedBasename)) {
try {
Resource[] resources = resourcePatternResolver.getResources(trimmedBasename);
for (Resource resource : resources) {
String uri = resource.getURI().toString();
if (!uri.contains(PROPERTIES_EXTENSION)) {
continue;
}
String baseName = processBasename(uri);
resolvedBasenames.add(baseName);
}
} catch (IOException e) {
logger.debug("No message source files found for basename " + trimmedBasename + ".");
}
}
}
setBasenames(resolvedBasenames.toArray(new String[0]));
}
private String processBasename(String uri) {
String baseName = StringUtils.substringBeforeLast(uri, PROPERTIES_EXTENSION);
String prefix = StringUtils.substringBeforeLast(baseName, "/");
String name = StringUtils.substringAfterLast(baseName, "/");
while (name.contains("_")) {
name = StringUtils.substringBeforeLast(name, "_");
}
return prefix + "/" + name;
}
}
@@ -0,0 +1,90 @@
package com.eactive.httpmockserver.common.search;
import org.springframework.data.jpa.domain.Specification;
import java.util.List;
/**
* Overview:
*
* BaseSearch 클래스는 Spring Data JPA 프레임워크를 사용하여 복잡한 검색 쿼리를 편리하게 작성할 수 있는 방법을 제공하는 추상 클래스입니다.
* 이 클래스를 사용하면 SearchModel 객체 목록을 사용하여 검색 쿼리를 생성할 수 있으며, 이를 결합하여 보다 복잡하고 구체적인 검색 조건을 만들 수 있습니다.
*
* How to Use:
*
* BaseSearch 클래스를 사용하려면 검색하려는 엔티티에 특정한 BaseSearch의 하위 클래스를 만들어야 합니다.
* 예를 들어 User 개체를 검색하려는 경우 BaseSearch<User>를 확장하는 UserSearch라는 클래스를 만들 수 있습니다.
*
* 하위 클래스에서 buildSearchCondition() 메서드를 구현해야 합니다.
* 이 메서드는 사용하려는 검색 조건을 나타내는 SearchModel 객체 목록을 반환해야 합니다.
*
* 예를 들어, 다음은 이름에 특정 문자열이 포함된 사용자를 검색하기 위해 buildSearchCondition() 메서드를 구현하는 방법입니다:
*
* public List<SearchModel> buildSearchCondition() {
* List<SearchModel> models = new ArrayList<>();
* models.add(new ColumnSearchModel("firstName", SearchCondition.LIKE, "John"));
* models.add(new ColumnSearchModel("lastName", SearchCondition.LIKE, "Doe"));
* return models;
* }
*
* 이 예제에서는 이름과 성에 각각 문자열 "John"과 "Doe"가 포함된 사용자를 검색하는 두 개의 ColumnSearchModel 객체를 만들고 있습니다.
*
* 검색 쿼리를 빌드하려면 UserSearch 클래스의 인스턴스를 생성하고 그 인스턴스에서 buildSpecification() 메서드를 호출하면 됩니다.
* 이 메서드는 Spring 데이터 JPA를 사용하여 데이터베이스를 쿼리하는 데 사용할 수 있는 Specification 객체를 반환합니다.
*
* UserSearch search = new UserSearch();
* Specification<User> spec = search.buildSpecification();
* List<User> users = userRepository.findAll(spec);
*
* 이 예제에서는 UserSearch 인스턴스를 만들고 buildSpecification() 메서드를 호출하여 사양 객체를 빌드한 다음 이 사양 객체를 사용하여 데이터베이스에서 검색 조건과 일치하는 모든 사용자 객체를 쿼리합니다.
* 결과는 User 객체 목록으로 반환됩니다.
*
* 추가 활용 방법
*
* BaseSearch 클래스는 유연하고 확장 가능하도록 설계되어 필요에 따라 더 복잡한 검색 쿼리를 사용할 수 있습니다.
* getSpecification() 메서드를 구현하는 SearchModel의 새로운 서브클래스를 생성하여 검색 조건을 추가할 수 있습니다.
* 필요에 따라 추가 검색 조건을 포함하도록 SpecificationUtil 클래스를 수정할 수도 있습니다.
*
* 또한 BaseSearch 클래스를 확장하여 정렬 및 페이징과 같은 추가 기능을 제공할 수 있습니다.
* 하위 클래스에 메서드와 속성을 추가하여 애플리케이션의 특정 요구 사항을 충족하는 검색 쿼리를 만들 수 있습니다.
*
* ColumnSearchModel은 검색조건이 컬럼명과 비교 연산자, 값으로 구성된다. SearchCondition 참조
* SpecificationSearchModel은 검색조건이 Specification을 리턴하는 형태로 구성된다. 검색조건을 복잡하게 구성해야 할 때 사용한다.
*
* public static Specification current(String user, ApproverStatus approverStatus) {
* return (root, criteriaQuery, criteriaBuilder) -> {
* ListJoin join = root.joinList("approvers");
* return criteriaBuilder.and(
* criteriaBuilder.equal(join.get("user"), user),
* criteriaBuilder.equal(join.get("status"), approverStatus));
* };
* }
*/
public interface BaseSearch<T> {
List<SearchModel> buildSearchCondition();
default Specification<T> buildSpecification() {
List<SearchModel> models = buildSearchCondition();
Specification<T> specifications = null;
for (SearchModel model : models) {
Specification spec = getSpecification(model);
if (spec != null) {
if (specifications == null) {
specifications = Specification.where(spec);
} else {
specifications = specifications.and(spec);
}
}
}
return specifications;
}
default Specification<T> getSpecification(SearchModel model) {
return model.getSpecification();
}
}
@@ -0,0 +1,65 @@
package com.eactive.httpmockserver.common.search;
import com.eactive.httpmockserver.common.util.SpecificationUtil;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.ObjectUtils;
import java.util.Collection;
public class ColumnSearchModel implements SearchModel {
private String column;
private Object value; //값의 형태는 String, Collection, Object 등이 될 수 있다.
private SearchCondition condition;
public ColumnSearchModel(String column, SearchCondition condition, Object value) {
this.column = column;
this.condition = condition;
this.value = value;
}
public String getColumn() {
return column;
}
public void setColumn(String column) {
this.column = column;
}
public SearchCondition getCondition() {
return condition;
}
public void setCondition(SearchCondition condition) {
this.condition = condition;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Specification getSpecification() {
if (condition == null) return null;
if (column == null) return null;
if (ObjectUtils.isEmpty(value)) return null;
if (condition.equals(SearchCondition.EQUAL)) {
return SpecificationUtil.equalTo(column, value);
} else if (condition.equals(SearchCondition.LIKE)) {
return SpecificationUtil.like(column, value.toString());
} else if (condition.equals(SearchCondition.IN)) {
return SpecificationUtil.in(column, (Collection) value);
} else if (condition.equals(SearchCondition.NOT_EQUAL)) {
return SpecificationUtil.notEqualTo(column, value);
}
return null;
}
}
@@ -0,0 +1,8 @@
package com.eactive.httpmockserver.common.search;
public enum SearchCondition {
EQUAL,
LIKE,
IN,
NOT_EQUAL
}
@@ -0,0 +1,10 @@
package com.eactive.httpmockserver.common.search;
import org.springframework.data.jpa.domain.Specification;
import java.io.Serializable;
public interface SearchModel extends Serializable {
Specification getSpecification();
}
@@ -0,0 +1,17 @@
package com.eactive.httpmockserver.common.search;
import org.springframework.data.jpa.domain.Specification;
public class SpecificationSearchModel implements SearchModel {
private final Specification specification;
public SpecificationSearchModel(Specification specification) {
this.specification = specification;
}
public Specification getSpecification() {
return specification;
}
}
@@ -0,0 +1,9 @@
package com.eactive.httpmockserver.common.security;
import java.lang.annotation.*;
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CurrentUser {
}
@@ -0,0 +1,48 @@
package com.eactive.httpmockserver.common.security;
import com.eactive.httpmockserver.user.entity.User;
import com.eactive.httpmockserver.user.service.UserService;
import com.eactive.httpmockserver.common.exception.NotFoundException;
import com.eactive.httpmockserver.common.exception.UserNotLoginException;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import java.lang.reflect.InvocationTargetException;
public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {
@Autowired
private UserService userService;
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterAnnotation(CurrentUser.class) != null &&
parameter.getParameterType().equals(User.class);
}
@Override
@Transactional
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
Authentication authentication = (Authentication) webRequest.getUserPrincipal();
if (authentication == null || !authentication.isAuthenticated()) {
throw new UserNotLoginException();
}
User user = null;
try {
user = userService.findByEsntlId((String) PropertyUtils.getProperty(authentication.getPrincipal(), "esntlId"));
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new NotFoundException("User not found");
}
if (user == null) throw new UserNotLoginException();
return user;
}
}
@@ -0,0 +1,36 @@
package com.eactive.httpmockserver.common.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* ApplicationContextUtil 클래스
*
* @author
* @version 1.0
*/
@Component("ApplicationContextUtil")
public class ApplicationContextUtil implements ApplicationContextAware {
public static ApplicationContext getContext() {
return context;
}
public static void setContext(ApplicationContext context) {
ApplicationContextUtil.context = context;
}
private static ApplicationContext context;
@SuppressWarnings("static-access")
public void setApplicationContext(ApplicationContext context)
throws BeansException {
this.context = context;
}
}
@@ -0,0 +1,62 @@
package com.eactive.httpmockserver.common.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @author
* @version 1.0
* @Class Name : EncryptionUtil.java
* @Description : 문자열 암호화 처리하는 유틸리티 클래스
* @since 2009.08.26
*/
@Component
public class EncryptionUtil {
private static final String SHA_256 = "SHA-256";
MessageDigest md;
public EncryptionUtil() throws NoSuchAlgorithmException {
md = MessageDigest.getInstance(SHA_256);
}
public String generateNewPassword() {
// 2. 임시 비밀번호를 생성한다.(영+영+숫+영+영+숫+영+영=8자리)
StringBuilder newpassword = new StringBuilder();
for (int i = 1; i <= 8; i++) {
// 영자
if (i % 3 != 0) {
newpassword.append(RandomUtil.getRandomStr('a', 'z'));
// 숫자
} else {
newpassword.append(RandomUtil.getRandomNum(0, 9));
}
}
return newpassword.toString();
}
/**
* 비밀번호를 암호화하는 기능(복호화가 되면 안되므로 SHA-256 인코딩 방식 적용)
*
* @param password 암호화될 패스워드
* @param id salt로 사용될 사용자 ID 지정
* @return 암호화된 패스워드
*/
public synchronized String encryptPassword(String password, String id) {
if (StringUtils.isEmpty(password)) return "";
if (StringUtils.isEmpty(id)) return "";
byte[] hashValue = null; // 해쉬값
md.reset();
md.update(id.getBytes());
hashValue = md.digest(password.getBytes());
return new String(Base64.encodeBase64(hashValue));
}
}
@@ -0,0 +1,58 @@
package com.eactive.httpmockserver.common.util;
import java.security.SecureRandom;
public class RandomUtil {
private RandomUtil() {
throw new IllegalStateException("Utility class");
}
public static int getRandomNum(int startNum, int endNum) {
int randomNum = 0;
// 랜덤 객체 생성
SecureRandom rnd = new SecureRandom();
do {
// 종료숫자내에서 랜덤 숫자를 발생시킨다.
randomNum = rnd.nextInt(endNum + 1);
} while (randomNum < startNum); // 랜덤 숫자가 시작숫자보다 작을경우 다시 랜덤숫자를 발생시킨다.
return randomNum;
}
/**
* 문자열 A에서 Z사이의 랜덤 문자열을 구하는 기능을 제공 시작문자열과 종료문자열 사이의 랜덤 문자열을 구하는 기능
*
* @param startChr - 첫 문자
* @param endChr - 마지막문자
* @return 랜덤문자
* @see
*/
public static String getRandomStr(char startChr, char endChr) {
int randomInt;
String randomStr = null;
// 시작문자열이 종료문자열보가 클경우
if (startChr > endChr) {
throw new IllegalArgumentException("Start String: " + startChr + " End String: " + endChr);
}
// 랜덤 객체 생성
SecureRandom rnd = new SecureRandom();
do {
// 시작문자 및 종료문자 중에서 랜덤 숫자를 발생시킨다.
randomInt = rnd.nextInt(endChr + 1);
} while (randomInt < startChr); // 입력받은 문자 'A'(65)보다 작으면 다시 랜덤 숫자 발생.
// 랜덤 숫자를 문자로 변환 후 스트링으로 다시 변환
randomStr = (char) randomInt + "";
// 랜덤문자열를 리턴
return randomStr;
}
}
@@ -0,0 +1,33 @@
package com.eactive.httpmockserver.common.util;
import com.eactive.httpmockserver.user.entity.AnonymousUser;
import com.eactive.httpmockserver.user.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
public class SecurityUtil {
private SecurityUtil() {
// Utility class
throw new IllegalStateException("Utility class");
}
public static final String ANONYMOUS_USER = "anonymousUser";
public static User getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && !authentication.getPrincipal().equals(ANONYMOUS_USER)) {
return ((User) authentication.getDetails());
}
return new AnonymousUser();
}
public static String getCurrentUserEsntlId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && !authentication.getPrincipal().equals(ANONYMOUS_USER)) {
return ((User) authentication.getDetails()).getEsntlId();
}
return "ANONYMOUS";
}
}
@@ -0,0 +1,101 @@
package com.eactive.httpmockserver.common.util;
import org.hibernate.query.criteria.internal.path.PluralAttributePath;
import org.springframework.data.jpa.domain.Specification;
import javax.persistence.criteria.*;
import java.util.Collection;
public class SpecificationUtil {
private SpecificationUtil() {
throw new IllegalStateException("Utility class");
}
public static <T> Path getPath(Root<T> root, String column) {
Path p = root;
if (column.contains(".")) {
String[] columns = column.split("\\.");
for (String s : columns) {
Path<Object> c = p.get(s);
if (c instanceof PluralAttributePath) {
p = root.joinList(s);
} else {
p = p.get(s);
}
}
return p;
} else {
return root.get(column);
}
}
public static <T> Specification<T> notNull(String column) {
return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.isNotNull(root.get(column));
}
public static <T> Specification<T> isNull(String column) {
return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.isNull(root.get(column));
}
public static <T> Specification<T> equalTo(String column, Object value) {
return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.equal(getPath(root, column), value);
}
public static <T> Specification<T> equalToJoin(String table, String column, Object value) {
return (root, criteriaQuery, criteriaBuilder) -> {
Join join = root.join(table, JoinType.INNER);
return criteriaBuilder.equal(join.get(column), value);
};
}
public static <T> Specification<T> equalToLeftJoin(String table, String column, Object value) {
return (root, criteriaQuery, criteriaBuilder) -> {
Join join = root.join(table, JoinType.LEFT);
return criteriaBuilder.equal(join.get(column), value);
};
}
public static <T> Specification<T> notEqualTo(String column, Object value) {
return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.notEqual(getPath(root, column), value);
}
public static <T> Specification<T> like(String column, String value) {
return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.like(criteriaBuilder.lower(getPath(root, column)), "%" + value.toLowerCase() + "%");
}
public static <T> Specification<T> in(String column, Collection<Object> value) {
return (root, criteriaQuery, criteriaBuilder) -> {
CriteriaBuilder.In<Object> in = criteriaBuilder.in(root.get(column));
value.forEach(in::value);
return in;
};
}
public static <T> Specification<T> greater(String column, Object value) {
return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.greaterThan(getPath(root, column), (Comparable) value);
}
public static <T> Specification<T> greaterAndEqual(String column, Object value) {
return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.greaterThanOrEqualTo(getPath(root, column), (Comparable) value);
}
public static <T> Specification<T> less(String column, Object value) {
return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.lessThan(getPath(root, column), (Comparable) value);
}
public static <T> Specification<T> lessAndEqual(String column, Object value) {
return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.lessThanOrEqualTo(getPath(root, column), (Comparable) value);
}
}
@@ -0,0 +1,21 @@
package com.eactive.httpmockserver.common.validator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Constraint(validatedBy = PasswordMatchValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PasswordMatch {
String message() default "{password.not.match}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String input();
String confirm();
}
@@ -0,0 +1,51 @@
package com.eactive.httpmockserver.common.validator;
import com.eactive.httpmockserver.common.util.ApplicationContextUtil;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;
public class PasswordMatchValidator implements ConstraintValidator<PasswordMatch, Object> {
private String field1;
private String field2;
@Override
public void initialize(PasswordMatch constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
this.field1 = constraintAnnotation.input();
this.field2 = constraintAnnotation.confirm();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
Object passwordValue = null;
Object password2Value = null;
try {
passwordValue = PropertyUtils.getProperty(value, field1);
password2Value = PropertyUtils.getProperty(value, field2);
} catch (Exception e) {
return false;
}
if (Objects.isNull(passwordValue) || Objects.isNull(password2Value)) {
return false;
}
MessageSource messageSource = (MessageSource) ApplicationContextUtil.getContext().getBean("messageSource");
String message = messageSource.getMessage("password.not.match", null, LocaleContextHolder.getLocale());
if (!passwordValue.equals(password2Value)) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message)
.addPropertyNode(field2)
.addConstraintViolation();
return false;
}
return true;
}
}
@@ -0,0 +1,17 @@
package com.eactive.httpmockserver.common.validator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Constraint(validatedBy = UniqueUserIdValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UniqueId {
String message() default "아이디가 사용중입니다.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
@@ -0,0 +1,22 @@
package com.eactive.httpmockserver.common.validator;
import com.eactive.httpmockserver.user.service.UserService;
import com.eactive.httpmockserver.common.exception.UserNotFoundException;
import com.eactive.httpmockserver.common.util.ApplicationContextUtil;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class UniqueUserIdValidator implements ConstraintValidator<UniqueId, String> {
@Override
public boolean isValid(String id, ConstraintValidatorContext constraintValidatorContext) {
UserService userService = ApplicationContextUtil.getContext().getBean(UserService.class);
try {
userService.findByUserId(id);
return false;
} catch (UserNotFoundException e) {
return true;
}
}
}
@@ -0,0 +1,15 @@
package com.eactive.httpmockserver.config;
import com.eactive.httpmockserver.common.util.SecurityUtil;
import org.springframework.data.domain.AuditorAware;
import java.util.Optional;
public class AuditorAwareImpl implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.ofNullable(SecurityUtil.getCurrentUserEsntlId());
}
}
@@ -0,0 +1,49 @@
package com.eactive.httpmockserver.config;
import com.eactive.httpmockserver.user.entity.User;
import com.eactive.httpmockserver.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;
public class PortalAuthenticationManager implements AuthenticationManager {
@Autowired
private UserService userService;
@Override
@Transactional
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
String username = token.getName();
String password = token.getCredentials().toString();
UserDetails user = userService.loadUserByUsername(username);
if (!user.isEnabled()) {
throw new DisabledException("계정이 " + ((User) user).getStatus().getDescription() + "상태입니다. 관리자에게 문의하세요.");
}
if (!user.isAccountNonLocked()) {
throw new LockedException("계정이 잠겨있습니다. 관리자에게 문의하세요.");
}
if (user.getPassword().equals(password)) {
UsernamePasswordAuthenticationToken authorityToken = new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
authorityToken.setDetails(user);
SecurityContextHolder.getContext().setAuthentication(authorityToken);
((User) user).setLockCnt(0);
userService.updateUser((User) user);
return authorityToken;
}
throw new BadCredentialsException("아이디 또는 비밀번호가 일치하지 않습니다.");
}
}
@@ -0,0 +1,37 @@
package com.eactive.httpmockserver.config;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.envers.repository.support.EnversRevisionRepositoryFactoryBean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/**
* @author
* @version : 1.0
*
* <pre>
* << 개정이력(Modification Information) >>
*
* 수정일 수정자 수정내용
* ------------- ------------ ---------------------
*
* </pre>
* @ClassName : PortalConfigAppDatasource.java
* @Description : DataSource 설정
* @since :
*/
@Configuration
@EnableJpaRepositories(basePackages = "com.eactive", repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class)
@EntityScan(basePackages = "com.eactive")
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class PortalConfigAppDatasource {
@Bean
public AuditorAware<String> auditorProvider() {
return new AuditorAwareImpl();
}
}
@@ -0,0 +1,40 @@
package com.eactive.httpmockserver.config;
import com.eactive.httpmockserver.common.message.PortalReloadableResourceBundleMessageSource;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
/**
* @author
* @version : 1.0
* @ClassName : PortalConfigMessageSource.java
* @Description : Portal Message 설정
* @since : 2021. 7. 20
*/
@Configuration
public class PortalConfigMessageSource {
/**
* @return [Resource 설정] 메세지 Properties 경로 설정
*/
@Bean
public ReloadableResourceBundleMessageSource messageSource() {
PortalReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource = new PortalReloadableResourceBundleMessageSource();
reloadableResourceBundleMessageSource.setEgovBaseNames(
"classpath*:message/**/*",
"classpath:/org/egovframe/rte/fdl/idgnr/messages/idgnr",
"classpath:/org/egovframe/rte/fdl/property/messages/properties");
return reloadableResourceBundleMessageSource;
}
@Bean
public LocalValidatorFactoryBean validator(MessageSource messageSource) {
LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
factoryBean.setValidationMessageSource(messageSource);
return factoryBean;
}
}
@@ -0,0 +1,53 @@
package com.eactive.httpmockserver.config;
import com.navercorp.lucy.security.xss.servletfilter.XssEscapeServletFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class PortalConfigSecurity extends WebSecurityConfigurerAdapter {
// @Bean
// public FilterRegistrationBean<XssEscapeServletFilter> xssFilterRegistrationBean() {
// FilterRegistrationBean<XssEscapeServletFilter> registrationBean = new FilterRegistrationBean<>();
// XssEscapeServletFilter xssEscapeServletFilter = new XssEscapeServletFilter();
// registrationBean.setFilter(xssEscapeServletFilter);
// registrationBean.setOrder(Integer.MIN_VALUE + 1);
// registrationBean.addUrlPatterns("/*");
// return registrationBean;
// }
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.disable();
http.headers().frameOptions().disable();//spring security 와 h2-console 같이 사용.
http.authorizeRequests() // 권한요청 처리 설정 메서드
.antMatchers("/h2-console/**").permitAll() // 누구나 h2-console 접속 허용
.and()
.csrf()
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/mgmt/**", "POST"))
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
@Override
@Bean
public PortalAuthenticationManager authenticationManager() {
return new PortalAuthenticationManager();
}
}
@@ -24,4 +24,5 @@ public class ServletConfig {
connector.setPort(serverPortHttp);
return connector;
}
}
@@ -1,18 +1,78 @@
package com.eactive.httpmockserver.config;
import com.eactive.httpmockserver.common.interceptor.AuthenticInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.resource.PathResourceResolver;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//registry.addViewController("/").setViewName("forward:/manage/findAllApis");
registry.addViewController("/").setViewName("redirect:/manage/findAllApis");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
WebMvcConfigurer.super.addViewControllers(registry);
}
private List<String> listAdminAuthPattern() {
List<String> patterns = new ArrayList<>();
patterns.add("/mgmt/**/*.do");
return patterns;
}
@Bean
public AuthenticInterceptor authenticInterceptor() {
AuthenticInterceptor authenticInterceptor = new AuthenticInterceptor();
authenticInterceptor.setAdminAuthPatternList(listAdminAuthPattern());
return authenticInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authenticInterceptor())
.addPathPatterns(
"/",
"/mgmt/**/*.do")
.excludePathPatterns(
"/h2-console/**",
"/css/**",
"/html/**",
"/images/**",
"/img/**",
"/js/**",
"/login",
"/intro.do",
"/join.do",
"/user_register.do",
"/actionLogin.do",
"/check_id.do",
"/search_id.do",
"/admin_register_view.do",
"/admin_register.do",
"/request_register_auth.do",
"/reset_password.do",
"/forgot_password.do"
);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/css/", "classpath:/static/css/").setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS)).resourceChain(true).addResolver(new PathResourceResolver());
registry.addResourceHandler("/fonts/**").addResourceLocations("/fonts/", "classpath:/static/fonts/").setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS)).resourceChain(true).addResolver(new PathResourceResolver());
registry.addResourceHandler("/font/**").addResourceLocations("/font/", "classpath:/static/fonts/").setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS)).resourceChain(true).addResolver(new PathResourceResolver());
registry.addResourceHandler("/html/**").addResourceLocations("/html/", "classpath:/static/html/").setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS)).resourceChain(true).addResolver(new PathResourceResolver());
registry.addResourceHandler("/images/**").addResourceLocations("/images/", "classpath:/static/images/").setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS)).resourceChain(true).addResolver(new PathResourceResolver());
registry.addResourceHandler("/img/**").addResourceLocations("/img/", "classpath:/static/img/").setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS)).resourceChain(true).addResolver(new PathResourceResolver());
registry.addResourceHandler("/js/**").addResourceLocations("/js/", "classpath:/static/js/").setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS)).resourceChain(true).addResolver(new PathResourceResolver());
registry.addResourceHandler("/favicon.ico").addResourceLocations("/favicon.ico", "classpath:/static/favicon.ico").setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS)).resourceChain(true).addResolver(new PathResourceResolver());
}
}
@@ -0,0 +1,13 @@
package com.eactive.httpmockserver.home;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "index";
}
}
@@ -0,0 +1,110 @@
package com.eactive.httpmockserver.login.controller;
import com.eactive.httpmockserver.common.util.EncryptionUtil;
import com.eactive.httpmockserver.login.dto.LoginRequestDTO;
import com.eactive.httpmockserver.login.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
/**
* 일반 로그인을 처리하는 컨트롤러 클래스
*
* @author
* @version 1.0
*/
@Controller
public class LoginController {
public static final String LOGIN_MESSAGE = "loginMessage";
@Resource(name = "loginService")
private LoginService loginService;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private EncryptionUtil encryptionUtil;
/**
* 로그인 화면으로 들어간다
*
* @return 로그인 페이지
*/
@GetMapping("/login")
public String loginUsrView(HttpServletRequest request,
ModelMap model) {
String message = request.getParameter(LOGIN_MESSAGE);
if (message != null)
model.addAttribute(LOGIN_MESSAGE, message);
return "page/login";
}
@PostMapping(value = "/actionLogin.do")
public String actionLogin(@ModelAttribute("loginVO") LoginRequestDTO loginUser,
HttpSession session,
ModelMap model) {
try {
String encryptPassword = encryptionUtil.encryptPassword(loginUser.getPassword(), loginUser.getId());
Authentication authentication = new UsernamePasswordAuthenticationToken(loginUser.getId(), encryptPassword);
authenticationManager.authenticate(authentication);
return "redirect:/";
} catch (BadCredentialsException e) {
loginService.processIncorrectLogin(loginUser);
model.addAttribute(LOGIN_MESSAGE, e.getMessage());
} catch (Exception e) {
model.addAttribute(LOGIN_MESSAGE, e.getMessage());
}
return "redirect:/login";
}
/**
* 세션타임아웃 시간을 연장한다.
* Cookie에 egovLatestServerTime, egovExpireSessionTime 기록하도록 한다.
*
* @return result - String
*/
@GetMapping(value = "/refreshSessionTimeout.do")
public ModelAndView refreshSessionTimeout(@RequestParam Map<String, Object> commandMap) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("jsonView");
modelAndView.addObject("result", "ok");
return modelAndView;
}
@GetMapping("/actionLogout.do")
public String logout(HttpServletRequest request, HttpServletResponse response) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && !authentication.getPrincipal().equals("anonymousUser")) {
new SecurityContextLogoutHandler().logout(request, response, authentication);
}
return "redirect:/";
}
}
@@ -0,0 +1,24 @@
package com.eactive.httpmockserver.login.dto;
public class FindIdRequest {
private String name;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
@@ -0,0 +1,24 @@
package com.eactive.httpmockserver.login.dto;
public class LoginRequestDTO {
private String id;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@@ -0,0 +1,22 @@
package com.eactive.httpmockserver.login.service;
import com.eactive.httpmockserver.login.dto.LoginRequestDTO;
/**
* 로그인을 처리하는 비즈니스 인터페이스 클래스
*
* @author
* @version 1.0
*/
public interface LoginService {
/**
* 로그인인증제한을 처리한다.
*
* @param loginRequestDTO LoginRequestDTO
* @return String
* @throws Exception
*/
void processIncorrectLogin(LoginRequestDTO loginRequestDTO);
}
@@ -0,0 +1,42 @@
package com.eactive.httpmockserver.login.service.impl;
import com.eactive.httpmockserver.common.entity.EnabledStatus;
import com.eactive.httpmockserver.login.dto.LoginRequestDTO;
import com.eactive.httpmockserver.login.service.LoginService;
import com.eactive.httpmockserver.user.entity.User;
import com.eactive.httpmockserver.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* 로그인을 처리하는 비즈니스 구현 클래스
*
* @author
* @version 1.0
* @see
* @since 2009.03.06
*/
@Service("loginService")
@Transactional
public class LoginServiceImpl implements LoginService {
@Autowired
UserService userService;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void processIncorrectLogin(LoginRequestDTO loginRequestDTO) {
User user = userService.findByUserId(loginRequestDTO.getId());
user.setLockCnt(user.getLockCnt() + 1);
if (user.getLockCnt() >= 5) {
user.setLockAt(EnabledStatus.Y);
}
userService.updateUser(user);
}
}
@@ -1,13 +0,0 @@
package com.eactive.httpmockserver.script;
public interface Script {
/**
* Script Process Function
* @param requestMessage 수신 받은 요청 메시지
* @param responseMessage 정의된 응답 메시지
* @return 스크립트 수행 후 응답 할 메시지
* @throws Exception
*/
public String postProcess(String requestMessage, String responseMessage) throws Exception;
}
@@ -1,124 +0,0 @@
package com.eactive.httpmockserver.script;
import com.eactive.httpmockserver.script.entity.ScriptInfo;
import com.eactive.httpmockserver.script.service.ScriptInfoService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.mdkt.compiler.InMemoryJavaCompiler;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ScriptLoader{
String path = ScriptLoader.class.getProtectionDomain().getCodeSource().getLocation().getPath();
public static final String DYNAMIC_BASE_PACKAGE = "com.eactive.httpmockserver.script.dynamic";
public static final String DYNAMIC_BASE_PATH = DYNAMIC_BASE_PACKAGE.replaceAll("[.]","/");
public static final String JAR_PREFIX = SystemUtils.IS_OS_WINDOWS ? "jar:file:/" : "jar:file:";
public static final String CLASS_PATH_SEPARATOR = System.getProperty("path.separator");
private static final ScriptLoader instance = new ScriptLoader();
private Map<String, Class<Script>> loadedClass;
private String classPath = null;
/**
* BOOT 일 경우 JAR 내의 Class 목록이 BOOT-INF로 들어가서 컴파일시 참조가 안되는 문제가 있음
* 임시로 /tmp 폴더에 압축해제하여 해당 경로를 참조하게 하였으나 메모리 내에서 참조가능거나 jar파일을 직접 참조 할 수 있는 방안을 찾아볼 예정임
* Groovy 스크립트로 변경도 검토 중
*/
private ScriptLoader(){
this.loadedClass = new HashMap<>();
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
try {
String uri = url.toURI().toString();
System.out.println(uri);
if(StringUtils.contains(uri, "jar:file:" )) {
String jarPath = StringUtils.substringBetween(uri, JAR_PREFIX, ".jar!") + ".jar";
System.out.println("jarPath => " + jarPath);
if(StringUtils.contains(uri, "BOOT-INF" )) {
String memoryWorkingPath = "/tmp/httpmockworking";
File workingDir = new File(memoryWorkingPath);
workingDir.mkdirs();
java.util.jar.JarFile jar = new java.util.jar.JarFile(jarPath);
java.util.Enumeration enumEntries = jar.entries();
while (enumEntries.hasMoreElements()) {
java.util.jar.JarEntry file = (java.util.jar.JarEntry) enumEntries.nextElement();
java.io.File f = new java.io.File(memoryWorkingPath + "/" + file.getName());
if (file.isDirectory()) { // if its a directory, create it
f.mkdirs();
continue;
}
java.io.InputStream is = jar.getInputStream(file); // get the input stream
BufferedInputStream bis = new BufferedInputStream(is);
java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int numBytes;
byte[] buffer = new byte[1024];
while ((numBytes = bis.read(buffer))!= -1)
{
bos.write(buffer, 0, numBytes);
}
bis.close();
bos.close();
}
jar.close();
classPath = memoryWorkingPath+"/BOOT-INF/classes"+CLASS_PATH_SEPARATOR+memoryWorkingPath+"/BOOT-INF/lib/*"+CLASS_PATH_SEPARATOR;
}else {
classPath = jarPath;
}
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ScriptLoader getInstance(){
return instance;
}
public Script newScript(String scriptName) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class<Script> scriptClass = this.loadedClass.get(scriptName);
Script newInstance = scriptClass.getDeclaredConstructor().newInstance();
return newInstance;
}
public void init(ScriptInfoService scriptInfoService) throws Exception {
List<ScriptInfo> scriptInfoList = scriptInfoService.findAllScriptInfos();
for (ScriptInfo info :scriptInfoList) {
load(info.getScriptName(), info.getScriptCode());
}
}
public void load(String scriptName, String scriptCode) throws Exception {
String source = scriptCode;
String fullPackage = DYNAMIC_BASE_PACKAGE + "." + scriptName;
InMemoryJavaCompiler compiler = InMemoryJavaCompiler.newInstance();
compiler.useParentClassLoader(getClass().getClassLoader());
if(StringUtils.isNotBlank(classPath)) {
compiler.useOptions("-classpath", classPath);
}
Class<Script> cls = (Class<Script>) compiler.compile(fullPackage, source);
this.loadedClass.put(scriptName, cls);
}
public void unLoad(String scriptName) throws ClassNotFoundException, IOException {
new File(path + DYNAMIC_BASE_PATH + "/" + scriptName +".class").delete();
this.loadedClass.remove(scriptName);
}
}
@@ -1,115 +0,0 @@
package com.eactive.httpmockserver.script.controller;
import com.eactive.httpmockserver.api.controller.ApiManageRestController;
import com.eactive.httpmockserver.datatables.DataTablesRequest;
import com.eactive.httpmockserver.datatables.DataTablesResponse;
import com.eactive.httpmockserver.script.ScriptLoader;
import com.eactive.httpmockserver.script.entity.ScriptInfo;
import com.eactive.httpmockserver.script.service.ScriptInfoService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
@Controller
public class ScriptController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private ScriptInfoService scriptInfoService;
@GetMapping("/manage/findAllScriptInfos")
public String getAllScriptInfoForDatatables(Pageable pageable, Model model) {
return "page/list-script-info";
}
@GetMapping(path = { "/manage/getScriptInfoForm", "/manage/getScriptInfoForm/{id}" })
public String getScriptInfoForm(Model model, @PathVariable Optional<Long> id) throws IOException {
if (id.isPresent()) {
Optional<ScriptInfo> optional = scriptInfoService.findById(id.get());
if (optional.isPresent()) {
model.addAttribute("scriptInfo", optional.get());
} else {
throw new IllegalArgumentException("No data, id: " + id.get());
}
} else {
ScriptInfo spec = new ScriptInfo();
InputStream is = getClass().getClassLoader().getResourceAsStream("basecodes/BaseScript.java.template");
String baseCode = IOUtils.toString(is, "utf-8");
spec.setScriptCode(baseCode);
model.addAttribute("scriptInfo", spec);
}
return "page/add-edit-script-info";
}
@PostMapping("/manage/saveScriptInfo")
public String saveScriptInfo(@Valid ScriptInfo spec, BindingResult result, Model model) throws Exception {
if (result.hasErrors()) {
return "page/add-edit-script-info";
}
ScriptLoader.getInstance().load(spec.getScriptName(), spec.getScriptCode());
if (spec.getId() == null) {
scriptInfoService.save(spec);
} else {
scriptInfoService.update(spec);
}
if (BooleanUtils.toBoolean(spec.getUseYn())) {
// 기존설정 useYn=N으로 수정
scriptInfoService.setUnuseOthers(spec.getId());
}
return "redirect:/manage/findAllScriptInfos";
}
@RequestMapping("/manage/deleteScriptInfo/{id}")
public String deleteScriptInfo(@PathVariable Long id) throws IOException, ClassNotFoundException {
if (id == null) {
throw new IllegalArgumentException("No data, id: " + id);
}
String scriptName = scriptInfoService.findById(id).get().getScriptName();
ScriptLoader.getInstance().unLoad(scriptName);
scriptInfoService.delete(id);
return "redirect:/manage/findAllScriptInfos";
}
@PostMapping("/manage/rest/scriptInfos")
@ResponseBody
public DataTablesResponse<ScriptInfo> getAllScriptInfoForDatatables(@RequestBody DataTablesRequest req) {
Pageable pageable = ApiManageRestController.assignJpaPageable(req);
// search option
Example<ScriptInfo> example = null;
if (StringUtils.isNotBlank(req.getSearch().getValue())) {
ScriptInfo spec = new ScriptInfo();
spec.setScriptName(req.getSearch().getValue());
ExampleMatcher matcher = ExampleMatcher.matchingAny().withMatcher("specName",
new ExampleMatcher.GenericPropertyMatcher().contains().ignoreCase());
example = Example.of(spec, matcher);
}
DataTablesResponse<ScriptInfo> res = new DataTablesResponse<ScriptInfo>(
scriptInfoService.findAllScriptInfos(example, pageable));
res.setRecordsFiltered(scriptInfoService.getRecordsCount(example));
res.setRecordsTotal(scriptInfoService.getRecordsCount(null));
res.setDraw(req.getDraw());
return res;
}
}
@@ -1,16 +0,0 @@
package com.eactive.httpmockserver.script.dao;
import com.eactive.httpmockserver.script.entity.ScriptInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface ScriptInfoDao extends JpaRepository<ScriptInfo, Long> {
ScriptInfo findFirstByUseYn(String useYn);
@Modifying
@Query(value = "update ScriptInfo b set b.useYn='N' where b.id <> ?1")
void updateUnuseOthers(Long id);
}
@@ -1,67 +0,0 @@
package com.eactive.httpmockserver.script.entity;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
@Entity
public class ScriptInfo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Column(length = 500, nullable = false)
private String scriptName;
@NotBlank
@Column(length = 4000, nullable = false)
private String scriptDesc;
@Column
@Lob
private String scriptCode;
@Column(length = 1)
private String useYn;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getScriptName() {
return scriptName;
}
public void setScriptName(String scriptName) {
this.scriptName = scriptName;
}
public String getScriptDesc() {
return scriptDesc;
}
public void setScriptDesc(String scriptDesc) {
this.scriptDesc = scriptDesc;
}
public String getScriptCode() {
return scriptCode;
}
public void setScriptCode(String scriptCode) {
this.scriptCode = scriptCode;
}
public String getUseYn() {
return useYn;
}
public void setUseYn(String useYn) {
this.useYn = useYn;
}
}
@@ -1,30 +0,0 @@
package com.eactive.httpmockserver.script.service;
import com.eactive.httpmockserver.script.entity.ScriptInfo;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Optional;
public interface ScriptInfoService {
public ScriptInfo findActiveScriptInfo();
public List<ScriptInfo> findAllScriptInfos();
public List<ScriptInfo> findAllScriptInfos(Pageable pageable);
public List<ScriptInfo> findAllScriptInfos(Example<ScriptInfo> example, Pageable pageable);
public long getRecordsCount(Example<ScriptInfo> example);
public Optional<ScriptInfo> findById(Long id);
public ScriptInfo save(ScriptInfo spec);
public ScriptInfo update(ScriptInfo spec);
public void delete(Long id);
public void setUnuseOthers(Long id);
}
@@ -1,94 +0,0 @@
package com.eactive.httpmockserver.script.service;
import com.eactive.httpmockserver.script.dao.ScriptInfoDao;
import com.eactive.httpmockserver.script.entity.ScriptInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class ScriptInfoServiceImpl implements ScriptInfoService {
@Autowired
private ScriptInfoDao dao;
@Override
public ScriptInfo findActiveScriptInfo() {
return dao.findFirstByUseYn("Y");
}
@Override
public List<ScriptInfo> findAllScriptInfos() {
return dao.findAll();
}
@Override
public List<ScriptInfo> findAllScriptInfos(Pageable pageable) {
Page<ScriptInfo> pagedResult = dao.findAll(pageable);
if (pagedResult.hasContent()) {
return pagedResult.getContent();
} else {
return new ArrayList<ScriptInfo>();
}
}
@Override
public List<ScriptInfo> findAllScriptInfos(Example<ScriptInfo> example, Pageable pageable) {
if (example == null) {
return findAllScriptInfos(pageable);
}
Page<ScriptInfo> pagedResult = dao.findAll(example, pageable);
if (pagedResult.hasContent()) {
return pagedResult.getContent();
} else {
return new ArrayList<ScriptInfo>();
}
}
@Override
public Optional<ScriptInfo> findById(Long id) {
return dao.findById(id);
}
@Override
public long getRecordsCount(Example<ScriptInfo> example) {
if (example == null) {
return dao.count();
} else {
return dao.count(example);
}
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public ScriptInfo save(ScriptInfo spec) {
return dao.save(spec);
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public ScriptInfo update(ScriptInfo spec) {
return dao.save(spec);
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void delete(Long id) {
dao.deleteById(id);
}
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void setUnuseOthers(Long id) {
dao.updateUnuseOthers(id);
}
}
@@ -1,164 +0,0 @@
package com.eactive.httpmockserver.socket;
import com.eactive.httpmockserver.api.controller.ApiManageRestController;
import com.eactive.httpmockserver.datatables.DataTablesRequest;
import com.eactive.httpmockserver.datatables.DataTablesResponse;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatcher;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.persistence.NoResultException;
import javax.validation.Valid;
import java.util.Optional;
@Controller
public class SocketServerManageController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private BytesMessageSpecService specService;
private EchoSocketServer echoSocketServer;
@GetMapping("/manage/findAllBytesMessageSpecs")
public String getAllBytesMessageSpecs(Pageable pageable, Model model) {
return "page/list-bytes-message-spec";
}
@GetMapping(path = { "/manage/getBytesMessageSpecForm", "/manage/getBytesMessageSpecForm/{id}" })
public String getBytesMessageSpecForm(Model model, @PathVariable Optional<Long> id) {
if (id.isPresent()) {
Optional<BytesMessageSpec> optional = specService.findById(id.get());
if (optional.isPresent()) {
model.addAttribute("bytesMessageSpec", optional.get());
} else {
throw new IllegalArgumentException("No data, id: " + id.get());
}
} else {
BytesMessageSpec spec = new BytesMessageSpec();
model.addAttribute("bytesMessageSpec", spec);
}
return "page/add-edit-bytes-message-spec";
}
@PostMapping("/manage/saveBytesMessageSpec")
public String saveBytesMessageSpec(@Valid BytesMessageSpec spec, BindingResult result, Model model) {
if (result.hasErrors()) {
return "page/add-edit-bytes-message-spec";
}
if (spec.getId() == null) {
specService.save(spec);
} else {
specService.update(spec);
}
if (BooleanUtils.toBoolean(spec.getUseYn())) {
// 기존서버 중지
stop();
// 기존설정 useYn=N으로 수정
specService.setUnuseOthers(spec.getId());
// 서버 기동
start();
}
return "redirect:/manage/findAllBytesMessageSpecs";
}
@PostMapping("/manage/rest/bytesMessageSpecs")
@ResponseBody
public DataTablesResponse<BytesMessageSpec> getAllApisForDatatables(@RequestBody DataTablesRequest req) {
Pageable pageable = ApiManageRestController.assignJpaPageable(req);
// search option
Example<BytesMessageSpec> example = null;
if (StringUtils.isNotBlank(req.getSearch().getValue())) {
BytesMessageSpec spec = new BytesMessageSpec();
spec.setSpecName(req.getSearch().getValue());
ExampleMatcher matcher = ExampleMatcher.matchingAny().withMatcher("specName",
new GenericPropertyMatcher().contains().ignoreCase());
example = Example.of(spec, matcher);
}
DataTablesResponse<BytesMessageSpec> res = new DataTablesResponse<BytesMessageSpec>(
specService.findAllBytesMessageSpecs(example, pageable));
res.setRecordsFiltered(specService.getRecordsCount(example));
res.setRecordsTotal(specService.getRecordsCount(null));
res.setDraw(req.getDraw());
return res;
}
@RequestMapping("/manage/deleteBytesMessageSpec/{id}")
public String deleteBytesMessageSpec(@PathVariable Long id) {
if (id == null) {
throw new IllegalArgumentException("No data, id: " + id);
}
specService.delete(id);
return "redirect:/manage/findAllBytesMessageSpecs";
}
@PostConstruct
public void start() {
logger.info("EchoSocketServer starting..");
BytesMessageSpec spec = specService.findActiveBytesMessageSpec();
if (spec == null) {
logger.info("EchoSocketServer not started(No have rule)");
return;
}
logger.info("BytesMessageSpec=" + spec.toString());
new Thread(new Runnable() {
@Override
public void run() {
try {
echoSocketServer = new EchoSocketServer(spec);
echoSocketServer.start();
logger.info("EchoSocketServer started");
} catch (NoResultException e) {
logger.info("EchoSocketServer not started(No have rule)");
} catch (Exception e) {
logger.error(e.getMessage());
}
}
}).start();
}
@PreDestroy
public void stop() {
logger.info("EchoSocketServer stopping..");
if (echoSocketServer != null) {
echoSocketServer.stop();
}
logger.info("EchoSocketServer stopped");
}
@RequestMapping("/manage/socket/restartEchoSocketServer")
@ResponseBody
public String restartEchoServer() {
stop();
start();
return "Success";
}
}
@@ -0,0 +1,57 @@
package com.eactive.httpmockserver.user.controller;
import com.eactive.httpmockserver.user.dto.PasswordChangeRequestDTO;
import com.eactive.httpmockserver.user.entity.User;
import com.eactive.httpmockserver.user.service.UserService;
import com.eactive.httpmockserver.common.security.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class AccountController {
@Autowired
private Validator validator;
@Autowired
private UserService userService;
@GetMapping("/change_password.do")
public String changePassword(ModelMap model, @ModelAttribute("passwordChangeRequest") PasswordChangeRequestDTO passwordChangeRequestDTO) {
return "/apps/main/updatePw";
}
@PostMapping(value = "/update_password.do")
@Transactional
public String updatePassword(ModelMap model, @ModelAttribute("passwordChangeRequest") PasswordChangeRequestDTO passwordChangeRequestDTO,
@CurrentUser User user,
BindingResult result) {
validator.validate(passwordChangeRequestDTO, result);
if (result.hasErrors()) {
model.addAttribute("errors", result);
return "apps/main/updatePw";
}
String oldPassword = passwordChangeRequestDTO.getOldPassword();
String newPassword = passwordChangeRequestDTO.getNewPassword();
String newPassword2 = passwordChangeRequestDTO.getNewPassword2();
String resultMsg = userService.updateUserPassword(user.getUserId(), oldPassword, newPassword, newPassword2);
model.addAttribute("resultMsg", resultMsg);
model.addAttribute("passwordChangeRequest", new PasswordChangeRequestDTO());
return "/apps/main/updatePw";
}
}
@@ -0,0 +1,65 @@
package com.eactive.httpmockserver.user.controller;
import com.eactive.httpmockserver.user.dto.UserRegisterDTO;
import com.eactive.httpmockserver.user.entity.StaffUser;
import com.eactive.httpmockserver.user.mapper.StaffUserMapper;
import com.eactive.httpmockserver.user.repository.StaffUserRepository;
import com.eactive.httpmockserver.user.service.StaffUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class AdminRegisterController {
@Autowired
StaffUserService staffUserService;
@Autowired
StaffUserRepository staffUserRepository;
@Autowired
private Validator validator;
@Autowired
private StaffUserMapper staffUserMapper;
@GetMapping("/admin_register_view.do")
public String adminRegisterView(ModelMap model) {
long users = staffUserRepository.count();
if (users == 0){
model.addAttribute("user", new StaffUser());
return "page/users/adminRegister";
}else {
return "redirect:/";
}
}
@PostMapping("/admin_register.do")
public String adminRegister(@ModelAttribute("user") UserRegisterDTO user,
BindingResult bindingResult,
ModelMap model) {
if (user == null) {
return "redirect:/admin_register_view.do";
}
validator.validate(user, bindingResult);
if (bindingResult.hasErrors()) {
model.addAttribute("user", user);
return "page/users/adminRegister";
}
StaffUser newUser = staffUserMapper.map(user);
staffUserService.create(newUser);
return "redirect:/login";
}
}
@@ -0,0 +1,121 @@
package com.eactive.httpmockserver.user.controller;
import com.eactive.httpmockserver.common.security.CurrentUser;
import com.eactive.httpmockserver.user.dto.UserRegisterDTO;
import com.eactive.httpmockserver.user.dto.UserSearch;
import com.eactive.httpmockserver.user.dto.UserUpdateDTO;
import com.eactive.httpmockserver.user.entity.StaffUser;
import com.eactive.httpmockserver.user.entity.User;
import com.eactive.httpmockserver.user.mapper.StaffUserMapper;
import com.eactive.httpmockserver.user.service.StaffUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/mgmt/users")
public class UserMgmtController {
public static final String STAFF_USER_EDIT = "page/users/staffUserEdit";
public static final String USERS_LIST_VIEW = "redirect:/mgmt/users/list_view.do";
@Autowired
private StaffUserService staffUserService;
@Autowired
private Validator validator;
@Autowired
private StaffUserMapper staffUserMapper;
@GetMapping("/list_view.do")
public String userList(@ModelAttribute("userSearch") UserSearch userSearch,
ModelMap model,
Pageable pageable) {
Page<StaffUser> page = staffUserService.findAll(userSearch.buildSpecification(), pageable);
model.addAttribute("page", page);
model.addAttribute("pageable", pageable);
model.addAttribute("modelSearch", userSearch);
return "page/users/staffUserList";
}
@GetMapping("/create_view.do")
public String createView(ModelMap model) {
model.addAttribute("user", new StaffUser());
return STAFF_USER_EDIT;
}
@GetMapping("/update_view.do")
public String updateView(ModelMap model,
@RequestParam("userId") String userId) {
StaffUser found = staffUserService.findById(userId);
model.addAttribute("user", found);
return STAFF_USER_EDIT;
}
@PostMapping("/register.do")
public String register(@ModelAttribute("user") UserRegisterDTO user,
BindingResult bindingResult,
ModelMap model) {
if (user == null) {
return "redirect:/mgmt/users/create_view.do";
}
validator.validate(user, bindingResult);
if (bindingResult.hasErrors()) {
model.addAttribute("user", user);
return STAFF_USER_EDIT;
}
StaffUser newUser = staffUserMapper.map(user);
staffUserService.create(newUser);
return USERS_LIST_VIEW;
}
@PostMapping("/update.do")
public String update(@RequestParam("esntlId") String esntlId,
@ModelAttribute("user") UserUpdateDTO user,
BindingResult bindingResult,
ModelMap model) {
if (StringUtils.isEmpty(esntlId)) {
return USERS_LIST_VIEW;
}
validator.validate(user, bindingResult);
if (bindingResult.hasErrors()) {
model.addAttribute("user", user);
return STAFF_USER_EDIT;
}
StaffUser newUser = staffUserMapper.map(user);
staffUserService.update(esntlId, newUser);
return USERS_LIST_VIEW;
}
@PostMapping("/delete.do")
public String delete(@CurrentUser User user,
@ModelAttribute UserSearch modelSearch) {
modelSearch.getCheckedIdForDel().forEach(id -> {
if (!user.getEsntlId().equals(id)) { // 자기 자신은 삭제 불가
staffUserService.deleteById(id);
}
});
return USERS_LIST_VIEW;
}
}
@@ -0,0 +1,42 @@
package com.eactive.httpmockserver.user.dto;
import com.eactive.httpmockserver.common.validator.PasswordMatch;
import javax.validation.constraints.NotEmpty;
@PasswordMatch(input = "newPassword", confirm = "newPassword2")
public class PasswordChangeRequestDTO {
@NotEmpty(message = "{field.required}")
private String oldPassword;
@NotEmpty(message = "{field.required}")
private String newPassword;
@NotEmpty(message = "{field.required}")
private String newPassword2;
public String getOldPassword() {
return oldPassword;
}
public void setOldPassword(String oldPassword) {
this.oldPassword = oldPassword;
}
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
public String getNewPassword2() {
return newPassword2;
}
public void setNewPassword2(String newPassword2) {
this.newPassword2 = newPassword2;
}
}
@@ -0,0 +1,113 @@
package com.eactive.httpmockserver.user.dto;
import com.eactive.httpmockserver.user.entity.UserStatus;
import com.eactive.httpmockserver.common.validator.PasswordMatch;
import com.eactive.httpmockserver.common.validator.UniqueId;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
@PasswordMatch(input = "password", confirm = "password2")
public class UserRegisterDTO implements Serializable {
/**
* 고유ID
*/
private String esntlId;
/**
* 업무사용자ID
*/
@NotEmpty
@UniqueId
@Email
private String userId;
/**
* 비밀번호
*/
@NotEmpty(message = "{field.required}")
@Length(min = 8)
private String password;
@NotEmpty(message = "{field.required}")
@Length(min = 8)
private String password2;
/**
* 사용자상태코드
*/
private UserStatus status;
/**
* 이동전화번호
*/
@NotEmpty
private String mobilePhone;
/**
* 사용자명
*/
@NotEmpty
private String username;
public String getEsntlId() {
return esntlId;
}
public void setEsntlId(String esntlId) {
this.esntlId = esntlId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public UserStatus getStatus() {
return status;
}
public void setStatus(UserStatus status) {
this.status = status;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
}
@@ -0,0 +1,43 @@
package com.eactive.httpmockserver.user.dto;
import com.eactive.httpmockserver.user.entity.StaffUser;
import com.eactive.httpmockserver.user.entity.UserStatus;
import com.eactive.httpmockserver.common.search.BaseSearch;
import com.eactive.httpmockserver.common.search.ColumnSearchModel;
import com.eactive.httpmockserver.common.search.SearchCondition;
import com.eactive.httpmockserver.common.search.SearchModel;
import java.util.ArrayList;
import java.util.List;
public class UserSearch implements BaseSearch<StaffUser> {
private String username;
private List<String> checkedIdForDel;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public List<String> getCheckedIdForDel() {
return checkedIdForDel;
}
public void setCheckedIdForDel(List<String> checkedIdForDel) {
this.checkedIdForDel = checkedIdForDel;
}
@Override
public List<SearchModel> buildSearchCondition() {
List<SearchModel> models = new ArrayList<>();
models.add(new ColumnSearchModel("username", SearchCondition.LIKE, username));
models.add(new ColumnSearchModel("status", SearchCondition.NOT_EQUAL, UserStatus.DELETED));
return models;
}
}
@@ -0,0 +1,92 @@
package com.eactive.httpmockserver.user.dto;
import com.eactive.httpmockserver.user.entity.UserStatus;
import com.eactive.httpmockserver.common.entity.EnabledStatus;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
public class UserUpdateDTO implements Serializable {
/**
* 고유ID
*/
private String esntlId;
/**
* 업무사용자ID
*/
@NotEmpty
private String userId;
/**
* 사용자상태코드
*/
private UserStatus status;
/**
* 이동전화번호
*/
@NotEmpty
private String mobilePhone;
/**
* 사용자명
*/
@NotEmpty
private String username;
@NotNull
private EnabledStatus lockAt;
public String getEsntlId() {
return esntlId;
}
public void setEsntlId(String esntlId) {
this.esntlId = esntlId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public UserStatus getStatus() {
return status;
}
public void setStatus(UserStatus status) {
this.status = status;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public EnabledStatus getLockAt() {
return lockAt;
}
public void setLockAt(EnabledStatus lockAt) {
this.lockAt = lockAt;
}
}
@@ -0,0 +1,65 @@
package com.eactive.httpmockserver.user.entity;
public class AnonymousUser extends User {
private String userId;
public AnonymousUser() {
this.userId = "ANONYMOUS";
this.setUserSecurity(new UserSecurity("ROLE_ANONYMOUS"));
}
@Override
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String getUserId() {
return this.userId;
}
@Override
public String getMobilePhone() {
return "";
}
@Override
public String getUserSe() {
return "";
}
@Override
public UserStatus getStatus() {
return null;
}
@Override
public void setStatus(UserStatus status) {
throw new UnsupportedOperationException();
}
@Override
public String getPasswordHint() {
return "";
}
@Override
public String getPasswordCnsr() {
return "";
}
@Override
public void setPassword(String password) {
throw new UnsupportedOperationException();
}
@Override
public String getPassword() {
return "";
}
@Override
public String getUsername() {
return "";
}
}
@@ -0,0 +1,153 @@
package com.eactive.httpmockserver.user.entity;
import javax.persistence.*;
import java.util.Objects;
/**
* PT_USER 내부사용자정보
*
* @author
* @version 1.0
*/
@Entity
@Table(name = "PT_USER")
public class StaffUser extends User {
private static final long serialVersionUID = 1L;
/**
* 업무사용자ID
*/
@Column(name = "USER_ID", nullable = false)
private String userId;
/**
* 사용자상태코드
*/
@Column(name = "EMPLYR_STTUS_CODE", nullable = false)
@Enumerated(EnumType.STRING)
private UserStatus status;
/**
* 이동전화번호
*/
@Column(name = "MBTLNUM")
private String mobilePhone;
/**
* 비밀번호
*/
@Column(name = "PASSWORD", nullable = false)
private String password;
@Transient
private String password2;
/**
* 비밀번호정답
*/
@Column(name = "PASSWORD_CNSR")
private String passwordCnsr;
/**
* 비밀번호힌트
*/
@Column(name = "PASSWORD_HINT")
private String passwordHint;
/**
* 사용자명
*/
@Column(name = "USER_NM", nullable = false)
private String username;
@Override
public UserStatus getStatus() {
return status;
}
@Override
public void setStatus(UserStatus status) {
this.status = status;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public String getPasswordCnsr() {
return passwordCnsr;
}
public void setPasswordCnsr(String passwordCnsr) {
this.passwordCnsr = passwordCnsr;
}
public String getPasswordHint() {
return passwordHint;
}
public void setPasswordHint(String passwordHint) {
this.passwordHint = passwordHint;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String getUserId() {
return userId;
}
@Override
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String getUserSe() {
return "USR";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StaffUser staffUser = (StaffUser) o;
return Objects.equals(userId, staffUser.userId) && status == staffUser.status && Objects.equals(mobilePhone, staffUser.mobilePhone) && Objects.equals(password, staffUser.password) && Objects.equals(passwordCnsr, staffUser.passwordCnsr) && Objects.equals(passwordHint, staffUser.passwordHint) && Objects.equals(username, staffUser.username);
}
@Override
public int hashCode() {
return Objects.hash(userId, status, mobilePhone, password, passwordCnsr, passwordHint, username);
}
}
@@ -0,0 +1,165 @@
package com.eactive.httpmockserver.user.entity;
import com.eactive.httpmockserver.common.entity.Auditable;
import com.eactive.httpmockserver.common.entity.EnabledStatus;
import org.hibernate.annotations.Type;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
@MappedSuperclass
public abstract class User extends Auditable implements Serializable, UserDetails {
private static final long serialVersionUID = 1L;
/**
* 고유ID
*/
@Id
@Column(name = "ESNTL_ID", nullable = false, updatable = false)
private String esntlId;
/**
* 잠금여부
*/
@Column(name = "LOCK_AT")
@Enumerated(EnumType.STRING)
private EnabledStatus lockAt;
/**
* 잠금회수
*/
@Column(name = "LOCK_CNT")
private Integer lockCnt;
/**
* 잠금최종시점
*/
@Column(name = "LAST_LOCK_DATE")
@Type(type = "org.hibernate.type.LocalDateTimeType")
private LocalDateTime lastLockDate;
@Column(name = "LAST_CHANGE_PASSWORD_DATE")
@Type(type = "org.hibernate.type.LocalDateTimeType")
private LocalDateTime lastPasswordChangeDate;
@Transient
private String ip;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ESNTL_ID", referencedColumnName = "SCRTY_DTRMN_TRGET_ID", insertable = false, updatable = false)
private UserSecurity userSecurity;
public String getEsntlId() {
return esntlId;
}
public void setEsntlId(String esntlId) {
this.esntlId = esntlId;
}
public abstract void setUserId(String userId);
public abstract String getUserId();
public abstract String getMobilePhone();
public abstract String getUserSe();
public abstract UserStatus getStatus();
public abstract void setStatus(UserStatus status);
public abstract String getPasswordHint();
public abstract String getPasswordCnsr();
public abstract void setPassword(String password);
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public EnabledStatus getLockAt() {
return lockAt;
}
public void setLockAt(EnabledStatus lockAt) {
this.lockAt = lockAt;
}
public Integer getLockCnt() {
return lockCnt;
}
public void setLockCnt(Integer lockCnt) {
this.lockCnt = lockCnt;
}
public LocalDateTime getLastLockDate() {
return lastLockDate;
}
public void setLastLockDate(LocalDateTime lockLastPnttm) {
this.lastLockDate = lockLastPnttm;
}
public LocalDateTime getLastPasswordChangeDate() {
return lastPasswordChangeDate;
}
public void setLastPasswordChangeDate(LocalDateTime lastPasswordChangeDate) {
this.lastPasswordChangeDate = lastPasswordChangeDate;
}
@Override
@Transient
public Collection<? extends GrantedAuthority> getAuthorities() {
if (userSecurity != null) {
return Arrays.asList(new SimpleGrantedAuthority(userSecurity.getAuthorCode()));
} else {
return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
}
}
@Override
@Transient
public boolean isAccountNonExpired() {
return getStatus().equals(UserStatus.ACTIVE);
}
@Override
@Transient
public boolean isAccountNonLocked() {
return getLockAt().equals(EnabledStatus.N);
}
@Override
@Transient
public boolean isCredentialsNonExpired() {
return true;
}
@Override
@Transient
public boolean isEnabled() {
return getStatus().equals(UserStatus.ACTIVE);
}
public UserSecurity getUserSecurity() {
return userSecurity;
}
public void setUserSecurity(UserSecurity userSecurity) {
this.userSecurity = userSecurity;
}
}
@@ -0,0 +1,68 @@
package com.eactive.httpmockserver.user.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
* COMTNEMPLYRSCRTYESTBS 사용자보안설정
*
* @author
* @version 1.0
*/
@Entity
@Table(name = "COMTNEMPLYRSCRTYESTBS")
public class UserSecurity implements Serializable {
public UserSecurity() {
}
public UserSecurity(String authorCode) {
this.authorCode = authorCode;
}
/**
* 권한코드
*/
@Column(name = "AUTHOR_CODE", nullable = false)
private String authorCode;
/**
* 회원유형코드
*/
@Column(name = "MBER_TY_CODE", nullable = true)
private String memberTypeCode;
/**
* 보안설정대상ID
*/
@Id
@Column(name = "SCRTY_DTRMN_TRGET_ID", nullable = false)
private String userEsntlId;
public String getAuthorCode() {
return authorCode;
}
public void setAuthorCode(String authorCode) {
this.authorCode = authorCode;
}
public String getMemberTypeCode() {
return memberTypeCode;
}
public void setMemberTypeCode(String memberTypeCode) {
this.memberTypeCode = memberTypeCode;
}
public String getUserEsntlId() {
return userEsntlId;
}
public void setUserEsntlId(String userEsntlId) {
this.userEsntlId = userEsntlId;
}
}
@@ -0,0 +1,20 @@
package com.eactive.httpmockserver.user.entity;
public enum UserStatus {
WAITING("가입승인 대기"),
ACTIVE("활성화"),
RESET_PASSWORD("비밀번호 초기화"),
INACTIVE("비활성화"),
LOCKED ("잠김"),
DELETED("삭제");
private String description;
UserStatus(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}

Some files were not shown because too many files have changed in this diff Show More