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

The following examples show how to use com.thoughtworks.go.plugin.api.request.GoApiRequest. 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
Source File: EmailNotificationPluginImplUnitTest.java    From email-notifier with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: EmailNotificationPluginImplUnitTest.java    From email-notifier with Apache License 2.0 6 votes vote down vote up
@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
Source File: YamlConfigPluginIntegrationTest.java    From gocd-yaml-config-plugin with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: PluginSettingsRequestProcessor.java    From gocd with 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 #5
Source File: ConsoleLogRequestProcessor.java    From gocd with 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 #6
Source File: ServerHealthRequestProcessor.java    From gocd with 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 #7
Source File: PluginAwareDefaultGoApplicationAccessorTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: StashBuildStatusNotifierPluginTest.java    From gocd-build-status-notifier with Apache License 2.0 5 votes vote down vote up
@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 #9
Source File: ConsoleLoggerTest.java    From docker-registry-artifact-plugin with Apache License 2.0 5 votes vote down vote up
@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
Source File: LogNotificationPluginImpl.java    From go-plugins with 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 #11
Source File: SampleAuthenticationPluginImpl.java    From go-plugins with 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 #12
Source File: SampleAuthenticationPluginImpl.java    From go-plugins with 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 #13
Source File: PluginAwareDefaultGoApplicationAccessor.java    From gocd with Apache License 2.0 5 votes vote down vote up
@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 #14
Source File: AuthorizationRequestProcessorTest.java    From gocd with 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 #15
Source File: ServerInfoRequestProcessor.java    From gocd with 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()));
    }
}
 
Example #16
Source File: AuthorizationRequestProcessor.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public GoApiResponse process(GoPluginDescriptor pluginDescriptor, GoApiRequest request) {

    validatePluginRequest(request);
    switch (Request.fromString(request.api())) {
        case INVALIDATE_CACHE_REQUEST:
            return processInvalidateCacheRequest(pluginDescriptor);
        default:
            return DefaultGoApiResponse.error("Illegal api request");
    }
}
 
Example #17
Source File: ElasticAgentRequestProcessorV1.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public GoApiResponse process(final GoPluginDescriptor pluginDescriptor, GoApiRequest goPluginApiRequest) {
    switch (goPluginApiRequest.api()) {
        case REQUEST_DISABLE_AGENTS:
            return processDisableAgent(pluginDescriptor, goPluginApiRequest);
        case REQUEST_DELETE_AGENTS:
            return processDeleteAgent(pluginDescriptor, goPluginApiRequest);
        case REQUEST_SERVER_LIST_AGENTS:
            return processListAgents(pluginDescriptor, goPluginApiRequest);
        default:
            return DefaultGoApiResponse.error("Illegal api request");
    }
}
 
Example #18
Source File: ElasticAgentRequestProcessorV1.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public GoApiResponse processDisableAgent(GoPluginDescriptor pluginDescriptor, GoApiRequest goPluginApiRequest) {
    Collection<AgentMetadata> agentsToDisable = elasticAgentProcessorConverterV1.deleteAndDisableAgentRequestBody(goPluginApiRequest.requestBody());
    final String pluginId = pluginDescriptor.id();
    disableAgents(pluginId, agentsToDisable);
    return new DefaultGoApiResponse(200);
}
 
Example #19
Source File: ArtifactRequestProcessor.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public GoApiResponse process(GoPluginDescriptor pluginDescriptor, GoApiRequest request) {
    validatePluginRequest(request);
    switch (Request.fromString(request.api())) {
        case CONSOLE_LOG:
            return processConsoleLogRequest(pluginDescriptor, request);
        default:
            return DefaultGoApiResponse.error("Illegal api request");
    }
}
 
Example #20
Source File: ArtifactRequestProcessor.java    From gocd with Apache License 2.0 5 votes vote down vote up
private GoApiResponse processConsoleLogRequest(GoPluginDescriptor pluginDescriptor, GoApiRequest request) {
    final ConsoleLogMessage consoleLogMessage = ConsoleLogMessage.fromJSON(request.requestBody());
    final String message = format("[%s] %s", pluginDescriptor.id(), consoleLogMessage.getMessage());
    Optional<String> parsedTag = parseTag(processType, consoleLogMessage.getLogLevel());
    if (parsedTag.isPresent()) {
        safeOutputStreamConsumer.taggedStdOutput(parsedTag.get(), message);
        return DefaultGoApiResponse.success(null);
    }
    return DefaultGoApiResponse.error(format("Unsupported log level `%s`.", consoleLogMessage.getLogLevel()));
}
 
Example #21
Source File: ArtifactRequestProcessorTestBase.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    request = mock(GoApiRequest.class);
    descriptor = mock(GoPluginDescriptor.class);
    goPublisher = mock(DefaultGoPublisher.class);
    EnvironmentVariableContext environmentVariableContext = mock(EnvironmentVariableContext.class);
    when(environmentVariableContext.secrets()).thenReturn(Collections.singletonList(new PasswordArgument("secret.value")));

    artifactRequestProcessorForPublish = ArtifactRequestProcessor.forPublishArtifact(goPublisher, environmentVariableContext);
    artifactRequestProcessorForFetch = ArtifactRequestProcessor.forFetchArtifact(goPublisher, environmentVariableContext);

    when(request.apiVersion()).thenReturn(getRequestPluginVersion());
    when(descriptor.id()).thenReturn("cd.go.artifact.docker");
    when(request.api()).thenReturn(CONSOLE_LOG.requestName());
}
 
Example #22
Source File: OAuthLoginPlugin.java    From gocd-oauth-login with 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 #23
Source File: ConsoleLoggerTest.java    From docker-registry-artifact-plugin with Apache License 2.0 5 votes vote down vote up
@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 #24
Source File: ConsoleLoggerTest.java    From docker-registry-artifact-plugin with Apache License 2.0 5 votes vote down vote up
@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 #25
Source File: YamlConfigPlugin.java    From gocd-yaml-config-plugin with 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 #26
Source File: YamlConfigPluginIntegrationTest.java    From gocd-yaml-config-plugin with Apache License 2.0 5 votes vote down vote up
@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 #27
Source File: YamlConfigPluginIntegrationTest.java    From gocd-yaml-config-plugin with Apache License 2.0 5 votes vote down vote up
@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 #28
Source File: BuildStatusNotifierPlugin.java    From gocd-build-status-notifier with 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 #29
Source File: OAuthLoginPlugin.java    From gocd-oauth-login with 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 #30
Source File: OAuthLoginPlugin.java    From gocd-oauth-login with 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
}