<commit_before>/**
 * Copyright (C) 2012 White Source Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.whitesource.teamcity.agent;

import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.ExtensionHolder;
import jetbrains.buildServer.agent.*;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.util.EventDispatcher;
import jetbrains.buildServer.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.CollectionUtils;
import org.whitesource.agent.api.dispatch.CheckPoliciesResult;
import org.whitesource.agent.api.dispatch.UpdateInventoryResult;
import org.whitesource.agent.api.model.AgentProjectInfo;
import org.whitesource.agent.api.model.DependencyInfo;
import org.whitesource.agent.client.WhitesourceService;
import org.whitesource.agent.client.WssServiceException;
import org.whitesource.agent.report.PolicyCheckReport;
import org.whitesource.teamcity.common.Constants;
import org.whitesource.teamcity.common.WssUtils;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Edo.Shor
 */
public class WhitesourceLifeCycleListener extends AgentLifeCycleAdapter {

    /* --- Static members --- */

    private static final String LOG_COMPONENT = "LifeCycleListener";

    private ExtensionHolder extensionHolder;

    /* --- Constructors --- */

    /**
     * Constructor
     */
    public WhitesourceLifeCycleListener(@NotNull final EventDispatcher<AgentLifeCycleListener> eventDispatcher,
                                        @NotNull final ExtensionHolder extensionHolder) {
        this.extensionHolder = extensionHolder;
        eventDispatcher.addListener(this);
    }

    @Override
    public void agentInitialized(@NotNull BuildAgent agent) {
        super.agentInitialized(agent);
        Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "initialized"));
    }

    /* --- Interface implementation methods --- */

    @Override
    public void beforeRunnerStart(@NotNull BuildRunnerContext runner) {
        super.beforeRunnerStart(runner);

        if (shouldUpdate(runner)) {
            Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "before runner start "
                    + runner.getBuild().getProjectName() + " type " + runner.getName()));
        }
    }

    @Override
    public void runnerFinished(@NotNull BuildRunnerContext runner, @NotNull BuildFinishedStatus status) {
        super.runnerFinished(runner, status);

        AgentRunningBuild build = runner.getBuild();
        Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "runner finished " + build.getProjectName() + " type " + runner.getName()));

        if (!shouldUpdate(runner)) { return; } // no need to update white source...

        final BuildProgressLogger buildLogger = build.getBuildLogger();
        buildLogger.message("Updating White Source");

        // make sure we have an organization token
        Map<String, String> runnerParameters = runner.getRunnerParameters();
        String orgToken = runnerParameters.get(Constants.RUNNER_OVERRIDE_ORGANIZATION_TOKEN);
        if (StringUtil.isEmptyOrSpaces(orgToken)) {
            orgToken = runnerParameters.get(Constants.RUNNER_ORGANIZATION_TOKEN);
        }
        if (StringUtil.isEmptyOrSpaces(orgToken)) {
            stopBuildOnError((AgentRunningBuildEx) build,
                    new IllegalStateException("Empty organization token. Please make sure an organization token is defined for this runner"));
            return;
        }

        // should we check policies first ?
        boolean shouldCheckPolicies;
        String overrideCheckPolicies = runnerParameters.get(Constants.RUNNER_OVERRIDE_CHECK_POLICIES);
        if (StringUtils.isBlank(overrideCheckPolicies) ||
                "global".equals(overrideCheckPolicies)) {
            shouldCheckPolicies = Boolean.parseBoolean(runnerParameters.get(Constants.RUNNER_CHECK_POLICIES));
        } else {
            shouldCheckPolicies = "enabled".equals(overrideCheckPolicies);
        }

        String product = runnerParameters.get(Constants.RUNNER_PRODUCT);
        String productVersion = runnerParameters.get(Constants.RUNNER_PRODUCT_VERSION);

        // collect OSS usage information
        buildLogger.message("Collecting OSS usage information");
        Collection<AgentProjectInfo> projectInfos;
        if (WssUtils.isMavenRunType(runner.getRunType())) {
            MavenOssInfoExtractor extractor = new MavenOssInfoExtractor(runner);
            projectInfos = extractor.extract();
            if (StringUtil.isEmptyOrSpaces(product)) {
                product = extractor.getTopMostProjectName();
            }
        } else {
            GenericOssInfoExtractor extractor = new GenericOssInfoExtractor(runner);
            projectInfos = extractor.extract();
        }
        debugAgentProjectInfos(projectInfos);

        // send to white source
        if (CollectionUtils.isEmpty(projectInfos)) {
            buildLogger.message("No open source information found.");
        } else {<commit_msg>Fix for override Check Policies in agent<commit_after>/**
 * Copyright (C) 2012 White Source Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.whitesource.teamcity.agent;

import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.ExtensionHolder;
import jetbrains.buildServer.agent.*;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.util.EventDispatcher;
import jetbrains.buildServer.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.CollectionUtils;
import org.whitesource.agent.api.dispatch.CheckPoliciesResult;
import org.whitesource.agent.api.dispatch.UpdateInventoryResult;
import org.whitesource.agent.api.model.AgentProjectInfo;
import org.whitesource.agent.api.model.DependencyInfo;
import org.whitesource.agent.client.WhitesourceService;
import org.whitesource.agent.client.WssServiceException;
import org.whitesource.agent.report.PolicyCheckReport;
import org.whitesource.teamcity.common.Constants;
import org.whitesource.teamcity.common.WssUtils;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Edo.Shor
 */
public class WhitesourceLifeCycleListener extends AgentLifeCycleAdapter {

    /* --- Static members --- */

    private static final String LOG_COMPONENT = "LifeCycleListener";

    private ExtensionHolder extensionHolder;

    /* --- Constructors --- */

    /**
     * Constructor
     */
    public WhitesourceLifeCycleListener(@NotNull final EventDispatcher<AgentLifeCycleListener> eventDispatcher,
                                        @NotNull final ExtensionHolder extensionHolder) {
        this.extensionHolder = extensionHolder;
        eventDispatcher.addListener(this);
    }

    @Override
    public void agentInitialized(@NotNull BuildAgent agent) {
        super.agentInitialized(agent);
        Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "initialized"));
    }

    /* --- Interface implementation methods --- */

    @Override
    public void beforeRunnerStart(@NotNull BuildRunnerContext runner) {
        super.beforeRunnerStart(runner);

        if (shouldUpdate(runner)) {
            Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "before runner start "
                    + runner.getBuild().getProjectName() + " type " + runner.getName()));
        }
    }

    @Override
    public void runnerFinished(@NotNull BuildRunnerContext runner, @NotNull BuildFinishedStatus status) {
        super.runnerFinished(runner, status);

        AgentRunningBuild build = runner.getBuild();
        Loggers.AGENT.info(WssUtils.logMsg(LOG_COMPONENT, "runner finished " + build.getProjectName() + " type " + runner.getName()));

        if (!shouldUpdate(runner)) { return; } // no need to update white source...

        final BuildProgressLogger buildLogger = build.getBuildLogger();
        buildLogger.message("Updating White Source");

        // make sure we have an organization token
        Map<String, String> runnerParameters = runner.getRunnerParameters();
        String orgToken = runnerParameters.get(Constants.RUNNER_OVERRIDE_ORGANIZATION_TOKEN);
        if (StringUtil.isEmptyOrSpaces(orgToken)) {
            orgToken = runnerParameters.get(Constants.RUNNER_ORGANIZATION_TOKEN);
        }
        if (StringUtil.isEmptyOrSpaces(orgToken)) {
            stopBuildOnError((AgentRunningBuildEx) build,
                    new IllegalStateException("Empty organization token. Please make sure an organization token is defined for this runner"));
            return;
        }

        // should we check policies first ?
        boolean shouldCheckPolicies;
        String overrideCheckPolicies = runnerParameters.get(Constants.RUNNER_OVERRIDE_CHECK_POLICIES);
        if (StringUtils.isBlank(overrideCheckPolicies) ||
                "global".equals(overrideCheckPolicies)) {
            shouldCheckPolicies = Boolean.parseBoolean(runnerParameters.get(Constants.RUNNER_CHECK_POLICIES));
        } else {
            shouldCheckPolicies = "enable".equals(overrideCheckPolicies);
        }

        String product = runnerParameters.get(Constants.RUNNER_PRODUCT);
        String productVersion = runnerParameters.get(Constants.RUNNER_PRODUCT_VERSION);

        // collect OSS usage information
        buildLogger.message("Collecting OSS usage information");
        Collection<AgentProjectInfo> projectInfos;
        if (WssUtils.isMavenRunType(runner.getRunType())) {
            MavenOssInfoExtractor extractor = new MavenOssInfoExtractor(runner);
            projectInfos = extractor.extract();
            if (StringUtil.isEmptyOrSpaces(product)) {
                product = extractor.getTopMostProjectName();
            }
        } else {
            GenericOssInfoExtractor extractor = new GenericOssInfoExtractor(runner);
            projectInfos = extractor.extract();
        }
        debugAgentProjectInfos(projectInfos);

        // send to white source
        if (CollectionUtils.isEmpty(projectInfos)) {
            buildLogger.message("No open source information found.");
        } else {
{'fraction_non_alphanumeric': 0.09129213483146068, 'fraction_numerical': 0.0014044943820224719, 'mean_word_length': 3.3634622749904253, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1894766', 'n_tokens_mistral': 2990, 'n_tokens_neox': 2931, 'n_words': 672}