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

The following examples show how to use com.thoughtworks.go.plugin.api.response.GoPluginApiResponse. 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 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 2
@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 3
@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 4
@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 5
@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 6
@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 7
@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 8
Source Project: gocd-s3-artifacts   Source File: PublishTask.java    License: 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 9
Source Project: gocd-plugins   Source File: DockerComposeTask.java    License: 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 10
@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 11
Source Project: go-plugins   Source File: GitPluginImpl.java    License: 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 12
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 13
@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 14
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 15
Source Project: go-plugins   Source File: PluginWithInvalidId.java    License: 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 16
Source Project: go-plugins   Source File: SampleAuthenticationPluginImpl.java    License: 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 17
@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 18
@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 19
Source Project: gocd-s3-artifacts   Source File: PublishTask.java    License: 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 20
Source Project: gocd   Source File: DummyClassProvidingAnonymousClass.java    License: 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 21
Source Project: go-plugins   Source File: Plugin1.java    License: 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 22
@Test
public void shouldSupportAgentAndPluginStatusReport() throws Exception {
    GoPluginApiResponse response = new GetCapabilitiesExecutor().execute();

    String expectedJSON = "{\n" +
            "    \"supports_plugin_status_report\":false\n," +
            "    \"supports_cluster_status_report\":true\n," +
            "    \"supports_agent_status_report\":true\n" +
            "}";

    JSONAssert.assertEquals(expectedJSON, response.responseBody(), true);
}
 
Example 23
@Test
public void shouldRespondSuccessToGetConfigurationRequest() throws UnhandledRequestTypeException {
    DefaultGoPluginApiRequest getConfigRequest = new DefaultGoPluginApiRequest("configrepo", "1.0", "go.plugin-settings.get-configuration");

    GoPluginApiResponse response = plugin.handle(getConfigRequest);
    assertThat(response.responseCode(), is(SUCCESS_RESPONSE_CODE));
}
 
Example 24
@Override
public GoPluginApiResponse execute() throws Exception {
    LOG.info("[server-ping] Starting execute server ping request.");
    List<ClusterProfileProperties> allClusterProfileProperties = serverPingRequest.allClusterProfileProperties();

    for (ClusterProfileProperties clusterProfileProperties : allClusterProfileProperties) {
        performCleanupForACluster(clusterProfileProperties, clusterSpecificAgentInstances.get(clusterProfileProperties.uuid()));
    }

    CheckForPossiblyMissingAgents();
    return DefaultGoPluginApiResponse.success("");
}
 
Example 25
@Override
public GoPluginApiResponse execute() {
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("template", Util.readResource("/profile.template.html"));
    DefaultGoPluginApiResponse defaultGoPluginApiResponse = new DefaultGoPluginApiResponse(200, GSON.toJson(jsonObject));
    return defaultGoPluginApiResponse;
}
 
Example 26
public GoPluginApiResponse execute() {
    final GitHubConfiguration gitHubConfiguration = request.githubConfiguration();
    final ValidationResult validationResult = new MetadataValidator().validate(gitHubConfiguration);

    if (gitHubConfiguration.authenticateWith() == AuthenticateWith.GITHUB_ENTERPRISE && Util.isBlank(gitHubConfiguration.gitHubEnterpriseUrl())) {
        validationResult.addError("GitHubEnterpriseUrl", "GitHubEnterpriseUrl must not be blank.");
    }

    if (Util.isBlank(gitHubConfiguration.personalAccessToken())) {
        validationResult.addError("PersonalAccessToken", "PersonalAccessToken must not be blank.");
    }

    return DefaultGoPluginApiResponse.success(validationResult.toJSON());
}
 
Example 27
@Test
@SuppressWarnings("unchecked")
public void shouldReturnSuccessJsonResponseForScmViewRequest() throws IOException {
    String template = IOUtils.toString(getClass().getResourceAsStream("/scm.template.html"), StandardCharsets.UTF_8);
    GoPluginApiRequest apiRequest = mock(GoPluginApiRequest.class);
    RequestHandler requestHandler = new SCMViewRequestHandler();

    GoPluginApiResponse apiResponse = requestHandler.handle(apiRequest);

    Map<String, Object> response = JsonHelper.getResponse(apiResponse);
    assertThat(apiResponse.responseCode(), is(equalTo(200)));
    assertThat(response, hasEntry("displayValue", SCMViewRequestHandler.PLUGIN_NAME));
    assertThat(response, hasEntry("template", template));
}
 
Example 28
@Test
public void shouldValidateValidEnvironmentVariablePrefix() throws Exception {
    String requestBody = new JSONObject().put("EnvironmentVariablePrefix", "ENVIRONMENT_VARIABLE").toString();
    when(request.requestBody()).thenReturn(requestBody);

    final GoPluginApiResponse response = new ValidateFetchArtifactConfigExecutor(request).execute();

    String expectedJSON = "[]";
    JSONAssert.assertEquals(expectedJSON, response.responseBody(), JSONCompareMode.NON_EXTENSIBLE);
}
 
Example 29
@Test
public void shouldRespondSuccessToParseDirectoryRequestWhenAliasesCaseFile() throws UnhandledRequestTypeException,
        IOException {
    GoPluginApiResponse response = parseAndGetResponseForDir(setupCase("aliases"));

    assertThat(response.responseCode(), is(SUCCESS_RESPONSE_CODE));
    JsonObject responseJsonObject = getJsonObjectFromResponse(response);
    assertNoError(responseJsonObject);
    JsonArray pipelines = responseJsonObject.get("pipelines").getAsJsonArray();
    assertThat(pipelines.size(), is(1));
    JsonObject expected = (JsonObject) readJsonObject("examples.out/aliases.gocd.json");
    assertThat(responseJsonObject, is(new JsonObjectMatcher(expected)));
}
 
Example 30
private GoPluginApiResponse getStatusReportUsingJobIdentifier(JobIdentifier jobIdentifier) throws Exception {
    Optional<DockerContainer> dockerContainer = dockerContainers.find(jobIdentifier);
    if (dockerContainer.isPresent()) {
        AgentStatusReport agentStatusReport = dockerContainers.getAgentStatusReport(request.getClusterProfile(), dockerContainer.get());
        final String statusReportView = viewBuilder.build(viewBuilder.getTemplate("agent-status-report.template.ftlh"), agentStatusReport);
        return constructResponseForReport(statusReportView);
    }

    return containerNotFoundApiResponse(jobIdentifier);
}