├── .travis.yml ├── cherry-core ├── src │ ├── main │ │ └── java │ │ │ └── cherry │ │ │ ├── PluginContextEvent.java │ │ │ ├── Plugin.java │ │ │ ├── PluginContextListener.java │ │ │ ├── config │ │ │ ├── ListenerDefinition.java │ │ │ ├── PluginConfig.java │ │ │ ├── Library.java │ │ │ ├── Param.java │ │ │ ├── PropertiesPlaceholder.java │ │ │ ├── PluginDefinition.java │ │ │ ├── DefaultPluginConfig.java │ │ │ └── AppConfig.java │ │ │ ├── PluginContext.java │ │ │ ├── exception │ │ │ └── PluginException.java │ │ │ ├── PluginFactory.java │ │ │ ├── DefaultPluginContext.java │ │ │ ├── util │ │ │ ├── StringUtils.java │ │ │ ├── IoUtils.java │ │ │ └── JaxbUtils.java │ │ │ ├── PluginClassLoader.java │ │ │ ├── DefaultPluginFactory.java │ │ │ ├── AbstractPluginFactory.java │ │ │ └── xml │ │ │ └── ConfigParser.java │ └── test │ │ └── java │ │ └── cherry │ │ └── core │ │ └── AppTest.java └── pom.xml ├── cherry-demo ├── cherry-demo-main │ ├── src │ │ ├── test │ │ │ └── java │ │ │ │ └── cherry │ │ │ │ └── demo │ │ │ │ └── main │ │ │ │ └── AppTest.java │ │ └── main │ │ │ ├── java │ │ │ └── cherry │ │ │ │ └── demo │ │ │ │ └── main │ │ │ │ └── App.java │ │ │ └── resources │ │ │ ├── plugins.xml │ │ │ └── logback.xml │ └── pom.xml ├── cherry-demo-plugin │ ├── src │ │ └── main │ │ │ ├── test │ │ │ └── cherry │ │ │ │ └── demo │ │ │ │ └── plugin │ │ │ │ └── AppTest.java │ │ │ └── java │ │ │ └── cherry │ │ │ └── demo │ │ │ └── plugin │ │ │ ├── ExampleContextListener.java │ │ │ ├── HelloServiceImpl.java │ │ │ └── UserServiceImpl.java │ └── pom.xml ├── cherry-demo-api │ ├── src │ │ └── main │ │ │ └── java │ │ │ └── cherry │ │ │ └── demo │ │ │ └── api │ │ │ ├── HelloService.java │ │ │ ├── UserService.java │ │ │ └── model │ │ │ └── User.java │ └── pom.xml └── pom.xml ├── .gitignore ├── README.md ├── pom.xml └── LICENSE /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/PluginContextEvent.java: -------------------------------------------------------------------------------- 1 | package cherry; 2 | 3 | /** 4 | * ${DESCRIPTION} 5 | * 6 | * @author Ricky Fung 7 | */ 8 | public interface PluginContextEvent { 9 | 10 | PluginContext getPluginContext(); 11 | } 12 | -------------------------------------------------------------------------------- /cherry-core/src/test/java/cherry/core/AppTest.java: -------------------------------------------------------------------------------- 1 | package cherry.core; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * Unit test for simple App. 7 | */ 8 | public class AppTest { 9 | 10 | @Test 11 | public void testApp(){ 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-main/src/test/java/cherry/demo/main/AppTest.java: -------------------------------------------------------------------------------- 1 | package cherry.demo.main; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * Unit test for simple App. 7 | */ 8 | public class AppTest { 9 | 10 | @Test 11 | public void testApp() { 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-plugin/src/main/test/cherry/demo/plugin/AppTest.java: -------------------------------------------------------------------------------- 1 | package cherry.demo.plugin; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * @author Ricky Fung 7 | */ 8 | public class AppTest { 9 | 10 | @Test 11 | public void testApp() { 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/Plugin.java: -------------------------------------------------------------------------------- 1 | package cherry; 2 | 3 | import cherry.config.PluginConfig; 4 | 5 | /** 6 | * ${DESCRIPTION} 7 | * 8 | * @author Ricky Fung 9 | */ 10 | public interface Plugin { 11 | 12 | void init(PluginConfig config); 13 | 14 | void destroy(); 15 | } 16 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/PluginContextListener.java: -------------------------------------------------------------------------------- 1 | package cherry; 2 | 3 | /** 4 | * ${DESCRIPTION} 5 | * 6 | * @author Ricky Fung 7 | */ 8 | public interface PluginContextListener { 9 | 10 | void contextInitialized(PluginContextEvent event); 11 | 12 | void contextDestroyed(PluginContextEvent event); 13 | } 14 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-api/src/main/java/cherry/demo/api/HelloService.java: -------------------------------------------------------------------------------- 1 | package cherry.demo.api; 2 | 3 | import cherry.Plugin; 4 | 5 | /** 6 | * ${DESCRIPTION} 7 | * 8 | * @author Ricky Fung 9 | */ 10 | public interface HelloService extends Plugin { 11 | 12 | String echo(String msg); 13 | 14 | void hello(String msg); 15 | } 16 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/config/ListenerDefinition.java: -------------------------------------------------------------------------------- 1 | package cherry.config; 2 | 3 | /** 4 | * ${DESCRIPTION} 5 | * 6 | * @author Ricky Fung 7 | */ 8 | public class ListenerDefinition { 9 | private String clazz; 10 | 11 | public String getClazz() { 12 | return clazz; 13 | } 14 | 15 | public void setClazz(String clazz) { 16 | this.clazz = clazz; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/PluginContext.java: -------------------------------------------------------------------------------- 1 | package cherry; 2 | 3 | import java.util.Set; 4 | 5 | /** 6 | * 上下文对象 7 | * 8 | * @author Ricky Fung 9 | */ 10 | public interface PluginContext { 11 | 12 | Object getAttribute(String attr); 13 | 14 | Set getAttributeNames(); 15 | 16 | void setAttribute(String attr, Object value); 17 | 18 | void removeAttribute(String attr); 19 | } 20 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-api/src/main/java/cherry/demo/api/UserService.java: -------------------------------------------------------------------------------- 1 | package cherry.demo.api; 2 | 3 | import cherry.Plugin; 4 | import cherry.demo.api.model.User; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * ${DESCRIPTION} 10 | * 11 | * @author Ricky Fung 12 | */ 13 | public interface UserService extends Plugin { 14 | 15 | User getUser(String name); 16 | 17 | List getUsers(); 18 | 19 | int insert(User user); 20 | } 21 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/config/PluginConfig.java: -------------------------------------------------------------------------------- 1 | package cherry.config; 2 | 3 | import cherry.PluginContext; 4 | import java.util.List; 5 | import java.util.Set; 6 | 7 | /** 8 | * ${DESCRIPTION} 9 | * 10 | * @author Ricky Fung 11 | */ 12 | public interface PluginConfig { 13 | 14 | String getPluginName(); 15 | 16 | PluginContext getPluginContext(); 17 | 18 | String getInitParameter(String name); 19 | 20 | Set getInitParameterNames(); 21 | } 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # maven ignore 2 | *target/ 3 | !tools/*.jar 4 | *.war 5 | *.zip 6 | *.tar 7 | *.tar.gz 8 | 9 | # Java class files 10 | *.class 11 | 12 | # eclipse ignore 13 | *.settings/ 14 | .project 15 | .classpath 16 | 17 | # idea ignore 18 | .idea/ 19 | *.ipr 20 | *.iml 21 | *.iws 22 | 23 | # temp ignore 24 | *.log 25 | *.log.* 26 | *.cache 27 | *.diff 28 | *.patch 29 | *.tmp 30 | 31 | # system ignore 32 | .DS_Store 33 | Thumbs.db 34 | 35 | sublime-project 36 | sublime-project.sublime-workspace 37 | 38 | coverage-report/ 39 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/config/Library.java: -------------------------------------------------------------------------------- 1 | package cherry.config; 2 | 3 | /** 4 | * ${DESCRIPTION} 5 | * 6 | * @author Ricky Fung 7 | */ 8 | public class Library { 9 | private String dir; 10 | private String regex; 11 | 12 | public String getDir() { 13 | return dir; 14 | } 15 | 16 | public void setDir(String dir) { 17 | this.dir = dir; 18 | } 19 | 20 | public String getRegex() { 21 | return regex; 22 | } 23 | 24 | public void setRegex(String regex) { 25 | this.regex = regex; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/config/Param.java: -------------------------------------------------------------------------------- 1 | package cherry.config; 2 | 3 | /** 4 | * ${DESCRIPTION} 5 | * 6 | * @author Ricky Fung 7 | */ 8 | public class Param { 9 | private String name; 10 | private String value; 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | public void setName(String name) { 17 | this.name = name; 18 | } 19 | 20 | public String getValue() { 21 | return value; 22 | } 23 | 24 | public void setValue(String value) { 25 | this.value = value; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/config/PropertiesPlaceholder.java: -------------------------------------------------------------------------------- 1 | package cherry.config; 2 | 3 | /** 4 | * ${DESCRIPTION} 5 | * 6 | * @author Ricky Fung 7 | */ 8 | public class PropertiesPlaceholder { 9 | private String name; 10 | private String value; 11 | 12 | public String getName() { 13 | return name; 14 | } 15 | 16 | public void setName(String name) { 17 | this.name = name; 18 | } 19 | 20 | public String getValue() { 21 | return value; 22 | } 23 | 24 | public void setValue(String value) { 25 | this.value = value; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/exception/PluginException.java: -------------------------------------------------------------------------------- 1 | package cherry.exception; 2 | 3 | /** 4 | * ${DESCRIPTION} 5 | * 6 | * @author Ricky Fung 7 | */ 8 | public class PluginException extends RuntimeException { 9 | 10 | public PluginException() { 11 | super(); 12 | } 13 | 14 | public PluginException(String message) { 15 | super(message); 16 | } 17 | 18 | public PluginException(String message, Throwable cause) { 19 | super(message, cause); 20 | } 21 | 22 | public PluginException(Throwable cause) { 23 | super(cause); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/PluginFactory.java: -------------------------------------------------------------------------------- 1 | package cherry; 2 | 3 | import cherry.config.PluginDefinition; 4 | import cherry.exception.PluginException; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * ${DESCRIPTION} 10 | * 11 | * @author Ricky Fung 12 | */ 13 | public interface PluginFactory { 14 | 15 | Plugin getPlugin(String name) throws PluginException; 16 | 17 | T getPlugin(Class type) throws PluginException; 18 | 19 | PluginDefinition getPluginDefinition(String name); 20 | 21 | List getPluginNames(); 22 | 23 | boolean hasPlugin(String name); 24 | 25 | void close(); 26 | } 27 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-plugin/src/main/java/cherry/demo/plugin/ExampleContextListener.java: -------------------------------------------------------------------------------- 1 | package cherry.demo.plugin; 2 | 3 | import cherry.PluginContextEvent; 4 | import cherry.PluginContextListener; 5 | 6 | /** 7 | * ${DESCRIPTION} 8 | * 9 | * @author Ricky Fung 10 | */ 11 | public class ExampleContextListener implements PluginContextListener { 12 | 13 | @Override 14 | public void contextInitialized(PluginContextEvent event) { 15 | System.out.println("context Initialized"); 16 | } 17 | 18 | @Override 19 | public void contextDestroyed(PluginContextEvent event) { 20 | System.out.println("context Destroyed"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cherry 2 | [![License](https://img.shields.io/badge/license-Apache%202-green.svg)](https://www.apache.org/licenses/LICENSE-2.0) [![Release Version](https://img.shields.io/badge/release-1.0.0-red.svg)](https://github.com/TFrise/cherry/releases) [![Build Status](https://travis-ci.org/TFrise/cherry.svg?branch=master)](https://travis-ci.org/TFrise/cherry) 3 | 4 | ## Overview 5 | A flexible, stable, easy-to-use plugin Framework for Java applications. For more information see [the wiki](https://github.com/TiFG/cherry/wiki). 6 | 7 | ## Download 8 | Download the latest JAR or grab via Maven: 9 | ``` 10 | 11 | com.mindflow 12 | cherry 13 | 1.0.0 14 | 15 | ``` 16 | or Gradle: 17 | ``` 18 | compile 'com.mindflow:cherry:1.0.0' 19 | ``` 20 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-api/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | cherry-demo 5 | com.mindflow 6 | 1.0.0-SNAPSHOT 7 | 8 | 4.0.0 9 | 10 | cherry-demo-api 11 | jar 12 | 13 | cherry-demo-api 14 | http://maven.apache.org 15 | 16 | 17 | UTF-8 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/config/PluginDefinition.java: -------------------------------------------------------------------------------- 1 | package cherry.config; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * ${DESCRIPTION} 7 | * 8 | * @author Ricky Fung 9 | */ 10 | public class PluginDefinition { 11 | private String name; 12 | private String clazz; 13 | private List params; 14 | 15 | public String getName() { 16 | return name; 17 | } 18 | 19 | public void setName(String name) { 20 | this.name = name; 21 | } 22 | 23 | public String getClazz() { 24 | return clazz; 25 | } 26 | 27 | public void setClazz(String clazz) { 28 | this.clazz = clazz; 29 | } 30 | 31 | public List getParams() { 32 | return params; 33 | } 34 | 35 | public void setParams(List params) { 36 | this.params = params; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/DefaultPluginContext.java: -------------------------------------------------------------------------------- 1 | package cherry; 2 | 3 | import java.util.Set; 4 | import java.util.concurrent.ConcurrentHashMap; 5 | 6 | /** 7 | * ${DESCRIPTION} 8 | * 9 | * @author Ricky Fung 10 | */ 11 | public class DefaultPluginContext implements PluginContext { 12 | 13 | private ConcurrentHashMap map = new ConcurrentHashMap<>(64); 14 | 15 | @Override 16 | public Object getAttribute(String attr) { 17 | return map.get(attr); 18 | } 19 | 20 | @Override 21 | public Set getAttributeNames() { 22 | return map.keySet(); 23 | } 24 | 25 | @Override 26 | public void setAttribute(String attr, Object value) { 27 | map.put(attr, value); 28 | } 29 | 30 | @Override 31 | public void removeAttribute(String attr) { 32 | map.remove(attr); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-plugin/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | cherry-demo 5 | com.mindflow 6 | 1.0.0-SNAPSHOT 7 | 8 | 4.0.0 9 | 10 | cherry-demo-plugin 11 | jar 12 | 13 | cherry-demo-plugin 14 | http://maven.apache.org 15 | 16 | 17 | UTF-8 18 | 19 | 20 | 21 | 22 | com.mindflow 23 | cherry-demo-api 24 | ${project.parent.version} 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /cherry-demo/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | com.mindflow 5 | cherry 6 | 1.0.0-SNAPSHOT 7 | 8 | 4.0.0 9 | 10 | cherry-demo 11 | pom 12 | 13 | cherry-demo 14 | http://maven.apache.org 15 | 16 | 17 | cherry-demo-api 18 | cherry-demo-plugin 19 | cherry-demo-main 20 | 21 | 22 | 23 | UTF-8 24 | 25 | 26 | 27 | 28 | com.mindflow 29 | cherry-core 30 | ${project.parent.version} 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-plugin/src/main/java/cherry/demo/plugin/HelloServiceImpl.java: -------------------------------------------------------------------------------- 1 | package cherry.demo.plugin; 2 | 3 | import cherry.config.PluginConfig; 4 | import cherry.demo.api.HelloService; 5 | 6 | /** 7 | * ${DESCRIPTION} 8 | * 9 | * @author Ricky Fung 10 | */ 11 | public class HelloServiceImpl implements HelloService { 12 | private PluginConfig config; 13 | 14 | @Override 15 | public String echo(String msg) { 16 | System.out.println("echo [" + msg + "]"); 17 | this.config.getPluginContext().setAttribute("echo", msg); 18 | return "echo [" + msg + "]"; 19 | } 20 | 21 | @Override 22 | public void hello(String msg) { 23 | System.out.println("hello "+msg); 24 | System.out.println("encoding="+config.getInitParameter("encoding")); 25 | this.config.getPluginContext().setAttribute("hello", msg); 26 | System.out.println("attr:"+this.config.getPluginContext().getAttribute("hello")); 27 | } 28 | 29 | @Override 30 | public void init(PluginConfig config) { 31 | this.config = config; 32 | System.out.println("HelloServiceImpl init..."); 33 | } 34 | 35 | @Override 36 | public void destroy() { 37 | System.out.println("HelloServiceImpl destroy..."); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-main/src/main/java/cherry/demo/main/App.java: -------------------------------------------------------------------------------- 1 | package cherry.demo.main; 2 | 3 | import cherry.DefaultPluginFactory; 4 | import cherry.PluginFactory; 5 | import cherry.demo.api.HelloService; 6 | import cherry.demo.api.UserService; 7 | import cherry.demo.api.model.User; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * Hello world! 13 | * 14 | */ 15 | public class App { 16 | 17 | public static void main( String[] args ) { 18 | 19 | PluginFactory pluginFactory = new DefaultPluginFactory("classpath:plugins.xml"); 20 | //PluginFactory pluginFactory = new DefaultPluginFactory(new File("/home/plugins.xml")); 21 | 22 | HelloService helloService = (HelloService) pluginFactory.getPlugin("helloService"); 23 | System.out.println(helloService); 24 | 25 | helloService.hello("cherry"); 26 | helloService.echo("cherry"); 27 | 28 | UserService userService = pluginFactory.getPlugin(UserService.class); 29 | System.out.println(userService); 30 | 31 | User user = userService.getUser("cherry"); 32 | System.out.println(user); 33 | 34 | List list = userService.getUsers(); 35 | System.out.println(list); 36 | 37 | //关闭 38 | pluginFactory.close(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-plugin/src/main/java/cherry/demo/plugin/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package cherry.demo.plugin; 2 | 3 | import cherry.config.PluginConfig; 4 | import cherry.demo.api.UserService; 5 | import cherry.demo.api.model.User; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | /** 10 | * ${DESCRIPTION} 11 | * 12 | * @author Ricky Fung 13 | */ 14 | public class UserServiceImpl implements UserService { 15 | 16 | private PluginConfig config; 17 | 18 | @Override 19 | public User getUser(String name) { 20 | User user = new User(); 21 | user.setName(name); 22 | user.setPassword("root"); 23 | user.setAge(25); 24 | return user; 25 | } 26 | 27 | @Override 28 | public List getUsers() { 29 | List list = new ArrayList<>(); 30 | for(int i=0; i<5; i++){ 31 | list.add(new User("ricky_"+i, "root", 25+i)); 32 | } 33 | return list; 34 | } 35 | 36 | @Override 37 | public int insert(User user) { 38 | return 1; 39 | } 40 | 41 | @Override 42 | public void init(PluginConfig config) { 43 | this.config = config; 44 | System.out.println("UserServiceImpl init..."); 45 | } 46 | 47 | @Override 48 | public void destroy() { 49 | System.out.println("UserServiceImpl destroy..."); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-main/src/main/resources/plugins.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | cherry-demo 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | app-version 16 | v1.0 17 | 18 | 19 | 20 | 21 | helloService 22 | cherry.demo.plugin.HelloServiceImpl 23 | 24 | encoding 25 | UTF-8 26 | 27 | 28 | path 29 | ${path} 30 | 31 | 32 | 33 | 34 | userService 35 | cherry.demo.plugin.UserServiceImpl 36 | 37 | 38 | 39 | cherry.demo.plugin.ExampleContextListener 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-main/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | cherry-demo 5 | com.mindflow 6 | 1.0.0-SNAPSHOT 7 | 8 | 4.0.0 9 | 10 | cherry-demo-main 11 | jar 12 | 13 | cherry-demo-main 14 | http://maven.apache.org 15 | 16 | 17 | UTF-8 18 | 19 | 20 | 21 | 22 | com.mindflow 23 | cherry-demo-api 24 | ${project.parent.version} 25 | 26 | 27 | 28 | ch.qos.logback 29 | logback-core 30 | ${logback.version} 31 | 32 | 33 | ch.qos.logback 34 | logback-classic 35 | ${logback.version} 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/config/DefaultPluginConfig.java: -------------------------------------------------------------------------------- 1 | package cherry.config; 2 | 3 | import cherry.PluginContext; 4 | 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.Set; 9 | 10 | /** 11 | * ${DESCRIPTION} 12 | * 13 | * @author Ricky Fung 14 | */ 15 | public class DefaultPluginConfig implements PluginConfig { 16 | private String pluginName; 17 | private Map params; 18 | private PluginContext context; 19 | 20 | public DefaultPluginConfig(PluginDefinition pd, PluginContext context) { 21 | this.pluginName = pd.getName(); 22 | this.params = getInitParams(pd.getParams()); 23 | this.context = context; 24 | } 25 | 26 | @Override 27 | public String getPluginName() { 28 | return pluginName; 29 | } 30 | 31 | @Override 32 | public PluginContext getPluginContext() { 33 | return context; 34 | } 35 | 36 | @Override 37 | public String getInitParameter(String name) { 38 | return params.get(name); 39 | } 40 | 41 | @Override 42 | public Set getInitParameterNames() { 43 | return params.keySet(); 44 | } 45 | 46 | private Map getInitParams(List list) { 47 | Map params = new HashMap<>(8); 48 | if(list!=null && list.size()>0){ 49 | for (Param param : list){ 50 | params.put(param.getName(), param.getValue()); 51 | } 52 | } 53 | return params; 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-api/src/main/java/cherry/demo/api/model/User.java: -------------------------------------------------------------------------------- 1 | package cherry.demo.api.model; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * ${DESCRIPTION} 7 | * 8 | * @author Ricky Fung 9 | * @create 2016-11-12 16:08 10 | */ 11 | public class User { 12 | private String name; 13 | private String password; 14 | private int age; 15 | private List hobbies; 16 | 17 | public User(){ 18 | 19 | } 20 | 21 | public User(String name, String password, int age) { 22 | this.name = name; 23 | this.password = password; 24 | this.age = age; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | public String getPassword() { 36 | return password; 37 | } 38 | 39 | public void setPassword(String password) { 40 | this.password = password; 41 | } 42 | 43 | public int getAge() { 44 | return age; 45 | } 46 | 47 | public void setAge(int age) { 48 | this.age = age; 49 | } 50 | 51 | public List getHobbies() { 52 | return hobbies; 53 | } 54 | 55 | public void setHobbies(List hobbies) { 56 | this.hobbies = hobbies; 57 | } 58 | 59 | @Override 60 | public String toString() { 61 | return "User{" + 62 | "name='" + name + '\'' + 63 | ", password='" + password + '\'' + 64 | ", age=" + age + 65 | ", hobbies=" + hobbies + 66 | '}'; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/util/StringUtils.java: -------------------------------------------------------------------------------- 1 | package cherry.util; 2 | 3 | /** 4 | * ${DESCRIPTION} 5 | * 6 | * @author Ricky Fung 7 | * @create 2016-10-31 10:19 8 | */ 9 | public class StringUtils { 10 | 11 | public static final String EMPTY = ""; 12 | 13 | public static boolean isEmpty(final CharSequence cs) { 14 | return cs == null || cs.length() == 0; 15 | } 16 | 17 | public static boolean isNotEmpty(final CharSequence str) { 18 | return !isEmpty(str); 19 | } 20 | 21 | public static boolean isBlank(final CharSequence cs) { 22 | int strLen; 23 | if (cs == null || (strLen = cs.length()) == 0) { 24 | return true; 25 | } 26 | for (int i = 0; i < strLen; i++) { 27 | if (Character.isWhitespace(cs.charAt(i)) == false) { 28 | return false; 29 | } 30 | } 31 | return true; 32 | } 33 | 34 | public static boolean isNotBlank(final CharSequence cs) { 35 | return !isBlank(cs); 36 | } 37 | 38 | public static boolean equals(String str1, String str2) { 39 | return str1 == null?str2 == null:str1.equals(str2); 40 | } 41 | 42 | public static boolean equalsIgnoreCase(String str1, String str2) { 43 | return str1 == null?str2 == null:str1.equalsIgnoreCase(str2); 44 | } 45 | 46 | public static String trim(final String str) { 47 | return str == null ? null : str.trim(); 48 | } 49 | 50 | public static boolean contains(String str, String searchStr) { 51 | if (str == null || searchStr == null) { 52 | return false; 53 | } 54 | return str.indexOf(searchStr) >= 0; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/util/IoUtils.java: -------------------------------------------------------------------------------- 1 | package cherry.util; 2 | 3 | import java.io.Closeable; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.io.OutputStream; 7 | 8 | /** 9 | * ${DESCRIPTION} 10 | * 11 | * @author Ricky Fung 12 | * @create 2016-10-31 10:19 13 | */ 14 | public class IoUtils { 15 | 16 | public static void closeQuietly(InputStream input){ 17 | closeQuietly((Closeable)input); 18 | } 19 | 20 | public static void closeQuietly(OutputStream output){ 21 | closeQuietly((Closeable)output); 22 | } 23 | 24 | public static void closeQuietly(Closeable closeable) { 25 | try { 26 | if(closeable != null) { 27 | closeable.close(); 28 | } 29 | } catch (IOException e) { 30 | e.printStackTrace(); 31 | } 32 | } 33 | 34 | public static void closeQuietly(Closeable... closeables){ 35 | for (Closeable closeable : closeables){ 36 | closeQuietly(closeable); 37 | } 38 | } 39 | 40 | public static long copy(InputStream in, OutputStream out, int bufferSize) throws IOException { 41 | byte[] buff = new byte[bufferSize]; 42 | return copy(in, out, buff); 43 | } 44 | 45 | public static long copy(InputStream in, OutputStream out) throws IOException { 46 | byte[] buff = new byte[1024]; 47 | return copy(in, out, buff); 48 | } 49 | 50 | public static long copy(InputStream in, OutputStream out, byte[] buff) throws IOException { 51 | long count = 0; 52 | int len = -1; 53 | while((len=in.read(buff, 0, buff.length))!=-1){ 54 | out.write(buff, 0, len); 55 | count += len; 56 | } 57 | return count; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /cherry-core/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | com.mindflow 5 | cherry 6 | 1.0.0-SNAPSHOT 7 | 8 | 4.0.0 9 | 10 | cherry-core 11 | jar 12 | 13 | cherry-core 14 | http://maven.apache.org 15 | 16 | 17 | UTF-8 18 | 19 | 20 | 21 | 22 | 23 | dom4j 24 | dom4j 25 | ${dom4j.version} 26 | 27 | 28 | jaxen 29 | jaxen 30 | 1.1.6 31 | 32 | 33 | 34 | 35 | 36 | 37 | org.apache.maven.plugins 38 | maven-source-plugin 39 | 2.2.1 40 | 41 | 42 | attach-sources 43 | 44 | jar-no-fork 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/config/AppConfig.java: -------------------------------------------------------------------------------- 1 | package cherry.config; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * ${DESCRIPTION} 7 | * 8 | * @author Ricky Fung 9 | */ 10 | public class AppConfig { 11 | private String contextName; // 12 | private List placeholders; //全局参数 13 | 14 | private List libs; //外部jar 15 | 16 | private List contextParams; 17 | 18 | private List plugins; //插件 19 | 20 | private List listeners; //Listener 21 | 22 | public String getContextName() { 23 | return contextName; 24 | } 25 | 26 | public void setContextName(String contextName) { 27 | this.contextName = contextName; 28 | } 29 | 30 | public List getPlaceholders() { 31 | return placeholders; 32 | } 33 | 34 | public void setPlaceholders(List placeholders) { 35 | this.placeholders = placeholders; 36 | } 37 | 38 | public List getLibs() { 39 | return libs; 40 | } 41 | 42 | public void setLibs(List libs) { 43 | this.libs = libs; 44 | } 45 | 46 | public List getContextParams() { 47 | return contextParams; 48 | } 49 | 50 | public void setContextParams(List contextParams) { 51 | this.contextParams = contextParams; 52 | } 53 | 54 | public List getPlugins() { 55 | return plugins; 56 | } 57 | 58 | public void setPlugins(List plugins) { 59 | this.plugins = plugins; 60 | } 61 | 62 | public List getListeners() { 63 | return listeners; 64 | } 65 | 66 | public void setListeners(List listeners) { 67 | this.listeners = listeners; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.mindflow 6 | cherry 7 | 1.0.0-SNAPSHOT 8 | 9 | pom 10 | 11 | cherry 12 | http://maven.apache.org 13 | 14 | 15 | cherry-core 16 | cherry-demo 17 | 18 | 19 | 20 | 1.6.1 21 | 1.2.3 22 | 1.7.25 23 | 4.12 24 | 1.7 25 | UTF-8 26 | 27 | 28 | 29 | 30 | org.slf4j 31 | slf4j-api 32 | ${slf4j.version} 33 | 34 | 35 | 36 | junit 37 | junit 38 | ${junit.version} 39 | test 40 | 41 | 42 | 43 | 44 | 45 | 46 | org.apache.maven.plugins 47 | maven-compiler-plugin 48 | 3.5.1 49 | 50 | ${java.version} 51 | ${java.version} 52 | ${java.version} 53 | ${java.version} 54 | ${project.build.sourceEncoding} 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/util/JaxbUtils.java: -------------------------------------------------------------------------------- 1 | package cherry.util; 2 | 3 | import javax.xml.bind.JAXBContext; 4 | import javax.xml.bind.JAXBException; 5 | import javax.xml.bind.Marshaller; 6 | import javax.xml.bind.Unmarshaller; 7 | import java.io.File; 8 | import java.io.InputStream; 9 | import java.io.StringReader; 10 | import java.io.StringWriter; 11 | 12 | /** 13 | * ${DESCRIPTION} 14 | * 15 | * @author Ricky Fung 16 | */ 17 | public class JaxbUtils { 18 | 19 | public final static String CHARSET_NAME = "UTF-8"; 20 | 21 | public static String marshal(Object obj) throws JAXBException { 22 | JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass()); 23 | Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); 24 | // output pretty printed 25 | jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 26 | jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, CHARSET_NAME); 27 | 28 | StringWriter writer = new StringWriter(); 29 | try{ 30 | jaxbMarshaller.marshal(obj, writer); 31 | return writer.toString(); 32 | } finally { 33 | IoUtils.closeQuietly(writer); 34 | } 35 | } 36 | 37 | public static T unmarshal(String xml, Class cls) throws JAXBException { 38 | JAXBContext jaxbContext = JAXBContext.newInstance(cls); 39 | Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); 40 | 41 | StringReader reader = null; 42 | try{ 43 | reader = new StringReader(xml); 44 | return (T) jaxbUnmarshaller.unmarshal(reader); 45 | } finally { 46 | IoUtils.closeQuietly(reader); 47 | } 48 | } 49 | 50 | public static T unmarshal(File file, Class cls) throws JAXBException { 51 | JAXBContext jaxbContext = JAXBContext.newInstance(cls); 52 | Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); 53 | 54 | return (T) jaxbUnmarshaller.unmarshal(file); 55 | } 56 | 57 | public static T unmarshal(InputStream in, Class cls) throws JAXBException { 58 | JAXBContext jaxbContext = JAXBContext.newInstance(cls); 59 | Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); 60 | 61 | return (T) jaxbUnmarshaller.unmarshal(in); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /cherry-demo/cherry-demo-main/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | cherry-demo 4 | 5 | 6 | 7 | 8 | 9 | 10 | %date{yyyy-MM-dd HH:mm:ss.SSS} | %thread | %-5level | %logger [%file:%line] | %msg%n 11 | 12 | 13 | 14 | 15 | ${LOG_HOME}/info/cherry-demo-info.log 16 | true 17 | 18 | 19 | INFO 20 | 21 | 22 | 23 | ${LOG_HOME}/info/cherry-demo.%d{yyyy-MM-dd}-info.log.gz 24 | 25 | 360 26 | 27 | 28 | 29 | %date{yyyy-MM-dd HH:mm:ss.SSS} | %thread | %-5level | %logger | %msg%n 30 | 31 | 32 | 33 | 34 | ${LOG_HOME}/error/cherry-demo-error.log 35 | true 36 | 37 | 38 | ERROR 39 | 40 | 41 | 42 | ${LOG_HOME}/error/cherry-demo.%d{yyyy-MM-dd}-error.log.gz 43 | 44 | 360 45 | 46 | 47 | 48 | %date{yyyy-MM-dd HH:mm:ss.SSS} | %thread | %-5level | %logger | %msg%n 49 | 50 | 51 | 52 | 53 | 54 | 10 55 | 2000 56 | 57 | 58 | 59 | 60 | 10 61 | 2000 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/PluginClassLoader.java: -------------------------------------------------------------------------------- 1 | package cherry; 2 | 3 | import cherry.util.IoUtils; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import java.io.File; 7 | import java.io.FileFilter; 8 | import java.net.MalformedURLException; 9 | import java.net.URL; 10 | import java.net.URLClassLoader; 11 | 12 | /** 13 | * 14 | * @author Ricky Fung 15 | * @create 2016-11-12 14:27 16 | */ 17 | public class PluginClassLoader { 18 | 19 | private final Logger logger = LoggerFactory.getLogger(PluginClassLoader.class); 20 | 21 | private URLClassLoader classLoader; 22 | 23 | public PluginClassLoader(String jarfileDir){ 24 | this(new File(jarfileDir), null); 25 | } 26 | public PluginClassLoader(File jarfileDir){ 27 | this(jarfileDir, null); 28 | } 29 | public PluginClassLoader(File jarfileDir, ClassLoader parent) { 30 | this.classLoader = createClassLoader(jarfileDir, parent); 31 | } 32 | 33 | public void addToClassLoader(final String baseDir, final FileFilter filter, 34 | boolean quiet) { 35 | 36 | File base = new File(baseDir); 37 | 38 | if (base != null && base.exists() && base.isDirectory()) { 39 | File[] files = base.listFiles(filter); 40 | if (files == null || files.length == 0) { 41 | if (!quiet) { 42 | logger.error("No files added to classloader from lib: " 43 | + baseDir + " (resolved as: " 44 | + base.getAbsolutePath() + ")."); 45 | } 46 | } else { 47 | this.classLoader = replaceClassLoader(classLoader, base, filter); 48 | } 49 | } else { 50 | if (!quiet) { 51 | logger.error("Can't find (or read) directory to add to classloader: " 52 | + baseDir 53 | + " (resolved as: " 54 | + base.getAbsolutePath() 55 | + ")."); 56 | } 57 | } 58 | } 59 | 60 | private URLClassLoader replaceClassLoader(final URLClassLoader oldLoader, 61 | final File base, final FileFilter filter) { 62 | 63 | if (null != base && base.canRead() && base.isDirectory()) { 64 | File[] files = base.listFiles(filter); 65 | 66 | if (null == files || 0 == files.length){ 67 | logger.error("replaceClassLoader base dir:{} is empty", base.getAbsolutePath()); 68 | return oldLoader; 69 | } 70 | 71 | logger.error("replaceClassLoader base dir: {} ,size: {}", base.getAbsolutePath(), files.length); 72 | 73 | URL[] oldElements = oldLoader.getURLs(); 74 | URL[] elements = new URL[oldElements.length + files.length]; 75 | System.arraycopy(oldElements, 0, elements, 0, oldElements.length); 76 | 77 | for (int j = 0; j < files.length; j++) { 78 | try { 79 | URL element = files[j].toURI().normalize().toURL(); 80 | elements[oldElements.length + j] = element; 81 | 82 | logger.info("Adding '{}' to classloader", element.toString()); 83 | 84 | } catch (MalformedURLException e) { 85 | logger.error("load jar file error", e); 86 | } 87 | } 88 | ClassLoader oldParent = oldLoader.getParent(); 89 | IoUtils.closeQuietly(oldLoader); // best effort 90 | return URLClassLoader.newInstance(elements, oldParent); 91 | } 92 | 93 | return oldLoader; 94 | } 95 | 96 | private URLClassLoader createClassLoader(final File libDir, 97 | ClassLoader parent) { 98 | if (null == parent) { 99 | parent = Thread.currentThread().getContextClassLoader(); 100 | } 101 | return replaceClassLoader( 102 | URLClassLoader.newInstance(new URL[0], parent), libDir, null); 103 | } 104 | 105 | public Class loadClass(String className) throws ClassNotFoundException{ 106 | 107 | return classLoader.loadClass(className); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/DefaultPluginFactory.java: -------------------------------------------------------------------------------- 1 | package cherry; 2 | 3 | import cherry.config.AppConfig; 4 | import cherry.config.Library; 5 | import cherry.config.PluginDefinition; 6 | import cherry.exception.PluginException; 7 | import cherry.util.StringUtils; 8 | import cherry.xml.ConfigParser; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | 12 | import java.io.File; 13 | import java.util.List; 14 | 15 | /** 16 | * ${DESCRIPTION} 17 | * 18 | * @author Ricky Fung 19 | */ 20 | public class DefaultPluginFactory extends AbstractPluginFactory { 21 | private final Logger logger = LoggerFactory.getLogger(this.getClass()); 22 | 23 | private PluginClassLoader classLoader; 24 | private AppConfig config; 25 | 26 | private PluginContext context = new DefaultPluginContext(); 27 | 28 | private volatile boolean closed = false; 29 | 30 | public DefaultPluginFactory(String path){ 31 | if(StringUtils.isEmpty(path)){ 32 | throw new IllegalArgumentException("path can not be empty!"); 33 | } 34 | if(path.startsWith("classpath:")){ 35 | path = path.substring(10); 36 | } 37 | this.config = new ConfigParser().parse(path); 38 | init(this.config); 39 | } 40 | 41 | public DefaultPluginFactory(File file){ 42 | this.config = new ConfigParser().parse(file); 43 | init(this.config); 44 | } 45 | 46 | @Override 47 | protected AppConfig getAppConfig() { 48 | return this.config; 49 | } 50 | 51 | @Override 52 | protected Class loadPluginClass(String clazz) throws ClassNotFoundException { 53 | return classLoader.loadClass(clazz); 54 | } 55 | 56 | @Override 57 | protected PluginContext getPluginContext() { 58 | return this.context; 59 | } 60 | 61 | @Override 62 | public void close() { 63 | 64 | if(!closed){ 65 | closed = true; 66 | for(Object o : pluginInstanceMap.values()) { 67 | Plugin plugin = (Plugin) o; 68 | try { 69 | plugin.destroy(); 70 | } catch (Exception e){ 71 | 72 | } 73 | } 74 | context = null; 75 | pluginInstanceMap.clear(); 76 | pluginNameMap.clear(); 77 | } 78 | } 79 | 80 | private void init(AppConfig config) { 81 | //加载libs 82 | List libs = config.getLibs(); 83 | if(libs!=null && libs.size()>0){ 84 | for (Library lib : libs){ 85 | addExternalJar(lib.getDir()); 86 | } 87 | } 88 | 89 | List pds = config.getPlugins(); 90 | if(pds!=null && pds.size()>0){ 91 | for (PluginDefinition pd : pds) { 92 | if(pluginNameMap.containsKey(pd.getName())){ 93 | throw new PluginException("Plugin name:"+pd.getName()+" already exists"); 94 | } 95 | pluginNameMap.put(pd.getName(), pd); 96 | } 97 | } 98 | } 99 | 100 | private void addExternalJar(String basePath){ 101 | if (StringUtils.isEmpty(basePath)) { 102 | throw new IllegalArgumentException("basePath can not be empty!"); 103 | } 104 | File dir = new File(basePath); 105 | if(!dir.exists()){ 106 | throw new IllegalArgumentException("basePath not exists:"+basePath); 107 | } 108 | if(!dir.isDirectory()){ 109 | throw new IllegalArgumentException("basePath must be a directory:"+basePath); 110 | } 111 | if(classLoader==null){ 112 | classLoader = new PluginClassLoader(basePath); 113 | } else { 114 | classLoader.addToClassLoader(basePath, null, false); 115 | } 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/AbstractPluginFactory.java: -------------------------------------------------------------------------------- 1 | package cherry; 2 | 3 | import cherry.config.*; 4 | import cherry.exception.PluginException; 5 | import java.util.ArrayList; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.concurrent.ConcurrentHashMap; 10 | 11 | /** 12 | * ${DESCRIPTION} 13 | * 14 | * @author Ricky Fung 15 | */ 16 | public abstract class AbstractPluginFactory implements PluginFactory { 17 | 18 | protected final Map pluginNameMap = new HashMap<>(); //key为plugin-name 19 | 20 | protected final ConcurrentHashMap pluginInstanceMap = new ConcurrentHashMap<>(); 21 | 22 | @Override 23 | public Plugin getPlugin(String name) throws PluginException { 24 | 25 | Plugin plugin = pluginInstanceMap.get(name); 26 | if(plugin==null){ 27 | PluginDefinition pd = getPluginDefinition(name); 28 | if(pd==null){ 29 | throw new PluginException("not found plugin:"+name+" definition"); 30 | } 31 | plugin = getPlugin(name, pd); 32 | } 33 | return plugin; 34 | } 35 | 36 | @Override 37 | public T getPlugin(Class type) throws PluginException { 38 | String name = type.getName(); 39 | Plugin plugin = pluginInstanceMap.get(name); 40 | if(plugin==null){ 41 | PluginDefinition pd = findCandidatePluginDefinition(type); 42 | if(pd==null){ 43 | throw new PluginException("not found plugin:"+type.getName()+" definition"); 44 | } 45 | plugin = getPlugin(name, pd); 46 | } 47 | return (T) plugin; 48 | } 49 | 50 | @Override 51 | public PluginDefinition getPluginDefinition(String name) { 52 | return pluginNameMap.get(name); 53 | } 54 | 55 | @Override 56 | public List getPluginNames() { 57 | return new ArrayList<>(pluginNameMap.keySet()); 58 | } 59 | 60 | @Override 61 | public boolean hasPlugin(String name) { 62 | return getPluginDefinition(name)!=null; 63 | } 64 | 65 | private Plugin getPlugin(String name, PluginDefinition pd) { 66 | Plugin plugin = pluginInstanceMap.get(name); 67 | if(plugin==null){ 68 | synchronized (this){ 69 | plugin = createPluginInstance(pd); 70 | invokePluginInitMethod(plugin, new DefaultPluginConfig(pd, getPluginContext())); 71 | Plugin old = pluginInstanceMap.putIfAbsent(name, plugin); 72 | if(old!=null){ 73 | plugin = old; 74 | } 75 | } 76 | } 77 | return plugin; 78 | } 79 | 80 | private PluginDefinition findCandidatePluginDefinition(Class type) { 81 | 82 | List pds = getAppConfig().getPlugins(); 83 | if(pds!=null && pds.size()>0) { 84 | for (PluginDefinition pd : pds) { 85 | try { 86 | Class clazz = loadPluginClass(pd.getClazz()); 87 | if(type.isAssignableFrom(clazz)){ 88 | return pd; 89 | } 90 | } catch (ClassNotFoundException e) { 91 | throw new PluginException("not found plugin class:"+pd.getClazz(), e); 92 | } 93 | } 94 | } 95 | return null; 96 | } 97 | 98 | private Plugin createPluginInstance(PluginDefinition pd) throws PluginException { 99 | try { 100 | Class clazz = loadPluginClass(pd.getClazz()); 101 | return (Plugin) clazz.newInstance(); 102 | } catch (ClassNotFoundException e) { 103 | throw new PluginException("not found plugin class:"+pd.getClazz(), e); 104 | } catch (InstantiationException e) { 105 | throw new PluginException("construct plugin instance error", e); 106 | } catch (IllegalAccessException e) { 107 | throw new PluginException("construct plugin instance error", e); 108 | } 109 | } 110 | 111 | private void invokePluginInitMethod(Plugin plugin, PluginConfig config) throws PluginException { 112 | try { 113 | //执行初始化方法 114 | plugin.init(config); 115 | } catch (Exception e) { 116 | throw new PluginException("invoke plugin init error", e); 117 | } 118 | } 119 | 120 | protected abstract AppConfig getAppConfig(); 121 | 122 | protected abstract Class loadPluginClass(String clazz) throws ClassNotFoundException; 123 | 124 | protected abstract PluginContext getPluginContext(); 125 | } 126 | -------------------------------------------------------------------------------- /cherry-core/src/main/java/cherry/xml/ConfigParser.java: -------------------------------------------------------------------------------- 1 | package cherry.xml; 2 | 3 | import cherry.config.*; 4 | import cherry.util.IoUtils; 5 | import org.dom4j.Document; 6 | import org.dom4j.DocumentException; 7 | import org.dom4j.Element; 8 | import org.dom4j.Node; 9 | import org.dom4j.io.SAXReader; 10 | 11 | import java.io.File; 12 | import java.io.FileInputStream; 13 | import java.io.FileNotFoundException; 14 | import java.io.InputStream; 15 | import java.util.*; 16 | 17 | /** 18 | * ${DESCRIPTION} 19 | * 20 | * @author Ricky Fung 21 | */ 22 | public class ConfigParser { 23 | 24 | private static final String PLACEHOLDER_PREFIX = "${"; 25 | private static final String PLACEHOLDER_SUFFIX = "}"; 26 | 27 | 28 | public AppConfig parse(File file) { 29 | InputStream in = null; 30 | try { 31 | in = new FileInputStream(file); 32 | return parse(in); 33 | } catch (FileNotFoundException e) { 34 | throw new RuntimeException("", e); 35 | } finally { 36 | IoUtils.closeQuietly(in); 37 | } 38 | } 39 | 40 | public AppConfig parse(String path) { 41 | InputStream in = null; 42 | try{ 43 | in = ConfigParser.class.getClassLoader().getResourceAsStream(path); 44 | return parse(in); 45 | } finally { 46 | IoUtils.closeQuietly(in); 47 | } 48 | } 49 | 50 | public AppConfig parse(InputStream in) { 51 | AppConfig config = null; 52 | try { 53 | config = parseConfig(getDocument(in)); 54 | } catch (Exception e) { 55 | throw new RuntimeException("解析xml出错", e); 56 | } 57 | return config; 58 | } 59 | 60 | private AppConfig parseConfig(Document document) { 61 | 62 | AppConfig config = new AppConfig(); 63 | 64 | Node node = document.selectSingleNode( "//configuration/context-name" ); 65 | config.setContextName(node.getText()); 66 | 67 | //全局变量 68 | Map props = new HashMap<>(); 69 | List list = document.selectNodes( "//configuration/property" ); 70 | if(list!=null && list.size()>0){ 71 | List placeholders = new ArrayList<>(list.size()); 72 | for (Iterator iter = list.iterator(); iter.hasNext(); ) { 73 | Element e = (Element) iter.next(); 74 | 75 | PropertiesPlaceholder pp = new PropertiesPlaceholder(); 76 | pp.setName(e.attributeValue("name")); 77 | pp.setValue(e.attributeValue("value")); 78 | 79 | placeholders.add(pp); 80 | props.put(pp.getName(), pp.getValue()); 81 | } 82 | config.setPlaceholders(placeholders); 83 | } 84 | 85 | //lib 86 | list = document.selectNodes( "//configuration/lib" ); 87 | if(list!=null && list.size()>0){ 88 | List libs = new ArrayList<>(list.size()); 89 | for (Iterator iter = list.iterator(); iter.hasNext(); ) { 90 | Element e = (Element) iter.next(); 91 | 92 | Library lib = new Library(); 93 | lib.setDir(e.attributeValue("dir")); 94 | lib.setRegex(e.attributeValue("regex")); 95 | 96 | libs.add(lib); 97 | } 98 | config.setLibs(libs); 99 | } 100 | 101 | //context-param 102 | list = document.selectNodes( "//configuration/context-param" ); 103 | if(list!=null && list.size()>0){ 104 | List contextParams = new ArrayList<>(list.size()); 105 | for (Iterator iter = list.iterator(); iter.hasNext(); ) { 106 | Element e = (Element) iter.next(); 107 | 108 | Param param = parseInitParam(e, props); 109 | 110 | contextParams.add(param); 111 | } 112 | config.setContextParams(contextParams); 113 | } 114 | 115 | //plugin 116 | list = document.selectNodes( "//configuration/plugin" ); 117 | if(list!=null && list.size()>0){ 118 | List plugins = new ArrayList<>(list.size()); 119 | for (Iterator iter = list.iterator(); iter.hasNext(); ) { 120 | Element e = (Element) iter.next(); 121 | 122 | PluginDefinition pd = new PluginDefinition(); 123 | pd.setName(e.elementText("plugin-name")); 124 | pd.setClazz(e.elementText("plugin-class")); 125 | 126 | List initParams = new ArrayList<>(4); 127 | Iterator it = e.elementIterator("init-param"); 128 | while (it!=null && it.hasNext()){ 129 | 130 | Element foo = (Element) it.next(); 131 | Param param = parseInitParam(foo, props); 132 | 133 | initParams.add(param); 134 | } 135 | pd.setParams(initParams); 136 | plugins.add(pd); 137 | } 138 | config.setPlugins(plugins); 139 | } 140 | 141 | //listener 142 | list = document.selectNodes( "//configuration/listener" ); 143 | if(list!=null && list.size()>0){ 144 | List listeners = new ArrayList<>(list.size()); 145 | for (Iterator iter = list.iterator(); iter.hasNext(); ) { 146 | Element e = (Element) iter.next(); 147 | 148 | ListenerDefinition ld = new ListenerDefinition(); 149 | ld.setClazz(e.elementText("listener-class")); 150 | 151 | listeners.add(ld); 152 | } 153 | config.setListeners(listeners); 154 | } 155 | 156 | return config; 157 | } 158 | 159 | private Param parseInitParam(Element foo, Map props){ 160 | Param param = new Param(); 161 | param.setName(foo.elementText("param-name")); 162 | 163 | String value = foo.elementText("param-value"); 164 | if(value!=null && value.startsWith(PLACEHOLDER_PREFIX) && value.endsWith(PLACEHOLDER_SUFFIX)){ 165 | String key = value.substring(2, value.length()-1); 166 | if(!props.containsKey(key)){ 167 | throw new IllegalArgumentException("unknown param:"+param.getName()+" value:"+value); 168 | } 169 | value = props.get(key); 170 | } 171 | param.setValue(value); 172 | return param; 173 | } 174 | 175 | private Document getDocument(InputStream in) throws DocumentException { 176 | SAXReader reader = new SAXReader(); 177 | Document document = reader.read(in); 178 | return document; 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------