Skip to content

Commit

Permalink
[ISSUE #4767] Refactor Admin server http handler. (#4768)
Browse files Browse the repository at this point in the history
* rebase master

* use httpRequest

* use httpRequest

* some enhancement

* some enhancement

* some enhancement

* some enhancement
  • Loading branch information
karsonto authored Apr 3, 2024
1 parent 172804a commit 98b1ed1
Show file tree
Hide file tree
Showing 37 changed files with 1,175 additions and 2,328 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@

import lombok.Data;

@Deprecated
@Data
public class HttpCommand implements ProtocolTransportObject {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Objects;

import com.fasterxml.jackson.annotation.JsonInclude;
Expand Down Expand Up @@ -52,6 +53,14 @@ public class JsonUtils {
OBJECT_MAPPER.registerModule(new JavaTimeModule());
}

public static <T> T mapToObject(Map<String, Object> map, Class<T> beanClass) {
if (map == null) {
return null;
}
Object obj = OBJECT_MAPPER.convertValue(map, beanClass);
return (T) obj;
}

/**
* Serialize object to json string.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,10 @@

package org.apache.eventmesh.common.utils;

import static org.apache.eventmesh.common.Constants.SUCCESS_CODE;

import org.apache.eventmesh.common.Constants;
import org.apache.eventmesh.common.enums.HttpMethod;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
Expand All @@ -34,8 +29,6 @@
import java.util.HashMap;
import java.util.Map;

import com.sun.net.httpserver.HttpExchange;

import lombok.extern.slf4j.Slf4j;

/**
Expand Down Expand Up @@ -81,26 +74,4 @@ public static String addressToString(Collection<InetSocketAddress> clients) {
}
return sb.toString();
}

public static String parsePostBody(HttpExchange exchange)
throws IOException {

if (!HttpMethod.POST.name().equalsIgnoreCase(exchange.getRequestMethod())
&& !HttpMethod.PUT.name().equalsIgnoreCase(exchange.getRequestMethod())) {
return "";
}
StringBuilder body = new StringBuilder(1024);
try (InputStreamReader reader = new InputStreamReader(exchange.getRequestBody(), Constants.DEFAULT_CHARSET.name())) {
char[] buffer = new char[256];
int readIndex;
while ((readIndex = reader.read(buffer)) != -1) {
body.append(buffer, 0, readIndex);
}
}
return body.toString();
}

public static void sendSuccessResponseHeaders(HttpExchange httpExchange) throws IOException {
httpExchange.sendResponseHeaders(SUCCESS_CODE, 0);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,13 @@

package org.apache.eventmesh.common.utils;

import org.apache.eventmesh.common.enums.HttpMethod;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import com.sun.net.httpserver.HttpExchange;

public class NetUtilsTest {

Expand All @@ -58,25 +50,4 @@ public void testAddressToString() {
Assertions.assertEquals(localAddress + "|", result);
}

@Test
public void testParsePostBody() throws Exception {

HttpExchange exchange = Mockito.mock(HttpExchange.class);
String expected = "mxsm";
ByteArrayInputStream inputStream = new ByteArrayInputStream(expected.getBytes(StandardCharsets.UTF_8));
Mockito.when(exchange.getRequestMethod()).thenReturn(HttpMethod.POST.name());
Mockito.when(exchange.getRequestBody()).thenReturn(inputStream);

String actual = NetUtils.parsePostBody(exchange);
Assertions.assertEquals(expected, actual);

}

@Test
public void testSendSuccessResponseHeaders() throws IOException {
HttpExchange exchange = Mockito.mock(HttpExchange.class);
NetUtils.sendSuccessResponseHeaders(exchange);
Mockito.verify(exchange, Mockito.times(1))
.sendResponseHeaders(Mockito.anyInt(), Mockito.anyLong());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,133 @@

package org.apache.eventmesh.runtime.admin.handler;

import com.sun.net.httpserver.HttpHandler;
import org.apache.eventmesh.common.enums.HttpMethod;
import org.apache.eventmesh.runtime.constants.EventMeshConstants;
import org.apache.eventmesh.runtime.util.HttpRequestUtil;
import org.apache.eventmesh.runtime.util.HttpResponseUtils;

import lombok.Data;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
* An abstract class that implements the {@link HttpHandler} interface
* and provides basic functionality for HTTP request handling.
* <p>
* Subclasses should extend this class to implement specific HTTP request handling logic.
*/
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.AsciiString;

import lombok.Data;

@Data
public abstract class AbstractHttpHandler implements HttpHandler {

protected void write(ChannelHandlerContext ctx, byte[] result) {
ctx.writeAndFlush(HttpResponseUtils.getHttpResponse(result, ctx, HttpHeaderValues.TEXT_HTML)).addListener(ChannelFutureListener.CLOSE);
}

protected void write(ChannelHandlerContext ctx, HttpResponse response) {
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

protected void write(ChannelHandlerContext ctx, byte[] result, AsciiString headerValue, HttpResponseStatus httpResponseStatus) {
ctx.writeAndFlush(HttpResponseUtils.getHttpResponse(result, ctx, headerValue, httpResponseStatus)).addListener(ChannelFutureListener.CLOSE);
}

protected void write401(ChannelHandlerContext ctx) {
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

protected void writeSuccess(ChannelHandlerContext ctx) {
HttpHeaders responseHeaders = new DefaultHttpHeaders();
responseHeaders.add(EventMeshConstants.HANDLER_ORIGIN, "*");
DefaultFullHttpResponse response =
new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.EMPTY_BUFFER, responseHeaders, responseHeaders);
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

protected void writeSuccess(ChannelHandlerContext ctx, DefaultHttpHeaders responseHeaders) {
DefaultFullHttpResponse response =
new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.EMPTY_BUFFER, responseHeaders, responseHeaders);
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

protected void preflight(ChannelHandlerContext ctx) {
HttpHeaders responseHeaders = new DefaultHttpHeaders();
responseHeaders.add(EventMeshConstants.HANDLER_ORIGIN, "*");
responseHeaders.add(EventMeshConstants.HANDLER_METHODS, "*");
responseHeaders.add(EventMeshConstants.HANDLER_HEADERS, "*");
responseHeaders.add(EventMeshConstants.HANDLER_AGE, EventMeshConstants.MAX_AGE);
DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.EMPTY_BUFFER,
responseHeaders, responseHeaders);
write(ctx, response);
}

/**
* Converts a query string to a map of key-value pairs.
* <p>
* This method takes a query string and parses it to create a map of key-value pairs, where each key and value are extracted from the query string
* separated by '='.
* <p>
* If the query string is null, an empty map is returned.
*
* @param query the query string to convert to a map
* @return a map containing the key-value pairs from the query string
*/
protected Map<String, String> queryToMap(String query) {
if (query == null) {
return new HashMap<>();
}
Map<String, String> result = new HashMap<>();
for (String param : query.split("&")) {
String[] entry = param.split("=");
if (entry.length > 1) {
result.put(entry[0], entry[1]);
} else {
result.put(entry[0], "");
}
}
return result;
}

@Override
public void handle(HttpRequest httpRequest, ChannelHandlerContext ctx) throws Exception {
switch (HttpMethod.valueOf(httpRequest.method().name())) {
case OPTIONS:
preflight(ctx);
break;
case GET:
get(httpRequest, ctx);
break;
case POST:
post(httpRequest, ctx);
break;
case DELETE:
delete(httpRequest, ctx);
break;
default: // do nothing
break;
}
}

protected void post(HttpRequest httpRequest, ChannelHandlerContext ctx) throws Exception {
}

protected void delete(HttpRequest httpRequest, ChannelHandlerContext ctx) throws Exception {
}

protected void get(HttpRequest httpRequest, ChannelHandlerContext ctx) throws Exception {
}

protected Map<String, Object> parseHttpRequestBody(final HttpRequest httpRequest) throws IOException {
return HttpRequestUtil.parseHttpRequestBody(httpRequest, null, null);
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import com.sun.net.httpserver.HttpHandler;

public class AdminHandlerManager {

Expand Down
Loading

0 comments on commit 98b1ed1

Please sign in to comment.