KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hudson > Functions


1 package hudson;
2
3 import hudson.model.Hudson;
4 import hudson.model.ModelObject;
5 import hudson.model.Node;
6 import hudson.model.Project;
7 import hudson.model.Run;
8 import hudson.model.Items;
9 import org.kohsuke.stapler.Ancestor;
10 import org.kohsuke.stapler.StaplerRequest;
11
12 import javax.servlet.http.Cookie JavaDoc;
13 import javax.servlet.http.HttpServletRequest JavaDoc;
14 import javax.servlet.http.HttpServletResponse JavaDoc;
15 import java.io.File JavaDoc;
16 import java.io.IOException JavaDoc;
17 import java.net.URI JavaDoc;
18 import java.net.URISyntaxException JavaDoc;
19 import java.util.Calendar JavaDoc;
20 import java.util.List JavaDoc;
21 import java.util.Map JavaDoc;
22 import java.util.SortedMap JavaDoc;
23 import java.util.TreeMap JavaDoc;
24 import java.util.logging.LogRecord JavaDoc;
25 import java.util.logging.SimpleFormatter JavaDoc;
26
27 /**
28  * Utility functions used in views.
29  *
30  * <p>
31  * An instance of this class is created for each request.
32  *
33  * @author Kohsuke Kawaguchi
34  */

35 public class Functions {
36     private static volatile int globalIota = 0;
37
38     private int iota;
39
40     public Functions() {
41         iota = globalIota;
42         // concurrent requests can use the same ID --- we are just trying to
43
// prevent the same user from seeing the same ID repeatedly.
44
globalIota+=1000;
45     }
46
47     /**
48      * Generates an unique ID.
49      */

50     public String JavaDoc generateId() {
51         return "id"+iota++;
52     }
53
54     public static boolean isModel(Object JavaDoc o) {
55         return o instanceof ModelObject;
56     }
57
58     public static String JavaDoc xsDate(Calendar JavaDoc cal) {
59         return Util.XS_DATETIME_FORMATTER.format(cal.getTime());
60     }
61
62     public static String JavaDoc rfc822Date(Calendar JavaDoc cal) {
63         return Util.RFC822_DATETIME_FORMATTER.format(cal.getTime());
64     }
65
66     /**
67      * Prints the integer as a string that represents difference,
68      * like "-5", "+/-0", "+3".
69      */

70     public static String JavaDoc getDiffString(int i) {
71         if(i==0) return "\u00B10"; // +/-0
72
String JavaDoc s = Integer.toString(i);
73         if(i>0) return "+"+s;
74         else return s;
75     }
76
77     /**
78      * {@link #getDiffString2(int)} that doesn't show anything for +/-0
79      */

80     public static String JavaDoc getDiffString2(int i) {
81         if(i==0) return "";
82         String JavaDoc s = Integer.toString(i);
83         if(i>0) return "+"+s;
84         else return s;
85     }
86
87     /**
88      * Adds the proper suffix.
89      */

90     public static String JavaDoc addSuffix(int n, String JavaDoc singular, String JavaDoc plural) {
91         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
92         buf.append(n).append(' ');
93         if(n==1)
94             buf.append(singular);
95         else
96             buf.append(plural);
97         return buf.toString();
98     }
99
100     public static RunUrl decompose(StaplerRequest req) {
101         @SuppressWarnings JavaDoc("unchecked") // pre-JDK 5 API?
102
List JavaDoc<Ancestor> ancestors = req.getAncestors();
103         for (Ancestor anc : ancestors) {
104             if(anc.getObject() instanceof Run) {
105                 // bingo
106
String JavaDoc ancUrl = anc.getUrl();
107
108                 String JavaDoc reqUri = req.getOriginalRequestURI();
109                 // despite the spec saying this string is not decoded,
110
// Tomcat apparently decodes this string. You see ' ' instead of '%20', which is what
111
// the browser has sent. So do some quick scan to see if it's ASCII safe, and if not
112
// re-encode it. Otherwise it won't match with ancUrl.
113
if(reqUri.indexOf(' ')>=0) {
114                     try {
115                         // 3 arg version accepts illegal character. 1-arg version doesn't
116
reqUri = new URI JavaDoc(null,reqUri,null).toASCIIString();
117                     } catch (URISyntaxException JavaDoc e) {
118                         // try to use reqUri as is.
119
}
120                 }
121
122                 return new RunUrl(
123                     (Run) anc.getObject(), ancUrl,
124                     reqUri.substring(ancUrl.length()),
125                     req.getContextPath() );
126             }
127         }
128         return null;
129     }
130
131     public static final class RunUrl {
132         private final String JavaDoc contextPath;
133         private final String JavaDoc basePortion;
134         private final String JavaDoc rest;
135         private final Run run;
136
137         public RunUrl(Run run, String JavaDoc basePortion, String JavaDoc rest, String JavaDoc contextPath) {
138             this.run = run;
139             this.basePortion = basePortion;
140             this.rest = rest;
141             this.contextPath = contextPath;
142         }
143
144         public String JavaDoc getBaseUrl() {
145             return basePortion;
146         }
147
148         /**
149          * Returns the same page in the next build.
150          */

151         public String JavaDoc getNextBuildUrl() {
152             return getUrl(run.getNextBuild());
153         }
154
155         /**
156          * Returns the same page in the previous build.
157          */

158         public String JavaDoc getPreviousBuildUrl() {
159             return getUrl(run.getPreviousBuild());
160         }
161
162         private String JavaDoc getUrl(Run n) {
163             if(n ==null)
164                 return null;
165             else {
166                 return basePortion+"/../"+n.getNumber()+rest;
167             }
168         }
169     }
170
171     public static Node.Mode[] getNodeModes() {
172         return Node.Mode.values();
173     }
174
175     public static String JavaDoc getProjectListString(List JavaDoc<Project> projects) {
176         return Items.toNameList(projects);
177     }
178
179     public static Object JavaDoc ifThenElse(boolean cond, Object JavaDoc thenValue, Object JavaDoc elseValue) {
180         return cond ? thenValue : elseValue;
181     }
182     
183     public static String JavaDoc appendIfNotNull(String JavaDoc text, String JavaDoc suffix, String JavaDoc nullText) {
184         return text == null ? nullText : text + suffix;
185     }
186
187     public static Map JavaDoc getSystemProperties() {
188         return new TreeMap JavaDoc<Object JavaDoc,Object JavaDoc>(System.getProperties());
189     }
190
191     public static Map JavaDoc getEnvVars() {
192         return new TreeMap JavaDoc<String JavaDoc,String JavaDoc>(EnvVars.masterEnvVars);
193     }
194
195     public static boolean isWindows() {
196         return File.pathSeparatorChar==';';
197     }
198
199     public static List JavaDoc<LogRecord JavaDoc> getLogRecords() {
200         return Hudson.logRecords;
201     }
202
203     public static String JavaDoc printLogRecord(LogRecord JavaDoc r) {
204         return formatter.format(r);
205     }
206
207     public static Cookie JavaDoc getCookie(HttpServletRequest JavaDoc req,String JavaDoc name) {
208         Cookie JavaDoc[] cookies = req.getCookies();
209         if(cookies!=null) {
210             for (Cookie JavaDoc cookie : cookies) {
211                 if(cookie.getName().equals(name)) {
212                     return cookie;
213                 }
214             }
215         }
216         return null;
217     }
218
219     public static String JavaDoc getCookie(HttpServletRequest JavaDoc req,String JavaDoc name, String JavaDoc defaultValue) {
220         Cookie JavaDoc c = getCookie(req, name);
221         if(c==null || c.getValue()==null) return defaultValue;
222         return c.getValue();
223     }
224
225     /**
226      * Gets the suffix to use for YUI JavaScript.
227      */

228     public static String JavaDoc getYuiSuffix() {
229         return DEBUG_YUI ? "debug" : "min";
230     }
231
232     /**
233      * Set to true if you need to use the debug version of YUI.
234      */

235     public static boolean DEBUG_YUI = false;
236
237     /**
238      * Creates a sub map by using the given range (both ends inclusive).
239      */

240     public static <V> SortedMap JavaDoc<Integer JavaDoc,V> filter(SortedMap JavaDoc<Integer JavaDoc,V> map, String JavaDoc from, String JavaDoc to) {
241         if(from==null && to==null) return map;
242         if(to==null)
243             return map.headMap(Integer.parseInt(from)-1);
244         if(from==null)
245             return map.tailMap(Integer.parseInt(to));
246
247         return map.subMap(Integer.parseInt(to),Integer.parseInt(from)-1);
248     }
249
250     private static final SimpleFormatter JavaDoc formatter = new SimpleFormatter JavaDoc();
251
252     /**
253      * Used by <tt>layout.jelly</tt> to control the auto refresh behavior.
254      *
255      * @param noAutoRefresh
256      * On certain pages, like a page with forms, will have annoying interference
257      * with auto refresh. On those pages, disable auto-refresh.
258      */

259     public static void configureAutoRefresh(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, boolean noAutoRefresh) {
260         if(noAutoRefresh)
261             return;
262
263         String JavaDoc param = request.getParameter("auto_refresh");
264         boolean refresh = isAutoRefresh(request);
265         if (param != null) {
266             refresh = Boolean.parseBoolean(param);
267             Cookie JavaDoc c = new Cookie JavaDoc("hudson_auto_refresh", Boolean.toString(refresh));
268             // Need to set path or it will not stick from e.g. a project page to the dashboard.
269
// Using request.getContextPath() might work but it seems simpler to just use the hudson_ prefix
270
// to avoid conflicts with any other web apps that might be on the same machine.
271
c.setPath("/");
272             response.addCookie(c);
273         }
274         if (refresh) {
275             response.addHeader("Refresh", "10");
276         }
277     }
278
279     public static boolean isAutoRefresh(HttpServletRequest JavaDoc request) {
280         String JavaDoc param = request.getParameter("auto_refresh");
281         if (param != null) {
282             return Boolean.parseBoolean(param);
283         }
284         Cookie JavaDoc[] cookies = request.getCookies();
285         if(cookies==null)
286             return false; // when API design messes it up, we all suffer
287

288         for (Cookie JavaDoc c : cookies) {
289             if (c.getName().equals("hudson_auto_refresh")) {
290                 return Boolean.parseBoolean(c.getValue());
291             }
292         }
293         return false;
294     }
295
296     /**
297      * Finds the given object in the ancestor list and returns its URL.
298      * This is used to determine the "current" URL assigned to the given object,
299      * so that one can compute relative URLs from it.
300      */

301     public static String JavaDoc getNearestAncestorUrl(StaplerRequest req,Object JavaDoc it) {
302         List JavaDoc list = req.getAncestors();
303         for( int i=list.size()-1; i>=0; i-- ) {
304             Ancestor anc = (Ancestor) list.get(i);
305             if(anc.getObject()==it)
306                 return anc.getUrl();
307         }
308         return null;
309     }
310
311     public static String JavaDoc appendSpaceIfNotNull(String JavaDoc n) {
312         if(n==null) return null;
313         else return n+' ';
314     }
315
316     public static String JavaDoc getWin32ErrorMessage(IOException JavaDoc e) {
317         return Util.getWin32ErrorMessage(e);
318     }
319
320     public static boolean isMultiline(String JavaDoc s) {
321         if(s==null) return false;
322         return s.indexOf('\r')>=0 || s.indexOf('\n')>=0;
323     }
324
325     public static String JavaDoc encode(String JavaDoc s) {
326         return Util.encode(s);
327     }
328 }
329
Popular Tags