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

The following examples show how to use com.thoughtworks.go.plugin.api.request.GoPluginApiRequest. 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: S3PackageMaterialPoller.java    From gocd-s3-artifacts with Apache License 2.0 6 votes vote down vote up
private GoPluginApiResponse handleRepositoryCheckConnection(GoPluginApiRequest goPluginApiRequest) {
    final Map<String, String> repositoryKeyValuePairs = keyValuePairs(goPluginApiRequest, REQUEST_REPOSITORY_CONFIGURATION);
    MaterialResult result;
    String s3Bucket = repositoryKeyValuePairs.get(S3_BUCKET);

    if(StringUtils.isBlank(s3Bucket)) {
       result = new MaterialResult(false, "S3 bucket must be specified");
    } else {
        S3ArtifactStore artifactStore = s3ArtifactStore(s3Bucket);
        if (artifactStore.bucketExists()) {
            result = new MaterialResult(true, "Success");
        } else {
            result = new MaterialResult(false, String.format("Couldn't find bucket [%s]", s3Bucket));
        }
    }
    return createResponse(result.responseCode(), result.toMap());
}
 
Example #2
Source File: InvalidXmlPlugin.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 #3
Source File: NotificationExtensionTestForV4.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotifyPluginSettingsChange() throws Exception {
    String supportedVersion = "4.0";
    Map<String, String> settings = Collections.singletonMap("foo", "bar");
    ArgumentCaptor<GoPluginApiRequest> requestArgumentCaptor = ArgumentCaptor.forClass(GoPluginApiRequest.class);

    when(pluginManager.resolveExtensionVersion(eq("pluginId"), eq(NOTIFICATION_EXTENSION), anyList())).thenReturn(supportedVersion);
    when(pluginManager.isPluginOfType(NOTIFICATION_EXTENSION, "pluginId")).thenReturn(true);
    when(pluginManager.submitTo(eq("pluginId"), eq(NOTIFICATION_EXTENSION), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, ""));

    NotificationExtension extension = new NotificationExtension(pluginManager, extensionsRegistry);
    extension.notifyPluginSettingsChange("pluginId", settings);

    assertRequest(requestArgumentCaptor.getValue(), NOTIFICATION_EXTENSION,
            supportedVersion, REQUEST_NOTIFY_PLUGIN_SETTINGS_CHANGE, "{\"foo\":\"bar\"}");
}
 
Example #4
Source File: CheckoutRequestHandlerTest.java    From gocd-git-path-material-plugin with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    PowerMockito.mockStatic(JsonUtils.class);
    PowerMockito.mockStatic(JGitHelper.class);
    PowerMockito.mockStatic(GitConfig.class);
    PowerMockito.mockStatic(HelperFactory.class);

    pluginApiRequestMock = mock(GoPluginApiRequest.class);
    jGitHelperMock = mock(JGitHelper.class);

    GitConfig gitConfigMock = mock(GitConfig.class);
    final String responseBody = "mocked body";

    Map<String, Object> requestBody = Map.of(
            "destination-folder", destinationFolder,
            "revision", Map.of("revision", revision)
    );

    when(pluginApiRequestMock.requestBody()).thenReturn(responseBody);
    when(JsonUtils.parseJSON(responseBody)).thenReturn(requestBody);
    when(JsonUtils.toAgentGitConfig(pluginApiRequestMock)).thenReturn(gitConfigMock);
    when(HelperFactory.git(eq(gitConfigMock),
            Mockito.any(File.class),
            Mockito.any(ProcessOutputStreamConsumer.class),
            Mockito.any(ProcessOutputStreamConsumer.class))).thenReturn(jGitHelperMock);
}
 
Example #5
Source File: SampleAuthenticationPluginImpl.java    From go-plugins with Apache License 2.0 6 votes vote down vote up
private GoPluginApiResponse handleAuthenticateWebRequest(final GoPluginApiRequest goPluginApiRequest) {
    try {
        String verificationCode = goPluginApiRequest.requestParameters().get("verification_code");
        if (verificationCode == null || verificationCode.trim().isEmpty() || !verificationCode.equals("123456")) {
            return renderRedirectResponse(getServerBaseURL() + "/go/auth/login?login_error=1");
        }

        String displayName = "test";
        String fullName = "display name";
        String emailId = "";
        emailId = emailId == null ? emailId : emailId.toLowerCase().trim();

        authenticateUser(displayName, fullName, emailId);

        return renderRedirectResponse(getServerBaseURL());
    } catch (Exception e) {
        LOGGER.error("Error occurred while Login authenticate.", e);
        return renderResponse(INTERNAL_ERROR_RESPONSE_CODE, null, null);
    }
}
 
Example #6
Source File: S3PackageMaterialPoller.java    From gocd-s3-artifacts with Apache License 2.0 6 votes vote down vote up
private GoPluginApiResponse handleLatestRevisionSince(GoPluginApiRequest goPluginApiRequest) {
    final Map<String, String> repositoryKeyValuePairs = keyValuePairs(goPluginApiRequest, REQUEST_REPOSITORY_CONFIGURATION);
    final Map<String, String> packageKeyValuePairs = keyValuePairs(goPluginApiRequest, REQUEST_PACKAGE_CONFIGURATION);
    Map<String, Object> previousRevisionMap = getMapFor(goPluginApiRequest, "previous-revision");
    String previousRevision = (String) previousRevisionMap.get("revision");


    String s3Bucket = repositoryKeyValuePairs.get(S3_BUCKET);
    S3ArtifactStore artifactStore = s3ArtifactStore(s3Bucket);
    try {
        RevisionStatus revision = artifactStore.getLatest(artifact(packageKeyValuePairs));
        if(new Revision(revision.revision.getRevision()).compareTo(new Revision(previousRevision)) > 0) {
            return createResponse(DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE, revision.toMap());
        }

        return createResponse(DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE, null);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return createResponse(DefaultGoPluginApiResponse.INTERNAL_ERROR, null);
    }
}
 
Example #7
Source File: SCMExtensionTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    initMocks(this);
    scmExtension = new SCMExtension(pluginManager, extensionsRegistry);
    scmExtension.getPluginSettingsMessageHandlerMap().put("1.0", pluginSettingsJSONMessageHandler);
    scmExtension.getMessageHandlerMap().put("1.0", jsonMessageHandler);

    pluginSettingsConfiguration = new PluginSettingsConfiguration();
    scmPropertyConfiguration = new SCMPropertyConfiguration();
    materialData = new HashMap<>();

    requestArgumentCaptor = ArgumentCaptor.forClass(GoPluginApiRequest.class);

    when(pluginManager.resolveExtensionVersion(PLUGIN_ID, SCM_EXTENSION, asList("1.0"))).thenReturn("1.0");
    when(pluginManager.isPluginOfType(SCM_EXTENSION, PLUGIN_ID)).thenReturn(true);
    when(pluginManager.submitTo(eq(PLUGIN_ID), eq(SCM_EXTENSION), requestArgumentCaptor.capture())).thenReturn(DefaultGoPluginApiResponse.success(responseBody));
}
 
Example #8
Source File: GetRolesRequestTest.java    From github-oauth-authorization-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldParseRequest() {
    GoPluginApiRequest apiRequest = mock(GoPluginApiRequest.class);
    when(apiRequest.requestBody()).thenReturn("{\n" +
            "  \"auth_config\": {\n" +
            "    \"configuration\": {\n" +
            "      \"AllowedOrganizations\": \"\",\n" +
            "      \"AuthenticateWith\": \"GitHub\",\n" +
            "      \"AuthorizeUsing\": \"PersonalAccessToken\",\n" +
            "      \"ClientId\": \"Foo\",\n" +
            "      \"ClientSecret\": \"bar\",\n" +
            "      \"GitHubEnterpriseUrl\": \"\",\n" +
            "      \"PersonalAccessToken\": \"Baz\"\n" +
            "    },\n" +
            "    \"id\": \"GitHub\"\n" +
            "  },\n" +
            "   \"role_configs\": [],\n" +
            "  \"username\": \"bob\"\n" +
            "}");

    GetRolesRequest request = (GetRolesRequest) GetRolesRequest.from(apiRequest);

    assertThat(request.getUsername(), is("bob"));
    assertThat(request.getAuthConfig().getId(), is("GitHub"));
    assertThat(request.getRoles(), hasSize(0));
}
 
Example #9
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 #10
Source File: CheckMkTask.java    From gocd-plugins with Apache License 2.0 6 votes vote down vote up
@Override
protected GoPluginApiResponse handleTaskExecution(GoPluginApiRequest request) throws Exception {
    Map executionRequest = (Map) new GsonBuilder().create().fromJson(request.requestBody(), Object.class);

    Map<String, Map> config = (Map) executionRequest.get("config");

    Context context = new Context((Map) executionRequest.get("context"));

    try {
        CheckMkTaskExecutor checkMkTaskExecutor = TaskExecutorFactory.Create(MaskingJobConsoleLogger.getConsoleLogger(),
                context, config);
        Result result = checkMkTaskExecutor.execute();
        return createResponse(result.responseCode(), result.toMap());
    } catch (JobNotSupportedException | IOException e) {
        return success(new Result(false, e.getMessage()));
    }
}
 
Example #11
Source File: ArtifactExtensionTestBase.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetFetchArtifactMetadataFromPlugin() {
    String responseBody = "[{\"key\":\"FILENAME\",\"metadata\":{\"required\":true,\"secure\":false}},{\"key\":\"VERSION\",\"metadata\":{\"required\":true,\"secure\":true}}]";

    when(pluginManager.submitTo(eq(PLUGIN_ID), eq(ARTIFACT_EXTENSION), requestArgumentCaptor.capture())).thenReturn(DefaultGoPluginApiResponse.success(responseBody));

    final List<PluginConfiguration> response = artifactExtension.getFetchArtifactMetadata(PLUGIN_ID);

    final GoPluginApiRequest request = requestArgumentCaptor.getValue();

    assertThat(request.extension(), is(ARTIFACT_EXTENSION));
    assertThat(request.requestName(), is(REQUEST_FETCH_ARTIFACT_METADATA));
    assertNull(request.requestBody());

    assertThat(response.size(), is(2));
    assertThat(response, containsInAnyOrder(
            new PluginConfiguration("FILENAME", new Metadata(true, false)),
            new PluginConfiguration("VERSION", new Metadata(true, true))
    ));
}
 
Example #12
Source File: OAuthLoginPlugin.java    From gocd-oauth-login with Apache License 2.0 5 votes vote down vote up
private GoPluginApiResponse handleSearchUserRequest(GoPluginApiRequest goPluginApiRequest) {
    Map<String, String> requestBodyMap = (Map<String, String>) JSONUtils.fromJSON(goPluginApiRequest.requestBody());
    String searchTerm = requestBodyMap.get("search-term");
    PluginSettings pluginSettings = getPluginSettings();
    List<User> users = provider.searchUser(pluginSettings, searchTerm);
    if (users == null || users.isEmpty()) {
        return renderJSON(SUCCESS_RESPONSE_CODE, null);
    } else {
        List<Map> searchResults = new ArrayList<Map>();
        for (User user : users) {
            searchResults.add(getUserMap(user));
        }
        return renderJSON(SUCCESS_RESPONSE_CODE, searchResults);
    }
}
 
Example #13
Source File: YamlConfigPlugin.java    From gocd-yaml-config-plugin with Apache License 2.0 5 votes vote down vote up
private GoPluginApiResponse handlePipelineExportRequest(GoPluginApiRequest request) {
    return handlingErrors(() -> {
        ParsedRequest parsed = ParsedRequest.parse(request);

        Map<String, Object> pipeline = parsed.getParam("pipeline");
        String name = (String) pipeline.get("name");

        Map<String, String> responseMap = Collections.singletonMap("pipeline", new RootTransform().inverseTransformPipeline(pipeline));
        DefaultGoPluginApiResponse response = success(gson.toJson(responseMap));

        response.addResponseHeader("Content-Type", "application/x-yaml; charset=utf-8");
        response.addResponseHeader("X-Export-Filename", name + ".gocd.yaml");
        return response;
    });
}
 
Example #14
Source File: DumbPluginThatRespondsWithClassloaderName.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public GoPluginApiResponse handle(GoPluginApiRequest goPluginApiRequest) throws UnhandledRequestTypeException {
    switch(goPluginApiRequest.requestName()){
        case "Thread.currentThread.getContextClassLoader":
            return DefaultGoPluginApiResponse.success(Thread.currentThread().getContextClassLoader().getClass().getCanonicalName());
        case "this.getClass.getClassLoader":
            return DefaultGoPluginApiResponse.success(this.getClass().getClassLoader().getClass().getCanonicalName());
        default:
            throw new UnhandledRequestTypeException(goPluginApiRequest.requestName());
    }
}
 
Example #15
Source File: PublishTask.java    From gocd-s3-artifacts with Apache License 2.0 5 votes vote down vote up
@Override
public GoPluginApiResponse handle(GoPluginApiRequest request) throws UnhandledRequestTypeException {
    if ("configuration".equals(request.requestName())) {
        return handleGetConfigRequest();
    } else if ("validate".equals(request.requestName())) {
        return handleValidation(request);
    } else if ("execute".equals(request.requestName())) {
        return handleTaskExecution(request);
    } else if ("view".equals(request.requestName())) {
        return handleTaskView();
    }
    throw new UnhandledRequestTypeException(request.requestName());
}
 
Example #16
Source File: DummyArtifactPluginTest.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
@Test
void shouldValidateArtifactConfig() throws UnhandledRequestTypeException, JSONException {
    final GoPluginApiRequest request = mock(GoPluginApiRequest.class);
    when(request.requestName()).thenReturn(RequestFromServer.REQUEST_PUBLISH_ARTIFACT_VALIDATE.getRequestName());
    when(request.requestBody()).thenReturn(GSON.toJson(Collections.singletonMap("Source", "abc")));

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

    final String expectedJson = "[{\"key\":\"Destination\",\"message\":\"must be provided.\"}]";
    assertThat(response.responseCode()).isEqualTo(200);
    JSONAssert.assertEquals(expectedJson,response.responseBody(),true);

}
 
Example #17
Source File: JsonUtils.java    From gocd-git-path-material-plugin with Apache License 2.0 5 votes vote down vote up
public static GoPluginApiResponse renderErrorApiResponse(GoPluginApiRequest apiRequest, Throwable t) {
    LOGGER.error(apiRequest.requestName() + " failed", t);
    return renderJSON(INTERNAL_ERROR_RESPONSE_CODE,
            String.format("%s failed due to [%s], rootCause [%s]",
                    apiRequest.requestName(),
                    ExceptionUtils.getMessage(t),
                    ExceptionUtils.getRootCauseMessage(t)));
}
 
Example #18
Source File: ArtifactExtensionTestBase.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetArtifactStoreViewFromPlugin() {
    when(pluginManager.submitTo(eq(PLUGIN_ID), eq(ARTIFACT_EXTENSION), requestArgumentCaptor.capture())).thenReturn(new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, "{ \"template\": \"artifact-store-view\"}"));

    String view = artifactExtension.getArtifactStoreView(PLUGIN_ID);

    final GoPluginApiRequest request = requestArgumentCaptor.getValue();

    assertThat(request.extension(), is(ARTIFACT_EXTENSION));
    assertThat(request.requestName(), is(REQUEST_STORE_CONFIG_VIEW));
    assertNull(request.requestBody());

    assertThat(view, is("artifact-store-view"));
}
 
Example #19
Source File: TestWithSomePluginXmlValues.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public GoPluginApiResponse handle(GoPluginApiRequest goPluginApiRequest) throws UnhandledRequestTypeException {

    if ("configuration".equals(goPluginApiRequest.requestName())) {
        return new GetTaskPluginConfig().execute();
    } else if ("view".equals(goPluginApiRequest.requestName())) {
        return getViewRequest();
    }
    throw new UnhandledRequestTypeException(goPluginApiRequest.requestName());
}
 
Example #20
Source File: JsonBasedPluggableTaskTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGetTheTaskConfig() {

    String jsonResponse = "{" +
            "\"URL\":{\"default-value\":\"\",\"secure\":false,\"required\":true}," +
            "\"USER\":{\"default-value\":\"foo\",\"secure\":true,\"required\":true}," +
            "\"PASSWORD\":{}" +
            "}";

    when(goPluginApiResponse.responseBody()).thenReturn(jsonResponse);

    TaskConfig config = task.config();

    Property url = config.get("URL");
    assertThat(url.getOption(Property.REQUIRED), is(true));
    assertThat(url.getOption(Property.SECURE), is(false));

    Property user = config.get("USER");
    assertThat(user.getOption(Property.REQUIRED), is(true));
    assertThat(user.getOption(Property.SECURE), is(true));

    Property password = config.get("PASSWORD");
    assertThat(password.getOption(Property.REQUIRED), is(true));
    assertThat(password.getOption(Property.SECURE), is(false));

    ArgumentCaptor<GoPluginApiRequest> argument = ArgumentCaptor.forClass(GoPluginApiRequest.class);
    verify(pluginManager).submitTo(eq(pluginId), eq(PLUGGABLE_TASK_EXTENSION), argument.capture());
    MatcherAssert.assertThat(argument.getValue().extension(), Matchers.is(PLUGGABLE_TASK_EXTENSION));
    MatcherAssert.assertThat(argument.getValue().extensionVersion(), Matchers.is(JsonBasedTaskExtensionHandler_V1.VERSION));
    MatcherAssert.assertThat(argument.getValue().requestName(), Matchers.is(TaskExtension.CONFIGURATION_REQUEST));
}
 
Example #21
Source File: SampleAuthenticationPluginImpl.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
private GoPluginApiResponse handleSearchUserRequest(GoPluginApiRequest goPluginApiRequest) {
    Map<String, String> requestBodyMap = (Map<String, String>) JSONUtils.fromJSON(goPluginApiRequest.requestBody());
    String searchTerm = requestBodyMap.get("search-term");

    List<Map> searchResults = new ArrayList<Map>();
    if (searchTerm.equalsIgnoreCase("t") || searchTerm.equalsIgnoreCase("te") || searchTerm.equalsIgnoreCase("tes") || searchTerm.equalsIgnoreCase("test")) {
        searchResults.add(getUserJSON("test", "display name", "[email protected]"));
    }

    return renderResponse(SUCCESS_RESPONSE_CODE, null, JSONUtils.toJSON(searchResults));
}
 
Example #22
Source File: DoNothingPlugin.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public GoPluginApiResponse handle(GoPluginApiRequest goPluginApiRequest) throws UnhandledRequestTypeException {

    if ("configuration".equals(goPluginApiRequest.requestName())) {
        return new GetTaskPluginConfig().execute();
    } else if ("view".equals(goPluginApiRequest.requestName())) {
        return getViewRequest();
    }
    throw new UnhandledRequestTypeException(goPluginApiRequest.requestName());
}
 
Example #23
Source File: DummyArtifactPluginTest.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
@Test
void shouldReturnArtifactStoreMetadata() throws UnhandledRequestTypeException {
    final String expectedMetadata = "[{\"key\":\"Url\",\"metadata\":{\"required\":true,\"secure\":false}},{\"key\":\"Username\",\"metadata\":{\"required\":true,\"secure\":false}},{\"key\":\"Password\",\"metadata\":{\"required\":true,\"secure\":true}}]";
    final GoPluginApiRequest request = mock(GoPluginApiRequest.class);
    when(request.requestName()).thenReturn(RequestFromServer.REQUEST_STORE_CONFIG_METADATA.getRequestName());

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

    assertThat(response.responseCode()).isEqualTo(200);
    assertThat(response.responseBody()).isEqualTo(expectedMetadata);
}
 
Example #24
Source File: DummyArtifactPluginTest.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
@Test
void shouldReturnArtifactStoreView() throws UnhandledRequestTypeException {
    final GoPluginApiRequest request = mock(GoPluginApiRequest.class);
    when(request.requestName()).thenReturn(RequestFromServer.REQUEST_STORE_CONFIG_VIEW.getRequestName());

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

    final Map<String, String> expectedTemplate = Collections.singletonMap("template", ResourceReader.read("/artifact-store.template.html"));
    assertThat(response.responseCode()).isEqualTo(200);
    assertThat(response.responseBody()).isEqualTo(new Gson().toJson(expectedTemplate));
}
 
Example #25
Source File: SCMConfigurationRequestHandler.java    From gocd-git-path-material-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public GoPluginApiResponse handle(GoPluginApiRequest apiRequest) {
    Map<String, Object> response = new HashMap<>();
    response.put(CONFIG_URL, createField("URL", null, true, true, false, "0"));
    response.put(CONFIG_USERNAME, createField("Username", null, true, false, false, "1"));
    response.put(CONFIG_PASSWORD, createField("Password", null, true, false, true, "2"));
    response.put(CONFIG_PATHS, createField("Monitored Paths", null, true, true, false, "3"));
    response.put(CONFIG_BRANCH, createField("Branch", "master", true, false, false, "4"));
    response.put(CONFIG_SHALLOW_CLONE, createField("Shallow Clone", "false", false, false, false, "5"));
    return JsonUtils.renderSuccessApiResponse(response);
}
 
Example #26
Source File: PluginRequestHelperTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void shouldInvokeOnFailureCallbackWhenResponseCodeOtherThan200() {
    PluginInteractionCallback pluginInteractionCallback = mock(PluginInteractionCallback.class);

    when(response.responseCode()).thenReturn(400);
    when(response.responseBody()).thenReturn("Error response");
    when(pluginManager.submitTo(eq(pluginId), eq(extensionName), any(GoPluginApiRequest.class))).thenReturn(response);
    when(pluginManager.resolveExtensionVersion(eq(pluginId), eq(extensionName), anyList())).thenReturn("1.0");

    assertThatCode(() -> helper.submitRequest(pluginId, requestName, pluginInteractionCallback))
            .isInstanceOf(RuntimeException.class);

    verify(pluginInteractionCallback).onFailure(400, "Error response", "1.0");
}
 
Example #27
Source File: SearchUsersRequestTest.java    From github-oauth-authorization-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnSearchUsersRequestExecutor() {
    GoPluginApiRequest apiRequest = mock(GoPluginApiRequest.class);
    when(apiRequest.requestBody()).thenReturn("{}");

    Request request = SearchUsersRequest.from(apiRequest);

    assertThat(request.executor() instanceof SearchUsersRequestExecutor, is(true));
}
 
Example #28
Source File: FetchTask.java    From gocd-s3-artifacts with Apache License 2.0 5 votes vote down vote up
@Override
public GoPluginApiResponse handle(GoPluginApiRequest request) throws UnhandledRequestTypeException {
    if ("configuration".equals(request.requestName())) {
        return handleGetConfigRequest();
    } else if ("validate".equals(request.requestName())) {
        return handleValidation(request);
    } else if ("execute".equals(request.requestName())) {
        return handleTaskExecution(request);
    } else if ("view".equals(request.requestName())) {
        return handleTaskView();
    }
    throw new UnhandledRequestTypeException(request.requestName());
}
 
Example #29
Source File: AnalyticsExtensionTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    initMocks(this);
    when(pluginManager.resolveExtensionVersion(PLUGIN_ID, ANALYTICS_EXTENSION, Arrays.asList("1.0", "2.0"))).thenReturn("1.0", "2.0");
    when(pluginManager.isPluginOfType(ANALYTICS_EXTENSION, PLUGIN_ID)).thenReturn(true);

    analyticsExtension = new AnalyticsExtension(pluginManager, extensionsRegistry);
    metadataStore = AnalyticsMetadataStore.instance();

    requestArgumentCaptor = ArgumentCaptor.forClass(GoPluginApiRequest.class);
}
 
Example #30
Source File: YamlConfigPlugin.java    From gocd-yaml-config-plugin with Apache License 2.0 5 votes vote down vote up
private GoPluginApiResponse handleParseContentRequest(GoPluginApiRequest request) {
    return handlingErrors(() -> {
        ParsedRequest parsed = ParsedRequest.parse(request);

        YamlConfigParser parser = new YamlConfigParser();
        Map<String, String> contents = parsed.getParam("contents");
        JsonConfigCollection result = new JsonConfigCollection();
        contents.forEach((filename, content) -> {
            parser.parseStream(result, new ByteArrayInputStream(content.getBytes()), filename);
        });
        result.updateTargetVersionFromFiles();

        return success(gson.toJson(result.getJsonObject()));
    });
}