com.tw.go.plugin.util.JSONUtils Java Examples

The following examples show how to use com.tw.go.plugin.util.JSONUtils. 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: OAuthLoginPlugin.java    From gocd-oauth-login with Apache License 2.0 6 votes vote down vote up
private GoPluginApiResponse renderJSON(final int responseCode, final Map<String, String> responseHeaders, Object response) {
    final String json = response == null ? null : JSONUtils.toJSON(response);
    return new GoPluginApiResponse() {
        @Override
        public int responseCode() {
            return responseCode;
        }

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

        @Override
        public String responseBody() {
            return json;
        }
    };
}
 
Example #2
Source File: OAuthLoginPlugin.java    From gocd-oauth-login with Apache License 2.0 5 votes vote down vote up
public PluginSettings getPluginSettings() {
    Map<String, Object> requestMap = new HashMap<String, Object>();
    requestMap.put("plugin-id", provider.getPluginId());
    GoApiResponse response = goApplicationAccessor.submit(createGoApiRequest(GET_PLUGIN_SETTINGS, JSONUtils.toJSON(requestMap)));
    if (response.responseBody() == null || response.responseBody().trim().isEmpty()) {
        throw new RuntimeException("plugin is not configured. please provide plugin settings.");
    }
    return provider.pluginSettings((Map<String, String>) JSONUtils.fromJSON(response.responseBody()));
}
 
Example #3
Source File: StashBuildStatusNotifierPluginTest.java    From gocd-build-status-notifier with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    initMocks(this);

    plugin = new StashBuildStatusNotifierPlugin();

    DefaultGoApiResponse pluginSettingsResponse = new DefaultGoApiResponse(200);
    pluginSettingsResponse.setResponseBody(JSONUtils.toJSON(new HashMap<String, String>()));
    when(goApplicationAccessor.submit(any(GoApiRequest.class))).thenReturn(pluginSettingsResponse);
    when(provider.pluginId()).thenReturn(PLUGIN_ID);
    when(provider.pollerPluginId()).thenReturn(POLLER_PLUGIN_ID);

    plugin.initializeGoApplicationAccessor(goApplicationAccessor);
    plugin.setProvider(provider);
}
 
Example #4
Source File: BuildStatusNotifierPlugin.java    From gocd-build-status-notifier with Apache License 2.0 5 votes vote down vote up
public PluginSettings getPluginSettings() {
    Map<String, Object> requestMap = new HashMap<String, Object>();
    requestMap.put("plugin-id", provider.pluginId());
    GoApiResponse response = goApplicationAccessor.submit(createGoApiRequest(GET_PLUGIN_SETTINGS, JSONUtils.toJSON(requestMap)));
    Map<String, String> responseBodyMap = response.responseBody() == null ? new HashMap<String, String>() : (Map<String, String>) JSONUtils.fromJSON(response.responseBody());
    return provider.pluginSettings(responseBodyMap);
}
 
Example #5
Source File: GerritBuildStatusNotifierPluginTest.java    From gocd-build-status-notifier with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    initMocks(this);

    plugin = new GerritBuildStatusNotifierPlugin();

    DefaultGoApiResponse pluginSettingsResponse = new DefaultGoApiResponse(200);
    pluginSettingsResponse.setResponseBody(JSONUtils.toJSON(new HashMap<String, String>()));
    when(goApplicationAccessor.submit(any(GoApiRequest.class))).thenReturn(pluginSettingsResponse);
    when(provider.pluginId()).thenReturn(PLUGIN_ID);
    when(provider.pollerPluginId()).thenReturn(POLLER_PLUGIN_ID);

    plugin.initializeGoApplicationAccessor(goApplicationAccessor);
    plugin.setProvider(provider);
}
 
Example #6
Source File: GerritProvider.java    From gocd-build-status-notifier with Apache License 2.0 5 votes vote down vote up
@Override
public void updateStatus(String url, PluginSettings pluginSettings, String branch, String revision, String pipelineInstance,
                         String result, String trackbackURL) throws Exception {
    GerritPluginSettings settings = (GerritPluginSettings) pluginSettings;

    String endPointToUse = settings.getEndPoint();
    String usernameToUse = settings.getUsername();
    String passwordToUse = settings.getPassword();
    String codeReviewLabel = settings.getReviewLabel();

    if (StringUtils.isEmpty(endPointToUse)) {
        endPointToUse = System.getProperty("go.plugin.build.status.gerrit.endpoint");
    }
    if (StringUtils.isEmpty(usernameToUse)) {
        usernameToUse = System.getProperty("go.plugin.build.status.gerrit.username");
    }
    if (StringUtils.isEmpty(passwordToUse)) {
        passwordToUse = System.getProperty("go.plugin.build.status.gerrit.password");
    }
    if (StringUtils.isEmpty(codeReviewLabel)) {
        codeReviewLabel = System.getProperty("go.plugin.build.status.gerrit.codeReviewLabel");
    }

    String commitDetailsURL = String.format("%s/a/changes/?q=commit:%s", endPointToUse, revision);
    String commitDetailsResponse = httpClient.getRequest(commitDetailsURL, AuthenticationType.DIGEST, usernameToUse, passwordToUse);
    CommitDetails commitDetails = new ResponseParser().parseCommitDetails(commitDetailsResponse);

    Map<String, Object> request = new HashMap<String, Object>();
    request.put("message", String.format("%s: %s", pipelineInstance, trackbackURL));
    Map<String, Object> labels = new HashMap<String, Object>();
    request.put("labels", labels);
    labels.put(codeReviewLabel, getCodeReviewValue(result));
    String updateStatusURL = String.format("%s/a/changes/%s/revisions/%s/review", endPointToUse, commitDetails.getId(), revision);
    httpClient.postRequest(updateStatusURL, AuthenticationType.DIGEST, usernameToUse, passwordToUse, JSONUtils.toJSON(request));
}
 
Example #7
Source File: GitHubBuildStatusNotifierPluginTest.java    From gocd-build-status-notifier with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    initMocks(this);

    plugin = new GitHubBuildStatusNotifierPlugin();

    DefaultGoApiResponse pluginSettingsResponse = new DefaultGoApiResponse(200);
    pluginSettingsResponse.setResponseBody(JSONUtils.toJSON(new HashMap<String, String>()));
    when(goApplicationAccessor.submit(any(GoApiRequest.class))).thenReturn(pluginSettingsResponse);
    when(provider.pluginId()).thenReturn(PLUGIN_ID);
    when(provider.pollerPluginId()).thenReturn(POLLER_PLUGIN_ID);

    plugin.initializeGoApplicationAccessor(goApplicationAccessor);
    plugin.setProvider(provider);
}
 
Example #8
Source File: EmailNotificationPluginImplUnitTest.java    From email-notifier with Apache License 2.0 5 votes vote down vote up
private static GoApiRequest testSettingsRequest() {

        final Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("plugin-id", "email.notifier");

        final String responseBody = JSONUtils.toJSON(requestMap);

        return new GoApiRequest() {
            @Override
            public String api() {
                return "go.processor.plugin-settings.get";
            }

            @Override
            public String apiVersion() {
                return "1.0";
            }

            @Override
            public GoPluginIdentifier pluginIdentifier() {
                return new GoPluginIdentifier("notification", Collections.singletonList("1.0"));
            }

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

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

            @Override
            public String requestBody() {
                return responseBody;
            }
        };
    }
 
Example #9
Source File: EmailNotificationPluginImpl.java    From email-notifier with Apache License 2.0 5 votes vote down vote up
public PluginSettings getPluginSettings() {
    Map<String, Object> requestMap = new HashMap<>();
    requestMap.put("plugin-id", PLUGIN_ID);
    GoApiResponse response = goApplicationAccessor.submit(createGoApiRequest(GET_PLUGIN_SETTINGS, JSONUtils.toJSON(requestMap)));
    if (response.responseBody() == null || response.responseBody().trim().isEmpty()) {
        throw new RuntimeException("plugin is not configured. please provide plugin settings.");
    }
    Map<String, String> responseBodyMap = (Map<String, String>) JSONUtils.fromJSON(response.responseBody());
    return new PluginSettings(responseBodyMap.get(PLUGIN_SETTINGS_SMTP_HOST), Integer.parseInt(responseBodyMap.get(PLUGIN_SETTINGS_SMTP_PORT)),
            Boolean.parseBoolean(responseBodyMap.get(PLUGIN_SETTINGS_IS_TLS)), responseBodyMap.get(PLUGIN_SETTINGS_SENDER_EMAIL_ID),
            responseBodyMap.get(PLUGIN_SETTINGS_SMTP_USERNAME),
            responseBodyMap.get(PLUGIN_SETTINGS_SENDER_PASSWORD), responseBodyMap.get(PLUGIN_SETTINGS_RECEIVER_EMAIL_ID),
            responseBodyMap.get(PLUGIN_SETTINGS_FILTER));
}
 
Example #10
Source File: GitLabProvider.java    From gocd-oauth-login with Apache License 2.0 5 votes vote down vote up
@Override
public List<User> searchUser(GitLabPluginSettings pluginSettings, String searchTerm) {
    HttpUrl searchBaseUrl = HttpUrl.parse(fullUrl(pluginSettings, "/api/v3/users"));

    HttpUrl url = new HttpUrl.Builder()
            .scheme(searchBaseUrl.scheme())
            .host(searchBaseUrl.host())
            .addPathSegments(searchBaseUrl.encodedPath())
            .addQueryParameter("private_token", pluginSettings.getOauthToken())
            .addQueryParameter("search", searchTerm)
            .build();

    Request request = new Request.Builder().url(url.url()).build();

    try {
        Response response = client.newCall(request).execute();
        List<User> users = new ArrayList<>();

        for (Map<String, String> userParams : (List<Map<String, String>>) JSONUtils.fromJSON(response.body().string())) {
            users.add(new User(userParams.get("email"), userParams.get("name"), userParams.get("email")));
        }
        return users;

    } catch (IOException e) {
        LOGGER.warn("Error occurred while trying to perform user search", e);
        return new ArrayList<>();
    }
}
 
Example #11
Source File: OAuthLoginPlugin.java    From gocd-oauth-login with Apache License 2.0 5 votes vote down vote up
private void authenticateUser(User user) {
    final Map<String, Object> userMap = new HashMap<String, Object>();
    userMap.put("user", getUserMap(user));
    GoApiRequest authenticateUserRequest = createGoApiRequest(GO_REQUEST_AUTHENTICATE_USER, JSONUtils.toJSON(userMap));
    GoApiResponse authenticateUserResponse = goApplicationAccessor.submit(authenticateUserRequest);
    // handle error
}
 
Example #12
Source File: OAuthLoginPlugin.java    From gocd-oauth-login with Apache License 2.0 5 votes vote down vote up
private void delete() {
    Map<String, Object> requestMap = new HashMap<String, Object>();
    requestMap.put("plugin-id", provider.getPluginId());
    GoApiRequest goApiRequest = createGoApiRequest(GO_REQUEST_SESSION_REMOVE, JSONUtils.toJSON(requestMap));
    GoApiResponse response = goApplicationAccessor.submit(goApiRequest);
    // handle error
}
 
Example #13
Source File: OAuthLoginPlugin.java    From gocd-oauth-login with Apache License 2.0 5 votes vote down vote up
private SocialAuthManager read() {
    Map<String, Object> requestMap = new HashMap<String, Object>();
    requestMap.put("plugin-id", provider.getPluginId());
    GoApiRequest goApiRequest = createGoApiRequest(GO_REQUEST_SESSION_GET, JSONUtils.toJSON(requestMap));
    GoApiResponse response = goApplicationAccessor.submit(goApiRequest);
    // handle error
    String responseBody = response.responseBody();
    Map<String, String> sessionData = (Map<String, String>) JSONUtils.fromJSON(responseBody);
    String socialAuthManagerStr = sessionData.get("social-auth-manager");
    return deserializeObject(socialAuthManagerStr);
}
 
Example #14
Source File: OAuthLoginPlugin.java    From gocd-oauth-login with Apache License 2.0 5 votes vote down vote up
private void  store(SocialAuthManager socialAuthManager) {
    Map<String, Object> requestMap = new HashMap<String, Object>();
    requestMap.put("plugin-id", provider.getPluginId());
    Map<String, Object> sessionData = new HashMap<String, Object>();
    String socialAuthManagerStr = serializeObject(socialAuthManager);
    sessionData.put("social-auth-manager", socialAuthManagerStr);
    requestMap.put("session-data", sessionData);
    GoApiRequest goApiRequest = createGoApiRequest(GO_REQUEST_SESSION_PUT, JSONUtils.toJSON(requestMap));
    GoApiResponse response = goApplicationAccessor.submit(goApiRequest);
    // handle error
}
 
Example #15
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 #16
Source File: EmailNotificationPluginImpl.java    From email-notifier with Apache License 2.0 4 votes vote down vote up
private GoPluginApiResponse handleStageNotification(GoPluginApiRequest goPluginApiRequest) {
    Map<String, Object> dataMap = (Map<String, Object>) JSONUtils.fromJSON(goPluginApiRequest.requestBody());

    int responseCode = SUCCESS_RESPONSE_CODE;
    Map<String, Object> response = new HashMap<>();
    List<String> messages = new ArrayList<>();
    try {
        Map<String, Object> pipelineMap = (Map<String, Object>) dataMap.get("pipeline");
        Map<String, Object> stageMap = (Map<String, Object>) pipelineMap.get("stage");


        String pipelineName = (String) pipelineMap.get("name");
        String stageName = (String) stageMap.get("name");
        String stageState = (String) stageMap.get("state");

        String subject = String.format("%s/%s is/has %s", pipelineName, stageName, stageState);
        String body = String.format("State: %s\nResult: %s\nCreate Time: %s\nLast Transition Time: %s", stageState, stageMap.get("result"), stageMap.get("create-time"), stageMap.get("last-transition-time"));

        PluginSettings pluginSettings = getPluginSettings();


        boolean matchesFilter = false;

        List<Filter> filterList = pluginSettings.getFilterList();

        if(filterList.isEmpty()) {
            matchesFilter = true;
        } else {
            for(Filter filter : filterList) {
                if(filter.matches(pipelineName, stageName, stageState)) {
                    matchesFilter = true;
                }
            }
        }

        if(matchesFilter) {
            LOGGER.info("Sending Email for " + subject);

            String receiverEmailIdString = pluginSettings.getReceiverEmailId();

            String[] receiverEmailIds = new String[]{receiverEmailIdString};

            if (receiverEmailIdString.contains(",")) {
                receiverEmailIds = receiverEmailIdString.split(",");
            }

            for (String receiverEmailId : receiverEmailIds) {
                SMTPSettings settings = new SMTPSettings(pluginSettings.getSmtpHost(), pluginSettings.getSmtpPort(), pluginSettings.isTls(), pluginSettings.getSenderEmailId(), pluginSettings.getSmtpUsername(), pluginSettings.getSenderPassword());
                new SMTPMailSender(settings, sessionFactory).send(subject, body, receiverEmailId);
            }

            LOGGER.info("Successfully delivered an email.");
        } else {
            LOGGER.info("Skipped email as no filter matched this pipeline/stage/state");
        }

        response.put("status", "success");
    } catch (Exception e) {
        LOGGER.warn("Error occurred while trying to deliver an email.", e);

        responseCode = INTERNAL_ERROR_RESPONSE_CODE;
        response.put("status", "failure");
        if (!isEmpty(e.getMessage())) {
            messages.add(e.getMessage());
        }
    }

    if (!messages.isEmpty()) {
        response.put("messages", messages);
    }
    return renderJSON(responseCode, response);
}
 
Example #17
Source File: GitHubBuildStatusNotifierPluginTest.java    From gocd-build-status-notifier with Apache License 2.0 4 votes vote down vote up
private DefaultGoPluginApiRequest createGoPluginAPIRequest(Map requestBody) {
    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(BuildStatusNotifierPlugin.EXTENSION_NAME, "1.0", BuildStatusNotifierPlugin.REQUEST_STAGE_STATUS);
    request.setRequestBody(JSONUtils.toJSON(requestBody));
    return request;
}
 
Example #18
Source File: GerritBuildStatusNotifierPluginTest.java    From gocd-build-status-notifier with Apache License 2.0 4 votes vote down vote up
private DefaultGoPluginApiRequest createGoPluginAPIRequest(Map requestBody) {
    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(BuildStatusNotifierPlugin.EXTENSION_NAME, "1.0", BuildStatusNotifierPlugin.REQUEST_STAGE_STATUS);
    request.setRequestBody(JSONUtils.toJSON(requestBody));
    return request;
}
 
Example #19
Source File: BuildStatusNotifierPlugin.java    From gocd-build-status-notifier with Apache License 2.0 4 votes vote down vote up
private GoPluginApiResponse handleValidatePluginSettingsConfiguration(GoPluginApiRequest goPluginApiRequest) {
    Map<String, Object> fields = (Map<String, Object>) JSONUtils.fromJSON(goPluginApiRequest.requestBody());
    List<Map<String, Object>> response = provider.validateConfig((Map<String, Object>) fields.get("plugin-settings"));
    return renderJSON(SUCCESS_RESPONSE_CODE, response);
}
 
Example #20
Source File: StashBuildStatusNotifierPluginTest.java    From gocd-build-status-notifier with Apache License 2.0 4 votes vote down vote up
private DefaultGoPluginApiRequest createGoPluginAPIRequest(Map requestBody) {
    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(BuildStatusNotifierPlugin.EXTENSION_NAME, "1.0", BuildStatusNotifierPlugin.REQUEST_STAGE_STATUS);
    request.setRequestBody(JSONUtils.toJSON(requestBody));
    return request;
}
 
Example #21
Source File: EmailNotificationPluginImplUnitTest.java    From email-notifier with Apache License 2.0 3 votes vote down vote up
private GoPluginApiRequest testStageChangeRequestFromServer() {
    GoPluginApiRequest requestFromGoServer = mock(GoPluginApiRequest.class);

    when(requestFromGoServer.requestName()).thenReturn("stage-status");

    when(requestFromGoServer.requestBody()).thenReturn(JSONUtils.toJSON(stateChangeResponseMap));

    return requestFromGoServer;
}
 
Example #22
Source File: EmailNotificationPluginImplUnitTest.java    From email-notifier with Apache License 2.0 3 votes vote down vote up
private GoApiResponse testSettingsResponse() {
    GoApiResponse settingsResponse = mock(GoApiResponse.class);

    when(settingsResponse.responseBody()).thenReturn(JSONUtils.toJSON(settingsResponseMap));

    return settingsResponse;
}