File D:\maven-qcr-plugin-testsunitaires\qcr4java\jenkins-master\target\site\qc\core\src\main\java\hudson\model\ItemGroupMixIn.java.html

1 /*
2 * The MIT License
3 *
4 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 package hudson.model;
25
26 import hudson.Util;
27 import hudson.model.listeners.ItemListener;
28 import hudson.security.AccessControlled;
29 import hudson.util.CopyOnWriteMap;
30 import hudson.util.Function1;
31 import hudson.util.IOUtils;
32 import jenkins.model.Jenkins;
33 import org.kohsuke.stapler.StaplerRequest;
34 import org.kohsuke.stapler.StaplerResponse;
35
36 import javax.servlet.ServletException;
37 import javax.servlet.http.HttpServletResponse;
38 import java.io.File;
39 import java.io.FileFilter;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.util.Map;
43
44 /**
45 * Defines a bunch of static methods to be used as a "mix-in" for {@link ItemGroup}
46 * implementations. Not meant for a consumption from outside {@link ItemGroup}s.
47 *
48 * @author Kohsuke Kawaguchi
49 * @see ViewGroupMixIn
50 */
51 public abstract class ItemGroupMixIn {
52 /**
53 * {@link ItemGroup} for which we are working.
54 */
55 private final ItemGroup parent;
56 private final AccessControlled acl;
57
58 protected ItemGroupMixIn(ItemGroup parent, AccessControlled acl) {
59 this.parent = parent;
60 this.acl = acl;
61 }
62
63 /*
64 * Callback methods to be implemented by the ItemGroup implementation.
65 */
66
67 /**
68 * Adds a newly created item to the parent.
69 */
70 protected abstract void add(TopLevelItem item);
71
72 /**
73 * Assigns the root directory for a prospective item.
74 */
75 protected abstract File getRootDirFor(String name);
76
77
78 /*
79 * The rest is the methods that provide meat.
80 */
81
82 /**
83 * Loads all the child {@link Item}s.
84 *
85 * @param modulesDir
86 * Directory that contains sub-directories for each child item.
87 */
88 public static <K,V extends Item> Map<K,V> loadChildren(ItemGroup parent, File modulesDir, Function1<? extends K,? super V> key) {
89 modulesDir.mkdirs(); // make sure it exists
90
91 File[] subdirs = modulesDir.listFiles(new FileFilter() {
92 public boolean accept(File child) {
93 return child.isDirectory();
94 }
95 });
96 CopyOnWriteMap.Tree<K,V> configurations = new CopyOnWriteMap.Tree<K,V>();
97 for (File subdir : subdirs) {
98 try {
99 V item = (V) Items.load(parent,subdir);
100 configurations.put(key.call(item), item);
101 } catch (IOException e) {
102 e.printStackTrace(); // TODO: logging
103 }
104 }
105
106 return configurations;
107 }
108
109 /**
110 * {@link Item} -> name function.
111 */
112 public static final Function1<String,Item> KEYED_BY_NAME = new Function1<String, Item>() {
113 public String call(Item item) {
114 return item.getName();
115 }
116 };
117
118 /**
119 * Creates a {@link TopLevelItem} from the submission of the '/lib/hudson/newFromList/formList'
120 * or throws an exception if it fails.
121 */
122 public synchronized TopLevelItem createTopLevelItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
123 acl.checkPermission(Job.CREATE);
124
125 TopLevelItem result;
126
127 String requestContentType = req.getContentType();
128 if(requestContentType==null)
129 throw new Failure("No Content-Type header set");
130
131 boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml");
132
133 String name = req.getParameter("name");
134 if(name==null)
135 throw new Failure("Query parameter 'name' is required");
136
137 {// check if the name looks good
138 Jenkins.checkGoodName(name);
139 name = name.trim();
140 if(parent.getItem(name)!=null)
141 throw new Failure(Messages.Hudson_JobAlreadyExists(name));
142 }
143
144 String mode = req.getParameter("mode");
145 if(mode!=null && mode.equals("copy")) {
146 String from = req.getParameter("from");
147
148 // resolve a name to Item
149 Item src = null;
150 if (!from.startsWith("/"))
151 src = parent.getItem(from);
152 if (src==null)
153 src = Jenkins.getInstance().getItemByFullName(from);
154
155 if(src==null) {
156 if(Util.fixEmpty(from)==null)
157 throw new Failure("Specify which job to copy");
158 else
159 throw new Failure("No such job: "+from);
160 }
161 if (!(src instanceof TopLevelItem))
162 throw new Failure(from+" cannot be copied");
163
164 result = copy((TopLevelItem) src,name);
165 } else {
166 if(isXmlSubmission) {
167 result = createProjectFromXML(name, req.getInputStream());
168 rsp.setStatus(HttpServletResponse.SC_OK);
169 return result;
170 } else {
171 if(mode==null)
172 throw new Failure("No mode given");
173
174 // create empty job and redirect to the project config screen
175 result = createProject(Items.all().findByName(mode), name, true);
176 }
177 }
178
179 rsp.sendRedirect2(redirectAfterCreateItem(req, result));
180 return result;
181 }
182
183 /**
184 * Computes the redirection target URL for the newly created {@link TopLevelItem}.
185 */
186 protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException {
187 return req.getContextPath()+'/'+result.getUrl()+"configure";
188 }
189
190 /**
191 * Copies an existing {@link TopLevelItem} to a new name.
192 *
193 * The caller is responsible for calling {@link ItemListener#fireOnCopied(Item, Item)}. This method
194 * cannot do that because it doesn't know how to make the newly added item reachable from the parent.
195 */
196 @SuppressWarnings({"unchecked"})
197 public synchronized <T extends TopLevelItem> T copy(T src, String name) throws IOException {
198 acl.checkPermission(Job.CREATE);
199
200 T result = (T)createProject(src.getDescriptor(),name,false);
201
202 // copy config
203 Util.copyFile(Items.getConfigFile(src).getFile(),Items.getConfigFile(result).getFile());
204
205 // reload from the new config
206 Items.updatingByXml.set(true);
207 try {
208 result = (T)Items.load(parent,result.getRootDir());
209 } finally {
210 Items.updatingByXml.set(false);
211 }
212 result.onCopiedFrom(src);
213
214 add(result);
215 ItemListener.fireOnCopied(src,result);
216 Hudson.getInstance().rebuildDependencyGraph();
217
218 return result;
219 }
220
221 public synchronized TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException {
222 acl.checkPermission(Job.CREATE);
223
224 Jenkins.getInstance().getProjectNamingStrategy().checkName(name);
225 // place it as config.xml
226 File configXml = Items.getConfigFile(getRootDirFor(name)).getFile();
227 configXml.getParentFile().mkdirs();
228 try {
229 IOUtils.copy(xml,configXml);
230
231 // load it
232 TopLevelItem result;
233 Items.updatingByXml.set(true);
234 try {
235 result = (TopLevelItem)Items.load(parent,configXml.getParentFile());
236 } finally {
237 Items.updatingByXml.set(false);
238 }
239 add(result);
240
241 ItemListener.fireOnCreated(result);
242 Jenkins.getInstance().rebuildDependencyGraph();
243
244 return result;
245 } catch (IOException e) {
246 // if anything fails, delete the config file to avoid further confusion
247 Util.deleteRecursive(configXml.getParentFile());
248 throw e;
249 }
250 }
251
252 public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify )
253 throws IOException {
254 acl.checkPermission(Job.CREATE);
255
256 Jenkins.getInstance().getProjectNamingStrategy().checkName(name);
257 if(parent.getItem(name)!=null)
258 throw new IllegalArgumentException("Project of the name "+name+" already exists");
259
260 TopLevelItem item;
261 try {
262 item = type.newInstance(parent,name);
263 } catch (Exception e) {
264 throw new IllegalArgumentException(e);
265 }
266 try {
267 callOnCreatedFromScratch(item);
268 } catch (AbstractMethodError e) {
269 // ignore this error. Must be older plugin that doesn't have this method
270 }
271 item.save();
272 add(item);
273
274 if (notify)
275 ItemListener.fireOnCreated(item);
276
277 return item;
278 }
279
280 /**
281 * Pointless wrapper to avoid HotSpot problem. See JENKINS-5756
282 */
283 private void callOnCreatedFromScratch(TopLevelItem item) {
284 item.onCreatedFromScratch();
285 }
286 }
287