View Javadoc

1   package org.apache.velocity.app.event.implement;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.    
20   */
21  
22  import org.apache.velocity.app.event.IncludeEventHandler;
23  
24  /**
25   * <p>Event handler that looks for included files relative to the path of the
26   * current template. The handler assumes that paths are separated by a forward
27   * slash "/" or backwards slash "\".
28   *
29   * @author <a href="mailto:wglass@forio.com">Will Glass-Husain </a>
30   * @version $Id: IncludeRelativePath.java 685685 2008-08-13 21:43:27Z nbubna $
31   * @since 1.5
32   */
33  public class IncludeRelativePath implements IncludeEventHandler {
34  
35      /**
36       * Return path relative to the current template's path.
37       * 
38       * @param includeResourcePath  the path as given in the include directive.
39       * @param currentResourcePath the path of the currently rendering template that includes the
40       *            include directive.
41       * @param directiveName  name of the directive used to include the resource. (With the
42       *            standard directives this is either "parse" or "include").
43  
44       * @return new path relative to the current template's path
45       */
46      public String includeEvent(
47          String includeResourcePath,
48          String currentResourcePath,
49          String directiveName)
50      {
51          // if the resource name starts with a slash, it's not a relative path
52          if (includeResourcePath.startsWith("/") || includeResourcePath.startsWith("\\") ) {
53              return includeResourcePath;
54          }
55  
56          int lastslashpos = Math.max(
57                  currentResourcePath.lastIndexOf("/"),
58                  currentResourcePath.lastIndexOf("\\")
59                  );
60  
61          // root of resource tree
62          if (lastslashpos == -1) {
63              return includeResourcePath;
64          }
65  
66          // prepend path to the include path
67          return currentResourcePath.substring(0,lastslashpos) + "/" + includeResourcePath;
68      }
69  }