Skip to content

Commit

Permalink
Create PostBodyTask class to allow for tasks to get the post body.
Browse files Browse the repository at this point in the history
  • Loading branch information
Al Scott authored and arteam committed Aug 4, 2016
1 parent af0472f commit ad4ed8e
Show file tree
Hide file tree
Showing 14 changed files with 155 additions and 27 deletions.
Expand Up @@ -123,7 +123,7 @@ public TestTask() {
}

@Override
public void execute(ImmutableMultimap<String, String> parameters, String body, PrintWriter output) throws Exception {
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception {
final String name = parameters.get("name").iterator().next();
output.print("Hello, " + name + "!");
output.flush();
Expand Down
Expand Up @@ -28,7 +28,7 @@ public class AdminEnvironmentTest {
public void addsATaskServlet() throws Exception {
final Task task = new Task("thing") {
@Override
public void execute(ImmutableMultimap<String, String> parameters, String body, PrintWriter output) throws Exception {
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception {
}
};
env.addTask(task);
Expand Down
Expand Up @@ -32,7 +32,7 @@ public GarbageCollectionTask(Runtime runtime) {

@Override
@SuppressWarnings("CallToSystemGC")
public void execute(ImmutableMultimap<String, String> parameters, String body, PrintWriter output) {
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) {
final int count = parseRuns(parameters);
for (int i = 0; i < count; i++) {
output.println("Running GC...");
Expand Down
Expand Up @@ -52,7 +52,7 @@ public LogConfigurationTask(LoggerContext loggerContext) {
}

@Override
public void execute(ImmutableMultimap<String, String> parameters, String body, PrintWriter output) throws Exception {
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception {
final List<String> loggerNames = getLoggerNames(parameters);
final Level loggerLevel = getLoggerLevel(parameters);

Expand Down
@@ -0,0 +1,45 @@
package io.dropwizard.servlets.tasks;

import com.google.common.collect.ImmutableMultimap;

import java.io.PrintWriter;

/**
* A task which can be performed via the admin interface and provides the post body of the request.
*
* @see Task
* @see TaskServlet
*/
public abstract class PostBodyTask extends Task {
/**
* Create a new task with the given name.
*
* @param name the task's name
*/
protected PostBodyTask(String name) {
super(name);
}

/**
* @param parameters the query string parameters
* @param body the plain text request body
* @param output a {@link PrintWriter} wrapping the output stream of the task
* @throws Exception
*/
public abstract void execute(ImmutableMultimap<String, String> parameters,
String body,
PrintWriter output) throws Exception;

/**
* Deprecated, use `execute(parameters, body, output)` or inherit from Task instead.
*
* @param parameters the query string parameters
* @param output a {@link PrintWriter} wrapping the output stream of the task
* @throws Exception
*/
@Override
@Deprecated
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception {
throw new UnsupportedOperationException("Use `execute(parameters, body, output)`");
}
}
Expand Up @@ -38,6 +38,5 @@ public String getName() {
* @throws Exception if something goes wrong
*/
public abstract void execute(ImmutableMultimap<String, String> parameters,
String body,
PrintWriter output) throws Exception;
}
Expand Up @@ -153,7 +153,12 @@ private TaskExecutor(Task task) {

public void executeTask(ImmutableMultimap<String, String> params, String body, PrintWriter output) throws Exception {
try {
task.execute(params, body, output);
if (task instanceof PostBodyTask) {
PostBodyTask postBodyTask = (PostBodyTask) task;
postBodyTask.execute(params, body, output);
} else {
task.execute(params, output);
}
} catch (Exception e) {
throw e;
}
Expand Down Expand Up @@ -214,7 +219,7 @@ private ExceptionMeteredTask(TaskExecutor underlying,
@Override
public void executeTask(ImmutableMultimap<String, String> params, String body, PrintWriter output) throws Exception {
try {
underlying.executeTask(params, body, output);
underlying.executeTask(params, body, output);
} catch (Exception e) {
if (exceptionMeter != null) {
if (exceptionClass.isAssignableFrom(e.getClass()) ||
Expand Down
Expand Up @@ -17,21 +17,21 @@ public class GarbageCollectionTaskTest {

@Test
public void runsOnceWithNoParameters() throws Exception {
task.execute(ImmutableMultimap.of(), "", output);
task.execute(ImmutableMultimap.of(), output);

verify(runtime, times(1)).gc();
}

@Test
public void usesTheFirstRunsParameter() throws Exception {
task.execute(ImmutableMultimap.of("runs", "3", "runs", "2"), "", output);
task.execute(ImmutableMultimap.of("runs", "3", "runs", "2"), output);

verify(runtime, times(3)).gc();
}

@Test
public void defaultsToOneRunIfTheQueryParamDoesNotParse() throws Exception {
task.execute(ImmutableMultimap.of("runs", "$"), "", output);
task.execute(ImmutableMultimap.of("runs", "$"), output);

verify(runtime, times(1)).gc();
}
Expand Down
Expand Up @@ -39,7 +39,7 @@ public void configuresSpecificLevelForALogger() throws Exception {
"level", "debug");

// when
task.execute(parameters, "", output);
task.execute(parameters, output);

// then
assertThat(logger1.getLevel()).isEqualTo(Level.DEBUG);
Expand All @@ -55,7 +55,7 @@ public void configuresDefaultLevelForALogger() throws Exception {
"logger", "logger.one");

// when
task.execute(parameters, "", output);
task.execute(parameters, output);

// then
assertThat(logger1.getLevel()).isNull();
Expand All @@ -73,7 +73,7 @@ public void configuresLevelForMultipleLoggers() throws Exception {
"level", "INFO");

// when
task.execute(parameters, "", output);
task.execute(parameters, output);

// then
assertThat(logger1.getLevel()).isEqualTo(Level.INFO);
Expand Down
@@ -0,0 +1,20 @@
package io.dropwizard.servlets.tasks;

import com.google.common.collect.ImmutableMultimap;
import org.junit.Test;

import java.io.PrintWriter;

public class PostBodyTaskTest {
private final PostBodyTask task = new PostBodyTask("test") {
@Override
public void execute(ImmutableMultimap<String, String> parameters, String body, PrintWriter output) throws Exception {

}
};

@Test(expected = UnsupportedOperationException.class)
public void throwsExceptionWhenCallingExecuteWithoutThePostBody() throws Exception {
task.execute(new ImmutableMultimap.Builder<String, String>().build(), new PrintWriter(System.out));
}
}
Expand Up @@ -18,7 +18,6 @@
import java.nio.charset.StandardCharsets;
import java.util.Collections;

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
Expand All @@ -27,11 +26,11 @@

public class TaskServletTest {
private final Task gc = mock(Task.class);
private final Task clearCache = mock(Task.class);
private final PostBodyTask printJSON = mock(PostBodyTask.class);

{
when(gc.getName()).thenReturn("gc");
when(clearCache.getName()).thenReturn("clear-cache");
when(printJSON.getName()).thenReturn("print-json");
}

private final TaskServlet servlet = new TaskServlet(new MetricRegistry());
Expand All @@ -41,7 +40,7 @@ public class TaskServletTest {
@Before
public void setUp() throws Exception {
servlet.add(gc);
servlet.add(clearCache);
servlet.add(printJSON);
}

@Test
Expand All @@ -67,7 +66,7 @@ public void runsATaskWhenFound() throws Exception {

servlet.service(request, response);

verify(gc).execute(ImmutableMultimap.of(), "", output);
verify(gc).execute(ImmutableMultimap.of(), output);
}

@Test
Expand All @@ -84,24 +83,24 @@ public void passesQueryStringParamsAlong() throws Exception {

servlet.service(request, response);

verify(gc).execute(ImmutableMultimap.of("runs", "1"), "", output);
verify(gc).execute(ImmutableMultimap.of("runs", "1"), output);
}

@Test
public void passesPostBodyAlong() throws Exception {
public void passesPostBodyAlongToPostBodyTasks() throws Exception {
String body = "{\"json\": true}";
final PrintWriter output = mock(PrintWriter.class);
final ServletInputStream bodyStream = new TestServletInputStream(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));

when(request.getMethod()).thenReturn("POST");
when(request.getPathInfo()).thenReturn("/gc");
when(request.getPathInfo()).thenReturn("/print-json");
when(request.getParameterNames()).thenReturn(Collections.enumeration(ImmutableList.of()));
when(request.getInputStream()).thenReturn(bodyStream);
when(response.getWriter()).thenReturn(output);

servlet.service(request, response);

verify(gc).execute(ImmutableMultimap.of(), body, output);
verify(printJSON).execute(ImmutableMultimap.of(), body, output);
}

@Test
Expand All @@ -116,7 +115,7 @@ public void returnsA500OnExceptions() throws Exception {

final RuntimeException ex = new RuntimeException("whoops");

doThrow(ex).when(gc).execute(any(ImmutableMultimap.class), anyString(), any(PrintWriter.class));
doThrow(ex).when(gc).execute(any(ImmutableMultimap.class), any(PrintWriter.class));

servlet.service(request, response);

Expand All @@ -130,12 +129,21 @@ public void returnsA500OnExceptions() throws Exception {
@Test
public void verifyTaskExecuteMethod() {
try {
Task.class.getMethod("execute", ImmutableMultimap.class, String.class, PrintWriter.class);
Task.class.getMethod("execute", ImmutableMultimap.class, PrintWriter.class);
} catch (NoSuchMethodException e) {
Assert.fail("Execute method for " + Task.class.getName() + " not found");
}
}

@Test
public void verifyPostBodyTaskExecuteMethod() {
try {
PostBodyTask.class.getMethod("execute", ImmutableMultimap.class, String.class, PrintWriter.class);
} catch (NoSuchMethodException e) {
Assert.fail("Execute method for " + PostBodyTask.class.getName() + " not found");
}
}

private static class TestServletInputStream extends ServletInputStream {
private InputStream delegate;

Expand Down
Expand Up @@ -11,7 +11,6 @@ public class TaskTest {
private final Task task = new Task("test") {
@Override
public void execute(ImmutableMultimap<String, String> parameters,
String body,
PrintWriter output) throws Exception {

}
Expand Down
Expand Up @@ -5,6 +5,7 @@
import com.google.common.collect.ImmutableMultimap;
import io.dropwizard.Application;
import io.dropwizard.Configuration;
import io.dropwizard.servlets.tasks.PostBodyTask;
import io.dropwizard.servlets.tasks.Task;
import io.dropwizard.setup.Environment;
import org.hibernate.validator.constraints.NotEmpty;
Expand Down Expand Up @@ -76,11 +77,23 @@ public void canPerformAdminTask() {
assertThat(response, is("Hello has been said to test_user"));
}

@Test
public void canPerformAdminTaskWithPostBody() {
final String response
= ClientBuilder.newClient().target("http://localhost:"
+ TEST_SUPPORT.getAdminPort() + "/tasks/echo")
.request()
.post(Entity.entity("Custom message", MediaType.TEXT_PLAIN), String.class);

assertThat(response, is("Custom message"));
}

public static class TestApplication extends Application<TestConfiguration> {
@Override
public void run(TestConfiguration configuration, Environment environment) throws Exception {
environment.jersey().register(new TestResource(configuration.getMessage()));
environment.admin().addTask(new HelloTask());
environment.admin().addTask(new EchoTask());
}
}

Expand Down Expand Up @@ -121,11 +134,24 @@ public HelloTask() {
}

@Override
public void execute(ImmutableMultimap<String, String> parameters, String body, PrintWriter output) throws Exception {
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception {
ImmutableCollection<String> names = parameters.get("name");
String name = !names.isEmpty() ? names.asList().get(0) : "Anonymous";
output.print("Hello has been said to " + name);
output.flush();
}
}

public static class EchoTask extends PostBodyTask {

public EchoTask() {
super("echo");
}

@Override
public void execute(ImmutableMultimap<String, String> parameters, String body, PrintWriter output) throws Exception {
output.print(body);
output.flush();
}
}
}

0 comments on commit ad4ed8e

Please sign in to comment.