View Javadoc
1   /**
2    * Copyright By Grandsoft Company Limited.  
3    * 2012-6-19 上午09:36:46
4    */
5   package gboat2.base.plugin.struts.velocity;
6   
7   import java.io.File;
8   import java.io.FileInputStream;
9   import java.io.FileNotFoundException;
10  import java.io.InputStream;
11  
12  import org.apache.commons.lang3.StringUtils;
13  import org.apache.velocity.exception.ResourceNotFoundException;
14  import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
15  
16  import com.opensymphony.xwork2.ActionContext;
17  
18  /**
19   * 扩展 Velocity 自身的 ClasspathResourceLoader,实现 OSGI Bundle 的 vm 页面动态部署
20   * @date 2013-01-14
21   * @author tanxw
22   * @since 1.0
23   */
24  public class DebugVelocityResourceLoader extends ClasspathResourceLoader {
25  	
26  	public static final String CURRENT_BUNDLE_RES_LOCATION = "_curr_bundle_res_location_";
27  	
28  	@Override
29      public InputStream getResourceStream(String name)
30              throws ResourceNotFoundException {
31          String currBundleResPath = (String) ActionContext.getContext().get(CURRENT_BUNDLE_RES_LOCATION);
32          if (StringUtils.isEmpty(currBundleResPath)) {
33              return null;
34          }
35  
36          String path = null;
37          if (currBundleResPath.endsWith("/") && name.startsWith("/")) {
38              path = currBundleResPath + name.substring(1);
39          } else if (!currBundleResPath.endsWith("/") && !name.startsWith("/")) {
40              path = currBundleResPath + "/" + name;
41          } else {
42              path = currBundleResPath + name;
43          }
44  
45          File file = new File(path);
46          if (file.exists()) {
47              try {
48                  return new FileInputStream(file);
49              } catch (FileNotFoundException e) {
50                  throw new ResourceNotFoundException(e);
51              }
52          }
53  
54          return null;
55      }
56  }