import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.charset.Charset;
+import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.prueba.api.persistence.Account;
+import com.prueba.core.context.util.AntPathMatcher;
import com.prueba.core.web.controller.Controller;
import com.prueba.services.impl.ApiServiceImpl;
import com.sun.net.httpserver.HttpExchange;
public class ApiController implements Controller {
+ private static final String USER_NAME_PARAM = "username";
+ private static final String API_URL_PATTERN = "/app/api/{" + USER_NAME_PARAM + "}";
@Override
public void handle(HttpExchange httpExchange) throws IOException {
- String requestMethod = httpExchange.getRequestMethod();
- ApiServiceImpl apiService = new ApiServiceImpl();
-
- String body = getBody(httpExchange);
-
- ObjectMapper mapper = new ObjectMapper();
- Account account = mapper.readValue(body, Account.class);
+ final String requestMethod = httpExchange.getRequestMethod();
+ final ApiServiceImpl apiService = new ApiServiceImpl();
+ final ObjectMapper mapper = new ObjectMapper();
+
+ final String uri = httpExchange.getRequestURI().toString();
+ final AntPathMatcher pathMatcher = new AntPathMatcher();
+ final Map<String, String> variables = pathMatcher.extractUriTemplateVariables(API_URL_PATTERN, uri);
+ final String userNameParam = variables.get(USER_NAME_PARAM);
switch (requestMethod) {
- case "GET":
- apiService.findAccountByCode("GUMARTIN");
- break;
- case "POST":
- apiService.createAccount(account);
- break;
- case "DELETE":
- apiService.deleteAccountByCode("GUMARTIN");
- break;
- default:
- httpExchange.sendResponseHeaders(404, 0);
- break;
- }
-
-
-
+ case "GET":
+ Account account = apiService.findAccountByCode(userNameParam);
+ String bodyResponse = "";
+ if (account != null) {
+ bodyResponse = mapper.writeValueAsString(account);
+ }
+
+ httpExchange.sendResponseHeaders(200, bodyResponse.length());
+
+ try (final OutputStream os = httpExchange.getResponseBody()) {
+ os.write(bodyResponse.getBytes());
+ }
+
+ break;
+ case "POST":
+ final String bodyRequest = getBody(httpExchange);
+ final Account accountRequest = mapper.readValue(bodyRequest, Account.class);
+
+ apiService.createAccount(accountRequest);
+
+ httpExchange.sendResponseHeaders(200, 0);
+ break;
+ case "DELETE":
+ apiService.deleteAccountByCode(userNameParam);
+
+ httpExchange.sendResponseHeaders(200, 0);
+ break;
+ default:
+ httpExchange.sendResponseHeaders(404, 0);
+ break;
+ }
}
protected String getBody (HttpExchange httpExchange) throws IOException {