Java Code Examples for com.thoughtworks.go.plugin.api.request.GoApiRequest

The following examples show how to use com.thoughtworks.go.plugin.api.request.GoApiRequest. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void shouldContainValidFieldsInResponseMessage() throws UnhandledRequestTypeException {
    GoApiResponse settingsResponse = DefaultGoApiResponse.success("{}");
    when(goAccessor.submit(any(GoApiRequest.class))).thenReturn(settingsResponse);

    GoPluginApiResponse response = parseAndGetResponseForDir(tempDir.getRoot());

    assertThat(response.responseCode(), is(SUCCESS_RESPONSE_CODE));
    final JsonParser parser = new JsonParser();
    JsonElement responseObj = parser.parse(response.responseBody());
    assertTrue(responseObj.isJsonObject());
    JsonObject obj = responseObj.getAsJsonObject();
    assertTrue(obj.has("errors"));
    assertTrue(obj.has("pipelines"));
    assertTrue(obj.has("environments"));
    assertTrue(obj.has("target_version"));
}
 
Example 2
@Test
public void testASingleEmailAddressSendsEmail() throws Exception {
    settingsResponseMap.put("receiver_email_id", "[email protected]");

    GoApiResponse settingsResponse = testSettingsResponse();

    when(goApplicationAccessor.submit(any(GoApiRequest.class))).thenReturn(settingsResponse);
    doCallRealMethod().when(mockSession).createMessage(anyString(), anyString(), anyString(), anyString());

    GoPluginApiRequest requestFromServer = testStageChangeRequestFromServer();

    emailNotificationPlugin.handle(requestFromServer);

    verify(mockTransport).sendMessage(any(Message.class), eq(new Address[]{new InternetAddress("[email protected]")}));
    verify(mockTransport, times(1)).connect(eq("test-smtp-host"), eq(25), eq("test-smtp-username"), eq("test-smtp-password"));
    verify(mockTransport, times(1)).close();
    verifyNoMoreInteractions(mockTransport);
}
 
Example 3
@Test
public void testMultipleEmailAddressSendsEmail() throws Exception {
    settingsResponseMap.put("receiver_email_id", "[email protected], [email protected]");

    GoApiResponse settingsResponse = testSettingsResponse();

    when(goApplicationAccessor.submit(any(GoApiRequest.class))).thenReturn(settingsResponse);
    doCallRealMethod().when(mockSession).createMessage(anyString(), anyString(), anyString(), anyString());

    GoPluginApiRequest requestFromServer = testStageChangeRequestFromServer();

    emailNotificationPlugin.handle(requestFromServer);

    verify(mockTransport).sendMessage(any(Message.class), eq(new Address[]{new InternetAddress("[email protected]")}));
    verify(mockTransport).sendMessage(any(Message.class), eq(new Address[]{new InternetAddress("[email protected]")}));
    verify(mockTransport, times(2)).connect(eq("test-smtp-host"), eq(25), eq("test-smtp-username"), eq("test-smtp-password"));
    verify(mockTransport, times(2)).close();
    verifyNoMoreInteractions(mockTransport);
}
 
Example 4
@Test
void shouldHandleExceptionThrownByProcessor() {
    String api = "api-uri";
    GoPluginApiRequestProcessor processor = mock(GoPluginApiRequestProcessor.class);
    GoApiRequest goApiRequest = mock(GoApiRequest.class);
    GoPluginDescriptor descriptor = mock(GoPluginDescriptor.class);
    when(goApiRequest.api()).thenReturn(api);
    Throwable cause = new RuntimeException("error");
    when(processor.process(descriptor, goApiRequest)).thenThrow(cause);

    PluginRequestProcessorRegistry pluginRequestProcessorRegistry = new PluginRequestProcessorRegistry();
    pluginRequestProcessorRegistry.registerProcessorFor(api, processor);
    PluginAwareDefaultGoApplicationAccessor accessor = new PluginAwareDefaultGoApplicationAccessor(descriptor, pluginRequestProcessorRegistry);

    assertThatCode(() -> accessor.submit(goApiRequest))
            .hasMessage(String.format("Error while processing request api %s", api))
            .hasCause(cause);
}
 
Example 5
Source Project: gocd   Source File: ServerHealthRequestProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public GoApiResponse process(GoPluginDescriptor pluginDescriptor, GoApiRequest goPluginApiRequest) {
    String errorMessageTitle = format("Message from plugin: {0}", pluginDescriptor.id());
    HealthStateScope scope = HealthStateScope.fromPlugin(pluginDescriptor.id());

    try {
        MessageHandlerForServerHealthRequestProcessor messageHandler = versionToMessageHandlerMap.get(goPluginApiRequest.apiVersion());
        List<PluginHealthMessage> pluginHealthMessages = messageHandler.deserializeServerHealthMessages(goPluginApiRequest.requestBody());
        replaceServerHealthMessages(errorMessageTitle, scope, pluginHealthMessages);
    } catch (Exception e) {
        DefaultGoApiResponse response = new DefaultGoApiResponse(DefaultGoApiResponse.INTERNAL_ERROR);
        response.setResponseBody(format("'{' \"message\": \"{0}\" '}'", e.getMessage()));
        LOGGER.warn("Failed to handle message from plugin {}: {}", pluginDescriptor.id(), goPluginApiRequest.requestBody(), e);
        return response;
    }

    return new DefaultGoApiResponse(DefaultGoApiResponse.SUCCESS_RESPONSE_CODE);
}
 
Example 6
Source Project: gocd   Source File: ConsoleLogRequestProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public GoApiResponse process(GoPluginDescriptor pluginDescriptor, GoApiRequest request) {
    try {
        validatePluginRequest(request);

        final MessageHandlerForConsoleLogRequestProcessor handler = versionToMessageHandlerMap.get(request.apiVersion());
        final ConsoleLogAppendRequest logUpdateRequest = handler.deserializeConsoleLogAppendRequest(request.requestBody());
        consoleService.appendToConsoleLog(logUpdateRequest.jobIdentifier(), logUpdateRequest.text());
    } catch (Exception e) {
        DefaultGoApiResponse response = new DefaultGoApiResponse(DefaultGoApiResponse.INTERNAL_ERROR);
        response.setResponseBody(format("'{' \"message\": \"Error: {0}\" '}'", e.getMessage()));
        LOGGER.warn("Failed to handle message from plugin {}: {}", pluginDescriptor.id(), request.requestBody(), e);
        return response;
    }

    return new DefaultGoApiResponse(DefaultGoApiResponse.SUCCESS_RESPONSE_CODE);
}
 
Example 7
Source Project: gocd   Source File: PluginSettingsRequestProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public GoApiResponse process(GoPluginDescriptor pluginDescriptor, GoApiRequest goPluginApiRequest) {
    try {
        MessageHandlerForPluginSettingsRequestProcessor processor = versionToMessageHandlerMap.get(goPluginApiRequest.apiVersion());

        DefaultGoApiResponse response = new DefaultGoApiResponse(200);
        response.setResponseBody(processor.pluginSettingsToJSON(pluginSettingsFor(pluginDescriptor.id())));

        return response;
    } catch (Exception e) {
        LOGGER.error(format("Error processing PluginSettings request from plugin: %s.", pluginDescriptor.id()), e);

        DefaultGoApiResponse errorResponse = new DefaultGoApiResponse(400);
        errorResponse.setResponseBody(format("Error while processing get PluginSettings request - %s", e.getMessage()));

        return errorResponse;
    }
}
 
Example 8
@BeforeClass
public static void setUp() {
    accessor = mock(GoApplicationAccessor.class);
    argumentCaptor = ArgumentCaptor.forClass(GoApiRequest.class);

    consoleLogger = ConsoleLogger.getLogger(accessor);

    when(accessor.submit(argumentCaptor.capture())).thenReturn(DefaultGoApiResponse.success(null));
}
 
Example 9
@Test
public void shouldLogInfoMessageToConsoleLog() throws JSONException {
    consoleLogger.info("This is info message.");

    final GoApiRequest request = argumentCaptor.getValue();
    assertThat(request.api()).isEqualTo(Constants.SEND_CONSOLE_LOG);
    assertThat(request.apiVersion()).isEqualTo(Constants.CONSOLE_LOG_PROCESSOR_API_VERSION);

    final String expectedJSON = "{\n" +
            "  \"logLevel\": \"INFO\",\n" +
            "  \"message\": \"This is info message.\"\n" +
            "}";

    JSONAssert.assertEquals(expectedJSON, request.requestBody(), true);
}
 
Example 10
@Test
public void shouldLogErrorMessageToConsoleLog() throws JSONException {
    consoleLogger.error("This is error.");

    final GoApiRequest request = argumentCaptor.getValue();
    assertThat(request.api()).isEqualTo(Constants.SEND_CONSOLE_LOG);
    assertThat(request.apiVersion()).isEqualTo(Constants.CONSOLE_LOG_PROCESSOR_API_VERSION);

    final String expectedJSON = "{\n" +
            "  \"logLevel\": \"ERROR\",\n" +
            "  \"message\": \"This is error.\"\n" +
            "}";

    JSONAssert.assertEquals(expectedJSON, request.requestBody(), true);
}
 
Example 11
Source Project: gocd-yaml-config-plugin   Source File: YamlConfigPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private GoApiRequest createGoApiRequest(final String api, final String responseBody) {
    return new GoApiRequest() {
        @Override
        public String api() {
            return api;
        }

        @Override
        public String apiVersion() {
            return "1.0";
        }

        @Override
        public GoPluginIdentifier pluginIdentifier() {
            return getGoPluginIdentifier();
        }

        @Override
        public Map<String, String> requestParameters() {
            return null;
        }

        @Override
        public Map<String, String> requestHeaders() {
            return null;
        }

        @Override
        public String requestBody() {
            return responseBody;
        }
    };
}
 
Example 12
@Before
public void setUp() {
    plugin = new YamlConfigPlugin();
    goAccessor = mock(GoApplicationAccessor.class);
    plugin.initializeGoApplicationAccessor(goAccessor);
    GoApiResponse settingsResponse = DefaultGoApiResponse.success("{}");
    when(goAccessor.submit(any(GoApiRequest.class))).thenReturn(settingsResponse);
    parser = new JsonParser();
}
 
Example 13
@Test
public void shouldRespondSuccessToParseDirectoryRequestWhenPluginHasConfiguration() throws UnhandledRequestTypeException {
    GoApiResponse settingsResponse = DefaultGoApiResponse.success("{}");
    when(goAccessor.submit(any(GoApiRequest.class))).thenReturn(settingsResponse);

    GoPluginApiResponse response = parseAndGetResponseForDir(tempDir.getRoot());

    verify(goAccessor, times(1)).submit(any(GoApiRequest.class));
    assertThat(response.responseCode(), is(SUCCESS_RESPONSE_CODE));
}
 
Example 14
Source Project: gocd-oauth-login   Source File: OAuthLoginPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private void  store(SocialAuthManager socialAuthManager) {
    Map<String, Object> requestMap = new HashMap<String, Object>();
    requestMap.put("plugin-id", provider.getPluginId());
    Map<String, Object> sessionData = new HashMap<String, Object>();
    String socialAuthManagerStr = serializeObject(socialAuthManager);
    sessionData.put("social-auth-manager", socialAuthManagerStr);
    requestMap.put("session-data", sessionData);
    GoApiRequest goApiRequest = createGoApiRequest(GO_REQUEST_SESSION_PUT, JSONUtils.toJSON(requestMap));
    GoApiResponse response = goApplicationAccessor.submit(goApiRequest);
    // handle error
}
 
Example 15
Source Project: gocd-oauth-login   Source File: OAuthLoginPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private SocialAuthManager read() {
    Map<String, Object> requestMap = new HashMap<String, Object>();
    requestMap.put("plugin-id", provider.getPluginId());
    GoApiRequest goApiRequest = createGoApiRequest(GO_REQUEST_SESSION_GET, JSONUtils.toJSON(requestMap));
    GoApiResponse response = goApplicationAccessor.submit(goApiRequest);
    // handle error
    String responseBody = response.responseBody();
    Map<String, String> sessionData = (Map<String, String>) JSONUtils.fromJSON(responseBody);
    String socialAuthManagerStr = sessionData.get("social-auth-manager");
    return deserializeObject(socialAuthManagerStr);
}
 
Example 16
Source Project: gocd-oauth-login   Source File: OAuthLoginPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private void delete() {
    Map<String, Object> requestMap = new HashMap<String, Object>();
    requestMap.put("plugin-id", provider.getPluginId());
    GoApiRequest goApiRequest = createGoApiRequest(GO_REQUEST_SESSION_REMOVE, JSONUtils.toJSON(requestMap));
    GoApiResponse response = goApplicationAccessor.submit(goApiRequest);
    // handle error
}
 
Example 17
Source Project: gocd-oauth-login   Source File: OAuthLoginPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private void authenticateUser(User user) {
    final Map<String, Object> userMap = new HashMap<String, Object>();
    userMap.put("user", getUserMap(user));
    GoApiRequest authenticateUserRequest = createGoApiRequest(GO_REQUEST_AUTHENTICATE_USER, JSONUtils.toJSON(userMap));
    GoApiResponse authenticateUserResponse = goApplicationAccessor.submit(authenticateUserRequest);
    // handle error
}
 
Example 18
Source Project: gocd-oauth-login   Source File: OAuthLoginPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private GoApiRequest createGoApiRequest(final String api, final String responseBody) {
    return new GoApiRequest() {
        @Override
        public String api() {
            return api;
        }

        @Override
        public String apiVersion() {
            return "1.0";
        }

        @Override
        public GoPluginIdentifier pluginIdentifier() {
            return getGoPluginIdentifier();
        }

        @Override
        public Map<String, String> requestParameters() {
            return null;
        }

        @Override
        public Map<String, String> requestHeaders() {
            return null;
        }

        @Override
        public String requestBody() {
            return responseBody;
        }
    };
}
 
Example 19
private GoApiRequest createGoApiRequest(final String api, final String responseBody) {
    return new GoApiRequest() {
        @Override
        public String api() {
            return api;
        }

        @Override
        public String apiVersion() {
            return "1.0";
        }

        @Override
        public GoPluginIdentifier pluginIdentifier() {
            return getGoPluginIdentifier();
        }

        @Override
        public Map<String, String> requestParameters() {
            return null;
        }

        @Override
        public Map<String, String> requestHeaders() {
            return null;
        }

        @Override
        public String requestBody() {
            return responseBody;
        }
    };
}
 
Example 20
private static GoApiRequest testSettingsRequest() {

        final Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("plugin-id", "email.notifier");

        final String responseBody = JSONUtils.toJSON(requestMap);

        return new GoApiRequest() {
            @Override
            public String api() {
                return "go.processor.plugin-settings.get";
            }

            @Override
            public String apiVersion() {
                return "1.0";
            }

            @Override
            public GoPluginIdentifier pluginIdentifier() {
                return new GoPluginIdentifier("notification", Collections.singletonList("1.0"));
            }

            @Override
            public Map<String, String> requestParameters() {
                return null;
            }

            @Override
            public Map<String, String> requestHeaders() {
                return null;
            }

            @Override
            public String requestBody() {
                return responseBody;
            }
        };
    }
 
Example 21
@Before
public void setUp() {
    initMocks(this);

    plugin = new GitHubBuildStatusNotifierPlugin();

    DefaultGoApiResponse pluginSettingsResponse = new DefaultGoApiResponse(200);
    pluginSettingsResponse.setResponseBody(JSONUtils.toJSON(new HashMap<String, String>()));
    when(goApplicationAccessor.submit(any(GoApiRequest.class))).thenReturn(pluginSettingsResponse);
    when(provider.pluginId()).thenReturn(PLUGIN_ID);
    when(provider.pollerPluginId()).thenReturn(POLLER_PLUGIN_ID);

    plugin.initializeGoApplicationAccessor(goApplicationAccessor);
    plugin.setProvider(provider);
}
 
Example 22
@Before
public void setUp() {
    initMocks(this);

    plugin = new GerritBuildStatusNotifierPlugin();

    DefaultGoApiResponse pluginSettingsResponse = new DefaultGoApiResponse(200);
    pluginSettingsResponse.setResponseBody(JSONUtils.toJSON(new HashMap<String, String>()));
    when(goApplicationAccessor.submit(any(GoApiRequest.class))).thenReturn(pluginSettingsResponse);
    when(provider.pluginId()).thenReturn(PLUGIN_ID);
    when(provider.pollerPluginId()).thenReturn(POLLER_PLUGIN_ID);

    plugin.initializeGoApplicationAccessor(goApplicationAccessor);
    plugin.setProvider(provider);
}
 
Example 23
private GoApiRequest createGoApiRequest(final String api, final String responseBody) {
    return new GoApiRequest() {
        @Override
        public String api() {
            return api;
        }

        @Override
        public String apiVersion() {
            return "1.0";
        }

        @Override
        public GoPluginIdentifier pluginIdentifier() {
            return getGoPluginIdentifier();
        }

        @Override
        public Map<String, String> requestParameters() {
            return null;
        }

        @Override
        public Map<String, String> requestHeaders() {
            return null;
        }

        @Override
        public String requestBody() {
            return responseBody;
        }
    };
}
 
Example 24
@Before
public void setUp() {
    initMocks(this);

    plugin = new StashBuildStatusNotifierPlugin();

    DefaultGoApiResponse pluginSettingsResponse = new DefaultGoApiResponse(200);
    pluginSettingsResponse.setResponseBody(JSONUtils.toJSON(new HashMap<String, String>()));
    when(goApplicationAccessor.submit(any(GoApiRequest.class))).thenReturn(pluginSettingsResponse);
    when(provider.pluginId()).thenReturn(PLUGIN_ID);
    when(provider.pollerPluginId()).thenReturn(POLLER_PLUGIN_ID);

    plugin.initializeGoApplicationAccessor(goApplicationAccessor);
    plugin.setProvider(provider);
}
 
Example 25
Source Project: go-plugins   Source File: LogNotificationPluginImpl.java    License: Apache License 2.0 5 votes vote down vote up
GoApiRequest getGoApiRequest(final String api, final String requestBody) {
    return new GoApiRequest() {
        @Override
        public String api() {
            return api;
        }

        @Override
        public String apiVersion() {
            return "1.0";
        }

        @Override
        public GoPluginIdentifier pluginIdentifier() {
            return getGoPluginIdentifier();
        }

        @Override
        public Map<String, String> requestParameters() {
            return null;
        }

        @Override
        public Map<String, String> requestHeaders() {
            return null;
        }

        @Override
        public String requestBody() {
            return requestBody;
        }
    };
}
 
Example 26
Source Project: go-plugins   Source File: SampleAuthenticationPluginImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void authenticateUser(String displayName, String fullName, String emailId) {
    Map<String, Object> userMap = new HashMap<String, Object>();
    userMap.put("user", getUserJSON(displayName, fullName, emailId));
    GoApiRequest authenticateUserRequest = createGoApiRequest("go.processor.authentication.authenticate-user", JSONUtils.toJSON(userMap));
    GoApiResponse authenticateUserResponse = goApplicationAccessor.submit(authenticateUserRequest);
    // handle error
}
 
Example 27
Source Project: go-plugins   Source File: SampleAuthenticationPluginImpl.java    License: Apache License 2.0 5 votes vote down vote up
private GoApiRequest createGoApiRequest(final String api, final String responseBody) {
    return new GoApiRequest() {
        @Override
        public String api() {
            return api;
        }

        @Override
        public String apiVersion() {
            return "1.0";
        }

        @Override
        public GoPluginIdentifier pluginIdentifier() {
            return getGoPluginIdentifier();
        }

        @Override
        public Map<String, String> requestParameters() {
            return null;
        }

        @Override
        public Map<String, String> requestHeaders() {
            return null;
        }

        @Override
        public String requestBody() {
            return responseBody;
        }
    };
}
 
Example 28
@Override
public GoApiResponse submit(final GoApiRequest request) {
    if (requestProcessorRegistry.canProcess(request)) {
        try {
            GoPluginApiRequestProcessor processor = requestProcessorRegistry.processorFor(request);
            return processor.process(pluginDescriptor, request);
        } catch (Exception e) {
            LOGGER.warn("Error while processing request api [{}]", request.api(), e);
            throw new RuntimeException(String.format("Error while processing request api %s", request.api()), e);
        }
    }
    LOGGER.warn("Plugin {} sent a request that could not be understood {} at version {}", request.pluginIdentifier().getExtension(), request.api(), request.apiVersion());
    return unhandledApiRequest();
}
 
Example 29
Source Project: gocd   Source File: AuthorizationRequestProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldProcessInvalidateCacheRequest() throws Exception {
    PluginRoleService pluginRoleService = mock(PluginRoleService.class);
    when(authorizationExtension.getMessageConverter(AuthorizationMessageConverterV1.VERSION)).thenReturn(new AuthorizationMessageConverterV1());

    GoApiRequest request = new DefaultGoApiRequest(INVALIDATE_CACHE_REQUEST.requestName(), "1.0", null);
    AuthorizationRequestProcessor authorizationRequestProcessor = new AuthorizationRequestProcessor(registry, pluginRoleService);

    GoApiResponse response = authorizationRequestProcessor.process(pluginDescriptor, request);

    assertThat(response.responseCode(), is(200));
    verify(pluginRoleService).invalidateRolesFor("cd.go.authorization.github");
}
 
Example 30
Source Project: gocd   Source File: ServerInfoRequestProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GoApiResponse process(GoPluginDescriptor pluginDescriptor, GoApiRequest goPluginApiRequest) {
    try {
        MessageHandlerForServerInfoRequestProcessor requestProcessor = this.versionToMessageHandlerMap.get(goPluginApiRequest.apiVersion());
        ServerConfig serverConfig = configService.serverConfig();

        String serverInfoJSON = requestProcessor.serverInfoToJSON(serverConfig);

        return DefaultGoApiResponse.success(serverInfoJSON);
    } catch (Exception e) {
        LOGGER.error(format("Error processing ServerInfo request from plugin: %s.", pluginDescriptor.id()), e);
        return DefaultGoApiResponse.badRequest(format("Error while processing get ServerInfo request - %s", e.getMessage()));
    }
}