Commits

jmort  committed d681c4a

AUTOPLAN-6: pom is created with 3 dummy stages

git-svn-id: https://adaptavist.jira.com/svn/AUTOPLAN/trunk@8729e6edf6fb-f266-4316-afb4-e53d95876a76

  • Participants
  • Parent commits d022212

Comments (0)

Files changed (9)

             <artifactId>atlassian-bamboo-web</artifactId>
             <version>${bamboo.version}</version>
             <scope>provided</scope>
+            <exclusions>
+                <exclusion>
+                    <groupId>com.atlassian.bamboo</groupId>
+                    <artifactId>atlassian-bamboo-migration</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>com.atlassian.bamboo</groupId>
+            <artifactId>atlassian-bamboo-api</artifactId>
+            <version>3.2</version>
+            <scope>provided</scope>
         </dependency>
 
         <dependency>

File src/main/java/com/adaptavist/bamboo/autoplan/CheckoutAction.java

+package com.adaptavist.bamboo.autoplan;
+
+import com.atlassian.bamboo.ww2.actions.admin.ImportMavenPlanCheckoutPomAction;
+import com.atlassian.spring.container.ContainerManager;
+
+public class CheckoutAction extends ImportMavenPlanCheckoutPomAction {
+    // for some reason unknown to me the bamboo action doesn't get fully injected unless explicitly autowire it from the ContainerManager
+    public CheckoutAction() {
+        ContainerManager.autowireComponent(this);
+    }
+}

File src/main/java/com/adaptavist/bamboo/autoplan/CreatePlanAction.java

+package com.adaptavist.bamboo.autoplan;
+
+import com.atlassian.bamboo.build.Job;
+import com.atlassian.bamboo.build.PlanCreationDeniedException;
+import com.atlassian.bamboo.build.creation.JobCreationService;
+import com.atlassian.bamboo.build.creation.PlanCreationService;
+import com.atlassian.bamboo.build.strategy.BuildStrategy;
+import com.atlassian.bamboo.build.strategy.PollingBuildStrategy;
+import com.atlassian.bamboo.chains.Chain;
+import com.atlassian.bamboo.fieldvalue.BuildDefinitionConverter;
+import com.atlassian.bamboo.fieldvalue.TaskConfigurationUtils;
+import com.atlassian.bamboo.notification.NotificationRule;
+import com.atlassian.bamboo.plan.PlanKeys;
+import com.atlassian.bamboo.task.TaskConfigConstants;
+import com.atlassian.bamboo.task.TaskDefinition;
+import com.atlassian.bamboo.task.TaskDefinitionImpl;
+import com.atlassian.bamboo.v2.build.trigger.DependencyBlockingStrategy;
+import com.atlassian.bamboo.webwork.util.ActionParametersMapImpl;
+import com.atlassian.bamboo.ww2.actions.admin.ImportMavenPlanCreatePlanAction;
+import com.atlassian.bamboo.ww2.actions.build.admin.create.BuildConfiguration;
+import com.atlassian.spring.container.ContainerManager;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.opensymphony.xwork.ActionContext;
+import org.apache.commons.configuration.XMLConfiguration;
+
+import java.util.List;
+import java.util.Map;
+
+public class CreatePlanAction extends ImportMavenPlanCreatePlanAction {
+    private static final String PROJECT_KEY = "projectKey";
+    private static final String PROJECT_NAME = "projectName";
+    private static final String NEW_PROJECT_MARKER = "newProject";
+    private static final String CHAIN_KEY = "chainKey";
+    private static final String CHAIN_NAME = "chainName";
+    private static final String TMP_CREATE_AS_ENABLED_PROPERTY = "tmp.createAsEnabled";
+    private static final String KEY_MAVEN2_TASK = "com.atlassian.bamboo.plugins.maven:task.builder.mvn2";
+    private static final String MAVEN_CFG_GOAL = "goal";
+    private static final long TASK_ID = 1;
+    private String fullPlanKey;
+
+
+    // for some reason unknown to me the bamboo action doesn't get fully injected unless explicitly autowire it from the ContainerManager
+    public CreatePlanAction() {
+        ContainerManager.autowireComponent(this);
+    }
+
+    @Override
+    public String doExecute() throws Exception {
+
+        final PlanCreationService.EnablePlan enablePlan;
+        if (getBuildConfiguration().getBoolean(TMP_CREATE_AS_ENABLED_PROPERTY, false)) {
+            enablePlan = PlanCreationService.EnablePlan.ENABLED;
+        } else {
+            enablePlan = PlanCreationService.EnablePlan.DISABLED;
+        }
+
+        BuildDefinitionConverter buildDefinitionConverter = (BuildDefinitionConverter) ContainerManager.getComponent("buildDefinitionConverter");
+
+        // create the chain
+        BuildConfiguration chainBuildConfiguration = new BuildConfiguration(getBuildConfiguration().asXml());
+        final BuildStrategy polling = new PollingBuildStrategy();
+        buildDefinitionConverter.setBuildStrategyToConfig(chainBuildConfiguration.getProjectConfig(), polling);
+        buildConfiguration.setProperty(DependencyBlockingStrategy.DEPENDENCY_BLOCKING_STRATEGY_CONFIG_KEY, DependencyBlockingStrategy.BuildParentIfChangesDetected.getValue());
+
+        ActionParametersMapImpl actionParametersMap = new ActionParametersMapImpl(ActionContext.getContext());
+        PlanCreationService chainCreationService = (PlanCreationService) ContainerManager.getComponent("chainCreationService");
+
+        String chainKey = chainCreationService.createPlan(chainBuildConfiguration, actionParametersMap, enablePlan);
+
+
+        fullPlanKey = createNewStageWithJob(chainKey, "Package", "PACKAGE", "Package Stage", "clean package", JobCreationService.NEW_STAGE_MARKER);
+        createNewStageWithJob(chainKey, "Integration Test", "INTTEST", "Integration Test Stage", "clean verify -DtestGroups=blah", JobCreationService.NEW_STAGE_MARKER);
+        createNewStageWithJob(chainKey, "Integration Test2", "INTTEST2", "Integration Test Stage", "clean verify -DtestGroups=blah", "Integration Test Stage");
+        createNewStageWithJob(chainKey, "Deploy", "Deploy", "Deploy Stage", "clean deploy", JobCreationService.NEW_STAGE_MARKER);
+
+
+        // add notifications to chain.
+        if (!getNotificationSet().getNotificationRules().isEmpty()) {
+            Chain chain = planManager.getPlanByKey(chainKey, Chain.class);
+            if (chain == null) {
+                throw new IllegalStateException("We just created a plan but can't find it in the database");
+            }
+
+            for (NotificationRule rule : getNotificationSet().getNotificationRules()) {
+                chain.getNotificationSet().addNotification(rule);
+            }
+            planManager.savePlan(chain);
+        }
+        return SUCCESS;
+    }
+
+    private String createNewStageWithJob(String newPlanKey, final String buildName, final String buildKey, final String stageName, final String mavenGoals, final String existingStage) throws PlanCreationDeniedException {
+        final JobCreationService jobCreationService = (JobCreationService) ContainerManager.getComponent("jobCreationService");
+        Map<String, Object> jobContext = Maps.newHashMap();
+        jobContext.put(JobCreationService.BUILD_KEY, newPlanKey);
+        jobContext.put(JobCreationService.BUILD_NAME, buildName);
+        jobContext.put(JobCreationService.SUB_BUILD_KEY, buildKey);
+        jobContext.put(JobCreationService.STAGE_NAME, stageName);
+        jobContext.put(JobCreationService.EXISTING_STAGE, existingStage);
+        BuildConfiguration jobBuildConfiguration = new BuildConfiguration();
+        jobBuildConfiguration.setProperty(BuildDefinitionConverter.INHERIT_REPOSITORY, "true");
+        addMaven2TaskToConfiguration(jobBuildConfiguration, mavenGoals, "Build for " + buildName);
+        String fullPlanKey = jobCreationService.createPlan(jobBuildConfiguration, new ActionParametersMapImpl(jobContext), PlanCreationService.EnablePlan.ENABLED);
+        jobCreationService.triggerCreationCompleteEvents(PlanKeys.getPlanKey(fullPlanKey));
+        Job job = planManager.getPlanByKey(fullPlanKey, Job.class);
+        if (job != null) {
+            List<TaskDefinition> tasks = job.getBuildDefinition().getTaskDefinitions();
+            for (TaskDefinition task : tasks) {
+                taskManager.calculateRequirementsForTaskDefinition(job, task);
+                buildDefinitionManager.savePlanAndDefinition(job, job.getBuildDefinition());
+            }
+        }
+        return fullPlanKey;
+    }
+
+    private void addMaven2TaskToConfiguration(BuildConfiguration buildConfiguration, final String goals, final String userDescription) {
+        TaskDefinition maven2Task = new TaskDefinitionImpl(TASK_ID,
+                KEY_MAVEN2_TASK,
+                userDescription,
+                Maps.newHashMap(ImmutableMap.of("environmentVariables", "DISPLAY:=99")));
+
+        maven2Task.getConfiguration().put(TaskConfigConstants.CFG_BUILDER_LABEL, findBestMaven2Builder());
+        maven2Task.getConfiguration().put(TaskConfigConstants.CFG_JDK_LABEL, uiConfigBean.getDefaultJdkLabel());
+        maven2Task.getConfiguration().put(MAVEN_CFG_GOAL, goals);
+        maven2Task.getConfiguration().put(TaskConfigConstants.CFG_HAS_TESTS, Boolean.TRUE.toString());
+        maven2Task.getConfiguration().put(TaskConfigConstants.CFG_TEST_RESULTS_FILE_PATTERN_OPTION, "customTestDirectory");
+        maven2Task.getConfiguration().put(TaskConfigConstants.CFG_TEST_RESULTS_FILE_PATTERN, "**/target/**/surefire-reports/*.xml");
+
+        // Actually set all the values
+        final XMLConfiguration config = buildConfiguration.getProjectConfig();
+        TaskConfigurationUtils.addTaskDefinitionsToConfig(Lists.newArrayList(maven2Task), config, TaskConfigurationUtils.TASK_PREFIX);
+    }
+
+    /**
+     * @return the name of the Maven 2 builder
+     */
+    private String findBestMaven2Builder() {
+        return "Maven 2";
+    }
+
+    public String getFullPlanKey() {
+        return fullPlanKey;
+    }
+}

File src/main/java/com/adaptavist/bamboo/autoplan/TestServlet.java

-package com.adaptavist.bamboo.autoplan;
-
-import com.atlassian.bamboo.build.PlanCreationDeniedException;
-import com.atlassian.bamboo.build.creation.PlanCreationService;
-import com.atlassian.bamboo.plan.PlanKeys;
-import com.atlassian.bamboo.template.TemplateRenderer;
-import com.atlassian.bamboo.webwork.util.ActionParametersMapImpl;
-import com.atlassian.bamboo.ww2.actions.build.admin.create.BuildConfiguration;
-import com.atlassian.spring.container.ContainerManager;
-import com.google.common.collect.Maps;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.util.HashMap;
-
-public class TestServlet extends HttpServlet {
-    private static final String PROJECT_KEY = "projectKey";
-    private static final String PROJECT_NAME = "projectName";
-    private static final String NEW_PROJECT_MARKER = "newProject";
-    private static final String CHAIN_KEY = "chainKey";
-    private static final String CHAIN_NAME = "chainName";
-
-
-    private final TemplateRenderer templateRenderer;
-
-    public TestServlet(TemplateRenderer templateRenderer) {
-        this.templateRenderer = templateRenderer;
-    }
-
-    @Override
-    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-        final PlanCreationService chainCreationService = (PlanCreationService) ContainerManager.getComponent("chainCreationService");
-        resp.setStatus(200);
-        resp.getWriter().println(templateRenderer.renderWithoutActionContext("templates/success.ftl", new HashMap<String, Object>()));
-        ActionParametersMapImpl actionParametersMap = new ActionParametersMapImpl(Maps.<String, Object>newHashMap());
-        actionParametersMap.put(NEW_PROJECT_MARKER, true);
-        actionParametersMap.put(PROJECT_KEY, "JONPROJ");
-        actionParametersMap.put(PROJECT_NAME, "Jon's Project");
-        actionParametersMap.put(CHAIN_KEY, "JON");
-        actionParametersMap.put(CHAIN_NAME, "Jon plan");
-
-
-        try {
-            String newPlanKey = chainCreationService.createPlan(new BuildConfiguration(), actionParametersMap, PlanCreationService.EnablePlan.DISABLED);
-            chainCreationService.triggerCreationCompleteEvents(PlanKeys.getPlanKey(newPlanKey));
-        } catch (PlanCreationDeniedException e) {
-            throw new RuntimeException(e);
-        }
-    }
-}

File src/main/resources/atlassian-plugin.xml

 
     <resource type="i18n" name="i18n" location="i18n"/>
 
-    <servlet key="test-servlet" name="Test Servlet" class="com.adaptavist.bamboo.autoplan.TestServlet">
-        <url-pattern>/autoplan*</url-pattern>
-    </servlet>
+    <xwork key="autoplan-actions">
+        <package name="autoplan" extends="buildAdminCreate">
+            <default-interceptor-ref name="buildConfigStack"/>
+            <!-- Import maven plan -->
+            <!-- Import maven plan: provide pom location -->
+            <action name="autoplan"
+                    class="com.adaptavist.bamboo.autoplan.CheckoutAction" method="input">
+                <result name="input" type="freemarker">/com/adaptavist/bamboo/autoplan/configureImportWithMaven.ftl</result>
+            </action>
+
+            <action name="autoplan"
+                    class="com.adaptavist.bamboo.autoplan.CheckoutAction" method="input">
+                <result name="input" type="freemarker">/com/adaptavist/bamboo/autoplan/configureImportWithMaven.ftl</result>
+            </action>
+
+            <!-- Import maven plan: checkout & parse POM -->
+            <action name="autoplanCheckout"
+                    class="com.adaptavist.bamboo.autoplan.CheckoutAction" method="execute">
+                <result name="input" type="freemarker">/com/adaptavist/bamboo/autoplan/configureImportWithMaven.ftl</result>
+                <result name="error" type="freemarker">/com/adaptavist/bamboo/autoplan/configureImportWithMaven.ftl</result>
+                <result name="success" type="redirect">/build/admin/create/autoplanConfigure.action</result>
+            </action>
+
+            <!-- Import maven plan: configure plan -->
+            <action name="autoplanConfigure"
+                    class="com.adaptavist.bamboo.autoplan.CreatePlanAction" method="input">
+                <result name="input" type="freemarker">/com/adaptavist/bamboo/autoplan/confirmImportWithMaven.ftl</result>
+                <result name="error" type="freemarker">/com/adaptavist/bamboo/autoplan/confirmImportWithMaven.ftl</result>
+            </action>
+
+            <!-- Import maven plan: create plan -->
+            <action name="autoplanCreatePlan"
+                    class="com.adaptavist.bamboo.autoplan.CreatePlanAction" method="execute">
+                <result name="input" type="freemarker">/com/adaptavist/bamboo/autoplan/confirmImportWithMaven.ftl</result>
+                <result name="success" type="redirect">/build/admin/edit/editBuildTasks.action?buildKey=${fullPlanKey}&amp;taskId=${taskId}</result>
+            </action>
+        </package>
+    </xwork>
 </atlassian-plugin>

File src/main/resources/com/adaptavist/bamboo/autoplan/configureImportWithMaven.ftl

+[#-- @ftlvariable name="action" type="com.adaptavist.bamboo.autoplan.CheckoutAction" --]
+[#-- @ftlvariable name="" type="com.adaptavist.bamboo.autoplan.CheckoutAction" --]
+
+<html>
+<head>
+    [@ui.header pageKey='autoplan.create.maven.title' title=true /]
+    <meta name="decorator" content="atl.general"/>
+</head>
+<body>
+    [@ui.header pageKey='autoplan.create.maven.title' descriptionKey='autoplan.create.maven.description'/]
+
+    [#if maven2BuilderAvailable]
+        [@ww.form action='autoplanCheckout' namespace='/build/admin/create'
+                  method="post" enctype="multipart/form-data"
+                  titleKey='importWithMaven.pom.title'
+                  submitLabelKey='global.buttons.import'
+                  cancelUri='addPlan.action'
+        ]
+            [#assign repositoryList = filteredRepositories /]
+
+            [@ww.select labelKey='repository.type' name='selectedRepository' toggle='true'
+                        list = repositoryList listKey='key' listValue='name']
+            [/@ww.select]
+            [@ui.clear/]
+
+            [#list repositoryList as repository]
+                [@ui.bambooSection dependsOn='selectedRepository' showOn='${repository.key}']
+                    ${repository.mavenPomAccessor.getMavenPomCheckoutAccessEditHtml(buildConfiguration)!}
+                [/@ui.bambooSection]
+            [/#list]
+
+        [/@ww.form]
+    [#else]
+        [@ui.messageBox type="error"]
+            [#if fn.hasAdminPermission()]
+               [@ww.text name='importWithMaven.error.missingMaven2Builder']
+                   [@ww.param][@ww.url action='configureSharedLocalCapabilities' namespace='/admin/agent' /][/@ww.param]
+               [/@ww.text]
+            [#else]
+                [@ww.text name='importWithMaven.error.missingMaven2Builder.nonAdmin'/]
+            [/#if]
+        [/@ui.messageBox]
+    [/#if]
+
+</body>
+</html>

File src/main/resources/com/adaptavist/bamboo/autoplan/confirmImportWithMaven.ftl

+[#-- @ftlvariable name="action" type="com.adaptavist.bamboo.autoplan.CreatePlanAction" --]
+[#-- @ftlvariable name="" type="com.adaptavist.bamboo.autoplan.CreatePlanAction" --]
+
+<html>
+<head>
+	<title>[@ww.text name="autoplan.create.maven.title"/]</title>
+    <meta name="decorator" content="atl.general"/>
+</head>
+<body>
+    [@ui.header pageKey="autoplan.create.maven.title" descriptionKey='importWithMaven.confirm.description' /]
+    
+    [@ww.form action='autoplanCreatePlan' namespace='/build/admin/create'
+              method="post" enctype="multipart/form-data"
+              titleKey='importWithMaven.confirm.title'
+              submitLabelKey='global.buttons.confirm'
+               cancelUri='/start.action'
+    ]
+        [#-- Plan details --]
+        [@ui.bambooSection]
+            [#include "/fragments/project/selectCreateProject.ftl"]
+            [#include "/fragments/chains/editChainKeyName.ftl"]
+        [/@ui.bambooSection]
+
+        [#-- Repository information details --]
+        [@ui.bambooSection titleKey='repository.title']
+
+            [#-- Source repository --]
+            [@ww.select labelKey='repository.type' name='selectedRepository' id='selectedRepository' toggle='true'
+                list='repositories' listKey='key' listValue='name']
+            [/@ww.select]
+
+            [#list repositories as repository]
+                [@ui.bambooSection dependsOn='selectedRepository' showOn='${repository.key}']
+                    ${repository.getMinimalEditHtml(buildConfiguration)!}
+                [/@ui.bambooSection]
+            [/#list]
+
+
+            [#-- Web repository viewer --]
+            [@ww.select labelKey='webRepositoryViewer.type' id='selectedWebRepositoryViewer' name='selectedWebRepositoryViewer' toggle='true'
+                            list='uiConfigBean.webRepositoryViewers' listKey='key' listValue='name']
+            [/@ww.select]
+
+            [#list uiConfigBean.webRepositoryViewers as viewer]
+                [@ui.bambooSection dependsOn='selectedWebRepositoryViewer' showOn='${viewer.key}']
+                    ${viewer.getEditHtml(buildConfiguration, build)!}
+                [/@ui.bambooSection]
+            [/#list]
+
+            [@ui.clear /]
+        [/@ui.bambooSection]
+
+        [#-- Notification details --]
+        [@ui.bambooSection titleKey='notification.title']
+            [#if notificationSet.notificationRules?has_content]
+                <table id="notificationTable" class="aui">
+                    <colgroup>
+                        <col width="40%">
+                        <col>
+                    </colgroup>
+                    <thead>
+                        <tr>
+                            <th>[@ww.text name='bulkAction.notification.eventHeading' /]</th>
+                            <th>[@ww.text name='bulkAction.notification.recipientHeading' /]</th>
+                        </tr>
+                    </thead>
+                    <tbody>
+                    [#list notificationSet.sortedNotificationRules  as notification]
+                        [#-- Setting the newRow group variable --]
+                        [#if notification.notificationTypeForView?has_content]
+                             [#if notification.notificationTypeForView.getViewHtml()?has_content]
+                                   [#assign thisNotificationType=notification.notificationTypeForView.getViewHtml() /]
+                             [#else]
+                                   [#assign thisNotificationType=notification.notificationTypeForView.name /]
+                             [/#if]
+                        [#else]
+                             [#assign thisNotificationType=notification.conditionKey! /]
+                        [/#if]
+
+                        [#if !lastNotificationType?has_content || lastNotificationType != thisNotificationType]
+                            [#assign newRow = true /]
+                        [#else]
+                            [#assign newRow = false /]
+                        [/#if]
+
+                        [#assign lastNotificationType=thisNotificationType /]
+
+                        <tr [#if lastModified?has_content && lastModified=notification.id]class="selectedNotification"[/#if] >
+                            <td>
+                                [#if newRow]${thisNotificationType}[/#if]
+                            </td>
+                            <td [#if lastModified?has_content && lastModified=notification.id]class="selectedNotification"[/#if]>
+                                [#if notification.notificationRecipient?has_content]
+                                    [#if notification.notificationRecipient.getViewHtml()?has_content]
+                                        ${notification.notificationRecipient.getViewHtml()}
+                                    [#else]
+                                        ${notification.notificationRecipient.description()}
+                                    [/#if]
+                                [#else]
+                                       ${notification.recipientType!}: ${notification.recipient!}
+                                [/#if]
+                            </td>
+                        </tr>
+                    [/#list]
+                    </tbody>
+                </table>
+            [#else]
+                <p>[@ww.text name='notification.empty' /]</p>
+            [/#if]
+        [/@ui.bambooSection]
+
+        [@ui.bambooSection titleKey="plan.create.enable.title"]
+            [@ww.checkbox labelKey="plan.create.enable.option" name='tmp.createAsEnabled' descriptionKey='plan.create.enable.description'/]
+        [/@ui.bambooSection]
+        [#--More fields to edit the parsed plan details to go here...?--]
+    [/@ww.form]
+
+    <script type="text/javascript">
+            AJS.$(function(){
+                AJS.$('#selectedRepository').change(function updateWebRepositoryFilter() {
+                    mutateSelectListContent(AJS.$(this), AJS.$('#selectedWebRepositoryViewer'), AJS.$.parseJSON('${uiConfigBean.webRepositoryJson}'));
+                }).change();
+            });
+    </script>
+</body>
+</html>

File src/main/resources/i18n.properties

+autoplan.create.maven.title = Import an Atlassian Plugin
+autoplan.create.maven.description = On this page you can import an Atlassian Plugin and the necessary test, integration-test and deploy goals will be generated.

File src/main/resources/templates/success.ftl

-Hello world from a template