com.thoughtworks.go.plugin.api.response.GoApiResponse Java Examples

The following examples show how to use com.thoughtworks.go.plugin.api.response.GoApiResponse. 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: ConsoleLogRequestProcessorV2Test.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldRouteMessageToConsoleService() throws IOException, IllegalArtifactLocationException {
    Map<String, String> requestMap = new HashMap<>();
    requestMap.put("pipeline_name", "p1");
    requestMap.put("pipeline_counter", "1");
    requestMap.put("stage_name", "s1");
    requestMap.put("stage_counter", "2");
    requestMap.put("job_name", "j1");
    requestMap.put("text", "message1");

    DefaultGoApiRequest goApiRequest = new DefaultGoApiRequest(APPEND_TO_CONSOLE_LOG, VERSION_2, null);
    goApiRequest.setRequestBody(new GsonBuilder().create().toJson(requestMap));

    final ConsoleLogRequestProcessor processor = new ConsoleLogRequestProcessor(pluginRequestProcessorRegistry, consoleService);
    final GoApiResponse response = processor.process(pluginDescriptor, goApiRequest);

    assertThat(response.responseCode(), is(DefaultGoApiResponse.SUCCESS_RESPONSE_CODE));

    final JobIdentifier jobIdentifier = new JobIdentifier("p1", 1, null, "s1", "2", "j1");
    verify(consoleService).appendToConsoleLog(jobIdentifier, "message1");
}
 
Example #2
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 #3
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 #4
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 #5
Source File: ServerHealthRequestProcessorTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddDeserializedServerHealthMessages() {
    String requestBody = new Gson().toJson(asList(
            new PluginHealthMessage("warning", "message 1"),
            new PluginHealthMessage("error", "message 2")
    ));

    GoApiResponse response = processor.process(descriptor, createRequest("1.0", requestBody));
    assertThat(response.responseCode()).isEqualTo(SUCCESS_RESPONSE_CODE);

    ArgumentCaptor<ServerHealthState> argumentCaptor = ArgumentCaptor.forClass(ServerHealthState.class);
    InOrder inOrder = inOrder(serverHealthService);
    inOrder.verify(serverHealthService, times(1)).removeByScope(HealthStateScope.fromPlugin(PLUGIN_ID));
    inOrder.verify(serverHealthService, times(2)).update(argumentCaptor.capture());

    assertThat(argumentCaptor.getAllValues().get(0).getDescription()).isEqualTo("message 1");
    assertThat(argumentCaptor.getAllValues().get(1).getDescription()).isEqualTo("message 2");
}
 
Example #6
Source File: PluginRequest.java    From kubernetes-elastic-agents with Apache License 2.0 6 votes vote down vote up
public void appendToConsoleLog(JobIdentifier jobIdentifier, String text) throws ServerRequestFailedException {
    Map<String, String> requestMap = new HashMap<>();
    requestMap.put("pipelineName", jobIdentifier.getPipelineName());
    requestMap.put("pipelineCounter", String.valueOf(jobIdentifier.getPipelineCounter()));
    requestMap.put("stageName", jobIdentifier.getStageName());
    requestMap.put("stageCounter", jobIdentifier.getStageCounter());
    requestMap.put("jobName", jobIdentifier.getJobName());
    requestMap.put("text", text);

    DefaultGoApiRequest request = new DefaultGoApiRequest(Constants.REQUEST_SERVER_APPEND_TO_CONSOLE_LOG, CONSOLE_LOG_API_VERSION, PLUGIN_IDENTIFIER);
    request.setRequestBody(new GsonBuilder().create().toJson(requestMap));

    GoApiResponse response = accessor.submit(request);

    if (response.responseCode() != 200) {
        LOG.error("Failed to append to console log for " + jobIdentifier.getRepresentation() + " with text: " + text);
    }
}
 
Example #7
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 #8
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 #9
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 #10
Source File: PluginRequest.java    From docker-elastic-agents-plugin with Apache License 2.0 6 votes vote down vote up
public void appendToConsoleLog(JobIdentifier jobIdentifier, String text) throws ServerRequestFailedException {
    Map<String, String> requestMap = new HashMap<>();
    requestMap.put("pipelineName", jobIdentifier.getPipelineName());
    requestMap.put("pipelineCounter", String.valueOf(jobIdentifier.getPipelineCounter()));
    requestMap.put("stageName", jobIdentifier.getStageName());
    requestMap.put("stageCounter", jobIdentifier.getStageCounter());
    requestMap.put("jobName", jobIdentifier.getJobName());
    requestMap.put("text", text);

    DefaultGoApiRequest request = new DefaultGoApiRequest(Constants.REQUEST_SERVER_APPEND_TO_CONSOLE_LOG, CONSOLE_LOG_API_VERSION, PLUGIN_IDENTIFIER);
    request.setRequestBody(new GsonBuilder().create().toJson(requestMap));

    GoApiResponse response = accessor.submit(request);

    if (response.responseCode() != 200) {
        LOG.error("Failed to append to console log for " + jobIdentifier.represent() + " with text: " + text);
    }
}
 
Example #11
Source File: LogNotificationPluginImplTest.java    From go-plugins with Apache License 2.0 6 votes vote down vote up
private GoApiResponse getGoApiResponse(final String responseBody) {
    return new GoApiResponse() {
        @Override
        public int responseCode() {
            return 0;
        }

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

        @Override
        public String responseBody() {
            return responseBody;
        }
    };
}
 
Example #12
Source File: ConsoleLogRequestProcessorV1Test.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldRouteMessageToConsoleService() throws IOException, IllegalArtifactLocationException {
    Map<String, String> requestMap = new HashMap<>();
    requestMap.put("pipelineName", "p1");
    requestMap.put("pipelineCounter", "1");
    requestMap.put("stageName", "s1");
    requestMap.put("stageCounter", "2");
    requestMap.put("jobName", "j1");
    requestMap.put("text", "message1");

    DefaultGoApiRequest goApiRequest = new DefaultGoApiRequest(APPEND_TO_CONSOLE_LOG, VERSION_1, null);
    goApiRequest.setRequestBody(new GsonBuilder().create().toJson(requestMap));

    final ConsoleLogRequestProcessor processor = new ConsoleLogRequestProcessor(pluginRequestProcessorRegistry, consoleService);
    final GoApiResponse response = processor.process(pluginDescriptor, goApiRequest);

    assertThat(response.responseCode(), is(DefaultGoApiResponse.SUCCESS_RESPONSE_CODE));

    final JobIdentifier jobIdentifier = new JobIdentifier("p1", 1, null, "s1", "2", "j1");
    verify(consoleService).appendToConsoleLog(jobIdentifier, "message1");
}
 
Example #13
Source File: PluginSettingsRequestProcessorTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetPluginSettingsForPluginThatExistsInDB() {
    String PLUGIN_ID = "plugin-foo-id";

    when(pluginDescriptor.id()).thenReturn(PLUGIN_ID);
    when(pluginSqlMapDao.findPlugin(PLUGIN_ID)).thenReturn(new Plugin(PLUGIN_ID, "{\"k1\": \"v1\",\"k2\": \"v2\"}"));

    DefaultGoApiRequest apiRequest = new DefaultGoApiRequest(PluginSettingsRequestProcessor.GET_PLUGIN_SETTINGS, "1.0", new GoPluginIdentifier("extension1", Collections.singletonList("1.0")));
    apiRequest.setRequestBody("expected-request");
    GoApiResponse response = processor.process(pluginDescriptor, apiRequest);

    assertThat(response.responseCode(), is(200));
    assertThat(response.responseBody(), is("{\"k1\":\"v1\",\"k2\":\"v2\"}"));
}
 
Example #14
Source File: EmailNotificationPluginImpl.java    From email-notifier with Apache License 2.0 5 votes vote down vote up
public PluginSettings getPluginSettings() {
    Map<String, Object> requestMap = new HashMap<>();
    requestMap.put("plugin-id", PLUGIN_ID);
    GoApiResponse response = goApplicationAccessor.submit(createGoApiRequest(GET_PLUGIN_SETTINGS, JSONUtils.toJSON(requestMap)));
    if (response.responseBody() == null || response.responseBody().trim().isEmpty()) {
        throw new RuntimeException("plugin is not configured. please provide plugin settings.");
    }
    Map<String, String> responseBodyMap = (Map<String, String>) JSONUtils.fromJSON(response.responseBody());
    return new PluginSettings(responseBodyMap.get(PLUGIN_SETTINGS_SMTP_HOST), Integer.parseInt(responseBodyMap.get(PLUGIN_SETTINGS_SMTP_PORT)),
            Boolean.parseBoolean(responseBodyMap.get(PLUGIN_SETTINGS_IS_TLS)), responseBodyMap.get(PLUGIN_SETTINGS_SENDER_EMAIL_ID),
            responseBodyMap.get(PLUGIN_SETTINGS_SMTP_USERNAME),
            responseBodyMap.get(PLUGIN_SETTINGS_SENDER_PASSWORD), responseBodyMap.get(PLUGIN_SETTINGS_RECEIVER_EMAIL_ID),
            responseBodyMap.get(PLUGIN_SETTINGS_FILTER));
}
 
Example #15
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
}
 
Example #16
Source File: ServerInfoRequestProcessorTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnAErrorResponseIfExtensionDoesNotSupportServerInfo() {
    DefaultGoApiRequest request = new DefaultGoApiRequest(GET_SERVER_INFO, "bad-version", new GoPluginIdentifier("foo", Arrays.asList("1.0")));

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

    assertThat(response.responseCode(), is(400));
}
 
Example #17
Source File: LogNotificationPluginImpl.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
private String getAppendValue(GoApiResponse response) {
    String appendValue = "";
    try {
        Map<String, String> responseBodyMap = new GsonBuilder().create().fromJson(response.responseBody(), Map.class);
        if (responseBodyMap.get("append_value") != null) {
            appendValue = responseBodyMap.get("append_value");
        }
    } catch (Exception e) {
        // ignore
    }
    return appendValue;
}
 
Example #18
Source File: OAuthLoginPlugin.java    From gocd-oauth-login with 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 #19
Source File: BuildStatusNotifierPlugin.java    From gocd-build-status-notifier with Apache License 2.0 5 votes vote down vote up
public PluginSettings getPluginSettings() {
    Map<String, Object> requestMap = new HashMap<String, Object>();
    requestMap.put("plugin-id", provider.pluginId());
    GoApiResponse response = goApplicationAccessor.submit(createGoApiRequest(GET_PLUGIN_SETTINGS, JSONUtils.toJSON(requestMap)));
    Map<String, String> responseBodyMap = response.responseBody() == null ? new HashMap<String, String>() : (Map<String, String>) JSONUtils.fromJSON(response.responseBody());
    return provider.pluginSettings(responseBodyMap);
}
 
Example #20
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 #21
Source File: ServerInfoRequestProcessorTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnSuccessForServerInfoV2() {
    DefaultGoApiRequest request = new DefaultGoApiRequest(GET_SERVER_INFO, "2.0", new GoPluginIdentifier("extension1", Arrays.asList("1.0")));

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

    assertThat(response.responseCode(), is(200));
}
 
Example #22
Source File: ServerInfoRequestProcessorTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnAServerIdInJSONForm() {
    DefaultGoApiRequest request = new DefaultGoApiRequest(GET_SERVER_INFO, "1.0", new GoPluginIdentifier("extension1", Arrays.asList("1.0")));


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

    assertThat(response.responseCode(), is(200));
    assertThat(response.responseBody(),
            is(format("{\"server_id\":\"%s\",\"site_url\":\"%s\",\"secure_site_url\":\"%s\"}",
                    serverConfig.getServerId(), serverConfig.getSiteUrl().getUrl(), serverConfig.getSecureSiteUrl().getUrl())));
}
 
Example #23
Source File: LogNotificationPluginImpl.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
String getMessage(GoPluginApiRequest goPluginApiRequest) {
    Map<String, Object> dataMap = getMapFor(goPluginApiRequest);
    Map pipelineMap = (Map) dataMap.get("pipeline");
    Map stageMap = (Map) pipelineMap.get("stage");
    String pipelineName = (String) pipelineMap.get("name");
    String pipelineCounter = (String) pipelineMap.get("counter");
    String stageName = (String) stageMap.get("name");
    String stageCounter = (String) stageMap.get("counter");
    String stageState = (String) stageMap.get("state");
    String stageResult = (String) stageMap.get("result");

    GoApiResponse response = goApplicationAccessor.submit(getGoApiRequest(GET_PLUGIN_SETTINGS, requestWithPluginId()));

    return String.format("[%s|%s|%s|%s|%s|%s|%s]", pipelineName, pipelineCounter, stageName, stageCounter, stageState, stageResult, getAppendValue(response));
}
 
Example #24
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 #25
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 #26
Source File: OAuthLoginPlugin.java    From gocd-oauth-login with Apache License 2.0 5 votes vote down vote up
public PluginSettings getPluginSettings() {
    Map<String, Object> requestMap = new HashMap<String, Object>();
    requestMap.put("plugin-id", provider.getPluginId());
    GoApiResponse response = goApplicationAccessor.submit(createGoApiRequest(GET_PLUGIN_SETTINGS, JSONUtils.toJSON(requestMap)));
    if (response.responseBody() == null || response.responseBody().trim().isEmpty()) {
        throw new RuntimeException("plugin is not configured. please provide plugin settings.");
    }
    return provider.pluginSettings((Map<String, String>) JSONUtils.fromJSON(response.responseBody()));
}
 
Example #27
Source File: ServerHealthRequestProcessorTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRespondWithAFailedResponseCodeAndMessageIfSomethingGoesWrong() {
    GoApiResponse response = processor.process(descriptor, createRequest("1.0", "INVALID_JSON"));

    assertThat(response.responseCode()).isEqualTo(INTERNAL_ERROR);
    assertThat(new Gson().fromJson(response.responseBody(), Map.class)).isEqualTo(m("message", "Failed to deserialize message from plugin: INVALID_JSON"));
}
 
Example #28
Source File: PluginRequest.java    From docker-elastic-agents-plugin with Apache License 2.0 5 votes vote down vote up
public void deleteAgents(Collection<Agent> toBeDeleted) throws ServerRequestFailedException {
    if (toBeDeleted.isEmpty()) {
        return;
    }

    DefaultGoApiRequest request = new DefaultGoApiRequest(Constants.REQUEST_SERVER_DELETE_AGENT, PROCESSOR_API_VERSION, PLUGIN_IDENTIFIER);
    request.setRequestBody(Agent.toJSONArray(toBeDeleted));
    GoApiResponse response = accessor.submit(request);

    if (response.responseCode() != 200) {
        throw ServerRequestFailedException.deleteAgents(response);
    }
}
 
Example #29
Source File: PluginRequest.java    From docker-elastic-agents-plugin with Apache License 2.0 5 votes vote down vote up
public void disableAgents(Collection<Agent> toBeDisabled) throws ServerRequestFailedException {
    if (toBeDisabled.isEmpty()) {
        return;
    }

    DefaultGoApiRequest request = new DefaultGoApiRequest(Constants.REQUEST_SERVER_DISABLE_AGENT, PROCESSOR_API_VERSION, PLUGIN_IDENTIFIER);
    request.setRequestBody(Agent.toJSONArray(toBeDisabled));

    GoApiResponse response = accessor.submit(request);

    if (response.responseCode() != 200) {
        throw ServerRequestFailedException.disableAgents(response);
    }
}
 
Example #30
Source File: PluginRequest.java    From docker-elastic-agents-plugin with Apache License 2.0 5 votes vote down vote up
public Agents listAgents() throws ServerRequestFailedException {
    DefaultGoApiRequest request = new DefaultGoApiRequest(Constants.REQUEST_SERVER_LIST_AGENTS, PROCESSOR_API_VERSION, PLUGIN_IDENTIFIER);
    GoApiResponse response = accessor.submit(request);

    if (response.responseCode() != 200) {
        throw ServerRequestFailedException.listAgents(response);
    }

    return new Agents(Agent.fromJSONArray(response.responseBody()));
}