<commit_before>package com.mjrichardson.teamCity.buildTriggers;

import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.ServiceLocator;
import jetbrains.buildServer.buildTriggers.BuildTriggerDescriptor;
import jetbrains.buildServer.buildTriggers.BuildTriggerException;
import jetbrains.buildServer.buildTriggers.PolledTriggerContext;
import jetbrains.buildServer.buildTriggers.async.*;
import jetbrains.buildServer.buildTriggers.async.impl.AsyncPolledBuildTrigger;
import jetbrains.buildServer.serverSide.*;
import jetbrains.buildServer.serverSide.impl.LogUtil;
import jetbrains.buildServer.users.SUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;

public class CustomAsyncPolledBuildTrigger<TItem> extends AsyncPolledBuildTrigger<TItem> {
    private final ExecutorService executorService;
    final Logger log;
    private final CheckJobStatusStorage<TItem> storage;
    final CustomAsyncBuildTrigger<TItem> asyncBuildTrigger;
    final ServiceLocator serviceLocator;

    public CustomAsyncPolledBuildTrigger(ExecutorService executorService,
                                         Logger log,
                                         CheckJobStatusStorage<TItem> storage,
                                         int pollInterval,
                                         CustomAsyncBuildTrigger<TItem> asyncBuildTrigger,
                                         ServiceLocator serviceLocator) {
        super(executorService, log, storage, pollInterval, asyncBuildTrigger);
        this.executorService = executorService;
        this.log = log;
        this.storage = storage;
        this.asyncBuildTrigger = asyncBuildTrigger;
        this.serviceLocator = serviceLocator;
    }

    @Override
    public void triggerBuild(@NotNull PolledTriggerContext context) throws BuildTriggerException {
        CustomCheckResult<TItem> result = (CustomCheckResult<TItem>)checkJobStatus(context.getBuildType(), context.getTriggerDescriptor(), context.getCustomDataStorage());
        if (result != null) {
            UUID correlationId = result.getCorrelationId();
            JobResult jobResult = mapCheckResultToJobResult(result, correlationId);

            if (jobResult.shouldTriggerBuild()) {
                SBuildType buildType = serviceLocator.getSingletonService(ProjectManager.class)
                        .findBuildTypeByExternalId(context.getBuildType().getExternalId());
                SUser user = null;
                final BuildCustomizer customizer = serviceLocator.getSingletonService(BuildCustomizerFactory.class)
                        .createBuildCustomizer(buildType, user);
                customizer.setParameters(jobResult.properties);
                try {
                    log.debug(String.format("%s: Creating build promotion", correlationId));
                    BuildPromotionEx promotion = (BuildPromotionEx)customizer.createPromotion();
                    log.debug(String.format("%s: Build promotion %d created", correlationId, promotion.getId()));

                    log.debug(String.format("%s: Adding '%s' to queue", correlationId, buildType.toString()));
                    SQueuedBuild addResult = ((BuildTypeEx)buildType).addToQueue(promotion, jobResult.triggeredBy);
                    log.info(String.format("%s: Added '%s' to queue", correlationId, addResult.toString()));
                }
                catch(Exception e) {
                    log.error(String.format("%s: Failed to create the build promotion", correlationId), e);
                }
            }

            if(jobResult.ex != null) {
                throw jobResult.ex;
            }
        }
    }

    @NotNull
    private JobResult mapCheckResultToJobResult(@NotNull CheckResult<TItem> checkResult, UUID correlationId) {
        JobResult summary = new JobResult();
        Throwable generalError = checkResult.getGeneralError();
        if(generalError != null) {
            summary.ex = asyncBuildTrigger.makeTriggerException(generalError);
        } else {
            Collection<DetectionException> errors = checkResult.getCheckErrors().values();
            if(!errors.isEmpty()) {
                DetectionException cause = errors.iterator().next();
                summary.ex = asyncBuildTrigger.makeTriggerException(cause);
            }
        }

        Collection<TItem> updated = checkResult.getUpdated();
        if (!updated.isEmpty()) {
            log.debug(String.format("%s: changes detected in %s", correlationId, updated));
            TItem update = updated.iterator().next();
            summary.triggeredBy = asyncBuildTrigger.getRequestorString(update);
            //todo: dont add null properties
            Map<String, String> properties = asyncBuildTrigger.getProperties(update);
            for (Map.Entry<String, String> entry : properties.entrySet()) {
                log.debug(String.format("%s: property['%s'] = '%s'", correlationId, entry.getKey(), entry.getValue()));
            }
            summary.properties = properties;
        } else {<commit_msg>Remove todo comment thats no longer necessary<commit_after>package com.mjrichardson.teamCity.buildTriggers;

import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.ServiceLocator;
import jetbrains.buildServer.buildTriggers.BuildTriggerDescriptor;
import jetbrains.buildServer.buildTriggers.BuildTriggerException;
import jetbrains.buildServer.buildTriggers.PolledTriggerContext;
import jetbrains.buildServer.buildTriggers.async.*;
import jetbrains.buildServer.buildTriggers.async.impl.AsyncPolledBuildTrigger;
import jetbrains.buildServer.serverSide.*;
import jetbrains.buildServer.serverSide.impl.LogUtil;
import jetbrains.buildServer.users.SUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;

public class CustomAsyncPolledBuildTrigger<TItem> extends AsyncPolledBuildTrigger<TItem> {
    private final ExecutorService executorService;
    final Logger log;
    private final CheckJobStatusStorage<TItem> storage;
    final CustomAsyncBuildTrigger<TItem> asyncBuildTrigger;
    final ServiceLocator serviceLocator;

    public CustomAsyncPolledBuildTrigger(ExecutorService executorService,
                                         Logger log,
                                         CheckJobStatusStorage<TItem> storage,
                                         int pollInterval,
                                         CustomAsyncBuildTrigger<TItem> asyncBuildTrigger,
                                         ServiceLocator serviceLocator) {
        super(executorService, log, storage, pollInterval, asyncBuildTrigger);
        this.executorService = executorService;
        this.log = log;
        this.storage = storage;
        this.asyncBuildTrigger = asyncBuildTrigger;
        this.serviceLocator = serviceLocator;
    }

    @Override
    public void triggerBuild(@NotNull PolledTriggerContext context) throws BuildTriggerException {
        CustomCheckResult<TItem> result = (CustomCheckResult<TItem>)checkJobStatus(context.getBuildType(), context.getTriggerDescriptor(), context.getCustomDataStorage());
        if (result != null) {
            UUID correlationId = result.getCorrelationId();
            JobResult jobResult = mapCheckResultToJobResult(result, correlationId);

            if (jobResult.shouldTriggerBuild()) {
                SBuildType buildType = serviceLocator.getSingletonService(ProjectManager.class)
                        .findBuildTypeByExternalId(context.getBuildType().getExternalId());
                SUser user = null;
                final BuildCustomizer customizer = serviceLocator.getSingletonService(BuildCustomizerFactory.class)
                        .createBuildCustomizer(buildType, user);
                customizer.setParameters(jobResult.properties);
                try {
                    log.debug(String.format("%s: Creating build promotion", correlationId));
                    BuildPromotionEx promotion = (BuildPromotionEx)customizer.createPromotion();
                    log.debug(String.format("%s: Build promotion %d created", correlationId, promotion.getId()));

                    log.debug(String.format("%s: Adding '%s' to queue", correlationId, buildType.toString()));
                    SQueuedBuild addResult = ((BuildTypeEx)buildType).addToQueue(promotion, jobResult.triggeredBy);
                    log.info(String.format("%s: Added '%s' to queue", correlationId, addResult.toString()));
                }
                catch(Exception e) {
                    log.error(String.format("%s: Failed to create the build promotion", correlationId), e);
                }
            }

            if(jobResult.ex != null) {
                throw jobResult.ex;
            }
        }
    }

    @NotNull
    private JobResult mapCheckResultToJobResult(@NotNull CheckResult<TItem> checkResult, UUID correlationId) {
        JobResult summary = new JobResult();
        Throwable generalError = checkResult.getGeneralError();
        if(generalError != null) {
            summary.ex = asyncBuildTrigger.makeTriggerException(generalError);
        } else {
            Collection<DetectionException> errors = checkResult.getCheckErrors().values();
            if(!errors.isEmpty()) {
                DetectionException cause = errors.iterator().next();
                summary.ex = asyncBuildTrigger.makeTriggerException(cause);
            }
        }

        Collection<TItem> updated = checkResult.getUpdated();
        if (!updated.isEmpty()) {
            log.debug(String.format("%s: changes detected in %s", correlationId, updated));
            TItem update = updated.iterator().next();
            summary.triggeredBy = asyncBuildTrigger.getRequestorString(update);
            Map<String, String> properties = asyncBuildTrigger.getProperties(update);
            for (Map.Entry<String, String> entry : properties.entrySet()) {
                log.debug(String.format("%s: property['%s'] = '%s'", correlationId, entry.getKey(), entry.getValue()));
            }
            summary.properties = properties;
        } else {
{'fraction_non_alphanumeric': 0.09193966759535017, 'fraction_numerical': 0.0, 'mean_word_length': 2.7099073414112618, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5457799', 'n_tokens_mistral': 2533, 'n_tokens_neox': 2452, 'n_words': 483}