Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do some refactor #28

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 16 additions & 19 deletions core/src/main/java/io/wttech/stubway/StubFinderService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,8 @@
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Component(service = StubFinderService.class)
Expand All @@ -27,44 +24,44 @@ public class StubFinderService {

public StubResponse getStubResponse(SlingHttpServletRequest request) {
String resourcePath = request.getRequestPathInfo().getResourcePath();
Resource stubsResource = request.getResourceResolver().getResource(resourcePath);
Resource stubEndpoint = request.getResourceResolver().getResource(resourcePath);
try {
RequestParameters params = new RequestParameters(request);
return createStubResponse(stubsResource, params);
RequestParameters stubParams = new RequestParameters(request);
return createStubResponse(stubEndpoint, stubParams);
} catch (FetchingParametersException fpe) {
return StubResponse.internalError(fpe);
}
}

private StubResponse createStubResponse(Resource stubsResource, RequestParameters params) {
return getStub(stubsResource, params).map(StubResponse::foundStub).orElse(StubResponse.empty());
private StubResponse createStubResponse(Resource stubEndpoint, RequestParameters stubParams) {
return getStub(stubEndpoint, stubParams).map(StubResponse::foundStub).orElse(StubResponse.empty());
}

private Optional<Stub> getStub(Resource stubsResource, RequestParameters params) {
return Optional.ofNullable(stubsResource)
private Optional<Stub> getStub(Resource stubEndpoint, RequestParameters stubParams) {
return Optional.ofNullable(stubEndpoint)
.map(Resource::getChildren)
.map(resources -> toStub(resources, params));
.map(stubsResources -> toStub(stubsResources, stubParams));
}

private Stub toStub(Iterable<Resource> resources, RequestParameters params) {
return StreamSupport.stream(resources.spliterator(), false)
private Stub toStub(Iterable<Resource> stubResources, RequestParameters stubParams) {
return StreamSupport.stream(stubResources.spliterator(), false)
.map(resource -> resource.adaptTo(Stub.class))
.filter(Objects::nonNull)
.filter(stub -> isMethodMatching(stub, params))
.filter(stub -> isStubMatching(stub, params))
.filter(stub -> isMethodMatching(stub, stubParams))
.filter(stub -> isStubMatching(stub, stubParams))
.findFirst()
.orElse(null);
}

private boolean isMethodMatching(Stub stub, RequestParameters params) {
private boolean isMethodMatching(Stub stub, RequestParameters stubParams) {
try {
return ObjectUtils.equals(params.getMethod(), stub.getMethod());
return ObjectUtils.equals(stubParams.getMethod(), stub.getMethod());
} catch (MissingSupportedMethodException ex) {
return false;
}
}

private boolean isStubMatching(Stub stub, RequestParameters params) {
return matchersRegistry.getMatcher(params.getMethod()).matches(stub, params);
private boolean isStubMatching(Stub stub, RequestParameters stubParams) {
return matchersRegistry.getMatcher(stubParams.getMethod()).matches(stub, stubParams);
}
}
9 changes: 4 additions & 5 deletions core/src/main/java/io/wttech/stubway/StubServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,11 @@ private void handleRequest(SlingHttpServletRequest request, SlingHttpServletResp
response.setCharacterEncoding(CharEncoding.UTF_8);

StubResponse stubResponse = stubFinderService.getStubResponse(request);
response.setStatus(stubResponse.getStatusCode());

Map<String, String> headers = Optional.ofNullable(stubResponse.getResponseHeaders()).orElse(Collections.emptyMap());
headers.keySet().forEach(k -> response.setHeader(k, headers.get(k)));

IOUtils.copy(stubResponse.getInputStream(), response.getOutputStream());
response.setStatus(stubResponse.getStatusCode());
stubResponse.getHeaders()
.ifPresent(headers -> headers.keySet().forEach(k -> response.setHeader(k, headers.get(k))));
IOUtils.copy(stubResponse.getBody(), response.getOutputStream());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
import java.util.Set;

public interface PropertiesCollector {
Set<StubProperty> collectProperties(RequestParameters request);
Set<StubProperty> collectProperties(RequestParameters request);
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@

public class QueryParametersCollector implements PropertiesCollector {

private static QueryParametersCollector instance;

private QueryParametersCollector() {}
private QueryParametersCollector() {
}

public static PropertiesCollector create() {
return new QueryParametersCollector();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@

public class RequestBodyCollector implements PropertiesCollector {

private static RequestBodyCollector instance;

private RequestBodyCollector() {}
private RequestBodyCollector() {
}

public static PropertiesCollector create() {
return new RequestBodyCollector();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ public Matcher getMatcher(HttpMethod method) {
public void activate() {
matchers.put(HttpMethod.GET, new DefaultMatcher(QueryParametersCollector.create()));
matchers.put(HttpMethod.POST, new DefaultMatcher(RequestBodyCollector.create(),
QueryParametersCollector.create()));
QueryParametersCollector.create()));
matchers.put(HttpMethod.PUT, new DefaultMatcher(RequestBodyCollector.create(),
QueryParametersCollector.create()));
QueryParametersCollector.create()));
matchers.put(HttpMethod.DELETE, new DefaultMatcher(RequestBodyCollector.create(),
QueryParametersCollector.create()));
QueryParametersCollector.create()));
}

}
2 changes: 1 addition & 1 deletion core/src/main/java/io/wttech/stubway/package-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@Version("1.0.0")
@Version("1.2.0")
package io.wttech.stubway;

import org.osgi.annotation.versioning.Version;
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
package io.wttech.stubway.response;

class ResponseBody {
class ErrorResponseBody {

private String message;
private int statusCode;

public ResponseBody() {
}

public ResponseBody(String message, int statusCode) {
public ErrorResponseBody(int statusCode, String message) {
this.message = message;
this.statusCode = statusCode;
}

public String getMessage() {
return message;
}

public int getStatusCode() {
return statusCode;
}

public String getMessage() {
return message;
}

}
53 changes: 24 additions & 29 deletions core/src/main/java/io/wttech/stubway/response/StubResponse.java
Original file line number Diff line number Diff line change
@@ -1,71 +1,66 @@
package io.wttech.stubway.response;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.wttech.stubway.stub.Stub;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Optional;

import io.wttech.stubway.stub.Stub;
import org.apache.commons.io.IOUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import static org.apache.commons.httpclient.HttpStatus.*;

public class StubResponse {

private InputStream inputStream;
private InputStream body;
private int statusCode;
private Map<String, String> responseHeaders;
private Map<String, String> headers;

private static Gson gson = new GsonBuilder().setPrettyPrinting().create();
private static Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();

public static StubResponse foundStub(Stub foundStub) {
return new StubResponse(foundStub);
}

public static StubResponse empty() {
return new StubResponse();
return new StubResponse(SC_NOT_FOUND, "Stub not found");
}

public static StubResponse error(Exception e) {
return new StubResponse(e, SC_BAD_REQUEST);
return new StubResponse(SC_BAD_REQUEST, e.getMessage());
}

public static StubResponse internalError(Exception e) {
return new StubResponse(e, SC_INTERNAL_SERVER_ERROR);
return new StubResponse(SC_INTERNAL_SERVER_ERROR, e.getMessage());
}

private StubResponse(Stub foundStub) {
this.inputStream = Optional.ofNullable(foundStub.getInputStream())
.orElse(IOUtils.toInputStream("", Charset.defaultCharset()));
this.statusCode = foundStub.getStatusCode();
this.responseHeaders = foundStub.getResponseHeaders();
}

private StubResponse() {
ResponseBody responseBody = new ResponseBody("Stub not found", SC_NOT_FOUND);
String message = gson.toJson(responseBody);
this.inputStream = IOUtils.toInputStream(message, Charset.defaultCharset());
this.statusCode = SC_NOT_FOUND;
this.headers = foundStub.getResponseHeaders();
this.body = Optional.ofNullable(foundStub.getInputStream())
.orElse(IOUtils.toInputStream("", Charset.defaultCharset()));
}

private StubResponse(Exception exception, int status) {
ResponseBody responseBody = new ResponseBody(exception.getMessage(), SC_BAD_REQUEST);
String message = gson.toJson(responseBody);
this.inputStream = IOUtils.toInputStream(message, Charset.defaultCharset());
private StubResponse(int status, String errorMessage) {
this.statusCode = status;
ErrorResponseBody errorBody = new ErrorResponseBody(status, errorMessage);
this.body = IOUtils.toInputStream(gson.toJson(errorBody), Charset.defaultCharset());
}

public InputStream getInputStream() {
return inputStream;
public InputStream getBody() {
return body;
}

public int getStatusCode() {
return statusCode;
}

public Map<String, String> getResponseHeaders() { return responseHeaders; }
public Optional<Map<String, String>> getHeaders() {
return Optional.ofNullable(headers);
}

}
3 changes: 2 additions & 1 deletion core/src/main/java/io/wttech/stubway/stub/Stub.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ private void afterCreated() {

this.responseHeaders = valueMap.keySet().stream()
.filter(key -> key.startsWith(StubConstants.RESPONSE_PREFIX))
.collect(Collectors.toMap(key -> StringUtils.removeStart(key, StubConstants.RESPONSE_PREFIX), key -> valueMap.get(key, String.class)));
.collect(Collectors.toMap(key -> StringUtils.removeStart(key, StubConstants.RESPONSE_PREFIX),
key -> valueMap.get(key, String.class)));
}

public InputStream getInputStream() {
Expand Down
67 changes: 34 additions & 33 deletions core/src/test/java/io/wttech/stubway/response/StubResponseTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,37 +14,38 @@

public class StubResponseTest {

@Test
public void emptyShouldReturnStubResponseWithEmptyParams() throws IOException {
StubResponse empty = StubResponse.empty();
Assertions.assertEquals(404, empty.getStatusCode());
String expected = "{\n"
+ " \"message\": \"Stub not found\",\n"
+ " \"statusCode\": 404\n"
+ "}";
Assertions.assertEquals(expected, IOUtils.toString(empty.getInputStream(), Charset.defaultCharset()));
}

@Test
public void internalErrorShouldReturnStubResponseWithStatusCode500() {
StubResponse internalError = StubResponse.internalError(new Exception());
Assertions.assertEquals(500, internalError.getStatusCode());
}

@Test
public void errorShouldReturnStubResponseWithStatusCode400() {
StubResponse error = StubResponse.error(new Exception());
Assertions.assertEquals(400, error.getStatusCode());
}

@Test
public void foundStubShouldReturnStubResponseWithSetValues() throws IOException {
Stub stub = mock(Stub.class);
when(stub.getStatusCode()).thenReturn(200);
when(stub.getInputStream()).thenReturn(IOUtils.toInputStream("fake input stream message", Charset.defaultCharset()));
StubResponse foundStub = StubResponse.foundStub(stub);
Assertions.assertEquals(200, foundStub.getStatusCode());
Assertions.assertEquals("fake input stream message",
IOUtils.toString(foundStub.getInputStream(), Charset.defaultCharset()));
}
@Test
public void emptyShouldReturnStubResponseWithEmptyParams() throws IOException {
StubResponse empty = StubResponse.empty();
Assertions.assertEquals(404, empty.getStatusCode());
String expected = "{\n"
+ " \"message\": \"Stub not found\",\n"
+ " \"statusCode\": 404\n"
+ "}";
Assertions.assertEquals(expected, IOUtils.toString(empty.getBody(), Charset.defaultCharset()));
}

@Test
public void internalErrorShouldReturnStubResponseWithStatusCode500() {
StubResponse internalError = StubResponse.internalError(new Exception());
Assertions.assertEquals(500, internalError.getStatusCode());
}

@Test
public void errorShouldReturnStubResponseWithStatusCode400() {
StubResponse error = StubResponse.error(new Exception());
Assertions.assertEquals(400, error.getStatusCode());
}

@Test
public void foundStubShouldReturnStubResponseWithSetValues() throws IOException {
Stub stub = mock(Stub.class);
when(stub.getStatusCode()).thenReturn(200);
when(stub.getInputStream())
.thenReturn(IOUtils.toInputStream("fake input stream message", Charset.defaultCharset()));
StubResponse foundStub = StubResponse.foundStub(stub);
Assertions.assertEquals(200, foundStub.getStatusCode());
Assertions.assertEquals("fake input stream message",
IOUtils.toString(foundStub.getBody(), Charset.defaultCharset()));
}
}