1 package org.apache.maven.jelly.tags.maven;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.util.StringTokenizer;
24
25 import org.apache.commons.jelly.JellyTagException;
26 import org.apache.commons.jelly.MissingAttributeException;
27 import org.apache.commons.jelly.Tag;
28 import org.apache.commons.jelly.XMLOutput;
29 import org.apache.maven.jelly.tags.BaseTagSupport;
30
31 /**
32 * Converts an absolute path into a path relative to a root dir. For
33 * example, if the root dir is "c:/apps/myproject" and the absolute
34 * path is "c:/apps/myproject/path/subproject2" then the computed
35 * relative path is "../..".
36 *
37 * @author <a href="mailto:vmassol@apache.org">Vincent Massol</a>
38 * @version $Id: RootRelativePathTag.java 517014 2007-03-11 21:15:50Z ltheussl $
39 */
40 public class RootRelativePathTag
41 extends BaseTagSupport
42 {
43 /** The root dir. */
44 private File rootdir;
45
46 /** The path to convert. */
47 private String path;
48
49 /** The jelly variable to store the result into. */
50 private String var;
51
52 /**
53 * Set the root directory.
54 * @param rootdir the root directory
55 */
56 public void setRootdir( File rootdir )
57 {
58 this.rootdir = rootdir;
59 }
60
61 /**
62 * Set the path.
63 * @param path the path.
64 */
65 public void setPath( String path )
66 {
67 this.path = path;
68 }
69
70 /**
71 * Set the result variable.
72 * @param var the result variable name.
73 */
74 public void setVar( String var )
75 {
76 this.var = var;
77 }
78
79 /**
80 * @see Tag#doTag(XMLOutput)
81 */
82 public void doTag( XMLOutput output )
83 throws MissingAttributeException, JellyTagException
84 {
85 checkAttribute( rootdir, "rootdir" );
86 checkAttribute( path, "path" );
87 checkAttribute( var, "var" );
88
89 String result;
90 try
91 {
92 result = computePath();
93 }
94 catch ( IOException e )
95 {
96 throw new JellyTagException( "Unable to create relative path", e );
97 }
98 getContext().setVariable( var, result );
99 }
100
101 /**
102 * @return the compute relative path to the root dir
103 * @throws IOException on error
104 */
105 public String computePath()
106 throws IOException
107 {
108 String canonicalRootdir = rootdir.getCanonicalPath();
109 String canonicalPath = new File( path ).getCanonicalPath();
110 if ( canonicalPath.equals( canonicalRootdir ) )
111 {
112 return ".";
113 }
114 else if ( canonicalPath.startsWith( canonicalRootdir ) )
115 {
116 canonicalPath = canonicalPath.substring( canonicalRootdir.length() );
117 }
118 else
119 {
120 throw new IOException( "Path [" + canonicalPath + "] is not a subset of [" + canonicalRootdir + "]" );
121 }
122
123 StringBuffer result = new StringBuffer( "." );
124 StringTokenizer tokens = new StringTokenizer( canonicalPath, "/\\" );
125 while ( tokens.hasMoreTokens() )
126 {
127 tokens.nextToken();
128 result.append( "/.." );
129 }
130 return result.toString();
131 }
132 }