KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > fr > jayasoft > ivy > util > IvyPatternHelper


1 /*
2  * This file is subject to the license found in LICENCE.TXT in the root directory of the project.
3  *
4  * #SNAPSHOT#
5  */

6 package fr.jayasoft.ivy.util;
7
8 import java.io.File JavaDoc;
9 import java.util.ArrayList JavaDoc;
10 import java.util.Collections JavaDoc;
11 import java.util.HashMap JavaDoc;
12 import java.util.List JavaDoc;
13 import java.util.Map JavaDoc;
14 import java.util.Stack JavaDoc;
15 import java.util.regex.Matcher JavaDoc;
16 import java.util.regex.Pattern JavaDoc;
17
18 import fr.jayasoft.ivy.Artifact;
19 import fr.jayasoft.ivy.ArtifactOrigin;
20 import fr.jayasoft.ivy.DefaultArtifact;
21 import fr.jayasoft.ivy.Ivy;
22 import fr.jayasoft.ivy.IvyContext;
23 import fr.jayasoft.ivy.ModuleRevisionId;
24
25 /**
26  * @author x.hanin
27  * @author Maarten Coene (for the optional part management)
28  */

29 public class IvyPatternHelper {
30     public static final String JavaDoc CONF_KEY = "conf";
31     public static final String JavaDoc TYPE_KEY = "type";
32     public static final String JavaDoc EXT_KEY = "ext";
33     public static final String JavaDoc ARTIFACT_KEY = "artifact";
34     public static final String JavaDoc BRANCH_KEY = "branch";
35     public static final String JavaDoc REVISION_KEY = "revision";
36     public static final String JavaDoc MODULE_KEY = "module";
37     public static final String JavaDoc ORGANISATION_KEY = "organisation";
38     public static final String JavaDoc ORGANISATION_KEY2 = "organization";
39     public static final String JavaDoc ORIGINAL_ARTIFACTNAME_KEY = "originalname";
40     
41     private static final Pattern JavaDoc PARAM_PATTERN = Pattern.compile("\\@\\{(.*?)\\}");
42     private static final Pattern JavaDoc VAR_PATTERN = Pattern.compile("\\$\\{(.*?)\\}");
43     
44     public static String JavaDoc substitute(String JavaDoc pattern, ModuleRevisionId moduleRevision) {
45         return substitute(pattern,
46                 moduleRevision.getOrganisation(),
47                 moduleRevision.getName(),
48                 moduleRevision.getRevision(),
49                 "ivy",
50                 "ivy",
51                 "xml",
52                 null,
53                 moduleRevision.getAttributes());
54     }
55     public static String JavaDoc substitute(String JavaDoc pattern, ModuleRevisionId moduleRevision, String JavaDoc artifact, String JavaDoc type, String JavaDoc ext) {
56         return substitute(pattern,
57                 moduleRevision,
58                 new DefaultArtifact(moduleRevision, null, artifact, type, ext),
59                 null);
60     }
61     public static String JavaDoc substitute(String JavaDoc pattern, Artifact artifact) {
62         return substitute(pattern, artifact, (String JavaDoc) null);
63     }
64     public static String JavaDoc substitute(String JavaDoc pattern, Artifact artifact, ArtifactOrigin origin) {
65         return substitute(pattern, artifact.getModuleRevisionId(), artifact, null, origin);
66     }
67     public static String JavaDoc substitute(String JavaDoc pattern, Artifact artifact, String JavaDoc conf) {
68         return substitute(pattern, artifact.getModuleRevisionId(), artifact, conf);
69     }
70     public static String JavaDoc substitute(String JavaDoc pattern, ModuleRevisionId mrid, Artifact artifact) {
71         return substitute(pattern, mrid, artifact, null);
72     }
73     public static String JavaDoc substitute(String JavaDoc pattern, ModuleRevisionId mrid, Artifact artifact, String JavaDoc conf) {
74         return substitute(pattern, mrid, artifact, conf, null);
75     }
76     
77     public static String JavaDoc substitute(String JavaDoc pattern, ModuleRevisionId mrid, Artifact artifact, String JavaDoc conf, ArtifactOrigin origin) {
78         Map JavaDoc attributes = new HashMap JavaDoc();
79         attributes.putAll(mrid.getAttributes());
80         attributes.putAll(artifact.getAttributes());
81         return substitute(pattern,
82                 mrid.getOrganisation(),
83                 mrid.getName(),
84                 mrid.getBranch(),
85                 mrid.getRevision(),
86                 artifact.getName(),
87                 artifact.getType(),
88                 artifact.getExt(),
89                 conf,
90                 origin,
91                 attributes);
92     }
93
94     
95     public static String JavaDoc substitute(String JavaDoc pattern, String JavaDoc org, String JavaDoc module, String JavaDoc revision, String JavaDoc artifact, String JavaDoc type, String JavaDoc ext) {
96         return substitute(pattern, org, module, revision, artifact, type, ext, null);
97     }
98     
99     public static String JavaDoc substitute(String JavaDoc pattern, String JavaDoc org, String JavaDoc module, String JavaDoc revision, String JavaDoc artifact, String JavaDoc type, String JavaDoc ext, String JavaDoc conf) {
100         return substitute(pattern, org, module, revision, artifact, type, ext, conf, null);
101     }
102     
103     public static String JavaDoc substitute(String JavaDoc pattern, String JavaDoc org, String JavaDoc module, String JavaDoc revision, String JavaDoc artifact, String JavaDoc type, String JavaDoc ext, String JavaDoc conf, Map JavaDoc extraAttributes) {
104         return substitute(pattern, org, module, revision, artifact, type, ext, conf, null, extraAttributes);
105     }
106     
107     public static String JavaDoc substitute(String JavaDoc pattern, String JavaDoc org, String JavaDoc module, String JavaDoc revision, String JavaDoc artifact, String JavaDoc type, String JavaDoc ext, String JavaDoc conf, ArtifactOrigin origin, Map JavaDoc extraAttributes) {
108         return substitute(pattern, org, module, null, revision, artifact, type, ext, conf, origin, extraAttributes);
109     }
110     public static String JavaDoc substitute(String JavaDoc pattern, String JavaDoc org, String JavaDoc module, String JavaDoc branch, String JavaDoc revision, String JavaDoc artifact, String JavaDoc type, String JavaDoc ext, String JavaDoc conf, ArtifactOrigin origin, Map JavaDoc extraAttributes) {
111         Map JavaDoc tokens = new HashMap JavaDoc(extraAttributes == null ? Collections.EMPTY_MAP : extraAttributes);
112         tokens.put(ORGANISATION_KEY, org==null?"":org);
113         tokens.put(ORGANISATION_KEY2, org==null?"":org);
114         tokens.put(MODULE_KEY, module==null?"":module);
115         tokens.put(BRANCH_KEY, branch==null?"":branch);
116         tokens.put(REVISION_KEY, revision==null?"":revision);
117         tokens.put(ARTIFACT_KEY, artifact==null?module:artifact);
118         tokens.put(TYPE_KEY, type==null?"jar":type);
119         tokens.put(EXT_KEY, ext==null?"jar":ext);
120         tokens.put(CONF_KEY, conf==null?"default":conf);
121         tokens.put(ORIGINAL_ARTIFACTNAME_KEY, origin==null?new OriginalArtifactNameValue(org, module, branch, revision, artifact, type, ext):new OriginalArtifactNameValue(origin));
122         return substituteTokens(pattern, tokens);
123     }
124     
125     public static String JavaDoc substitute(String JavaDoc pattern, Map JavaDoc variables, Map JavaDoc tokens) {
126         return substituteTokens(substituteVariables(pattern, variables), tokens);
127     }
128     
129     public static String JavaDoc substituteVariables(String JavaDoc pattern, Map JavaDoc variables) {
130         return substituteVariables(pattern, variables, new Stack JavaDoc());
131     }
132     
133     private static String JavaDoc substituteVariables(String JavaDoc pattern, Map JavaDoc variables, Stack JavaDoc substituting) {
134         // if you supply null, null is what you get
135
if (pattern == null) {
136             return null;
137         }
138         
139         Matcher JavaDoc m = VAR_PATTERN.matcher(pattern);
140         
141         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
142         while (m.find()) {
143             String JavaDoc var = m.group(1);
144             String JavaDoc val = (String JavaDoc)variables.get(var);
145             if (val != null) {
146                 int index;
147                 if ((index = substituting.indexOf(var)) != -1) {
148                     List JavaDoc cycle = new ArrayList JavaDoc(substituting.subList(index, substituting.size()));
149                     cycle.add(var);
150                     throw new IllegalArgumentException JavaDoc("cyclic variable definition: cycle = "+cycle);
151                 }
152                 substituting.push(var);
153                 val = substituteVariables(val, variables, substituting);
154                 substituting.pop();
155             } else {
156                 val = m.group();
157             }
158             m.appendReplacement(sb, val.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\$", "\\\\\\$"));
159         }
160         m.appendTail(sb);
161
162         return sb.toString();
163     }
164     
165     public static String JavaDoc substituteTokens(String JavaDoc pattern, Map JavaDoc tokens) {
166         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
167         
168         char[] chars = pattern.toCharArray();
169         
170         StringBuffer JavaDoc optionalPart = null;
171         StringBuffer JavaDoc tokenBuffer = null;
172         boolean insideOptionalPart = false;
173         boolean insideToken = false;
174         boolean tokenHadValue = false;
175         
176         for (int i = 0; i < chars.length; i++) {
177             switch (chars[i]) {
178             case '(':
179                 if (insideOptionalPart) {
180                     throw new IllegalArgumentException JavaDoc("invalid start of optional part at position " + i + " in pattern " + pattern);
181                 }
182
183                 optionalPart = new StringBuffer JavaDoc();
184                 insideOptionalPart = true;
185                 tokenHadValue = false;
186                 break;
187
188             case ')':
189                 if (!insideOptionalPart || insideToken) {
190                     throw new IllegalArgumentException JavaDoc("invalid end of optional part at position " + i + " in pattern " + pattern);
191                 }
192
193                 if (tokenHadValue) {
194                     buffer.append(optionalPart.toString());
195                 }
196
197                 insideOptionalPart = false;
198                 break;
199                 
200             case '[':
201                 if (insideToken) {
202                     throw new IllegalArgumentException JavaDoc("invalid start of token at position " + i + " in pattern " + pattern);
203                 }
204                 
205                 tokenBuffer = new StringBuffer JavaDoc();
206                 insideToken = true;
207                 break;
208                 
209             case ']':
210                 if (!insideToken) {
211                     throw new IllegalArgumentException JavaDoc("invalid end of token at position " + i + " in pattern " + pattern);
212                 }
213                 
214                 String JavaDoc token = tokenBuffer.toString();
215                 Object JavaDoc tokenValue = tokens.get(token);
216                 String JavaDoc value = (tokenValue == null) ? null : tokenValue.toString();
217                 
218                 if (insideOptionalPart) {
219                     tokenHadValue = (value != null) && (value.length() > 0);
220                     optionalPart.append(value);
221                 } else {
222                     if (value == null) { // the token wasn't set, it's kept as is
223
value = "["+token+"]";
224                     }
225                     buffer.append(value);
226                 }
227                 
228                 insideToken = false;
229                 break;
230                 
231             default:
232                 if (insideToken) {
233                     tokenBuffer.append(chars[i]);
234                 } else if (insideOptionalPart) {
235                     optionalPart.append(chars[i]);
236                 } else {
237                     buffer.append(chars[i]);
238                 }
239             
240                 break;
241             }
242         }
243         
244         if (insideToken) {
245             throw new IllegalArgumentException JavaDoc("last token hasn't been closed in pattern " + pattern);
246         }
247         
248         if (insideOptionalPart) {
249             throw new IllegalArgumentException JavaDoc("optional part hasn't been closed in pattern " + pattern);
250         }
251         
252         return buffer.toString();
253     }
254     
255     public static String JavaDoc substituteVariable(String JavaDoc pattern, String JavaDoc variable, String JavaDoc value) {
256         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(pattern);
257         substituteVariable(buf, variable, value);
258         return buf.toString();
259     }
260     
261     public static void substituteVariable(StringBuffer JavaDoc buf, String JavaDoc variable, String JavaDoc value) {
262         String JavaDoc from = "${"+variable+"}";
263         int fromLength = from.length();
264         for (int index = buf.indexOf(from); index != -1; index = buf.indexOf(from, index)) {
265             buf.replace(index, index + fromLength, value);
266         }
267     }
268     
269     public static String JavaDoc substituteToken(String JavaDoc pattern, String JavaDoc token, String JavaDoc value) {
270         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(pattern);
271         substituteToken(buf, token, value);
272         return buf.toString();
273     }
274     
275     public static void substituteToken(StringBuffer JavaDoc buf, String JavaDoc token, String JavaDoc value) {
276         String JavaDoc from = getTokenString(token);
277         int fromLength = from.length();
278         for (int index = buf.indexOf(from); index != -1; index = buf.indexOf(from, index)) {
279             buf.replace(index, index + fromLength, value);
280         }
281     }
282     public static String JavaDoc getTokenString(String JavaDoc token) {
283         return "["+token+"]";
284     }
285     
286     public static String JavaDoc substituteParams(String JavaDoc pattern, Map JavaDoc params) {
287         return substituteParams(pattern, params, new Stack JavaDoc());
288     }
289     
290     private static String JavaDoc substituteParams(String JavaDoc pattern, Map JavaDoc params, Stack JavaDoc substituting) {
291         //TODO : refactor this with substituteVariables
292
// if you supply null, null is what you get
293
if (pattern == null) {
294             return null;
295         }
296         
297         Matcher JavaDoc m = PARAM_PATTERN.matcher(pattern);
298         
299         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
300         while (m.find()) {
301             String JavaDoc var = m.group(1);
302             String JavaDoc val = (String JavaDoc)params.get(var);
303             if (val != null) {
304                 int index;
305                 if ((index = substituting.indexOf(var)) != -1) {
306                     List JavaDoc cycle = new ArrayList JavaDoc(substituting.subList(index, substituting.size()));
307                     cycle.add(var);
308                     throw new IllegalArgumentException JavaDoc("cyclic param definition: cycle = "+cycle);
309                 }
310                 substituting.push(var);
311                 val = substituteVariables(val, params, substituting);
312                 substituting.pop();
313             } else {
314                 val = m.group();
315             }
316             m.appendReplacement(sb, val.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\@", "\\\\\\@"));
317         }
318         m.appendTail(sb);
319
320         return sb.toString();
321     }
322     
323     public static void main(String JavaDoc[] args) {
324         String JavaDoc pattern = "[organisation]/[module]/build/archives/[type]s/[artifact]-[revision].[ext]";
325         System.out.println("pattern= "+pattern);
326         System.out.println("resolved= "+substitute(pattern, "jayasoft", "Test", "1.0", "test", "jar", "jar"));
327         
328         Map JavaDoc variables = new HashMap JavaDoc();
329         variables.put("test", "mytest");
330         variables.put("test2", "${test}2");
331         pattern = "${test} ${test2} ${nothing}";
332         System.out.println("pattern= "+pattern);
333         System.out.println("resolved= "+substituteVariables(pattern, variables));
334     }
335     
336     /**
337      * This class returns the original name of the artifact 'on demand'. This is done to avoid
338      * having to read the cached datafile containing the original location of the artifact if we
339      * don't need it.
340      */

341     private static class OriginalArtifactNameValue {
342         // module properties
343
private String JavaDoc org;
344         private String JavaDoc moduleName;
345         private String JavaDoc branch;
346         private String JavaDoc revision;
347         
348         // artifact properties
349
private String JavaDoc artifactName;
350         private String JavaDoc artifactType;
351         private String JavaDoc artifactExt;
352         
353         // cached origin;
354
private ArtifactOrigin origin;
355         
356         public OriginalArtifactNameValue(String JavaDoc org, String JavaDoc moduleName, String JavaDoc branch, String JavaDoc revision, String JavaDoc artifactName, String JavaDoc artifactType, String JavaDoc artifactExt) {
357             this.org = org;
358             this.moduleName = moduleName;
359             this.branch = branch;
360             this.revision = revision;
361             this.artifactName = artifactName;
362             this.artifactType = artifactType;
363             this.artifactExt = artifactExt;
364         }
365
366
367         /**
368          * @param origin
369          */

370         public OriginalArtifactNameValue(ArtifactOrigin origin) {
371             this.origin = origin;
372         }
373
374         // Called by substituteTokens only if the original artifact name is needed
375
public String JavaDoc toString() {
376             if (origin == null) {
377                 ModuleRevisionId revId = ModuleRevisionId.newInstance(org, moduleName, branch, revision);
378                 Artifact artifact = new DefaultArtifact(revId, null, artifactName, artifactType, artifactExt);
379                 
380                 Ivy ivy = IvyContext.getContext().getIvy();
381                 File JavaDoc cache = IvyContext.getContext().getCache();
382     
383                 origin = ivy.getSavedArtifactOrigin(cache, artifact);
384
385                 if (origin == null) {
386                     Message.debug("no artifact origin found for "+artifact+" in "+cache);
387                     return null;
388                 }
389             }
390             
391             // we assume that the original filename is the last part of the original file location
392
String JavaDoc location = origin.getLocation();
393             int lastPathIndex = location.lastIndexOf('/');
394             if (lastPathIndex == -1) {
395                 lastPathIndex = location.lastIndexOf('\\');
396             }
397             int lastColonIndex = location.lastIndexOf('.');
398             
399             return location.substring(lastPathIndex + 1, lastColonIndex);
400         }
401     }
402
403     public static String JavaDoc getTokenRoot(String JavaDoc pattern) {
404         int index = pattern.indexOf('[');
405         if (index == -1) {
406             return pattern;
407         } else {
408             return pattern.substring(0, index);
409         }
410     }
411 }
412
Popular Tags