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

The following examples show how to use com.thoughtworks.go.plugin.api.request.GoPluginApiRequest. 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
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 2
Source Project: gocd-s3-artifacts   Source File: S3PackageMaterialPoller.java    License: 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 3
Source Project: gocd   Source File: SCMExtensionTest.java    License: 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 4
@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 5
Source Project: gocd   Source File: ArtifactExtensionTestBase.java    License: 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 6
Source Project: go-plugins   Source File: InvalidXmlPlugin.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 7
Source Project: gocd-s3-artifacts   Source File: S3PackageMaterialPoller.java    License: 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 8
Source Project: gocd   Source File: NotificationExtensionTestForV4.java    License: 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 9
@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 10
Source Project: go-plugins   Source File: SampleAuthenticationPluginImpl.java    License: 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 11
Source Project: gocd-plugins   Source File: CheckMkTask.java    License: 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 12
@Override
public GoPluginApiResponse handle(GoPluginApiRequest request) {
    try {
        switch (Request.fromString(request.requestName())) {
            case REQUEST_GET_PLUGIN_ICON:
                return new GetPluginIconExecutor().execute();
            case REQUEST_GET_PLUGIN_CAPABILITIES:
                return new GetCapabilitiesExecutor().execute();
            case REQUEST_STORE_CONFIG_METADATA:
                return new GetArtifactStoreConfigMetadataExecutor().execute();
            case REQUEST_STORE_CONFIG_VIEW:
                return new GetArtifactStoreViewExecutor().execute();
            case REQUEST_STORE_CONFIG_VALIDATE:
                return new ValidateArtifactStoreConfigExecutor(request).execute();
            case REQUEST_PUBLISH_ARTIFACT_METADATA:
                return new GetPublishArtifactConfigMetadataExecutor().execute();
            case REQUEST_PUBLISH_ARTIFACT_VIEW:
                return new GetPublishArtifactViewExecutor().execute();
            case REQUEST_PUBLISH_ARTIFACT_VALIDATE:
                return new ValidatePublishArtifactConfigExecutor(request).execute();
            case REQUEST_FETCH_ARTIFACT_METADATA:
                return new GetFetchArtifactMetadataExecutor().execute();
            case REQUEST_FETCH_ARTIFACT_VIEW:
                return new GetFetchArtifactViewExecutor().execute();
            case REQUEST_FETCH_ARTIFACT_VALIDATE:
                return new ValidateFetchArtifactConfigExecutor(request).execute();
            case REQUEST_PUBLISH_ARTIFACT:
                return new PublishArtifactExecutor(request, consoleLogger).execute();
            case REQUEST_FETCH_ARTIFACT:
                return new FetchArtifactExecutor(request, consoleLogger).execute();
            default:
                throw new UnhandledRequestTypeException(request.requestName());
        }
    } catch (Exception e) {
        LOG.error("Error while executing request " + request.requestName(), e);
        throw new RuntimeException(e);
    }
}
 
Example 13
Source Project: gocd   Source File: PluginRequestHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void shouldInvokeSuccessBlockOnSuccessfulResponse() {
    when(response.responseCode()).thenReturn(DefaultGoApiResponse.SUCCESS_RESPONSE_CODE);
    when(pluginManager.submitTo(eq(pluginId), eq(extensionName), any(GoPluginApiRequest.class))).thenReturn(response);

    helper.submitRequest(pluginId, requestName, new DefaultPluginInteractionCallback<Object>() {
        @Override
        public Object onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) {
            isSuccessInvoked[0] = true;
            return null;
        }
    });
    assertThat(isSuccessInvoked[0]).isTrue();
    verify(pluginManager).submitTo(eq(pluginId), eq(extensionName), any(GoPluginApiRequest.class));
}
 
Example 14
Source Project: go-plugins   Source File: DummyArtifactPluginTest.java    License: 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 15
Source Project: gocd   Source File: SecretsExtensionV1Test.java    License: Apache License 2.0 5 votes vote down vote up
private void assertExtensionRequest(String requestName, String requestBody) {
    final GoPluginApiRequest request = requestArgumentCaptor.getValue();
    assertThat(request.requestName()).isEqualTo(requestName);
    assertThat(request.extensionVersion()).isEqualTo("1.0");
    assertThat(request.extension()).isEqualTo(SECRETS_EXTENSION);
    assertThatJson(requestBody).isEqualTo(request.requestBody());
}
 
Example 16
@Test
public void shouldLookForExactUsernameMatchInsteadOfRegExp() throws Exception {
    final GoPluginApiRequest request = mock(GoPluginApiRequest.class);

    final Properties properties = new Properties();
    properties.put("bobby", "password1");
    when(fileReader.read("/var/etc/password.properties")).thenReturn(properties);
    when(request.requestBody()).thenReturn(requestJson("bob"));

    final GoPluginApiResponse response = new IsValidUserRequestExecutor(request, fileReader).execute();

    assertThat(response.responseCode(), is(404));
}
 
Example 17
Source Project: gocd-plugins   Source File: FetchAnyArtifactTask.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected GoPluginApiResponse handleGetConfigRequest(GoPluginApiRequest request) {
    return success(new ConfigDef()
            .add("FAA_PIPELINE_NAME", "", Required.NO)
            .add("FAA_ARTIFACT_SOURCE", "", Required.YES)
            .add("FAA_ARTIFACT_DESTINATION", "", Required.NO)
            .add("FAA_STAGE_NAME", "", Required.NO)
            .add("FAA_JOB_NAME", "", Required.NO)
            .add("FAA_ARTIFACT_IS_FILE", "", Required.NO)
            .add("FAA_FETCH_IF_FAILED", "", Required.NO)
            .toMap());
}
 
Example 18
Source Project: go-plugins   Source File: DummyArtifactPluginTest.java    License: 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 19
Source Project: gocd   Source File: DefaultPluginManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GoPluginApiResponse submitTo(final String pluginId, String extensionType, final GoPluginApiRequest apiRequest) {
    return goPluginOSGiFramework.doOn(GoPlugin.class, pluginId, extensionType, (plugin, pluginDescriptor) -> {
        ensureInitializerInvoked(pluginDescriptor, plugin, extensionType);
        try {
            return plugin.handle(apiRequest);
        } catch (UnhandledRequestTypeException e) {
            LOGGER.error(e.getMessage());
            LOGGER.debug(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    });
}
 
Example 20
Source Project: gocd-s3-artifacts   Source File: PublishTask.java    License: 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 21
Source Project: go-plugins   Source File: TestWithSomePluginXmlValues.java    License: 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 22
Source Project: go-plugins   Source File: SampleAuthenticationPluginImpl.java    License: 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 23
Source Project: go-plugins   Source File: DoNothingPlugin.java    License: 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 24
@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 25
Source Project: go-plugins   Source File: DummyArtifactPluginTest.java    License: 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 26
Source Project: gocd   Source File: PluginRequestHelperTest.java    License: 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
@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 Project: gocd-s3-artifacts   Source File: FetchTask.java    License: 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 Project: gocd   Source File: AnalyticsExtensionTest.java    License: 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 Project: gocd-yaml-config-plugin   Source File: YamlConfigPlugin.java    License: 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()));
    });
}