Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: f0c2947780d4977897f43137f6a5e448a02f9178 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/*******************************************************************************
 *
 * Copyright (c) 2011 Oracle Corporation.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *
 *    Nikita Levyankov
 *
 *******************************************************************************/
package hudson.util;

import hudson.Functions;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.Job;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.hudson.api.model.IJob;
import org.eclipse.hudson.api.model.IProjectProperty;
import org.eclipse.hudson.api.model.project.property.AxisListProjectProperty;
import org.eclipse.hudson.api.model.project.property.BaseProjectProperty;
import org.eclipse.hudson.api.model.project.property.BooleanProjectProperty;
import org.eclipse.hudson.api.model.project.property.DescribableListProjectProperty;
import org.eclipse.hudson.api.model.project.property.ExternalProjectProperty;
import org.eclipse.hudson.api.model.project.property.IntegerProjectProperty;
import org.eclipse.hudson.api.model.project.property.LogRotatorProjectProperty;
import org.eclipse.hudson.api.model.project.property.ResultProjectProperty;
import org.eclipse.hudson.api.model.project.property.SCMProjectProperty;
import org.eclipse.hudson.api.model.project.property.StringProjectProperty;
import org.eclipse.hudson.api.model.project.property.TriggerProjectProperty;
import org.kohsuke.stapler.StaplerRequest;

/**
 * Utility class for cascading functionality.
 * <p/>
 * Date: 10/25/11
 *
 * @author Nikita Levyankov
 */
public class CascadingUtil {

    /**
     * Returns job property by specified key.
     *
     * @param currentJob job that should be analyzed.
     * @param key key.
     * @return {@link import org.eclipse.hudson.api.model.IProjectProperty} instance or null.
     * @throws NullPointerException if currentJob is null.
     */
    public static IProjectProperty getProjectProperty(Job currentJob, String key) {
        return getProjectProperty(currentJob, key, null);
    }

    /**
     * Returns StringProjectProperty by specified key. If property doesn't exists, it will be initialized and added to
     * current job.
     *
     * @param currentJob job that should be analyzed.
     * @param key key.
     * @return {@link org.eclipse.hudson.api.model.project.property.StringProjectProperty} instance.
     * @throws NullPointerException if currentJob is null.
     */
    public static StringProjectProperty getStringProjectProperty(Job currentJob, String key) {
        return getProjectProperty(currentJob, key, StringProjectProperty.class);
    }

    /**
     * Returns BaseProjectProperty by specified key. If property doesn't exists, it will be initialized and added to
     * current job.
     *
     * @param currentJob job that should be analyzed.
     * @param key key.
     * @return {@link org.eclipse.hudson.api.model.project.property.BaseProjectProperty} instance.
     * @throws NullPointerException if currentJob is null.
     */
    public static BaseProjectProperty getBaseProjectProperty(Job currentJob, String key) {
        return getProjectProperty(currentJob, key, BaseProjectProperty.class);
    }

    /**
     * Returns ExternalProjectProperty by specified key. If property doesn't exists, it will be initialized and added to
     * current job.
     *
     * @param currentJob job that should be analyzed.
     * @param key key.
     * @return {@link org.eclipse.hudson.api.model.project.property.ExternalProjectProperty} instance.
     * @throws NullPointerException if currentJob is null.
     */
    public static ExternalProjectProperty getExternalProjectProperty(Job currentJob, String key) {
        return getProjectProperty(currentJob, key, ExternalProjectProperty.class);
    }

    /**
     * Returns ResultProjectProperty by specified key. If property doesn't exists, it will be initialized and added to
     * current job.
     *
     * @param currentJob job that should be analyzed.
     * @param key key.
     * @return {@link org.eclipse.hudson.api.model.project.property.ResultProjectProperty} instance.
     * @throws NullPointerException if currentJob is null.
     */
    public static ResultProjectProperty getResultProjectProperty(Job currentJob, String key) {
        return getProjectProperty(currentJob, key, ResultProjectProperty.class);
    }

    /**
     * Returns BooleanProjectProperty by specified key. If property doesn't exists, it will be initialized and added to
     * current job.
     *
     * @param currentJob job that should be analyzed.
     * @param key key.
     * @return {@link org.eclipse.hudson.api.model.project.property.BooleanProjectProperty} instance.
     * @throws NullPointerException if currentJob is null.
     */
    public static BooleanProjectProperty getBooleanProjectProperty(Job currentJob, String key) {
        return getProjectProperty(currentJob, key, BooleanProjectProperty.class);
    }

    /**
     * Returns IntegerProjectProperty by specified key. If property doesn't exists, it will be initialized and added to
     * current job.
     *
     * @param currentJob job that should be analyzed.
     * @param key key.
     * @return {@link org.eclipse.hudson.api.model.project.property.IntegerProjectProperty} instance.
     * @throws NullPointerException if currentJob is null.
     */
    public static IntegerProjectProperty getIntegerProjectProperty(Job currentJob, String key) {
        return getProjectProperty(currentJob, key, IntegerProjectProperty.class);
    }

    /**
     * Returns LogRotatorProjectProperty by specified key. If property doesn't exists, it will be initialized and added
     * to current job.
     *
     * @param currentJob job that should be analyzed.
     * @param key key.
     * @return {@link org.eclipse.hudson.api.model.project.property.LogRotatorProjectProperty} instance.
     * @throws NullPointerException if currentJob is null.
     */
    public static LogRotatorProjectProperty getLogRotatorProjectProperty(Job currentJob, String key) {
        return getProjectProperty(currentJob, key, LogRotatorProjectProperty.class);
    }

    /**
     * Returns DescribableListProjectProperty by specified key. If property doesn't exists, it will be initialized and
     * added to current job.
     *
     * @param currentJob job that should be analyzed.
     * @param key key.
     * @return {@link org.eclipse.hudson.api.model.project.property.DescribableListProjectProperty} instance.
     * @throws NullPointerException if currentJob is null.
     */
    public static DescribableListProjectProperty getDescribableListProjectProperty(Job currentJob, String key) {
        return getProjectProperty(currentJob, key, DescribableListProjectProperty.class);
    }

    /**
     * Returns AxisListProjectProperty by specified key. If property doesn't exists, it will be initialized and added to
     * current job.
     *
     * @param currentJob job that should be analyzed.
     * @param key key.
     * @return {@link org.eclipse.hudson.api.model.project.property.AxisListProjectProperty} instance.
     * @throws NullPointerException if currentJob is null.
     */
    public static AxisListProjectProperty getAxesListProjectProperty(Job currentJob, String key) {
        return getProjectProperty(currentJob, key, AxisListProjectProperty.class);
    }

    /**
     * Returns SCMProjectProperty by specified key. If property doesn't exists, it will be initialized and added to
     * current job.
     *
     * @param currentJob job that should be analyzed.
     * @param key key.
     * @return {@link org.eclipse.hudson.api.model.project.property.SCMProjectProperty} instance.
     * @throws NullPointerException if currentJob is null.
     */
    public static SCMProjectProperty getScmProjectProperty(Job currentJob, String key) {
        return getProjectProperty(currentJob, key, SCMProjectProperty.class);
    }

    /**
     * Returns TriggerProjectProperty by specified key. If property doesn't exists, it will be initialized and added to
     * current job.
     *
     * @param currentJob job that should be analyzed.
     * @param key key.
     * @return {@link org.eclipse.hudson.api.model.project.property.TriggerProjectProperty} instance.
     * @throws NullPointerException if currentJob is null.
     */
    public static TriggerProjectProperty getTriggerProjectProperty(Job currentJob, String key) {
        return getProjectProperty(currentJob, key, TriggerProjectProperty.class);
    }

    /**
     * Returns project property by specified key.
     *
     * @param currentJob job that should be analyzed.
     * @param key key.
     * @param clazz required property class.
     * If class is not null and property was not found, property of given class will be created.
     * @return {@link org.eclipse.hudson.api.model.IProjectProperty} instance or null.
     * @throws NullPointerException if currentJob is null.
     */
    @SuppressWarnings("unchecked")
    public static <T extends IProjectProperty> T getProjectProperty(Job currentJob, String key, Class<T> clazz) {
        IProjectProperty t = (IProjectProperty) currentJob.getProjectProperties().get(key);
        if (null == t && null != clazz) {
            try {
                t = clazz.getConstructor(IJob.class).newInstance(currentJob);
                t.setKey(key);
                currentJob.putProjectProperty(key, t);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        }
        return (T) t;
    }

    /**
     * Checks whether cascadingCandidate project can produce cycle cascading dependencies.
     *
     * @param cascadingCandidate candidate.
     * @param cascadingChildren children of given job.
     * @return false - if cyclic cascading dependency is not possible, true - otherwise.
     */
    @SuppressWarnings("unchecked")
    public static boolean hasCyclicCascadingLink(Job cascadingCandidate, Set<String> cascadingChildren) {
        if (null != cascadingCandidate && CollectionUtils.isNotEmpty(cascadingChildren)) {
            if (cascadingChildren.contains(cascadingCandidate.getName())) {
                return true;
            }
            for (String childName : cascadingChildren) {
                Job job = Functions.getItemByName(Hudson.getInstance().getAllItems(Job.class), childName);
                if (hasCyclicCascadingLink(cascadingCandidate, job.getCascadingChildrenNames())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Recursively unlink specified project from cascading hierarchy.
     *
     * @param cascadingProject cascading project to start from.
     * @param projectToUnlink project that should be unlinked.
     * @return true if project was unlinked, false - if cascadingProject or projectToUnlink is Null
     */
    public static boolean unlinkProjectFromCascadingParents(Job cascadingProject, String projectToUnlink) {
        if (null != cascadingProject && null != projectToUnlink) {
            Job job = Functions.getItemByName(Hudson.getInstance().getAllItems(Job.class), projectToUnlink);
            Set<String> set = new HashSet<String>(job.getCascadingChildrenNames());
            set.add(projectToUnlink);
            return unlinkProjectFromCascadingParents(cascadingProject, set);
        }
        return false;
    }

    /**
     * Recursively unlink set of projects from cascading hierarchy.
     *
     * @param cascadingProject cascading project to start from.
     * @param projectsToUnlink projects that should be unlinked.
     * @return if project was unlinked
     */
    private static boolean unlinkProjectFromCascadingParents(Job cascadingProject, Set<String> projectsToUnlink) {
        if (null != cascadingProject && null != projectsToUnlink) {
            for (String toUnlink : projectsToUnlink) {
                cascadingProject.removeCascadingChild(toUnlink);
            }
            if (cascadingProject.hasCascadingProject()) {
                unlinkProjectFromCascadingParents(cascadingProject.getCascadingProject(), projectsToUnlink);
            }
            return true;
        }
        return false;
    }

    /**
     * Links cascading project to children project. Method updates all parent cascading projects starting
     * from the specified cascadingProject.
     *
     * @param cascadingProject cascadingProject.
     * @param childProjectName the name of child project name.
     */
    public static void linkCascadingProjectsToChild(Job cascadingProject, String childProjectName) {
        if (cascadingProject != null) {
            cascadingProject.addCascadingChild(childProjectName);
            if (cascadingProject.hasCascadingProject()) {
                linkCascadingProjectsToChild(cascadingProject.getCascadingProject(), childProjectName);
            }
        }
    }

    /**
     * Updates the name of the project in all children cascading references.
     * If this project uses some cascading parent, the name of this project will be renamed in the cascading children
     * collection of the cascading parent project.
     *
     * @param cascadingProject cascading project.
     * @param oldName old project name.
     * @param newName new project name.
     */
    public static void renameCascadingChildLinks(Job cascadingProject, String oldName, String newName) {
        if (cascadingProject != null) {
            cascadingProject.renameCascadingChildName(oldName, newName);
            if (cascadingProject.hasCascadingProject()) {
                renameCascadingChildLinks(cascadingProject.getCascadingProject(), oldName, newName);
            }
        }
    }

    /**
     * Updates the name of the project in all parent cascading references.
     * If this project is used as cascading parent, it's name will be renamed in all children projects.
     *
     * @param oldName old project name.
     * @param newName new project name.
     */
    public static void renameCascadingParentLinks(final String oldName, final String newName) {
        if (StringUtils.isBlank(newName) || StringUtils.isBlank(oldName)) {
            return;
        }
        for (Job job : Hudson.getInstance().getAllItems(Job.class)) {
            if (oldName.equals(job.getCascadingProjectName())) {
                job.renameCascadingProjectNameTo(newName);
            }
        }
    }

    /**
     * Returns possible cascading parents for current job, which are filtered by type and checked for avoidness cyclic
     * dependency
     *
     * @param type project type.
     * @param currentJob current job instance
     * @param <T> Item
     * @return list of cascading parents.
     */
    @SuppressWarnings("unchecked")
    public static <T extends Item> List<Job> getCascadingParents(Class<T> type, Job currentJob) {
        List<T> allItems = Hudson.getInstance().getAllItems(type);
        List<Job> result = new ArrayList<Job>(allItems.size());
        for (T item : allItems) {
            Job job = (Job) item;
            if (!StringUtils.equals(currentJob.getName(), job.getName())
                && !hasCyclicCascadingLink(job, currentJob.getCascadingChildrenNames())) {
                result.add(job);
            }
        }
        return result;
    }

    /**
     * Creates {@link ExternalProjectProperty} based on Descriptors collection, StaplerRequest and JSON resonse.
     *
     * @param req StaplerRequest
     * @param json JSONObject
     * @param descriptors list of descriptors
     * @param owner job to be updated.
     * @param <T> Describable
     * @throws Descriptor.FormException if any.
     */
    @SuppressWarnings("unchecked")
    public static <T extends Describable<T>> void buildExternalProperties(StaplerRequest req, JSONObject json,
                                                                          List<Descriptor<T>> descriptors, Job owner)
        throws Descriptor.FormException {
        for (Descriptor d : descriptors) {
            String name = d.getJsonSafeClassName();
            ExternalProjectProperty<Describable> baseProperty = getExternalProjectProperty(owner, name);
            Describable describable = null;
            if (json.has(name)) {
                describable = d.newInstance(req, json.getJSONObject(name));
            }
            baseProperty.setValue(describable);
        }
    }

    /**
        * Sets trigger for job and all its children if necessary.
        *
        * @param job parentJob
        * @param descriptor trigger descriptor
        * @param key trigger property key
        * @param req stapler request
        * @param json submited json
        * @throws hudson.model.Descriptor.FormException if incorrect parameters
        */
       @SuppressWarnings("unchecked")
       public static void setChildrenTrigger(Job job, TriggerDescriptor descriptor, String key, StaplerRequest req,
                                         JSONObject json) throws Descriptor.FormException {
           TriggerProjectProperty<Trigger<?>> property = CascadingUtil.getTriggerProjectProperty(job, key);
           if (property.getValue() != null) {
               property.getValue().stop();
           }
           Trigger trigger = null;
           if (json.has(key)) {
               trigger = descriptor.newInstance(req, json.getJSONObject(key));
               trigger.start(job, true);
           }
           property.setValue(trigger);
           Set<String> cascadingChildrenNames = job.getCascadingChildrenNames();
           for (String childName : cascadingChildrenNames) {
               Job childJob = (Job)Hudson.getInstance().getItem(childName);
               if (StringUtils.equals(job.getName(), childJob.getCascadingProjectName())) {
                   TriggerProjectProperty childProperty = CascadingUtil.getTriggerProjectProperty(childJob, key);
                   if (!childProperty.isOverridden()) {
                       setChildrenTrigger(childJob, descriptor, key, req, json);
                   } else if (!childProperty.allowOverrideValue(trigger, childProperty.getValue())) {
                       childProperty.setOverridden(false);
                   }
               }
           }
       }
   }

Back to the top