/
ExtensibleChoiceParameterDefinition.java
462 lines (419 loc) · 16.6 KB
/
ExtensibleChoiceParameterDefinition.java
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/*
* The MIT License
*
* Copyright (c) 2012-2013 IKEDA Yasuyuki
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jp.ikedam.jenkins.plugins.extensible_choice_parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import jenkins.model.Jenkins;
import hudson.Extension;
import hudson.DescriptorExtensionList;
import hudson.Util;
import hudson.model.Descriptor;
import hudson.model.Describable;
import hudson.model.DescriptorVisibilityFilter;
import hudson.model.ParameterValue;
import hudson.model.StringParameterValue;
import hudson.model.SimpleParameterDefinition;
import hudson.util.FormValidation;
import hudson.util.VariableResolver;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import net.sf.json.JSONObject;
/**
* Provides a choice parameter whose choices can be extended using Extension Points.
*
*/
public class ExtensibleChoiceParameterDefinition extends SimpleParameterDefinition
{
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(ExtensibleChoiceParameterDefinition.class.getName());
private static final Pattern namePattern = Pattern.compile("[A-Za-z_][A-Za-z_0-9]*");
/**
* Deprecated
*/
@Deprecated
public static Pattern getNamePattern()
{
return namePattern;
}
/**
* The internal class to work with views.
*
* The following files are used (put in main/resource directory in the source tree).
* <dl>
* <dt>config.jelly</dt>
* <dd>shown as a part of a job configuration page.</dd>
* <dt>index.jelly</dt>
* <dd>shown when a user launches a build, and specifies parameters of the build.</dd>
* </dt>
* </dl>
*/
@Extension
public static class DescriptorImpl extends ParameterDescriptor
{
private Map<String,Boolean> choiceListEnabledMap;
public DescriptorImpl()
{
setChoiceListEnabledMap(Collections.<String, Boolean>emptyMap());
load();
}
protected void setChoiceListEnabledMap(Map<String, Boolean> choiceListEnabledMap)
{
this.choiceListEnabledMap = choiceListEnabledMap;
}
protected Map<String, Boolean> getChoiceListEnabledMap()
{
return choiceListEnabledMap;
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws hudson.model.Descriptor.FormException
{
Map<String, Boolean> configuredChoiceListEnableMap = new HashMap<String, Boolean>();
for(Descriptor<ChoiceListProvider> d: getChoiceListProviderList())
{
String name = d.getJsonSafeClassName();
JSONObject o = json.optJSONObject(name);
if(o != null)
{
configuredChoiceListEnableMap.put(d.getId(), true);
if(d instanceof ChoiceListProviderDescriptor)
{
d.configure(req, o);
}
}
else
{
configuredChoiceListEnableMap.put(d.getId(), false);
}
}
setChoiceListEnabledMap(configuredChoiceListEnableMap);
save();
return super.configure(req, json);
}
public boolean isProviderEnabled(Descriptor<?> d)
{
Boolean b = getChoiceListEnabledMap().get(d.getId());
if(b != null)
{
return b.booleanValue();
}
if(!(d instanceof ChoiceListProviderDescriptor))
{
return true;
}
return ((ChoiceListProviderDescriptor)d).isEnabledByDefault();
}
/**
* Create a new instance of {@link SystemGroovyChoiceListProvider} from user inputs.
*
* @param req
* @param formData
* @return
* @throws hudson.model.Descriptor.FormException
* @see hudson.model.Descriptor#newInstance(org.kohsuke.stapler.StaplerRequest, net.sf.json.JSONObject)
*/
@Override
public ExtensibleChoiceParameterDefinition newInstance(StaplerRequest req,
JSONObject formData)
throws hudson.model.Descriptor.FormException
{
return new ExtensibleChoiceParameterDefinition(
formData.getString("name"),
bindJSONWithDescriptor(req, formData, "choiceListProvider", ChoiceListProvider.class),
formData.getBoolean("editable"),
formData.getString("description")
);
}
/**
* Create a new {@link Describable} object from user inputs.
*
* @param req
* @param formData
* @param fieldName
* @param clazz
* @return
* @throws hudson.model.Descriptor.FormException
*/
private <T extends Describable<?>> T bindJSONWithDescriptor(
StaplerRequest req,
JSONObject formData,
String fieldName,
Class<T> clazz
) throws hudson.model.Descriptor.FormException {
formData = formData.getJSONObject(fieldName);
if (formData == null || formData.isNullObject()) {
return null;
}
String staplerClazzName = formData.optString("$class", null);
if (staplerClazzName == null) {
// Fall back on the legacy stapler-class attribute.
staplerClazzName = formData.optString("stapler-class", null);
}
if (staplerClazzName == null) {
throw new FormException("No $stapler nor stapler-class is specified", fieldName);
}
try {
@SuppressWarnings("unchecked")
Class<? extends T> staplerClass = (Class<? extends T>)Jenkins.getInstance().getPluginManager().uberClassLoader.loadClass(staplerClazzName);
Descriptor<?> d = Jenkins.getInstance().getDescriptorOrDie(staplerClass);
@SuppressWarnings("unchecked")
T instance = (T)d.newInstance(req, formData);
return instance;
} catch(ClassNotFoundException e) {
throw new FormException(
String.format("Failed to instantiate %s", staplerClazzName),
e,
fieldName
);
}
}
/**
* Returns the string to be shown in a job configuration page, in the dropdown of "Add Parameter".
*
* @return a name of this parameter type.
* @see hudson.model.ParameterDefinition.ParameterDescriptor#getDisplayName()
*/
@Override
public String getDisplayName()
{
return Messages._ExtensibleChoiceParameterDefinition_DisplayName().toString();
}
/**
* Returns all the available methods to provide choices.
*
* @return DescriptorExtensionList of ChoiceListProvider subclasses.
*/
public DescriptorExtensionList<ChoiceListProvider,Descriptor<ChoiceListProvider>> getChoiceListProviderList()
{
return ChoiceListProvider.all();
}
/**
* Returns all the available methods to provide choices that are enabled in the global configuration.
*
* Used for showing dropdown for users to select a choice provider.
*
* @return DescriptorExtensionList of ChoiceListProvider subclasses.
*/
public List<Descriptor<ChoiceListProvider>> getEnabledChoiceListProviderList()
{
return DescriptorVisibilityFilter.apply(this, ChoiceListProvider.all());
}
public FormValidation doCheckName(@QueryParameter String name){
if(StringUtils.isBlank(name))
{
return FormValidation.error(Messages.ExtensibleChoiceParameterDefinition_Name_empty());
}
final String trimmedName = StringUtils.trim(name);
final String EXPANDED = "GOOD";
String expanded = Util.replaceMacro(
String.format("${%s}", trimmedName),
new VariableResolver<String>()
{
@Override
public String resolve(String name)
{
if(trimmedName.equals(name))
{
return EXPANDED;
}
return null;
}
}
);
if(!EXPANDED.equals(expanded)){
return FormValidation.warning(Messages.ExtensibleChoiceParameterDefinition_Name_invalid());
}
return FormValidation.ok();
}
}
@Extension
public static class DescriptorVisibilityFilterImpl extends DescriptorVisibilityFilter
{
@SuppressWarnings("unchecked")
@Override
public boolean filter(Object context, @SuppressWarnings("rawtypes") Descriptor descriptor)
{
if(!(context instanceof DescriptorImpl))
{
return true;
}
return ((DescriptorImpl)context).isProviderEnabled(descriptor);
}
}
private boolean editable = false;
/**
* Is this parameter value can be set to a value not in the choices?
*
* @return whether this parameter is editable.
*/
public boolean isEditable()
{
return editable;
}
private ChoiceListProvider choiceListProvider = null;
/**
* The choice provider the user specified.
*
* @return choice provider.
*/
public ChoiceListProvider getChoiceListProvider()
{
return choiceListProvider;
}
/**
* @return choice provider only when it's enabled
* @see DescriptorImpl#isProviderEnabled(Descriptor)
*/
public ChoiceListProvider getEnabledChoiceListProvider()
{
ChoiceListProvider p = getChoiceListProvider();
if(p == null)
{
return null;
}
// filter providers.
List<Descriptor<ChoiceListProvider>> testList = DescriptorVisibilityFilter.apply(
getDescriptor(),
Arrays.asList(p.getDescriptor())
);
if(testList.isEmpty())
{
LOGGER.log(Level.WARNING, "{0} is configured but disabled in the system configuration.", p.getDescriptor().getDisplayName());
return null;
}
return p;
}
/**
* Return choices available for this parameter.
*
* @return list of choices. never null.
*/
public List<String> getChoiceList()
{
ChoiceListProvider provider = getEnabledChoiceListProvider();
List<String> choiceList = (provider != null)?provider.getChoiceList():null;
return (choiceList != null)?choiceList:new ArrayList<String>(0);
}
/**
* Constructor instantiating with parameters in the configuration page.
*
* When instantiating from the saved configuration,
* the object is directly serialized with XStream,
* and no constructor is used.
*
* @param name the name of this parameter (used as a variable name).
* @param choiceListProvider the choice provider
* @param editable whether this parameter can be a value not in choices.
* @param description the description of this parameter. Used only for the convenience of users.
*/
@DataBoundConstructor
public ExtensibleChoiceParameterDefinition(String name, ChoiceListProvider choiceListProvider, boolean editable, String description)
{
// There seems no way to forbid invalid values to be submitted.
// SimpleParameterDefinition seems not to trim name parameter, so trim here.
super(StringUtils.trim(name), description);
this.choiceListProvider = choiceListProvider;
this.editable = editable;
}
/**
* Test passed ParameterValue and return.
*
* Common processing of createValue
*
* @param value a value to test.
* @return a value tested. same with value.
*/
protected ParameterValue createValueCommon(StringParameterValue value)
{
if(!isEditable() && !getChoiceList().contains(value.value))
{
// Something strange!: Not editable and specified a value not in the choices.
throw new IllegalArgumentException("Illegal choice: " + value.value);
}
return value;
}
/**
* Decide a value of this parameter from the user input.
*
* @param request
* @param jo the user input
* @return the value of this parameter.
* @see hudson.model.ParameterDefinition#createValue(org.kohsuke.stapler.StaplerRequest, net.sf.json.JSONObject)
*/
@Override
public ParameterValue createValue(StaplerRequest request, JSONObject jo)
{
StringParameterValue value = request.bindJSON(StringParameterValue.class, jo);
value.setDescription(getDescription());
return createValueCommon(value);
}
/**
* Decide a value of this parameter from the user input.
*
* @param value the user input
* @return the value of this parameter.
* @throws IllegalArgumentException The value is not in choices even the field is not editable.
* @see hudson.model.SimpleParameterDefinition#createValue(java.lang.String)
*/
@Override
public ParameterValue createValue(String value) throws IllegalArgumentException
{
return createValueCommon(new StringParameterValue(getName(), value, getDescription()));
}
/**
* Returns the default value of this parameter.
*
* If not specified by the provider,
* the first value in the choice is used.
* returns null if no choice list is defined.
*
* @return the default value of this parameter.
* @see hudson.model.ParameterDefinition#getDefaultParameterValue()
*/
@Override
public ParameterValue getDefaultParameterValue()
{
ChoiceListProvider p = getEnabledChoiceListProvider();
String defaultChoice = (p != null)?p.getDefaultChoice():null;
if(defaultChoice != null)
{
return createValue(defaultChoice);
}
List<String> choiceList = getChoiceList();
return (choiceList.size() <= 0)?null:
new StringParameterValue(
getName(),
choiceList.get(0),
getDescription()
);
}
}