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

The following examples show how to use com.thoughtworks.go.plugin.api.response.GoPluginApiResponse. 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: DockerComposeTask.java    From gocd-plugins with Apache License 2.0 6 votes vote down vote up
@Override
protected GoPluginApiResponse handleGetConfigRequest(GoPluginApiRequest request) {
    return success(new ConfigDef()
            .add(VMNAME, "", Required.YES)
            .add(SERVICE, "", Required.NO)
            .add(ENV_VARS, "", Required.NO)
            .add(COMPOSE_BUILD, "", Required.NO)
            .add(COMPOSE_FILE, "", Required.NO)
            .add(FORCE_RECREATE, "false", Required.NO)
            .add(FORCE_BUILD, "false", Required.NO)
            .add(COMPOSE_NO_CACHE, "false", Required.NO)
            .add(COMPOSE_REMOVE_VOLUMES, "false", Required.NO)
            .add(COMPOSE_DOWN, "false", Required.NO)
            .add(FORCE_PULL, "false", Required.NO)
            .add(FORCE_BUILD_ONLY, "false", Required.NO)
            .add(BUNDLE_OUTPUT_PATH, "", Required.NO)
            .toMap());
}
 
Example #2
Source File: GetLatestRevisionRequestHandlerTest.java    From gocd-git-path-material-plugin with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void shouldHandleApiRequestAndRenderSuccessApiResponse() {
    Revision revision = new Revision("1", new Date(), "comment", "user", "[email protected]", Collections.emptyList());
    RequestHandler checkoutRequestHandler = new GetLatestRevisionRequestHandler();
    ArgumentCaptor<Map> responseArgumentCaptor = ArgumentCaptor.forClass(Map.class);
    List<String> paths = List.of("path1", "path2");

    when(JsonUtils.renderSuccessApiResponse(responseArgumentCaptor.capture())).thenReturn(mock(GoPluginApiResponse.class));
    when(JsonUtils.getPaths(pluginApiRequestMock)).thenReturn(paths);
    when(gitConfigMock.getUrl()).thenReturn("https://github.com/TWChennai/gocd-git-path-material-plugin.git");
    when(jGitHelperMock.getLatestRevision(any())).thenReturn(revision);

    checkoutRequestHandler.handle(pluginApiRequestMock);

    verify(jGitHelperMock).cloneOrFetch();
    verify(jGitHelperMock).getLatestRevision(paths);

    Map<String, Object> responseMap = responseArgumentCaptor.getValue();
    assertThat(responseMap.size(), is(1));
}
 
Example #3
Source File: FetchArtifactExecutorTest.java    From docker-registry-artifact-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSetEnvironmentVariablesWithImageInformationInResponseRegardlessOfWhetherThePrefixIsProvided() {
    final ArtifactStoreConfig storeConfig = new ArtifactStoreConfig("localhost:5000", "other", "admin", "admin123");
    final HashMap<String, String> artifactMetadata = new HashMap<>();
    artifactMetadata.put("image", "localhost:5000/alpine:v1");
    artifactMetadata.put("digest", "foo");
    final FetchArtifactRequest fetchArtifactRequest = new FetchArtifactRequest(storeConfig, artifactMetadata, new FetchArtifactConfig());

    when(request.requestBody()).thenReturn(new Gson().toJson(fetchArtifactRequest));
    when(dockerProgressHandler.getDigest()).thenReturn("foo");

    final GoPluginApiResponse response = new FetchArtifactExecutor(request, consoleLogger, dockerProgressHandler, dockerClientFactory).execute();

    assertThat(response.responseCode()).isEqualTo(200);
    assertThat(response.responseBody()).isEqualTo("[{\"name\":\"ARTIFACT_IMAGE\",\"value\":\"localhost:5000/alpine:v1\"}]");
}
 
Example #4
Source File: AgentStatusReportExecutor.java    From kubernetes-elastic-agents with Apache License 2.0 6 votes vote down vote up
public GoPluginApiResponse execute() {
    String elasticAgentId = request.getElasticAgentId();
    JobIdentifier jobIdentifier = request.getJobIdentifier();
    LOG.info(format("[status-report] Generating status report for agent: {0} with job: {1}", elasticAgentId, jobIdentifier));
    KubernetesClient client = factory.client(request.clusterProfileProperties());

    try {
        Pod pod;
        if (StringUtils.isNotBlank(elasticAgentId)) {
            pod = findPodUsingElasticAgentId(elasticAgentId, client);
        } else {
            pod = findPodUsingJobIdentifier(jobIdentifier, client);
        }

        KubernetesElasticAgent elasticAgent = KubernetesElasticAgent.fromPod(client, pod, jobIdentifier);

        final String statusReportView = statusReportViewBuilder.build(statusReportViewBuilder.getTemplate("agent-status-report.template.ftlh"), elasticAgent);

        final JsonObject responseJSON = new JsonObject();
        responseJSON.addProperty("view", statusReportView);

        return DefaultGoPluginApiResponse.success(responseJSON.toString());
    } catch (Exception e) {
        return StatusReportGenerationErrorHandler.handle(statusReportViewBuilder, e);
    }
}
 
Example #5
Source File: AgentStatusReportExecutorTest.java    From kubernetes-elastic-agents with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnErrorWhenPodForSpecifiedJobIdentifierNotFound() throws Exception {
    when(client.pods()).thenThrow(new RuntimeException("Boom!")); //can not find pod for specified job identitier

    JobIdentifier jobIdentifier = new JobIdentifier("up42", 1L, "1", "up42_stage", "1", "job_name", 1L);
    when(statusReportRequest.getJobIdentifier()).thenReturn(jobIdentifier);
    when(statusReportRequest.getElasticAgentId()).thenReturn(null);

    ClusterProfileProperties clusterProfileProperties = new ClusterProfileProperties();

    when(statusReportRequest.clusterProfileProperties()).thenReturn(clusterProfileProperties);
    when(kubernetesClientFactory.client(clusterProfileProperties)).thenReturn(client);

    when(builder.getTemplate("error.template.ftlh")).thenReturn(template);
    when(builder.build(eq(template), any(StatusReportGenerationError.class))).thenReturn("my-error-view");

    GoPluginApiResponse response = executor.execute();

    assertThat(response.responseCode(), is(200));
    assertThat(response.responseBody(), is("{\"view\":\"my-error-view\"}"));
}
 
Example #6
Source File: PublishTask.java    From gocd-s3-artifacts with Apache License 2.0 6 votes vote down vote up
private GoPluginApiResponse handleGetConfigRequest() {
    HashMap config = new HashMap();

    HashMap sourceDestinations = new HashMap();
    sourceDestinations.put("default-value", "");
    sourceDestinations.put("required", true);
    config.put(SOURCEDESTINATIONS, sourceDestinations);

    HashMap destinationPrefix = new HashMap();
    destinationPrefix.put("default-value", "");
    destinationPrefix.put("required", false);
    config.put(DESTINATION_PREFIX, destinationPrefix);

    HashMap artifactsBucket = new HashMap();
    artifactsBucket.put("default-value", "");
    artifactsBucket.put("required", false);
    config.put(ARTIFACTS_BUCKET, artifactsBucket);

    return createResponse(DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE, config);
}
 
Example #7
Source File: PluginWithInvalidId.java    From go-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public GoPluginApiResponse handle(GoPluginApiRequest goPluginApiRequest) throws UnhandledRequestTypeException {
    return new GoPluginApiResponse() {
        @Override
        public int responseCode() {
            return 200;
        }

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

        @Override
        public String responseBody() {
            return "{}";
        }
    };
}
 
Example #8
Source File: SampleAuthenticationPluginImpl.java    From go-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public GoPluginApiResponse handle(GoPluginApiRequest goPluginApiRequest) {
    String requestName = goPluginApiRequest.requestName();
    if (requestName.equals(PLUGIN_CONFIGURATION)) {
        return handlePluginConfigurationRequest();
    } else if (requestName.equals(SEARCH_USER)) {
        return handleSearchUserRequest(goPluginApiRequest);
    } else if (requestName.equals(AUTHENTICATE_USER)) {
        return handleAuthenticateUserRequest(goPluginApiRequest);
    } else if (requestName.equals(WEB_REQUEST_INDEX)) {
        return handleSetupLoginWebRequest(goPluginApiRequest);
    } else if (requestName.equals(WEB_REQUEST_AUTHENTICATE)) {
        return handleAuthenticateWebRequest(goPluginApiRequest);
    }
    return renderResponse(404, null, null);
}
 
Example #9
Source File: ClusterProfileValidateRequestExecutor.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 6 votes vote down vote up
public GoPluginApiResponse execute() {
    final List<String> knownFields = new ArrayList<>();
    final ValidationResult validationResult = new ValidationResult();

    for (Metadata field : GetClusterProfileMetadataExecutor.FIELDS) {
        knownFields.add(field.getKey());
        validationResult.addError(field.validate(request.getProperties().get(field.getKey())));
    }
    final Set<String> set = new HashSet<>(request.getProperties().keySet());
    set.removeAll(knownFields);

    if (!set.isEmpty()) {
        for (String key : set) {
            validationResult.addError(key, "Is an unknown property.");
        }
    }
    List<Map<String, String>> validateErrors = new PrivateDockerRegistrySettingsValidator().validate(request);
    validateErrors.forEach(error -> validationResult.addError(new ValidationError(error.get("key"), error.get("message"))));
    return DefaultGoPluginApiResponse.success(validationResult.toJSON());
}
 
Example #10
Source File: BuildStatusNotifierPlugin.java    From gocd-build-status-notifier with Apache License 2.0 6 votes vote down vote up
@Override
public GoPluginApiResponse handle(GoPluginApiRequest goPluginApiRequest) {
    String requestName = goPluginApiRequest.requestName();
    if (requestName.equals(PLUGIN_SETTINGS_GET_CONFIGURATION)) {
        return handleGetPluginSettingsConfiguration();
    } else if (requestName.equals(PLUGIN_SETTINGS_GET_VIEW)) {
        try {
            return handleGetPluginSettingsView();
        } catch (IOException e) {
            return renderJSON(500, String.format("Failed to find template: %s", e.getMessage()));
        }
    } else if (requestName.equals(PLUGIN_SETTINGS_VALIDATE_CONFIGURATION)) {
        return handleValidatePluginSettingsConfiguration(goPluginApiRequest);
    } else if (requestName.equals(REQUEST_NOTIFICATIONS_INTERESTED_IN)) {
        return handleNotificationsInterestedIn();
    } else if (requestName.equals(REQUEST_STAGE_STATUS)) {
        return handleStageNotification(goPluginApiRequest);
    }
    return renderJSON(NOT_FOUND_RESPONSE_CODE, null);
}
 
Example #11
Source File: JobCompletionRequestExecutorTest.java    From docker-elastic-agents-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTerminateElasticAgentOnJobCompletion() throws Exception {
    JobIdentifier jobIdentifier = new JobIdentifier(100L);
    ClusterProfileProperties clusterProfileProperties = new ClusterProfileProperties();
    String elasticAgentId = "agent-1";
    JobCompletionRequest request = new JobCompletionRequest(elasticAgentId, jobIdentifier, null, clusterProfileProperties);
    JobCompletionRequestExecutor executor = new JobCompletionRequestExecutor(request, mockAgentInstances, mockPluginRequest);
    GoPluginApiResponse response = executor.execute();

    InOrder inOrder = inOrder(mockPluginRequest, mockAgentInstances);
    inOrder.verify(mockPluginRequest).disableAgents(agentsArgumentCaptor.capture());
    List<Agent> agentsToDisabled = agentsArgumentCaptor.getValue();
    assertEquals(1, agentsToDisabled.size());
    assertEquals(elasticAgentId, agentsToDisabled.get(0).elasticAgentId());
    inOrder.verify(mockAgentInstances).terminate(elasticAgentId, clusterProfileProperties);
    inOrder.verify(mockPluginRequest).deleteAgents(agentsArgumentCaptor.capture());
    List<Agent> agentsToDelete = agentsArgumentCaptor.getValue();
    assertEquals(agentsToDisabled, agentsToDelete);
    assertEquals(200, response.responseCode());
    assertTrue(response.responseBody().isEmpty());
}
 
Example #12
Source File: MigrateConfigurationRequestExecutorTest.java    From kubernetes-elastic-agents with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldMigratePluginSettingsToClusterProfile_WhenNoElasticAgentProfilesAreConfigured() throws Exception {
    MigrateConfigurationRequest request = new MigrateConfigurationRequest(pluginSettings, Collections.emptyList(), Collections.emptyList());
    MigrateConfigurationRequestExecutor executor = new MigrateConfigurationRequestExecutor(request);

    GoPluginApiResponse response = executor.execute();

    MigrateConfigurationRequest responseObject = MigrateConfigurationRequest.fromJSON(response.responseBody());

    assertThat(responseObject.getPluginSettings(), is(pluginSettings));
    List<ClusterProfile> actual = responseObject.getClusterProfiles();
    ClusterProfile actualClusterProfile = actual.get(0);
    this.clusterProfile.setId(actualClusterProfile.getId());

    assertThat(actual, is(Collections.singletonList(this.clusterProfile)));
    assertThat(responseObject.getElasticAgentProfiles(), is(Collections.emptyList()));
}
 
Example #13
Source File: AuthConfigValidateRequestExecutorTest.java    From gocd-filebased-authentication-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBarfWhenUnknownKeysArePassed() throws Exception {
    when(request.requestBody()).thenReturn(new Gson().toJson(Collections.singletonMap("foo", "bar")));

    GoPluginApiResponse response = new AuthConfigValidateRequestExecutor(request).execute();
    String json = response.responseBody();

    String expectedJSON = "[\n" +
            "  {\n" +
            "    \"message\": \"PasswordFilePath must not be blank.\",\n" +
            "    \"key\": \"PasswordFilePath\"\n" +
            "  },\n" +
            "  {\n" +
            "    \"key\": \"foo\",\n" +
            "    \"message\": \"Is an unknown property\"\n" +
            "  }\n" +
            "]";
    JSONAssert.assertEquals(expectedJSON, json, JSONCompareMode.NON_EXTENSIBLE);
}
 
Example #14
Source File: CheckoutRequestHandlerTest.java    From gocd-git-path-material-plugin with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void shouldHandleApiRequestAndRenderSuccessApiResponse() {
    RequestHandler checkoutRequestHandler = new CheckoutRequestHandler();
    ArgumentCaptor<HashMap> responseArgumentCaptor = ArgumentCaptor.forClass(HashMap.class);

    when(JsonUtils.renderSuccessApiResponse(responseArgumentCaptor.capture())).thenReturn(mock(GoPluginApiResponse.class));

    checkoutRequestHandler.handle(pluginApiRequestMock);

    verify(jGitHelperMock).cloneOrFetch();
    verify(jGitHelperMock).resetHard(revision);

    Map<String, Object> responseMap = responseArgumentCaptor.getValue();
    ArrayList<String> messages = (ArrayList<String>) responseMap.get("messages");

    assertThat(responseMap, hasEntry("status", "success"));
    assertThat(messages, Matchers.contains(String.format("Start updating %s to revision %s from null", destinationFolder, revision)));
}
 
Example #15
Source File: Plugin1.java    From go-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public GoPluginApiResponse handle(GoPluginApiRequest goPluginApiRequest) throws UnhandledRequestTypeException {

    if ("configuration".equals(goPluginApiRequest.requestName())) {
        HashMap<String, Object> config = new HashMap<>();

        HashMap<String, Object> url = new HashMap<>();
        url.put("display-order", "0");
        url.put("display-name", "Url");
        url.put("required", true);
        config.put("Url", url);
        return DefaultGoPluginApiResponse.success(new GsonBuilder().create().toJson(config));
    } else if ("view".equals(goPluginApiRequest.requestName())) {
        return getViewRequest();
    }
    throw new UnhandledRequestTypeException(goPluginApiRequest.requestName());
}
 
Example #16
Source File: ClusterProfileValidateRequestExecutorTest.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldValidateAConfigurationWithAllPrivateRegistryInfos() throws Exception {
    HashMap<String, String> properties = new HashMap<>();
    ClusterProfileValidateRequest request = new ClusterProfileValidateRequest(properties);
    properties.put("max_docker_containers", "1");
    properties.put("docker_uri", "https://api.example.com");
    properties.put("docker_ca_cert", "some ca cert");
    properties.put("docker_client_key", "some client key");
    properties.put("docker_client_cert", "sone client cert");
    properties.put("go_server_url", "https://ci.example.com/go");
    properties.put("enable_private_registry_authentication", "true");
    properties.put("private_registry_server", "server");
    properties.put("private_registry_username", "username");
    properties.put("private_registry_password", "password");
    properties.put("auto_register_timeout", "10");
    GoPluginApiResponse response = new ClusterProfileValidateRequestExecutor(request).execute();

    assertThat(response.responseCode(), is(200));
    JSONAssert.assertEquals("[]", response.responseBody(), true);
}
 
Example #17
Source File: GitPluginImpl.java    From go-plugins with Apache License 2.0 6 votes vote down vote up
private GoPluginApiResponse handleSCMValidation(GoPluginApiRequest goPluginApiRequest) {
    Map<String, Object> responseMap = (Map<String, Object>) parseJSON(goPluginApiRequest.requestBody());
    Map<String, String> configuration = keyValuePairs(responseMap, "scm-configuration");
    final GitConfig gitConfig = getGitConfig(configuration);

    List<Map<String, Object>> response = new ArrayList<Map<String, Object>>();

    validate(response, new FieldValidator() {
        @Override
        public void validate(Map<String, Object> fieldValidation) {
            validateUrl(gitConfig, fieldValidation);
        }
    });

    return renderJSON(SUCCESS_RESPONSE_CODE, response);
}
 
Example #18
Source File: DummyClassProvidingAnonymousClass.java    From gocd with Apache License 2.0 6 votes vote down vote up
public static GoPlugin getAnonymousClass() {
    return new GoPlugin() {
        @Override
        public void initializeGoApplicationAccessor(GoApplicationAccessor goApplicationAccessor) {
        }

        @Override
        public GoPluginApiResponse handle(GoPluginApiRequest requestMessage) throws UnhandledRequestTypeException {
            return null;
        }

        @Override
        public GoPluginIdentifier pluginIdentifier() {
            return null;
        }
    };
}
 
Example #19
Source File: MigrateConfigurationRequestExecutorTest.java    From docker-elastic-agents-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPopulateNoOpClusterProfileWithPluginSettingsConfigurations_WithoutChangingClusterProfileIdIfItsNotNoOp() throws Exception {
    String clusterProfileId = "i-renamed-no-op-cluster-to-something-else";
    ClusterProfile emptyClusterProfile = new ClusterProfile(clusterProfileId, Constants.PLUGIN_ID, new PluginSettings());
    elasticAgentProfile.setClusterProfileId(emptyClusterProfile.getId());
    MigrateConfigurationRequest request = new MigrateConfigurationRequest(pluginSettings, Arrays.asList(emptyClusterProfile), Arrays.asList(elasticAgentProfile));
    MigrateConfigurationRequestExecutor executor = new MigrateConfigurationRequestExecutor(request);

    GoPluginApiResponse response = executor.execute();

    MigrateConfigurationRequest responseObject = MigrateConfigurationRequest.fromJSON(response.responseBody());

    assertThat(responseObject.getPluginSettings(), is(pluginSettings));
    List<ClusterProfile> actual = responseObject.getClusterProfiles();
    ClusterProfile actualClusterProfile = actual.get(0);

    assertThat(actualClusterProfile.getId(), is(clusterProfileId));
    this.clusterProfile.setId(actualClusterProfile.getId());

    assertThat(actual, is(Arrays.asList(this.clusterProfile)));
    assertThat(responseObject.getElasticAgentProfiles(), is(Arrays.asList(elasticAgentProfile)));

    assertThat(elasticAgentProfile.getClusterProfileId(), is(clusterProfileId));
}
 
Example #20
Source File: PublishTask.java    From gocd-s3-artifacts with Apache License 2.0 6 votes vote down vote up
private GoPluginApiResponse handleGetConfigRequest() {
    HashMap config = new HashMap();

    HashMap sourceDestinations = new HashMap();
    sourceDestinations.put("default-value", "");
    sourceDestinations.put("required", true);
    config.put(SOURCEDESTINATIONS, sourceDestinations);

    HashMap destinationPrefix = new HashMap();
    destinationPrefix.put("default-value", "");
    destinationPrefix.put("required", false);
    config.put(DESTINATION_PREFIX, destinationPrefix);

    HashMap artifactsBucket = new HashMap();
    artifactsBucket.put("default-value", "");
    artifactsBucket.put("required", false);
    config.put(ARTIFACTS_BUCKET, artifactsBucket);

    return createResponse(DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE, config);
}
 
Example #21
Source File: MigrateConfigurationRequestExecutorTest.java    From kubernetes-elastic-agents with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPopulateNoOpClusterProfileWithPluginSettingsConfigurations_WithoutChangingClusterProfileIdIfItsNotNoOp() throws Exception {
    String clusterProfileId = "i-renamed-no-op-cluster-to-something-else";
    ClusterProfile emptyClusterProfile = new ClusterProfile(clusterProfileId, Constants.PLUGIN_ID, new PluginSettings());
    elasticAgentProfile.setClusterProfileId(emptyClusterProfile.getId());
    MigrateConfigurationRequest request = new MigrateConfigurationRequest(pluginSettings, Collections.singletonList(emptyClusterProfile), Collections.singletonList(elasticAgentProfile));
    MigrateConfigurationRequestExecutor executor = new MigrateConfigurationRequestExecutor(request);

    GoPluginApiResponse response = executor.execute();

    MigrateConfigurationRequest responseObject = MigrateConfigurationRequest.fromJSON(response.responseBody());

    assertThat(responseObject.getPluginSettings(), is(pluginSettings));
    List<ClusterProfile> actual = responseObject.getClusterProfiles();
    ClusterProfile actualClusterProfile = actual.get(0);

    assertThat(actualClusterProfile.getId(), is(clusterProfileId));
    this.clusterProfile.setId(actualClusterProfile.getId());

    assertThat(actual, is(Collections.singletonList(this.clusterProfile)));
    assertThat(responseObject.getElasticAgentProfiles(), is(Collections.singletonList(elasticAgentProfile)));

    assertThat(elasticAgentProfile.getClusterProfileId(), is(clusterProfileId));
}
 
Example #22
Source File: AnalyticsExtensionImplementation.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public GoPluginApiResponse handle(GoPluginApiRequest goPluginApiRequest) {
    System.setProperty("valid-plugin-with-multiple-extensions.analytics_extension.request.count", String.valueOf(++numberOfCallsToHandle));
    System.setProperty("valid-plugin-with-multiple-extensions.analytics_extension.request.name", goPluginApiRequest.requestName());
    System.setProperty("valid-plugin-with-multiple-extensions.analytics_extension.request.body", goPluginApiRequest.requestBody());

    return new DefaultGoPluginApiResponse(DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE, "{}");
}
 
Example #23
Source File: GetClusterProfilePropertiesMetadataExecutorTest.java    From docker-elastic-agents-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeAllFields() throws Exception {
    GoPluginApiResponse response = new GetClusterProfileMetadataExecutor().execute();
    final Type type = new TypeToken<List<Metadata>>() {
    }.getType();

    List<Metadata> list = new Gson().fromJson(response.responseBody(), type);
    assertEquals(list.size(), GetClusterProfileMetadataExecutor.FIELDS.size());
}
 
Example #24
Source File: YamlConfigPluginIntegrationTest.java    From gocd-yaml-config-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRespondSuccessToGetViewRequest() throws UnhandledRequestTypeException {
    DefaultGoPluginApiRequest getConfigRequest = new DefaultGoPluginApiRequest("configrepo", "1.0", "go.plugin-settings.get-view");

    GoPluginApiResponse response = plugin.handle(getConfigRequest);
    assertThat(response.responseCode(), is(SUCCESS_RESPONSE_CODE));
}
 
Example #25
Source File: YamlConfigPlugin.java    From gocd-yaml-config-plugin with Apache License 2.0 5 votes vote down vote up
private GoPluginApiResponse handleGetConfigFiles(GoPluginApiRequest request) {
    return handlingErrors(() -> {
        ParsedRequest parsed = ParsedRequest.parse(request);
        File baseDir = new File(parsed.getStringParam("directory"));

        Map<String, String[]> result = new HashMap<>();
        result.put("files", scanForConfigFiles(parsed, baseDir));

        return success(gson.toJson(result));
    });
}
 
Example #26
Source File: DummyArtifactPluginTest.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
@Test
void shouldReturnPublishArtifactMetadata() throws UnhandledRequestTypeException {
    final GoPluginApiRequest request = mock(GoPluginApiRequest.class);
    when(request.requestName()).thenReturn(RequestFromServer.REQUEST_PUBLISH_ARTIFACT_METADATA.getRequestName());

    final GoPluginApiResponse response = new DummyArtifactPlugin().handle(request);

    String expectedMetadata = "[{\"key\":\"Source\",\"metadata\":{\"required\":true,\"secure\":false}},{\"key\":\"Destination\",\"metadata\":{\"required\":true,\"secure\":false}}]";
    assertThat(response.responseCode()).isEqualTo(200);
    assertThat(response.responseBody()).isEqualTo(expectedMetadata);
}
 
Example #27
Source File: RoleConfigValidateRequestExecutorTest.java    From github-oauth-authorization-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldValidateValidRoleConfig() throws Exception {
    when(request.requestBody()).thenReturn(new Gson().toJson(singletonMap("Teams", "Org:team-1")));

    GoPluginApiResponse response = RoleConfigValidateRequest.from(request).execute();
    String json = response.responseBody();

    String expectedJSON = "[]";

    JSONAssert.assertEquals(expectedJSON, json, JSONCompareMode.NON_EXTENSIBLE);
}
 
Example #28
Source File: VerifyConnectionRequestExecutor.java    From gocd-filebased-authentication-plugin with Apache License 2.0 5 votes vote down vote up
private GoPluginApiResponse respondWith(String status, String message, List<Map<String, String>> errors) {
    HashMap<String, Object> response = new HashMap<>();
    response.put("status", status);
    response.put("message", message);

    if (errors != null && errors.size() > 0) {
        response.put("errors", errors);
    }

    return DefaultGoPluginApiResponse.success(GSON.toJson(response));
}
 
Example #29
Source File: GetTaskPluginConfig.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
public GoPluginApiResponse execute() {
    HashMap<String, Object> config = new HashMap<>();

    HashMap<String, Object> url = new HashMap<>();
    url.put("display-order", "0");
    url.put("display-name", "Url");
    url.put("required", true);
    config.put("Url", url);

    HashMap<String, Object> secure = new HashMap<>();
    secure.put("default-value", "SecureConnection");
    secure.put("display-order", "1");
    secure.put("display-name", "Secure Connection");
    secure.put("required", false);
    config.put("SecureConnection", secure);

    HashMap<String, Object> requestType = new HashMap<>();
    requestType.put("default-value", "RequestType");
    requestType.put("display-order", "2");
    requestType.put("display-name", "Request Type");
    requestType.put("required", false);
    config.put("RequestType", requestType);

    HashMap<String, Object> additionalOptions = new HashMap<>();
    additionalOptions.put("display-order", "3");
    additionalOptions.put("display-name", "Additional Options");
    additionalOptions.put("required", false);
    config.put("AdditionalOptions", additionalOptions);

    return DefaultGoPluginApiResponse.success(new GsonBuilder().create().toJson(config));
}
 
Example #30
Source File: VerifyConnectionRequestExecutorTest.java    From github-oauth-authorization-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnValidationFailedStatusForInvalidAuthConfig() throws Exception {
    when(request.githubConfiguration()).thenReturn(new GitHubConfiguration());

    GoPluginApiResponse response = executor.execute();

    String expectedJSON = "{\n" +
            "  \"errors\": [\n" +
            "    {\n" +
            "      \"key\": \"PersonalAccessToken\",\n" +
            "      \"message\": \"PersonalAccessToken must not be blank.\"\n" +
            "    },\n" +
            "    {\n" +
            "      \"key\": \"ClientId\",\n" +
            "      \"message\": \"ClientId must not be blank.\"\n" +
            "    },\n" +
            "    {\n" +
            "      \"key\": \"ClientSecret\",\n" +
            "      \"message\": \"ClientSecret must not be blank.\"\n" +
            "    }\n" +
            "  ],\n" +
            "  \"message\": \"Validation failed for the given Auth Config\",\n" +
            "  \"status\": \"validation-failed\"\n" +
            "}";

    assertThat(response.responseCode(), is(200));
    JSONAssert.assertEquals(expectedJSON, response.responseBody(), JSONCompareMode.NON_EXTENSIBLE);
}