From 999fc958ad0942e79050bb1d255d132e6675824a Mon Sep 17 00:00:00 2001 From: Shaun Chyxion Date: Tue, 30 May 2017 12:19:29 +0800 Subject: [PATCH] tab to spaces, remove Tigon Sql session factory bean thread --- .../tigon/codegen/CodeGenCustomizer.java | 12 +- .../codegen/controller/CodeGenController.java | 124 +- .../tigon/codegen/model/CodeGenArgs.java | 2 +- .../codegen/service/CodeGenBaseTool.java | 1004 ++++++++--------- .../tigon/codegen/service/CodeGenService.java | 48 +- .../tigon/codegen/service/CodeGenerator.java | 86 +- .../support/CodeGenServiceSupport.java | 432 +++---- .../service/support/ControllerCodeGen.java | 38 +- .../support/ControllerTestCodeGen.java | 18 +- .../service/support/MapperCodeGen.java | 32 +- .../service/support/MapperTestCodeGen.java | 18 +- .../service/support/MapperXmlCodeGen.java | 32 +- .../codegen/service/support/ModelCodeGen.java | 32 +- .../service/support/ServiceCodeGen.java | 58 +- .../codegen/service/support/TableCodeGen.java | 92 +- .../codegen/service/support/ViewCodeGen.java | 42 +- .../chyxion/tigon/codegen/utils/DbTool.java | 478 ++++---- .../tigon/codegen/test/package-info.java | 2 +- .../mybatis/mappers/table-test-mapper.xml | 88 +- .../test/resources/spring/controller-test.xml | 10 +- tigon-extjs/pom.xml | 10 +- tigon-freemarker-support/pom.xml | 82 +- .../freemarker/FreeMarkerViewResolverExt.java | 16 +- .../spring/spring-freemarker-support.xml | 2 +- .../test/resources/spring/controller-test.xml | 8 +- tigon-jsp-support/pom.xml | 74 +- .../jsp/InternalResourceViewResolverExt.java | 48 +- .../resources/spring/spring-jsp-support.xml | 4 +- tigon-model/pom.xml | 34 +- .../tigon/exception/BaseException.java | 46 +- .../chyxion/tigon/exception/ErrorCoded.java | 20 +- .../exception/InvalidParamException.java | 10 +- .../exception/InvalidStateException.java | 10 +- .../java/me/chyxion/tigon/form/BaseForm.java | 138 +-- .../me/chyxion/tigon/form/BaseFormApi.java | 56 +- .../tigon/form/BaseFormForUpdateApi.java | 20 +- .../main/java/me/chyxion/tigon/form/FC0.java | 4 +- .../main/java/me/chyxion/tigon/form/FC1.java | 10 +- .../main/java/me/chyxion/tigon/form/FC2.java | 6 +- .../main/java/me/chyxion/tigon/form/FU0.java | 10 +- .../main/java/me/chyxion/tigon/form/FU1.java | 12 +- .../main/java/me/chyxion/tigon/form/FU2.java | 8 +- .../me/chyxion/tigon/model/ListResult.java | 2 +- .../me/chyxion/tigon/model/ListResultApi.java | 2 +- .../main/java/me/chyxion/tigon/model/M0.java | 46 +- .../main/java/me/chyxion/tigon/model/M1.java | 44 +- .../main/java/me/chyxion/tigon/model/M2.java | 10 +- .../main/java/me/chyxion/tigon/model/M3.java | 14 +- .../me/chyxion/tigon/model/ViewModel.java | 154 +-- .../me/chyxion/tigon/model/ViewModelable.java | 14 +- .../java/me/chyxion/tigon/mybatis/Search.java | 608 +++++----- .../java/me/chyxion/tigon/util/WordUtils.java | 118 +- .../me/chyxion/tigon/test/TestDriver.java | 62 +- tigon-model/src/test/resources/log4j2.xml | 42 +- tigon-mybatis-redis-cache/pom.xml | 26 +- .../tigon/mybatis/cache/CacheTool.java | 24 +- .../tigon/mybatis/cache/RedisCache.java | 196 ++-- .../tigon/mybatis/cache/RedisCacheConfig.java | 50 +- .../cache/support/CacheToolSupport.java | 66 +- .../src/test/resources/log4j2.xml | 42 +- tigon-mybatis/pom.xml | 52 +- .../me/chyxion/tigon/mybatis/BaseMapper.java | 8 +- .../mybatis/TigonSqlSessionFactoryBean.java | 351 +++--- .../src/main/resources/__tigon_mybatis__.xml | 38 +- .../tigon/mybatis/test/AppMapperTest.java | 70 +- .../tigon/mybatis/test/model/Activity.java | 6 +- .../chyxion/tigon/mybatis/test/model/App.java | 6 +- tigon-mybatis/src/test/resources/log4j2.xml | 42 +- .../test/resources/mybatis/mybatis-config.xml | 2 +- .../test/resources/spring/spring-mybatis.xml | 24 +- .../src/test/resources/spring/spring-test.xml | 8 +- tigon-props-config/pom.xml | 80 +- .../tigon/propsconfig/PropsConfig.java | 196 ++-- .../servlet-spring-summer-props-config.xml | 2 +- .../spring/spring-summer-props-config.xml | 2 +- .../src/test/resources/log4j.xml | 38 +- .../src/test/resources/spring/dao.xml | 26 +- tigon-redis/pom.xml | 36 +- .../chyxion/tigon/redis/pub/PubProducer.java | 24 +- .../redis/pub/support/PubProducerSupport.java | 54 +- .../com/flaginfo/echat/redis/TestDriver.java | 8 +- .../flaginfo/echat/redis/test/TestPub.java | 16 +- .../flaginfo/echat/redis/test/TestSub.java | 16 +- tigon-sequence/pom.xml | 60 +- .../me/chyxion/tigon/sequence/IdSequence.java | 10 +- .../sequence/support/IdSequenceSupport.java | 12 +- .../spring/spring-summer-sequence.xml | 4 +- .../me/chyxion/tigon/sequence/TestDriver.java | 16 +- tigon-sequence/src/test/resources/log4j2.xml | 42 +- tigon-service-api/pom.xml | 24 +- .../tigon/service/BaseCrudByFormService.java | 32 +- .../tigon/service/BaseCrudService.java | 64 +- .../tigon/service/BaseDeleteService.java | 22 +- .../tigon/service/BaseQueryService.java | 174 +-- .../me/chyxion/tigon/service/BaseService.java | 24 +- tigon-service-support/pom.xml | 6 +- .../support/BaseCrudByFormServiceSupport.java | 82 +- .../support/BaseCrudServiceSupport.java | 114 +- .../support/BaseQueryServiceSupport.java | 200 ++-- .../service/support/BaseServiceSupport.java | 130 +-- .../test/resources/spring/spring-mybatis.xml | 26 +- .../src/test/resources/spring/spring-test.xml | 10 +- tigon-shiro-core/pom.xml | 24 +- .../me/chyxion/tigon/shiro/AuthCallback.java | 10 +- .../me/chyxion/tigon/shiro/AuthConfig.java | 16 +- .../tigon/shiro/AuthConfigFactory.java | 154 +-- .../tigon/shiro/AuthExceptionResolver.java | 104 +- .../me/chyxion/tigon/shiro/AuthRealm.java | 66 +- .../tigon/shiro/AuthorizingRealmSupport.java | 114 +- .../shiro/DefaultWebSecurityManagerExt.java | 70 +- .../shiro/DefaultWebSessionManagerExt.java | 76 +- .../tigon/shiro/SessionDAOSupport.java | 68 +- .../chyxion/tigon/shiro/SessionIdManager.java | 44 +- .../tigon/shiro/SessionListenerExt.java | 12 +- .../me/chyxion/tigon/shiro/UserFilterExt.java | 144 +-- .../chyxion/tigon/shiro/model/AuthInfo.java | 100 +- .../chyxion/tigon/shiro/model/Credential.java | 134 +-- .../shiro/model/SerializableByteSource.java | 20 +- .../tigon/shiro/service/AuthService.java | 78 +- .../service/support/AuthServiceSupport.java | 114 +- .../resources/spring/spring-summer-shiro.xml | 6 +- .../me/chyxion/tigon/shiro/TestDriver.java | 6 +- tigon-shiro-redis-cache/pom.xml | 40 +- .../tigon/shiro/cache/SessionCache.java | 38 +- .../support/UserIdKeyRedisSessionCache.java | 256 ++--- .../chyxion/tigon/shiro/model/AuthUser.java | 186 +-- .../spring-summer-shiro-redis-cache.xml | 2 +- .../me/chyxion/tigon/shiro/TestDriver.java | 6 +- tigon-shiro-spring-boot/pom.xml | 24 +- .../tigon/shiro/SiteControllerTest.java | 48 +- .../me/chyxion/tigon/shiro/TestDriver.java | 6 +- .../src/test/resources/log4j2.xml | 54 +- .../src/test/resources/spring/spring-test.xml | 6 +- tigon-shiro-war/pom.xml | 24 +- .../me/chyxion/tigon/shiro/package-info.java | 2 +- .../main/resources/META-INF/web-fragment.xml | 2 +- .../me/chyxion/tigon/shiro/TestDriver.java | 6 +- .../shiro/controller/SiteController.java | 132 +-- tigon-shiro-war/src/test/resources/log4j2.xml | 54 +- .../resources/spring/servlet-spring-test.xml | 8 +- tigon-webmvc-core/pom.xml | 58 +- .../tigon/webmvc/DefaultViewResolver.java | 20 +- .../me/chyxion/tigon/webmvc/JSONView.java | 2 +- .../chyxion/tigon/webmvc/JSONViewConfig.java | 2 +- .../tigon/webmvc/JSONViewDataModel.java | 286 ++--- .../webmvc/JSONViewDataModelAssembler.java | 14 +- .../chyxion/tigon/webmvc/ResourceModel.java | 206 ++-- .../tigon/webmvc/TigonControllerAdvice.java | 42 +- .../tigon/webmvc/TigonControllerAspect.java | 14 +- .../tigon/webmvc/TigonReturnValueHandler.java | 132 +-- .../converter/StringToDateTypeConverter.java | 30 +- .../StringToJSONArrayTypeConverter.java | 30 +- .../StringToJSONObjectTypeConverter.java | 30 +- .../exception/BaseExceptionResolver.java | 28 +- .../exception/BindingResultResolver.java | 64 +- .../ConstraintViolationExceptionResolver.java | 48 +- .../exception/DefaultExceptionResolver.java | 204 ++-- .../webmvc/exception/ExceptionMessage.java | 14 +- .../webmvc/exception/ExceptionResolver.java | 24 +- ...EmptyToNullAnnotationFormatterFactory.java | 62 +- .../formatter/EmptyToNullFormatter.java | 28 +- .../tigon/webmvc/util/ResponseTool.java | 110 +- .../spring/spring-summer-webmvc-core.xml | 2 +- .../src/test/resources/log4j2.xml | 54 +- tigon-webmvc-spring-boot/pom.xml | 92 +- .../tigon/webmvc/test/SiteControllerTest.java | 84 +- .../test/controller/SiteController.java | 170 +-- .../src/test/resources/log4j2.xml | 54 +- .../src/test/resources/spring/spring-test.xml | 6 +- tigon-webmvc-war/pom.xml | 50 +- .../webmvc/war/AppContextInitializer.java | 18 +- .../main/resources/META-INF/web-fragment.xml | 20 +- .../resources/spring/spring-summer-webmvc.xml | 2 +- .../tigon/webmvc/test/SiteControllerTest.java | 114 +- .../test/controller/SiteController.java | 132 +-- .../src/test/resources/log4j2.xml | 54 +- 176 files changed, 5743 insertions(+), 5764 deletions(-) diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/CodeGenCustomizer.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/CodeGenCustomizer.java index ed44306..193c77c 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/CodeGenCustomizer.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/CodeGenCustomizer.java @@ -11,10 +11,10 @@ import me.chyxion.tigon.codegen.model.CodeGenArgs; */ public interface CodeGenCustomizer { - /** - * customize your code gen result - * @param args - * @return - */ - void customize(CodeGenArgs args); + /** + * customize your code gen result + * @param args + * @return + */ + void customize(CodeGenArgs args); } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/controller/CodeGenController.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/controller/CodeGenController.java index b438a9c..28a6181 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/controller/CodeGenController.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/controller/CodeGenController.java @@ -31,74 +31,74 @@ import static org.springframework.web.bind.annotation.RequestMethod.DELETE; @Controller @RequestMapping("/codegen") public class CodeGenController { - @Autowired - private CodeGenService service; - @Autowired - private CodeGenBaseTool tool; + @Autowired + private CodeGenService service; + @Autowired + private CodeGenBaseTool tool; - @RequestMapping(method = GET) - public ModelAndView index() { + @RequestMapping(method = GET) + public ModelAndView index() { return new ModelAndView("webapp/views/codegen") - .addObject("pkg", tool.getPkg()); - } + .addObject("pkg", tool.getPkg()); + } - @RequestMapping(value = "/tables") - public List> tables() { - return service.tables(); - } + @RequestMapping(value = "/tables") + public List> tables() { + return service.tables(); + } - @RequestMapping(method = POST) - public boolean gen(@Valid GenForm form) { - service.process(form.getModule(), form.getModel(), - form.getJaColumns(), form.getTable(), form); - return true; - } + @RequestMapping(method = POST) + public boolean gen(@Valid GenForm form) { + service.process(form.getModule(), form.getModel(), + form.getJaColumns(), form.getTable(), form); + return true; + } - @RequestMapping("/list") - public List list() { - return service.list(); - } + @RequestMapping("/list") + public List list() { + return service.list(); + } - @RequestMapping(method = DELETE) - public boolean delete( - @RequestParam("items") - String items, - @RequestParam(value = "dropTable", defaultValue = "true") - boolean dropTable) { - service.delete(JSON.parseArray(items), dropTable); - return true; - } + @RequestMapping(method = DELETE) + public boolean delete( + @RequestParam("items") + String items, + @RequestParam(value = "dropTable", defaultValue = "true") + boolean dropTable) { + service.delete(JSON.parseArray(items), dropTable); + return true; + } - @Getter - @Setter - public static class GenForm { - @NotNull - private String columns; - @NotBlank - private String model; - @NotBlank - private String table; - private String module; - private String pkg; - private boolean genController; - private boolean genService; - private boolean genMapper; - private boolean genModel; - private boolean genTable; - private boolean genView; - private boolean createTable; + @Getter + @Setter + public static class GenForm { + @NotNull + private String columns; + @NotBlank + private String model; + @NotBlank + private String table; + private String module; + private String pkg; + private boolean genController; + private boolean genService; + private boolean genMapper; + private boolean genModel; + private boolean genTable; + private boolean genView; + private boolean createTable; - /** - * @return the columns - */ - public JSONArray getJaColumns() { - return JSON.parseArray(columns); - } - /** - * @return the module - */ - public String getModule() { - return StringUtils.isNotBlank(module) ? module : ""; - } - } + /** + * @return the columns + */ + public JSONArray getJaColumns() { + return JSON.parseArray(columns); + } + /** + * @return the module + */ + public String getModule() { + return StringUtils.isNotBlank(module) ? module : ""; + } + } } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/model/CodeGenArgs.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/model/CodeGenArgs.java index 892a19b..2734cb1 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/model/CodeGenArgs.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/model/CodeGenArgs.java @@ -14,7 +14,7 @@ import lombok.Setter; @Getter @Setter public class CodeGenArgs { - + public static final String TARGET_MODEL = "MODEL"; public static final String TARGET_MAPPER = "MAPPER"; public static final String TARGET_MAPPER_XML = "MAPPER_XML"; diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/CodeGenBaseTool.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/CodeGenBaseTool.java index 5988e82..fc56d91 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/CodeGenBaseTool.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/CodeGenBaseTool.java @@ -57,530 +57,530 @@ import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; * Dec 3, 2014 11:25:17 AM */ public class CodeGenBaseTool { - private static final Logger log = - LoggerFactory.getLogger(CodeGenBaseTool.class); + private static final Logger log = + LoggerFactory.getLogger(CodeGenBaseTool.class); - @Autowired - private FreeMarkerConfigurer fmCfg; - @Autowired(required = false) - private DataSource dataSource; - private JdbcTemplate jdbcTpl; - @Value("#{systemProperties['project.basedir']}") - private String projDir; - private String groupId; - private String pkg; - private Properties config = new Properties(); - private Set baseCols = new HashSet(); + @Autowired + private FreeMarkerConfigurer fmCfg; + @Autowired(required = false) + private DataSource dataSource; + private JdbcTemplate jdbcTpl; + @Value("#{systemProperties['project.basedir']}") + private String projDir; + private String groupId; + private String pkg; + private Properties config = new Properties(); + private Set baseCols = new HashSet(); - /** - * @param col - * @return true if col is base col - */ - public boolean isBaseCol(String col) { - return baseCols.contains(col); - } + /** + * @param col + * @return true if col is base col + */ + public boolean isBaseCol(String col) { + return baseCols.contains(col); + } - /** - * @param key - * @return - */ - public String getConfig(String key) { - return config.getProperty(key); - } + /** + * @param key + * @return + */ + public String getConfig(String key) { + return config.getProperty(key); + } - /** - * @param key - * @param defaultValue - * @return - */ - public String getConfig(String key, String defaultValue) { - return config.getProperty(key, defaultValue); - } + /** + * @param key + * @param defaultValue + * @return + */ + public String getConfig(String key, String defaultValue) { + return config.getProperty(key, defaultValue); + } - /** - * get config - * @param key - * @param defaultValue - * @return - */ - public boolean getConfig(String key, boolean defaultValue) { - return Boolean.valueOf(getConfig(key, String.valueOf(defaultValue))); - } + /** + * get config + * @param key + * @param defaultValue + * @return + */ + public boolean getConfig(String key, boolean defaultValue) { + return Boolean.valueOf(getConfig(key, String.valueOf(defaultValue))); + } - /** - * @param key - * @param defaultValue - * @return - */ - public int getConfig(String key, int defaultValue) { - return Integer.valueOf(getConfig(key, String.valueOf(defaultValue))); - } + /** + * @param key + * @param defaultValue + * @return + */ + public int getConfig(String key, int defaultValue) { + return Integer.valueOf(getConfig(key, String.valueOf(defaultValue))); + } - /** - * @param key - * @param defaultValue - * @return - */ - public long getConfig(String key, long defaultValue) { - return Long.valueOf(getConfig(key, String.valueOf(defaultValue))); - } + /** + * @param key + * @param defaultValue + * @return + */ + public long getConfig(String key, long defaultValue) { + return Long.valueOf(getConfig(key, String.valueOf(defaultValue))); + } - /** - * @param key - * @param defaultValue - * @return - */ - public double getConfig(String key, double defaultValue) { - return Double.valueOf(getConfig(key, String.valueOf(defaultValue))); - } + /** + * @param key + * @param defaultValue + * @return + */ + public double getConfig(String key, double defaultValue) { + return Double.valueOf(getConfig(key, String.valueOf(defaultValue))); + } - /** - * @param key - * @param defaultValue - * @return - */ - public float getConfig(String key, float defaultValue) { - return Float.valueOf(getConfig(key, String.valueOf(defaultValue))); - } + /** + * @param key + * @param defaultValue + * @return + */ + public float getConfig(String key, float defaultValue) { + return Float.valueOf(getConfig(key, String.valueOf(defaultValue))); + } - /** - * @return the projDir - */ - public String getProjDir() { - return projDir; - } + /** + * @return the projDir + */ + public String getProjDir() { + return projDir; + } - /** - * @return the groupId - */ - public String getGroupId() { - return groupId; - } + /** + * @return the groupId + */ + public String getGroupId() { + return groupId; + } - /** - * @return the groupId - */ - public String getPkg() { - return pkg; - } + /** + * @return the groupId + */ + public String getPkg() { + return pkg; + } - /** - * save record to file - * @param mapRec map record - */ - public void saveRecord(Map mapRec) { - mapRec.put(M1.DATE_CREATED, new Date()); - writeStore(addRec(mapRec)); - } + /** + * save record to file + * @param mapRec map record + */ + public void saveRecord(Map mapRec) { + mapRec.put(M1.DATE_CREATED, new Date()); + writeStore(addRec(mapRec)); + } - /** - * exec SQL file - * @param sqlFile - */ - public void execSQL(File sqlFile) { - if (jdbcTpl != null) { - DbTool.executeSqlScript(jdbcTpl, new FileSystemResource(sqlFile), false); - } - } - - /** - * exec SQL string - * @param sql - */ - public void execSQL(String sql) { - if (jdbcTpl != null) { - jdbcTpl.execute(sql); - } - } - - /** - * init config - */ - @PostConstruct - void init() { - // disable cache - log.info("Disable FreeMarker Cache In Dev Mode."); - fmCfg.getConfiguration().setTemplateUpdateDelayMilliseconds(0); - if (dataSource != null) { - jdbcTpl = new JdbcTemplate(dataSource, true); - } - - try { - log.info("Parse Group ID From [{}/pom.xml].", projDir); - Element root = DocumentBuilderFactory.newInstance() - .newDocumentBuilder() - .parse(new File(projDir, "pom.xml")) - .getDocumentElement(); - root.normalize(); - groupId = root.getElementsByTagName("groupId").item(0).getTextContent().trim(); - log.info("Group ID [{}] Found.", groupId); - } - catch (Exception e) { - throw new IllegalStateException( - "Parse [groupId] From Maven POM File [" + projDir + "/pom.xml] Error Caused", e); - } - - InputStream cfgIns = CodeGenBaseTool.class - .getResourceAsStream("/codegen/config.properties"); - if (cfgIns != null) { - try { - config.load(cfgIns); - log.info("Code Gen Config [{}] Found.", config); - } - catch (IOException e) { - throw new IllegalStateException( - "Load Code Gen Config Error Caused", e); - } - finally { - IOUtils.closeQuietly(cfgIns); - } - } - - baseCols.add("id"); - String baseColsProp = config.getProperty("base.cols"); - if (StringUtils.isNotBlank(baseColsProp)) { - log.info("Code Gen Base Cols [{}] Found.", baseColsProp); - baseCols.addAll(Arrays.asList( - org.springframework.util.StringUtils - .tokenizeToStringArray( - baseColsProp, CONFIG_LOCATION_DELIMITERS, true, true))); - } - log.info("Code Gen Base Cols [{}] Result.", baseCols); - pkg = config.getProperty("base.package", groupId); - log.info("Code Gen Package [{}].", pkg); - } - - /** - * list all model generated - * @return - */ - @SuppressWarnings("unchecked") - public List> listAll() { - return (List>) getStore().get("items"); - } - - /** - * get store data - * @return - */ - private Map getStore() { - File file = getStoreFile(); - Map mapData = null; - if (file.exists()) { - FileInputStream fin = null; - try { - fin = new FileInputStream(file); - mapData = JSON.parseObject(IOUtils.toString(fin, CharEncoding.UTF_8)); - } - catch (IOException e) { - log.info("Parse JSON File [{}] ERROR Caused.", file.getName()); - try { - String backupFileName = - "codegen/data_broken_" + - DateFormatUtils.format(new Date(), "yyyy_MM_dd_HH_mm_ss") + - ".json"; - log.info("Backup Data File To [{}].", backupFileName); - if (fin != null) { - // backup data file - IOUtils.copy(fin, - new FileWriter(new File(projDir, backupFileName)), - CharEncoding.UTF_8); - } - } - catch (IOException e1) { - log.info("Backup JSON File [{}] ERROR Caused.", file.getName()); - } - } - finally { - IOUtils.closeQuietly(fin); - } - } - if (mapData == null) { - mapData = new HashMap(); - mapData.put("items", new LinkedList()); - } - return mapData; - } - - private void writeStore(Map storeData) { - File file = getStoreFile(); - try { - storeData.put("date_updated", new Date()); - FileUtils.write(file, JSON.toJSONStringWithDateFormat(storeData, - "yyyy-MM-dd HH:mm:ss", - SerializerFeature.PrettyFormat), - CharEncoding.UTF_8); - } - catch (IOException e) { - throw new RuntimeException("Write Data To File [" + file.getAbsolutePath() + "] ERROR Caused.", e); - } - } - - private File getStoreFile() { - return new File(projDir, ".codegen/data.json"); - } - - @SuppressWarnings("unchecked") - private Map addRec(Map mapRec) { - Map mapData = getStore(); - Map rec = - findRec(mapData, (String) mapRec.get("module"), - (String) mapRec.get("model")); - if (rec != null) { - rec.putAll(mapRec); - } - else { - ((List>) mapData.get("items")).add(mapRec); - } - return mapData; - } - - @SuppressWarnings("unchecked") - private Map findRec(Map store, String module, String model) { - for (Map item : (List>) store.get("items")) { - if (eqauls(item, module, model)) { - return item; - } - } - return null; - } - - /** - * delete rec - * @param module - * @param model - */ - @SuppressWarnings("unchecked") - public void deleteRec(String module, String model, boolean dropTable) { - Map mapData = getStore(); - Iterator> it = - ((List>) mapData.get("items")).listIterator(); - while (it.hasNext()) { - Map item = it.next(); - if (eqauls(item, module, model)) { - List files = (List) item.get("files"); - for (String filePath : files) { - File file = new File(projDir, filePath); - File fileParent = file.getParentFile(); - FileUtils.deleteQuietly(file); - deleteEmptyDir(fileParent); - } - if (dropTable) { - // drop table - try { - execSQL("drop table " + item.get("table")); - } - catch (Exception e) { - log.info("Drop Table Error Caused.", e); - } - } - it.remove(); - break; - } - } - writeStore(mapData); - } - - /** - * render FreeMarker Template - * @param ftl - * @param model - * @return - */ - public String renderFtl(String ftl, Map model) { - try { - return FreeMarkerTemplateUtils.processTemplateIntoString( - new Template(ftl, new InputStreamReader( - CodeGenBaseTool.class.getResourceAsStream(ftl), - CharEncoding.UTF_8), fmCfg.getConfiguration()), model); - } - catch (Exception e) { - throw new RuntimeException("Code Generate Render ERROR, [" + e.getMessage() + "].", e); + /** + * exec SQL file + * @param sqlFile + */ + public void execSQL(File sqlFile) { + if (jdbcTpl != null) { + DbTool.executeSqlScript(jdbcTpl, new FileSystemResource(sqlFile), false); } - } + } - public List> tables() { - if (jdbcTpl != null) { - return jdbcTpl.execute(new ConnectionCallback>>() { - @Override - public List> doInConnection(Connection conn) - throws SQLException, DataAccessException { - List> tables = new LinkedList>(); - ResultSet rs = null; - try { - DatabaseMetaData md = conn.getMetaData(); - rs = md.getTables(null, null, "%", new String[] {"TABLE"}); - String tablePrefix = - config.getProperty("table.prefix", "") - .toLowerCase(); - while (rs.next()) { - Map mapTable = new HashMap(); - String table = rs.getString(3).toLowerCase(); - mapTable.put("id", table); - mapTable.put("text", table); - mapTable.put("table", table); - String[] tableNameParts = null; - if (StringUtils.isNotBlank(tablePrefix) && - table.startsWith(tablePrefix + "_")) { - log.info("Table Prefix [{}] Found, Trim.", tablePrefix); - tableNameParts = - table.substring(tablePrefix.length() + 1) - .split("_"); - } - else { - tableNameParts = table.split("_"); - } - String model = ""; - for (String tblNamePart : tableNameParts) { - model += StringUtils.capitalize(tblNamePart); - } - mapTable.put("model", model); - mapTable.put("leaf", true); - Set keys = keys(md, table); - mapTable.put("keys", keys); - Set indexes = indexes(md, table, false); - mapTable.put("indexes", indexes); - mapTable.put("cols", cols(md, table, keys, indexes)); - tables.add(mapTable); - } - } - finally { - JdbcUtils.closeResultSet(rs); - } - return tables; - } - }); - } - return new LinkedList>(); - } + /** + * exec SQL string + * @param sql + */ + public void execSQL(String sql) { + if (jdbcTpl != null) { + jdbcTpl.execute(sql); + } + } - // -- - // private methods - private List> cols(DatabaseMetaData md, - final String table, Set keys, Set indexes) { - List> cols = new LinkedList>(); - ResultSet rs = null; - try { - rs = md.getColumns(null, "%", table, "%"); - while (rs.next()) { - Map col = new HashMap(); - String colName = rs.getString("COLUMN_NAME"); - col.put("isKey", keys.contains(colName)); - col.put("isIndex", indexes.contains(colName)); - col.put("col", colName); - col.put("name", - StringUtils.uncapitalize( - WordUtils.convertToCamelCase(colName, "_"))); - int size = rs.getInt("COLUMN_SIZE"); - col.put("size", size); - String type = rs.getString("TYPE_NAME").toLowerCase(); - String javaType = "String"; - if (type.endsWith("char")) { - type = type + "(" + size + ")"; - } - else if (type.contains("date") || type.contains("time")) { - javaType = "Date"; - } - else if (type.equals("int")) { - javaType = "int"; - } - else if (type.equals("bigint")) { - javaType = "long"; - } - else if (type.contains("int")) { - javaType = "int"; - } - else if (type.equals("float")) { - javaType = "float"; - } - else if (type.contains("double")) { - javaType = "double"; - } - else if (type.contains("blob")) { - javaType = "byte[]"; - } + /** + * init config + */ + @PostConstruct + void init() { + // disable cache + log.info("Disable FreeMarker Cache In Dev Mode."); + fmCfg.getConfiguration().setTemplateUpdateDelayMilliseconds(0); + if (dataSource != null) { + jdbcTpl = new JdbcTemplate(dataSource, true); + } - col.put("sqlType", type); - col.put("javaType", javaType); - col.put("notNull", rs.getInt("NULLABLE") == 0); - cols.add(col); - } - } - catch (Exception e) { - throw new RuntimeException("Get Table Columns Error Caused.", e); - } - finally { - JdbcUtils.closeResultSet(rs); - } - return cols; - } + try { + log.info("Parse Group ID From [{}/pom.xml].", projDir); + Element root = DocumentBuilderFactory.newInstance() + .newDocumentBuilder() + .parse(new File(projDir, "pom.xml")) + .getDocumentElement(); + root.normalize(); + groupId = root.getElementsByTagName("groupId").item(0).getTextContent().trim(); + log.info("Group ID [{}] Found.", groupId); + } + catch (Exception e) { + throw new IllegalStateException( + "Parse [groupId] From Maven POM File [" + projDir + "/pom.xml] Error Caused", e); + } + + InputStream cfgIns = CodeGenBaseTool.class + .getResourceAsStream("/codegen/config.properties"); + if (cfgIns != null) { + try { + config.load(cfgIns); + log.info("Code Gen Config [{}] Found.", config); + } + catch (IOException e) { + throw new IllegalStateException( + "Load Code Gen Config Error Caused", e); + } + finally { + IOUtils.closeQuietly(cfgIns); + } + } - private Set keys(DatabaseMetaData md, String table) { - ResultSet rs = null; - Set keys = new TreeSet(); - try { - rs = md.getPrimaryKeys(null, null, table); - while (rs.next()) { - keys.add(rs.getString("COLUMN_NAME")); - } - } - catch (Exception e) { - throw new RuntimeException("Get Table Keys Error Caused.", e); - } - finally { - JdbcUtils.closeResultSet(rs); - } - // find unique indexes - if (keys.size() == 0) { - keys = indexes(md, table, true); - } - return keys; - } + baseCols.add("id"); + String baseColsProp = config.getProperty("base.cols"); + if (StringUtils.isNotBlank(baseColsProp)) { + log.info("Code Gen Base Cols [{}] Found.", baseColsProp); + baseCols.addAll(Arrays.asList( + org.springframework.util.StringUtils + .tokenizeToStringArray( + baseColsProp, CONFIG_LOCATION_DELIMITERS, true, true))); + } + log.info("Code Gen Base Cols [{}] Result.", baseCols); + pkg = config.getProperty("base.package", groupId); + log.info("Code Gen Package [{}].", pkg); + } - private Set indexes(DatabaseMetaData md, String table, boolean unique) { - ResultSet rs = null; - Set keys = new TreeSet(); - try { - rs = md.getIndexInfo(null, null, table, false, false); - while (rs.next()) { - if (unique && rs.getBoolean("NON_UNIQUE")) { - continue; - } - keys.add(rs.getString("COLUMN_NAME")); - } - } - catch (Exception e) { - throw new RuntimeException("Get Table Indexes Error Caused.", e); - } - finally { - JdbcUtils.closeResultSet(rs); - } - return keys; - } + /** + * list all model generated + * @return + */ + @SuppressWarnings("unchecked") + public List> listAll() { + return (List>) getStore().get("items"); + } - private void deleteEmptyDir(File file) { - if (file.exists() && file.isDirectory() && file.list().length == 0) { - File fileParent = file.getParentFile(); - FileUtils.deleteQuietly(file); - deleteEmptyDir(fileParent); - } - } + /** + * get store data + * @return + */ + private Map getStore() { + File file = getStoreFile(); + Map mapData = null; + if (file.exists()) { + FileInputStream fin = null; + try { + fin = new FileInputStream(file); + mapData = JSON.parseObject(IOUtils.toString(fin, CharEncoding.UTF_8)); + } + catch (IOException e) { + log.info("Parse JSON File [{}] ERROR Caused.", file.getName()); + try { + String backupFileName = + "codegen/data_broken_" + + DateFormatUtils.format(new Date(), "yyyy_MM_dd_HH_mm_ss") + + ".json"; + log.info("Backup Data File To [{}].", backupFileName); + if (fin != null) { + // backup data file + IOUtils.copy(fin, + new FileWriter(new File(projDir, backupFileName)), + CharEncoding.UTF_8); + } + } + catch (IOException e1) { + log.info("Backup JSON File [{}] ERROR Caused.", file.getName()); + } + } + finally { + IOUtils.closeQuietly(fin); + } + } + if (mapData == null) { + mapData = new HashMap(); + mapData.put("items", new LinkedList()); + } + return mapData; + } - private boolean eqauls(Map item, String module, String model) { - return item.get("module").equals(module) && item.get("model").equals(model); - } + private void writeStore(Map storeData) { + File file = getStoreFile(); + try { + storeData.put("date_updated", new Date()); + FileUtils.write(file, JSON.toJSONStringWithDateFormat(storeData, + "yyyy-MM-dd HH:mm:ss", + SerializerFeature.PrettyFormat), + CharEncoding.UTF_8); + } + catch (IOException e) { + throw new RuntimeException("Write Data To File [" + file.getAbsolutePath() + "] ERROR Caused.", e); + } + } - /** - * @return the baseCols - */ - public Set getBaseCols() { - return baseCols; - } + private File getStoreFile() { + return new File(projDir, ".codegen/data.json"); + } + + @SuppressWarnings("unchecked") + private Map addRec(Map mapRec) { + Map mapData = getStore(); + Map rec = + findRec(mapData, (String) mapRec.get("module"), + (String) mapRec.get("model")); + if (rec != null) { + rec.putAll(mapRec); + } + else { + ((List>) mapData.get("items")).add(mapRec); + } + return mapData; + } - /** - * @param baseCols the baseCols to set - */ - public void setBaseCols(Set baseCols) { - this.baseCols = baseCols; - } + @SuppressWarnings("unchecked") + private Map findRec(Map store, String module, String model) { + for (Map item : (List>) store.get("items")) { + if (eqauls(item, module, model)) { + return item; + } + } + return null; + } + + /** + * delete rec + * @param module + * @param model + */ + @SuppressWarnings("unchecked") + public void deleteRec(String module, String model, boolean dropTable) { + Map mapData = getStore(); + Iterator> it = + ((List>) mapData.get("items")).listIterator(); + while (it.hasNext()) { + Map item = it.next(); + if (eqauls(item, module, model)) { + List files = (List) item.get("files"); + for (String filePath : files) { + File file = new File(projDir, filePath); + File fileParent = file.getParentFile(); + FileUtils.deleteQuietly(file); + deleteEmptyDir(fileParent); + } + if (dropTable) { + // drop table + try { + execSQL("drop table " + item.get("table")); + } + catch (Exception e) { + log.info("Drop Table Error Caused.", e); + } + } + it.remove(); + break; + } + } + writeStore(mapData); + } + + /** + * render FreeMarker Template + * @param ftl + * @param model + * @return + */ + public String renderFtl(String ftl, Map model) { + try { + return FreeMarkerTemplateUtils.processTemplateIntoString( + new Template(ftl, new InputStreamReader( + CodeGenBaseTool.class.getResourceAsStream(ftl), + CharEncoding.UTF_8), fmCfg.getConfiguration()), model); + } + catch (Exception e) { + throw new RuntimeException("Code Generate Render ERROR, [" + e.getMessage() + "].", e); + } + } + + public List> tables() { + if (jdbcTpl != null) { + return jdbcTpl.execute(new ConnectionCallback>>() { + @Override + public List> doInConnection(Connection conn) + throws SQLException, DataAccessException { + List> tables = new LinkedList>(); + ResultSet rs = null; + try { + DatabaseMetaData md = conn.getMetaData(); + rs = md.getTables(null, null, "%", new String[] {"TABLE"}); + String tablePrefix = + config.getProperty("table.prefix", "") + .toLowerCase(); + while (rs.next()) { + Map mapTable = new HashMap(); + String table = rs.getString(3).toLowerCase(); + mapTable.put("id", table); + mapTable.put("text", table); + mapTable.put("table", table); + String[] tableNameParts = null; + if (StringUtils.isNotBlank(tablePrefix) && + table.startsWith(tablePrefix + "_")) { + log.info("Table Prefix [{}] Found, Trim.", tablePrefix); + tableNameParts = + table.substring(tablePrefix.length() + 1) + .split("_"); + } + else { + tableNameParts = table.split("_"); + } + String model = ""; + for (String tblNamePart : tableNameParts) { + model += StringUtils.capitalize(tblNamePart); + } + mapTable.put("model", model); + mapTable.put("leaf", true); + Set keys = keys(md, table); + mapTable.put("keys", keys); + Set indexes = indexes(md, table, false); + mapTable.put("indexes", indexes); + mapTable.put("cols", cols(md, table, keys, indexes)); + tables.add(mapTable); + } + } + finally { + JdbcUtils.closeResultSet(rs); + } + return tables; + } + }); + } + return new LinkedList>(); + } + + // -- + // private methods + private List> cols(DatabaseMetaData md, + final String table, Set keys, Set indexes) { + List> cols = new LinkedList>(); + ResultSet rs = null; + try { + rs = md.getColumns(null, "%", table, "%"); + while (rs.next()) { + Map col = new HashMap(); + String colName = rs.getString("COLUMN_NAME"); + col.put("isKey", keys.contains(colName)); + col.put("isIndex", indexes.contains(colName)); + col.put("col", colName); + col.put("name", + StringUtils.uncapitalize( + WordUtils.convertToCamelCase(colName, "_"))); + int size = rs.getInt("COLUMN_SIZE"); + col.put("size", size); + String type = rs.getString("TYPE_NAME").toLowerCase(); + String javaType = "String"; + if (type.endsWith("char")) { + type = type + "(" + size + ")"; + } + else if (type.contains("date") || type.contains("time")) { + javaType = "Date"; + } + else if (type.equals("int")) { + javaType = "int"; + } + else if (type.equals("bigint")) { + javaType = "long"; + } + else if (type.contains("int")) { + javaType = "int"; + } + else if (type.equals("float")) { + javaType = "float"; + } + else if (type.contains("double")) { + javaType = "double"; + } + else if (type.contains("blob")) { + javaType = "byte[]"; + } + + col.put("sqlType", type); + col.put("javaType", javaType); + col.put("notNull", rs.getInt("NULLABLE") == 0); + cols.add(col); + } + } + catch (Exception e) { + throw new RuntimeException("Get Table Columns Error Caused.", e); + } + finally { + JdbcUtils.closeResultSet(rs); + } + return cols; + } + + private Set keys(DatabaseMetaData md, String table) { + ResultSet rs = null; + Set keys = new TreeSet(); + try { + rs = md.getPrimaryKeys(null, null, table); + while (rs.next()) { + keys.add(rs.getString("COLUMN_NAME")); + } + } + catch (Exception e) { + throw new RuntimeException("Get Table Keys Error Caused.", e); + } + finally { + JdbcUtils.closeResultSet(rs); + } + // find unique indexes + if (keys.size() == 0) { + keys = indexes(md, table, true); + } + return keys; + } + + private Set indexes(DatabaseMetaData md, String table, boolean unique) { + ResultSet rs = null; + Set keys = new TreeSet(); + try { + rs = md.getIndexInfo(null, null, table, false, false); + while (rs.next()) { + if (unique && rs.getBoolean("NON_UNIQUE")) { + continue; + } + keys.add(rs.getString("COLUMN_NAME")); + } + } + catch (Exception e) { + throw new RuntimeException("Get Table Indexes Error Caused.", e); + } + finally { + JdbcUtils.closeResultSet(rs); + } + return keys; + } + + private void deleteEmptyDir(File file) { + if (file.exists() && file.isDirectory() && file.list().length == 0) { + File fileParent = file.getParentFile(); + FileUtils.deleteQuietly(file); + deleteEmptyDir(fileParent); + } + } + + private boolean eqauls(Map item, String module, String model) { + return item.get("module").equals(module) && item.get("model").equals(model); + } + + /** + * @return the baseCols + */ + public Set getBaseCols() { + return baseCols; + } + + /** + * @param baseCols the baseCols to set + */ + public void setBaseCols(Set baseCols) { + this.baseCols = baseCols; + } } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/CodeGenService.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/CodeGenService.java index 3a00be6..780cb86 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/CodeGenService.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/CodeGenService.java @@ -12,31 +12,31 @@ import me.chyxion.tigon.codegen.controller.CodeGenController.GenForm; * Oct 6, 2014 1:08:14 PM */ public interface CodeGenService { - /** - * process code generation - * @param module - * @param model - * @param cols - * @param table - * @param form - */ - void process(String module, String model, List cols, String table, GenForm form); + /** + * process code generation + * @param module + * @param model + * @param cols + * @param table + * @param form + */ + void process(String module, String model, List cols, String table, GenForm form); - /** - * list generated items - * @return items list - */ - List list(); + /** + * list generated items + * @return items list + */ + List list(); - /** - * list tables - * @return - */ - List> tables(); + /** + * list tables + * @return + */ + List> tables(); - /** - * delete items - * @param items - */ - void delete(List items, boolean dropTable); + /** + * delete items + * @param items + */ + void delete(List items, boolean dropTable); } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/CodeGenerator.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/CodeGenerator.java index e247302..ac685f3 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/CodeGenerator.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/CodeGenerator.java @@ -17,52 +17,52 @@ import org.springframework.beans.factory.annotation.Autowired; * Oct 6, 2014 1:10:55 PM */ public abstract class CodeGenerator { - @Autowired(required = false) - private List customizers; - @Autowired - protected CodeGenBaseTool baseTool; - protected String codeDir = "src/main/java/"; - protected String testDir = "src/test/java/"; - protected String resourcesDir = "src/main/resources/"; - protected String viewsDir = "src/main/webapp/assets/js/views/"; + @Autowired(required = false) + private List customizers; + @Autowired + protected CodeGenBaseTool baseTool; + protected String codeDir = "src/main/java/"; + protected String testDir = "src/test/java/"; + protected String resourcesDir = "src/main/resources/"; + protected String viewsDir = "src/main/webapp/assets/js/views/"; - /** - * @param dataModel - * @param module - * @param model - */ - public abstract String process(Map dataModel, String module, String model); + /** + * @param dataModel + * @param module + * @param model + */ + public abstract String process(Map dataModel, String module, String model); - /** - * @param dataModel - * @return - */ - public boolean accept(Map dataModel) { - return true; - } + /** + * @param dataModel + * @return + */ + public boolean accept(Map dataModel) { + return true; + } - /** - * render FreeMarker Tpl - * @param args code gen args - * @return gen result file path - */ - protected String render(CodeGenArgs args) { - try { - // customize - if (customizers != null && customizers.size() > 0) { - for (CodeGenCustomizer customizer : customizers) { - customizer.customize(args); - } - } - // write result - FileUtils.write(new File(baseTool.getProjDir(), args.getFile()), - baseTool.renderFtl(args.getFtl(), args.getModel()), - CharEncoding.UTF_8); - return args.getFile(); + /** + * render FreeMarker Tpl + * @param args code gen args + * @return gen result file path + */ + protected String render(CodeGenArgs args) { + try { + // customize + if (customizers != null && customizers.size() > 0) { + for (CodeGenCustomizer customizer : customizers) { + customizer.customize(args); + } + } + // write result + FileUtils.write(new File(baseTool.getProjDir(), args.getFile()), + baseTool.renderFtl(args.getFtl(), args.getModel()), + CharEncoding.UTF_8); + return args.getFile(); } - catch (Exception e) { - throw new IllegalStateException( - "Code Gen Render File Error Caused.", e); + catch (Exception e) { + throw new IllegalStateException( + "Code Gen Render File Error Caused.", e); } - } + } } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/CodeGenServiceSupport.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/CodeGenServiceSupport.java index 25beea2..66ffd47 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/CodeGenServiceSupport.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/CodeGenServiceSupport.java @@ -42,251 +42,251 @@ import org.springframework.beans.factory.annotation.Autowired; * Oct 6, 2014 1:10:02 PM */ public class CodeGenServiceSupport implements CodeGenService { - private static final Logger log = LoggerFactory.getLogger(CodeGenServiceSupport.class); - private static final Map TYPE_PACKAGES = new HashMap() { + private static final Logger log = LoggerFactory.getLogger(CodeGenServiceSupport.class); + private static final Map TYPE_PACKAGES = new HashMap() { private static final long serialVersionUID = 1L; { - put(Date.class.getSimpleName(), Date.class.getName()); + put(Date.class.getSimpleName(), Date.class.getName()); } - }; + }; - @Autowired - private CodeGenBaseTool baseTool; - @Autowired - private List codeGen; + @Autowired + private CodeGenBaseTool baseTool; + @Autowired + private List codeGen; - /** - * {@inheritDoc} - */ - @Override + /** + * {@inheritDoc} + */ + @Override @SuppressWarnings("unchecked") public void process(String module, String model, List columns, String table, GenForm form) { - String minusJoinedModelName = WordUtils.convertCamelCase(model, "-").toLowerCase(); - String mappingUrl = minusJoinedModelName; - String pkg = form.getPkg(); - if (StringUtils.isBlank(pkg)) { - pkg = baseTool.getPkg(); - } - if (StringUtils.isNotBlank(module)) { - mappingUrl = module + "/" + mappingUrl; - pkg += "." + module; - } - else { - module = ""; - } + String minusJoinedModelName = WordUtils.convertCamelCase(model, "-").toLowerCase(); + String mappingUrl = minusJoinedModelName; + String pkg = form.getPkg(); + if (StringUtils.isBlank(pkg)) { + pkg = baseTool.getPkg(); + } + if (StringUtils.isNotBlank(module)) { + mappingUrl = module + "/" + mappingUrl; + pkg += "." + module; + } + else { + module = ""; + } - model = StringUtils.capitalize(model); - Map fmDataModel = new HashMap(); - fmDataModel.put("genController", form.isGenController()); - fmDataModel.put("genService", form.isGenService()); - fmDataModel.put("genMapper", form.isGenMapper()); - fmDataModel.put("genModel", form.isGenModel()); - fmDataModel.put("genTable", form.isGenTable()); - fmDataModel.put("genView", form.isGenView()); - fmDataModel.put("createTable", form.isCreateTable()); + model = StringUtils.capitalize(model); + Map fmDataModel = new HashMap(); + fmDataModel.put("genController", form.isGenController()); + fmDataModel.put("genService", form.isGenService()); + fmDataModel.put("genMapper", form.isGenMapper()); + fmDataModel.put("genModel", form.isGenModel()); + fmDataModel.put("genTable", form.isGenTable()); + fmDataModel.put("genView", form.isGenView()); + fmDataModel.put("createTable", form.isCreateTable()); - fmDataModel.put("table", table.toLowerCase()); - fmDataModel.put("notNull", false); - fmDataModel.put("notBlank", false); - fmDataModel.put("cacheEnabled", baseTool.getConfig("cache.enabled", false)); - fmDataModel.put("useGeneratedKeys", false); + fmDataModel.put("table", table.toLowerCase()); + fmDataModel.put("notNull", false); + fmDataModel.put("notBlank", false); + fmDataModel.put("cacheEnabled", baseTool.getConfig("cache.enabled", false)); + fmDataModel.put("useGeneratedKeys", false); - // collect col names - String idType = null; - List colNames = new ArrayList(columns.size()); - for (Map col : (List>) columns) { - String colName = ((String) col.get("col")).toLowerCase(); - colNames.add(colName); - if (M0.ID.equals(colName)) { - String javaType = (String) col.get("javaType"); - if (ArrayUtils.contains( - new String[] {"int", "long", "boolean", "double", "byte"}, - javaType)) { - javaType = StringUtils.capitalize(javaType); - } - idType = javaType; - } - } - String baseModelName = null; - String baseModelFullName = null; - Collection baseCols = null; - if (colNames.containsAll(new M3().cols())) { - baseModelName = M3.class.getSimpleName() + - "<" + idType + ", " + idType + ">"; - baseModelFullName = M3.class.getName(); - baseCols = new M3().cols(); - } - else if (colNames.containsAll(new M2().cols())) { - baseModelName = M2.class.getSimpleName() + "<" + idType + ">"; - baseModelFullName = M2.class.getName(); - baseCols = new M2().cols(); - } - else if (colNames.containsAll(new M1().cols())) { - baseModelName = M1.class.getSimpleName() + "<" + idType + ">"; - baseModelFullName = M1.class.getName(); - baseCols = new M1().cols(); - } - else { - baseModelName = M0.class.getSimpleName(); - baseModelFullName = M0.class.getName(); - baseCols = new M0().cols(); - } - // custom config - String cfgBaseModelName = baseTool.getConfig("super.base.model.name"); - if (StringUtils.isNotBlank(cfgBaseModelName)) { - baseCols = baseTool.getBaseCols(); - } + // collect col names + String idType = null; + List colNames = new ArrayList(columns.size()); + for (Map col : (List>) columns) { + String colName = ((String) col.get("col")).toLowerCase(); + colNames.add(colName); + if (M0.ID.equals(colName)) { + String javaType = (String) col.get("javaType"); + if (ArrayUtils.contains( + new String[] {"int", "long", "boolean", "double", "byte"}, + javaType)) { + javaType = StringUtils.capitalize(javaType); + } + idType = javaType; + } + } + String baseModelName = null; + String baseModelFullName = null; + Collection baseCols = null; + if (colNames.containsAll(new M3().cols())) { + baseModelName = M3.class.getSimpleName() + + "<" + idType + ", " + idType + ">"; + baseModelFullName = M3.class.getName(); + baseCols = new M3().cols(); + } + else if (colNames.containsAll(new M2().cols())) { + baseModelName = M2.class.getSimpleName() + "<" + idType + ">"; + baseModelFullName = M2.class.getName(); + baseCols = new M2().cols(); + } + else if (colNames.containsAll(new M1().cols())) { + baseModelName = M1.class.getSimpleName() + "<" + idType + ">"; + baseModelFullName = M1.class.getName(); + baseCols = new M1().cols(); + } + else { + baseModelName = M0.class.getSimpleName(); + baseModelFullName = M0.class.getName(); + baseCols = new M0().cols(); + } + // custom config + String cfgBaseModelName = baseTool.getConfig("super.base.model.name"); + if (StringUtils.isNotBlank(cfgBaseModelName)) { + baseCols = baseTool.getBaseCols(); + } - String cfgBaseModelFullName = - baseTool.getConfig("super.base.model.full.name"); + String cfgBaseModelFullName = + baseTool.getConfig("super.base.model.full.name"); - fmDataModel.put("baseModelName", - baseTool.getConfig("super.base.model.name", baseModelName)); + fmDataModel.put("baseModelName", + baseTool.getConfig("super.base.model.name", baseModelName)); - fmDataModel.put("baseModelFullName", - "NONE".equalsIgnoreCase(cfgBaseModelFullName) ? null : - StringUtils.isNotBlank(cfgBaseModelFullName) ? - cfgBaseModelFullName : baseModelFullName); + fmDataModel.put("baseModelFullName", + "NONE".equalsIgnoreCase(cfgBaseModelFullName) ? null : + StringUtils.isNotBlank(cfgBaseModelFullName) ? + cfgBaseModelFullName : baseModelFullName); - fmDataModel.put("tableAnnotationClassName", Table.class.getName()); - fmDataModel.put("tableAnnotationName", Table.class.getSimpleName()); + fmDataModel.put("tableAnnotationClassName", Table.class.getName()); + fmDataModel.put("tableAnnotationName", Table.class.getSimpleName()); - Set imports = new HashSet(); + Set imports = new HashSet(); List> colsWithoutBase = - (List>) columns; - Iterator> colIt = - colsWithoutBase.iterator(); + (List>) columns; + Iterator> colIt = + colsWithoutBase.iterator(); - while (colIt.hasNext()) { - Map col = colIt.next(); - // col name - String colName = ((String) col.get("col")).toLowerCase(); - if (!baseCols.contains(colName)) { - // prop name - String propName = (String) col.get("name"); - // for setName - col.put("Name", StringUtils.capitalize(propName)); - if ((Boolean) col.get("notNull")) { - if ("String".equals(col.get("javaType"))) { - fmDataModel.put("notBlank", true); - } - else { - fmDataModel.put("notNull", true); - } - } - // imports - String p = TYPE_PACKAGES.get(col.get("javaType")); - if (StringUtils.isNotBlank(p)) { - imports.add(p); - } - } - // remove base col - else { - colIt.remove(); - } + while (colIt.hasNext()) { + Map col = colIt.next(); + // col name + String colName = ((String) col.get("col")).toLowerCase(); + if (!baseCols.contains(colName)) { + // prop name + String propName = (String) col.get("name"); + // for setName + col.put("Name", StringUtils.capitalize(propName)); + if ((Boolean) col.get("notNull")) { + if ("String".equals(col.get("javaType"))) { + fmDataModel.put("notBlank", true); + } + else { + fmDataModel.put("notNull", true); + } + } + // imports + String p = TYPE_PACKAGES.get(col.get("javaType")); + if (StringUtils.isNotBlank(p)) { + imports.add(p); + } + } + // remove base col + else { + colIt.remove(); + } } - fmDataModel.put("idType", idType); - fmDataModel.put("cols", colsWithoutBase); - fmDataModel.put("imports", imports); - fmDataModel.put("url", mappingUrl); - fmDataModel.put("pkg", pkg); - fmDataModel.put("pkgDir", pkg.replace('.', '/')); - fmDataModel.put("modelFullName", pkg + "." + model); - fmDataModel.put("module", module); - fmDataModel.put("ModelName", model); - fmDataModel.put("modelName", StringUtils.uncapitalize(model)); - fmDataModel.put("minusJoinedModelName", minusJoinedModelName); - /* - // super classes name - fmDataModel.put("baseControllerName", BaseController.class.getSimpleName()); - fmDataModel.put("baseControllerFullName", BaseController.class.getName()); - */ + fmDataModel.put("idType", idType); + fmDataModel.put("cols", colsWithoutBase); + fmDataModel.put("imports", imports); + fmDataModel.put("url", mappingUrl); + fmDataModel.put("pkg", pkg); + fmDataModel.put("pkgDir", pkg.replace('.', '/')); + fmDataModel.put("modelFullName", pkg + "." + model); + fmDataModel.put("module", module); + fmDataModel.put("ModelName", model); + fmDataModel.put("modelName", StringUtils.uncapitalize(model)); + fmDataModel.put("minusJoinedModelName", minusJoinedModelName); + /* + // super classes name + fmDataModel.put("baseControllerName", BaseController.class.getSimpleName()); + fmDataModel.put("baseControllerFullName", BaseController.class.getName()); + */ - // service interface - fmDataModel.put("baseServiceName", BaseCrudService.class.getSimpleName()); - fmDataModel.put("baseServiceFullName", BaseService.class.getName()); - // server support - fmDataModel.put("baseServiceSupportName", BaseCrudServiceSupport.class.getSimpleName()); - fmDataModel.put("baseServiceSupportFullName", BaseCrudServiceSupport.class.getName()); + // service interface + fmDataModel.put("baseServiceName", BaseCrudService.class.getSimpleName()); + fmDataModel.put("baseServiceFullName", BaseService.class.getName()); + // server support + fmDataModel.put("baseServiceSupportName", BaseCrudServiceSupport.class.getSimpleName()); + fmDataModel.put("baseServiceSupportFullName", BaseCrudServiceSupport.class.getName()); - // model - // - // mapper - fmDataModel.put("baseMapperName", BaseMapper.class.getSimpleName()); - fmDataModel.put("baseMapperFullName", BaseMapper.class.getName()); + // model + // + // mapper + fmDataModel.put("baseMapperName", BaseMapper.class.getSimpleName()); + fmDataModel.put("baseMapperFullName", BaseMapper.class.getName()); -// fmDataModel.put("mockMapperName", MockMapper.class.getSimpleName()); -// fmDataModel.put("mockMapperFullName", MockMapper.class.getName()); - // fmDataModel.put("mockName", Mock.class.getSimpleName()); - // fmDataModel.put("mockFullName", Mock.class.getName()); +// fmDataModel.put("mockMapperName", MockMapper.class.getSimpleName()); +// fmDataModel.put("mockMapperFullName", MockMapper.class.getName()); + // fmDataModel.put("mockName", Mock.class.getSimpleName()); + // fmDataModel.put("mockFullName", Mock.class.getName()); - fmDataModel.put("ctrlrTestToolName", ControllerTestTool.class.getSimpleName()); - fmDataModel.put("ctrlrTestToolFullName", ControllerTestTool.class.getName()); - // Object Doc - Map objDocModel = new HashMap(); - // time now - objDocModel.put("now", - DateFormat.getDateTimeInstance(DateFormat.DEFAULT, - DateFormat.DEFAULT, Locale.US).format(new Date())); - // code doc - fmDataModel.put("objDoc", - baseTool.renderFtl("/codegen/obj-doc.ftl", objDocModel)); - List files = new LinkedList(); - for (CodeGenerator gen : codeGen) { - if (gen.accept(fmDataModel)) { - String genResult = gen.process(fmDataModel, module, model); - if (StringUtils.isNotBlank(genResult)) { - files.addAll(Arrays.asList(genResult.split(";"))); - } - } + fmDataModel.put("ctrlrTestToolName", ControllerTestTool.class.getSimpleName()); + fmDataModel.put("ctrlrTestToolFullName", ControllerTestTool.class.getName()); + // Object Doc + Map objDocModel = new HashMap(); + // time now + objDocModel.put("now", + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, + DateFormat.DEFAULT, Locale.US).format(new Date())); + // code doc + fmDataModel.put("objDoc", + baseTool.renderFtl("/codegen/obj-doc.ftl", objDocModel)); + List files = new LinkedList(); + for (CodeGenerator gen : codeGen) { + if (gen.accept(fmDataModel)) { + String genResult = gen.process(fmDataModel, module, model); + if (StringUtils.isNotBlank(genResult)) { + files.addAll(Arrays.asList(genResult.split(";"))); + } + } } - log.info("Save Code Generated Data, Module [{}], Model [{}].", module, model); - Map mapRec = new HashMap(); - mapRec.put("cols", columns); - mapRec.put("module", module); - mapRec.put("model", model); - mapRec.put("files", files); - mapRec.put("table", table); - baseTool.saveRecord(mapRec); + log.info("Save Code Generated Data, Module [{}], Model [{}].", module, model); + Map mapRec = new HashMap(); + mapRec.put("cols", columns); + mapRec.put("module", module); + mapRec.put("model", model); + mapRec.put("files", files); + mapRec.put("table", table); + baseTool.saveRecord(mapRec); } /** * {@inheritDoc} */ - @Override - public List list() { - List> items = baseTool.listAll(); - for (Map item : items) { - String text = (String) item.get("model"); - String module = (String) item.get("module"); - if (StringUtils.isNotBlank(module)) { - text = module + "/" + text; - } - item.put("text", text); - item.put("checked", false); - item.put("leaf", true); - item.remove("files"); - } - return items; - } + @Override + public List list() { + List> items = baseTool.listAll(); + for (Map item : items) { + String text = (String) item.get("model"); + String module = (String) item.get("module"); + if (StringUtils.isNotBlank(module)) { + text = module + "/" + text; + } + item.put("text", text); + item.put("checked", false); + item.put("leaf", true); + item.remove("files"); + } + return items; + } - /** - * {@inheritDoc} - */ - @Override - @SuppressWarnings("unchecked") - public void delete(List items, boolean dropTable) { - for (Map item : (List>) items) { - baseTool.deleteRec((String) item.get("module"), (String) item.get("model"), dropTable); - } - } + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("unchecked") + public void delete(List items, boolean dropTable) { + for (Map item : (List>) items) { + baseTool.deleteRec((String) item.get("module"), (String) item.get("model"), dropTable); + } + } - /** - * {@inheritDoc} - */ - @Override - public List> tables() { - return baseTool.tables(); - } + /** + * {@inheritDoc} + */ + @Override + public List> tables() { + return baseTool.tables(); + } } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ControllerCodeGen.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ControllerCodeGen.java index 922ed9b..7206ba3 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ControllerCodeGen.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ControllerCodeGen.java @@ -13,25 +13,25 @@ import me.chyxion.tigon.codegen.service.CodeGenerator; */ public class ControllerCodeGen extends CodeGenerator { - /** - * {@inheritDoc} - */ - @Override - public boolean accept(Map dataModel) { - return (Boolean) dataModel.get("genController"); - } - - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ @Override - public String process(Map dataModel, String module, String model) { - return render(new CodeGenArgs( - CodeGenArgs.TARGET_CONTROLLER, - "/codegen/controller.ftl", - dataModel, - codeDir + dataModel.get("pkgDir") + - "/controller/" + - model + "Controller.java")); + public boolean accept(Map dataModel) { + return (Boolean) dataModel.get("genController"); + } + + /** + * {@inheritDoc} + */ + @Override + public String process(Map dataModel, String module, String model) { + return render(new CodeGenArgs( + CodeGenArgs.TARGET_CONTROLLER, + "/codegen/controller.ftl", + dataModel, + codeDir + dataModel.get("pkgDir") + + "/controller/" + + model + "Controller.java")); } } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ControllerTestCodeGen.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ControllerTestCodeGen.java index 8f2af8c..c86d673 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ControllerTestCodeGen.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ControllerTestCodeGen.java @@ -12,16 +12,16 @@ import me.chyxion.tigon.codegen.model.CodeGenArgs; */ public class ControllerTestCodeGen extends ControllerCodeGen { - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ @Override public String process(Map dataModel, String module, String model) { - return render(new CodeGenArgs( - CodeGenArgs.TARGET_CONTROLLER_TEST, - "/codegen/controller-test.ftl", - dataModel, - testDir + dataModel.get("pkgDir") + - "/controller/" + model + "ControllerTest.java")); + return render(new CodeGenArgs( + CodeGenArgs.TARGET_CONTROLLER_TEST, + "/codegen/controller-test.ftl", + dataModel, + testDir + dataModel.get("pkgDir") + + "/controller/" + model + "ControllerTest.java")); } } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/MapperCodeGen.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/MapperCodeGen.java index 0279c12..fb97756 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/MapperCodeGen.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/MapperCodeGen.java @@ -13,24 +13,24 @@ import me.chyxion.tigon.codegen.service.CodeGenerator; */ public class MapperCodeGen extends CodeGenerator { - /** - * {@inheritDoc} - */ - @Override - public boolean accept(Map dataModel) { - return (Boolean) dataModel.get("genMapper"); - } + /** + * {@inheritDoc} + */ + @Override + public boolean accept(Map dataModel) { + return (Boolean) dataModel.get("genMapper"); + } - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ @Override public String process(Map dataModel, String module, String model) { - return render(new CodeGenArgs( - CodeGenArgs.TARGET_MAPPER, - "/codegen/mapper.ftl", - dataModel, - codeDir + dataModel.get("pkgDir") + - "/mapper/" + model + "Mapper.java")); + return render(new CodeGenArgs( + CodeGenArgs.TARGET_MAPPER, + "/codegen/mapper.ftl", + dataModel, + codeDir + dataModel.get("pkgDir") + + "/mapper/" + model + "Mapper.java")); } } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/MapperTestCodeGen.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/MapperTestCodeGen.java index acb2b53..7f733e9 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/MapperTestCodeGen.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/MapperTestCodeGen.java @@ -12,16 +12,16 @@ import me.chyxion.tigon.codegen.model.CodeGenArgs; */ public class MapperTestCodeGen extends MapperCodeGen { - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ @Override public String process(Map dataModel, String module, String model) { - return render(new CodeGenArgs( - CodeGenArgs.TARGET_MAPPER_TEST, - "/codegen/mapper-test.ftl", - dataModel, - testDir + dataModel.get("pkgDir") + - "/mapper/" + model + "MapperTest.java")); + return render(new CodeGenArgs( + CodeGenArgs.TARGET_MAPPER_TEST, + "/codegen/mapper-test.ftl", + dataModel, + testDir + dataModel.get("pkgDir") + + "/mapper/" + model + "MapperTest.java")); } } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/MapperXmlCodeGen.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/MapperXmlCodeGen.java index 98a3ab1..3f80037 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/MapperXmlCodeGen.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/MapperXmlCodeGen.java @@ -13,23 +13,23 @@ import me.chyxion.tigon.codegen.model.CodeGenArgs; */ public class MapperXmlCodeGen extends MapperCodeGen { - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ @Override - public String process(Map dataModel, - String module, String model) { - StringBuilder sbFilePath = new StringBuilder(resourcesDir) - .append("mybatis/mappers/"); - if (StringUtils.isNotBlank(module)) { - sbFilePath.append(module).append("/"); - } - sbFilePath.append(dataModel.get("minusJoinedModelName")).append("-mapper.xml"); + public String process(Map dataModel, + String module, String model) { + StringBuilder sbFilePath = new StringBuilder(resourcesDir) + .append("mybatis/mappers/"); + if (StringUtils.isNotBlank(module)) { + sbFilePath.append(module).append("/"); + } + sbFilePath.append(dataModel.get("minusJoinedModelName")).append("-mapper.xml"); - return render(new CodeGenArgs( - CodeGenArgs.TARGET_MAPPER_XML, - "/codegen/mapper-xml.ftl", - dataModel, - sbFilePath.toString())); + return render(new CodeGenArgs( + CodeGenArgs.TARGET_MAPPER_XML, + "/codegen/mapper-xml.ftl", + dataModel, + sbFilePath.toString())); } } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ModelCodeGen.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ModelCodeGen.java index 83296cd..da934df 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ModelCodeGen.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ModelCodeGen.java @@ -13,24 +13,24 @@ import me.chyxion.tigon.codegen.service.CodeGenerator; */ public class ModelCodeGen extends CodeGenerator { - /** - * {@inheritDoc} - */ - @Override - public boolean accept(Map dataModel) { - return (Boolean) dataModel.get("genModel"); - } + /** + * {@inheritDoc} + */ + @Override + public boolean accept(Map dataModel) { + return (Boolean) dataModel.get("genModel"); + } - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ @Override public String process(Map dataModel, String module, String model) { - return render(new CodeGenArgs( - CodeGenArgs.TARGET_MODEL, - "/codegen/model.ftl", - dataModel, - codeDir + dataModel.get("pkgDir") + - "/model/" + model + ".java")); + return render(new CodeGenArgs( + CodeGenArgs.TARGET_MODEL, + "/codegen/model.ftl", + dataModel, + codeDir + dataModel.get("pkgDir") + + "/model/" + model + ".java")); } } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ServiceCodeGen.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ServiceCodeGen.java index 7b39c69..494ff19 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ServiceCodeGen.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ServiceCodeGen.java @@ -13,37 +13,37 @@ import me.chyxion.tigon.codegen.service.CodeGenerator; */ public class ServiceCodeGen extends CodeGenerator { - /** - * {@inheritDoc} - */ - @Override - public boolean accept(Map dataModel) { - return (Boolean) dataModel.get("genService"); - } + /** + * {@inheritDoc} + */ + @Override + public boolean accept(Map dataModel) { + return (Boolean) dataModel.get("genService"); + } - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ @Override public String process(Map dataModel, String module, String model) { - String pkgDir = (String) dataModel.get("pkgDir"); - // interface - String strRtn = render(new CodeGenArgs( - CodeGenArgs.TARGET_SERVICE, - "/codegen/service.ftl", - dataModel, - codeDir + pkgDir + - "/service/" + model + "Service.java")); - - // support - strRtn +=";"; - strRtn += render(new CodeGenArgs( - CodeGenArgs.TARGET_SERVICE_SUPPORT, - "/codegen/service-support.ftl", - dataModel, - codeDir + pkgDir + - "/service/support/" + model + "ServiceSupport.java" - )); - return strRtn; + String pkgDir = (String) dataModel.get("pkgDir"); + // interface + String strRtn = render(new CodeGenArgs( + CodeGenArgs.TARGET_SERVICE, + "/codegen/service.ftl", + dataModel, + codeDir + pkgDir + + "/service/" + model + "Service.java")); + + // support + strRtn +=";"; + strRtn += render(new CodeGenArgs( + CodeGenArgs.TARGET_SERVICE_SUPPORT, + "/codegen/service-support.ftl", + dataModel, + codeDir + pkgDir + + "/service/support/" + model + "ServiceSupport.java" + )); + return strRtn; } } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/TableCodeGen.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/TableCodeGen.java index 91b9573..e07fa78 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/TableCodeGen.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/TableCodeGen.java @@ -19,55 +19,55 @@ import me.chyxion.tigon.codegen.service.CodeGenerator; */ @Order(Ordered.LOWEST_PRECEDENCE) public class TableCodeGen extends CodeGenerator { - private static final Logger log = LoggerFactory.getLogger(TableCodeGen.class); + private static final Logger log = LoggerFactory.getLogger(TableCodeGen.class); - /** - * {@inheritDoc} - */ - @Override - public boolean accept(Map dataModel) { - return (Boolean) dataModel.get("genTable"); - } + /** + * {@inheritDoc} + */ + @Override + public boolean accept(Map dataModel) { + return (Boolean) dataModel.get("genTable"); + } - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ @Override public String process(Map dataModel, String module, String model) { - String table = (String) dataModel.get("table"); - log.info("Process Generate Table [{}] SQL File.", table); - StringBuilder filePath = new StringBuilder(resourcesDir) - .append("db/"); - if (StringUtils.isNotBlank(module)) { - filePath.append(module).append("/"); - } - filePath.append(table).append(".sql"); - render(new CodeGenArgs( - CodeGenArgs.TARGET_TABLE, - "/codegen/table.ftl", - dataModel, - filePath.toString())); - - if (!Boolean.FALSE.equals(dataModel.get("createTable"))) { - // ignore drop table error - try { - log.info("Execute Drop Table [{}].", table); - baseTool.execSQL("drop table " + table); - } - catch (Exception e) { - log.info("Drop Table Failed, Error Message [{}], Ingore.", - e.getMessage()); - } - // ignore execute sql error - try { - log.info("Execut Create Table SQL File [{}].", filePath); - baseTool.execSQL(new File(baseTool.getProjDir(), filePath - .toString())); - } - catch (Exception e) { - log.warn("Database Create Table Error, Ingore.", e); - } - } - return filePath.toString(); + String table = (String) dataModel.get("table"); + log.info("Process Generate Table [{}] SQL File.", table); + StringBuilder filePath = new StringBuilder(resourcesDir) + .append("db/"); + if (StringUtils.isNotBlank(module)) { + filePath.append(module).append("/"); + } + filePath.append(table).append(".sql"); + render(new CodeGenArgs( + CodeGenArgs.TARGET_TABLE, + "/codegen/table.ftl", + dataModel, + filePath.toString())); + + if (!Boolean.FALSE.equals(dataModel.get("createTable"))) { + // ignore drop table error + try { + log.info("Execute Drop Table [{}].", table); + baseTool.execSQL("drop table " + table); + } + catch (Exception e) { + log.info("Drop Table Failed, Error Message [{}], Ingore.", + e.getMessage()); + } + // ignore execute sql error + try { + log.info("Execut Create Table SQL File [{}].", filePath); + baseTool.execSQL(new File(baseTool.getProjDir(), filePath + .toString())); + } + catch (Exception e) { + log.warn("Database Create Table Error, Ingore.", e); + } + } + return filePath.toString(); } } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ViewCodeGen.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ViewCodeGen.java index feb1f48..35832da 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ViewCodeGen.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/service/support/ViewCodeGen.java @@ -14,28 +14,28 @@ import me.chyxion.tigon.codegen.service.CodeGenerator; */ public class ViewCodeGen extends CodeGenerator { - /** - * {@inheritDoc} - */ - @Override - public boolean accept(Map dataModel) { - return (Boolean) dataModel.get("genView"); - } - - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ + @Override + public boolean accept(Map dataModel) { + return (Boolean) dataModel.get("genView"); + } + + /** + * {@inheritDoc} + */ @Override public String process(Map dataModel, String module, String model) { - StringBuilder sbFilePath = new StringBuilder(viewsDir); - if (StringUtils.isNotBlank(module)) { - sbFilePath.append(module).append("/"); - } - sbFilePath.append(model).append("/List.js"); - return render(new CodeGenArgs( - CodeGenArgs.TARGET_VIEW, - "/codegen/view.ftl", - dataModel, - sbFilePath.toString())); + StringBuilder sbFilePath = new StringBuilder(viewsDir); + if (StringUtils.isNotBlank(module)) { + sbFilePath.append(module).append("/"); + } + sbFilePath.append(model).append("/List.js"); + return render(new CodeGenArgs( + CodeGenArgs.TARGET_VIEW, + "/codegen/view.ftl", + dataModel, + sbFilePath.toString())); } } diff --git a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/utils/DbTool.java b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/utils/DbTool.java index 13c7dbc..2e0b75d 100644 --- a/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/utils/DbTool.java +++ b/tigon-codegen/src/main/java/me/chyxion/tigon/codegen/utils/DbTool.java @@ -21,253 +21,253 @@ import org.springframework.util.StringUtils; * Oct 30, 2014 5:08:25 PM */ public class DbTool { - private static final Logger logger = LoggerFactory.getLogger(DbTool.class); + private static final Logger logger = LoggerFactory.getLogger(DbTool.class); - private static final String DEFAULT_COMMENT_PREFIX = "--"; + private static final String DEFAULT_COMMENT_PREFIX = "--"; - private static final char DEFAULT_STATEMENT_SEPARATOR = ';'; + private static final char DEFAULT_STATEMENT_SEPARATOR = ';'; - /** - * Execute the given SQL script. - *

The script will typically be loaded from the classpath. Statements - * should be delimited with a semicolon. If statements are not delimited with - * a semicolon then there should be one statement per line. Statements are - * allowed to span lines only if they are delimited with a semicolon. Any - * line comments will be removed. - *

Do not use this method to execute DDL if you expect rollback. - * @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations - * @param resource the resource to load the SQL script from - * @param continueOnError whether or not to continue without throwing an - * exception in the event of an error - * @throws DataAccessException if there is an error executing a statement - * and {@code continueOnError} is {@code false} - * @see ResourceDatabasePopulator - * @see #executeSqlScript(JdbcTemplate, EncodedResource, boolean) - */ - public static void executeSqlScript(JdbcTemplate jdbcTemplate, Resource resource, boolean continueOnError) - throws DataAccessException { - executeSqlScript(jdbcTemplate, new EncodedResource(resource), continueOnError); - } + /** + * Execute the given SQL script. + *

The script will typically be loaded from the classpath. Statements + * should be delimited with a semicolon. If statements are not delimited with + * a semicolon then there should be one statement per line. Statements are + * allowed to span lines only if they are delimited with a semicolon. Any + * line comments will be removed. + *

Do not use this method to execute DDL if you expect rollback. + * @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations + * @param resource the resource to load the SQL script from + * @param continueOnError whether or not to continue without throwing an + * exception in the event of an error + * @throws DataAccessException if there is an error executing a statement + * and {@code continueOnError} is {@code false} + * @see ResourceDatabasePopulator + * @see #executeSqlScript(JdbcTemplate, EncodedResource, boolean) + */ + public static void executeSqlScript(JdbcTemplate jdbcTemplate, Resource resource, boolean continueOnError) + throws DataAccessException { + executeSqlScript(jdbcTemplate, new EncodedResource(resource), continueOnError); + } - /** - * Execute the given SQL script. - *

The script will typically be loaded from the classpath. There should - * be one statement per line. Any semicolons and line comments will be removed. - *

Do not use this method to execute DDL if you expect rollback. - * @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations - * @param resource the resource (potentially associated with a specific encoding) - * to load the SQL script from - * @param continueOnError whether or not to continue without throwing an - * exception in the event of an error - * @throws DataAccessException if there is an error executing a statement - * and {@code continueOnError} is {@code false} - * @see ResourceDatabasePopulator - */ - public static void executeSqlScript(JdbcTemplate jdbcTemplate, EncodedResource resource, boolean continueOnError) - throws DataAccessException { + /** + * Execute the given SQL script. + *

The script will typically be loaded from the classpath. There should + * be one statement per line. Any semicolons and line comments will be removed. + *

Do not use this method to execute DDL if you expect rollback. + * @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations + * @param resource the resource (potentially associated with a specific encoding) + * to load the SQL script from + * @param continueOnError whether or not to continue without throwing an + * exception in the event of an error + * @throws DataAccessException if there is an error executing a statement + * and {@code continueOnError} is {@code false} + * @see ResourceDatabasePopulator + */ + public static void executeSqlScript(JdbcTemplate jdbcTemplate, EncodedResource resource, boolean continueOnError) + throws DataAccessException { - if (logger.isInfoEnabled()) { - logger.info("Executing SQL script from " + resource); - } - long startTime = System.currentTimeMillis(); - List statements = new LinkedList(); - LineNumberReader reader = null; - try { - reader = new LineNumberReader(resource.getReader()); - String script = readScript(reader); - char delimiter = DEFAULT_STATEMENT_SEPARATOR; - if (!containsSqlScriptDelimiters(script, delimiter)) { - delimiter = '\n'; - } - splitSqlScript(script, delimiter, statements); - int lineNumber = 0; - for (String statement : statements) { - lineNumber++; - try { - int rowsAffected = jdbcTemplate.update(statement); - if (logger.isDebugEnabled()) { - logger.debug(rowsAffected + " rows affected by SQL: " + statement); - } - } - catch (DataAccessException ex) { - if (continueOnError) { - if (logger.isWarnEnabled()) { - logger.warn("Failed to execute SQL script statement at line " + lineNumber - + " of resource " + resource + ": " + statement, ex); - } - } - else { - throw ex; - } - } - } - long elapsedTime = System.currentTimeMillis() - startTime; - if (logger.isInfoEnabled()) { - logger.info(String.format("Executed SQL script from %s in %s ms.", resource, elapsedTime)); - } - } - catch (IOException ex) { - throw new DataAccessResourceFailureException("Failed to open SQL script from " + resource, ex); - } - finally { - try { - if (reader != null) { - reader.close(); - } - } - catch (IOException ex) { - // ignore - } - } - } + if (logger.isInfoEnabled()) { + logger.info("Executing SQL script from " + resource); + } + long startTime = System.currentTimeMillis(); + List statements = new LinkedList(); + LineNumberReader reader = null; + try { + reader = new LineNumberReader(resource.getReader()); + String script = readScript(reader); + char delimiter = DEFAULT_STATEMENT_SEPARATOR; + if (!containsSqlScriptDelimiters(script, delimiter)) { + delimiter = '\n'; + } + splitSqlScript(script, delimiter, statements); + int lineNumber = 0; + for (String statement : statements) { + lineNumber++; + try { + int rowsAffected = jdbcTemplate.update(statement); + if (logger.isDebugEnabled()) { + logger.debug(rowsAffected + " rows affected by SQL: " + statement); + } + } + catch (DataAccessException ex) { + if (continueOnError) { + if (logger.isWarnEnabled()) { + logger.warn("Failed to execute SQL script statement at line " + lineNumber + + " of resource " + resource + ": " + statement, ex); + } + } + else { + throw ex; + } + } + } + long elapsedTime = System.currentTimeMillis() - startTime; + if (logger.isInfoEnabled()) { + logger.info(String.format("Executed SQL script from %s in %s ms.", resource, elapsedTime)); + } + } + catch (IOException ex) { + throw new DataAccessResourceFailureException("Failed to open SQL script from " + resource, ex); + } + finally { + try { + if (reader != null) { + reader.close(); + } + } + catch (IOException ex) { + // ignore + } + } + } - /** - * Read a script from the provided {@code LineNumberReader}, using - * "{@code --}" as the comment prefix, and build a {@code String} containing - * the lines. - * @param lineNumberReader the {@code LineNumberReader} containing the script - * to be processed - * @return a {@code String} containing the script lines - * @see #readScript(LineNumberReader, String) - */ - public static String readScript(LineNumberReader lineNumberReader) throws IOException { - return readScript(lineNumberReader, DEFAULT_COMMENT_PREFIX); - } + /** + * Read a script from the provided {@code LineNumberReader}, using + * "{@code --}" as the comment prefix, and build a {@code String} containing + * the lines. + * @param lineNumberReader the {@code LineNumberReader} containing the script + * to be processed + * @return a {@code String} containing the script lines + * @see #readScript(LineNumberReader, String) + */ + public static String readScript(LineNumberReader lineNumberReader) throws IOException { + return readScript(lineNumberReader, DEFAULT_COMMENT_PREFIX); + } - /** - * Read a script from the provided {@code LineNumberReader}, using the supplied - * comment prefix, and build a {@code String} containing the lines. - *

Lines beginning with the comment prefix are excluded from the - * results; however, line comments anywhere else — for example, within - * a statement — will be included in the results. - * @param lineNumberReader the {@code LineNumberReader} containing the script - * to be processed - * @param commentPrefix the prefix that identifies comments in the SQL script — typically "--" - * @return a {@code String} containing the script lines - */ - public static String readScript(LineNumberReader lineNumberReader, String commentPrefix) throws IOException { - String currentStatement = lineNumberReader.readLine(); - StringBuilder scriptBuilder = new StringBuilder(); - while (currentStatement != null) { - if (StringUtils.hasText(currentStatement) - && (commentPrefix != null && !currentStatement.startsWith(commentPrefix))) { - if (scriptBuilder.length() > 0) { - scriptBuilder.append('\n'); - } - scriptBuilder.append(currentStatement); - } - currentStatement = lineNumberReader.readLine(); - } - return scriptBuilder.toString(); - } + /** + * Read a script from the provided {@code LineNumberReader}, using the supplied + * comment prefix, and build a {@code String} containing the lines. + *

Lines beginning with the comment prefix are excluded from the + * results; however, line comments anywhere else — for example, within + * a statement — will be included in the results. + * @param lineNumberReader the {@code LineNumberReader} containing the script + * to be processed + * @param commentPrefix the prefix that identifies comments in the SQL script — typically "--" + * @return a {@code String} containing the script lines + */ + public static String readScript(LineNumberReader lineNumberReader, String commentPrefix) throws IOException { + String currentStatement = lineNumberReader.readLine(); + StringBuilder scriptBuilder = new StringBuilder(); + while (currentStatement != null) { + if (StringUtils.hasText(currentStatement) + && (commentPrefix != null && !currentStatement.startsWith(commentPrefix))) { + if (scriptBuilder.length() > 0) { + scriptBuilder.append('\n'); + } + scriptBuilder.append(currentStatement); + } + currentStatement = lineNumberReader.readLine(); + } + return scriptBuilder.toString(); + } - /** - * Determine if the provided SQL script contains the specified delimiter. - * @param script the SQL script - * @param delim character delimiting each statement — typically a ';' character - * @return {@code true} if the script contains the delimiter; {@code false} otherwise - */ - public static boolean containsSqlScriptDelimiters(String script, char delim) { - boolean inLiteral = false; - char[] content = script.toCharArray(); - for (int i = 0; i < script.length(); i++) { - if (content[i] == '\'') { - inLiteral = !inLiteral; - } - if (content[i] == delim && !inLiteral) { - return true; - } - } - return false; - } + /** + * Determine if the provided SQL script contains the specified delimiter. + * @param script the SQL script + * @param delim character delimiting each statement — typically a ';' character + * @return {@code true} if the script contains the delimiter; {@code false} otherwise + */ + public static boolean containsSqlScriptDelimiters(String script, char delim) { + boolean inLiteral = false; + char[] content = script.toCharArray(); + for (int i = 0; i < script.length(); i++) { + if (content[i] == '\'') { + inLiteral = !inLiteral; + } + if (content[i] == delim && !inLiteral) { + return true; + } + } + return false; + } - /** - * Split an SQL script into separate statements delimited by the provided - * delimiter character. Each individual statement will be added to the - * provided {@code List}. - *

Within a statement, "{@code --}" will be used as the comment prefix; - * any text beginning with the comment prefix and extending to the end of - * the line will be omitted from the statement. In addition, multiple adjacent - * whitespace characters will be collapsed into a single space. - * @param script the SQL script - * @param delim character delimiting each statement — typically a ';' character - * @param statements the list that will contain the individual statements - */ - public static void splitSqlScript(String script, char delim, List statements) { - splitSqlScript(script, "" + delim, DEFAULT_COMMENT_PREFIX, statements); - } + /** + * Split an SQL script into separate statements delimited by the provided + * delimiter character. Each individual statement will be added to the + * provided {@code List}. + *

Within a statement, "{@code --}" will be used as the comment prefix; + * any text beginning with the comment prefix and extending to the end of + * the line will be omitted from the statement. In addition, multiple adjacent + * whitespace characters will be collapsed into a single space. + * @param script the SQL script + * @param delim character delimiting each statement — typically a ';' character + * @param statements the list that will contain the individual statements + */ + public static void splitSqlScript(String script, char delim, List statements) { + splitSqlScript(script, "" + delim, DEFAULT_COMMENT_PREFIX, statements); + } - /** - * Split an SQL script into separate statements delimited by the provided - * delimiter string. Each individual statement will be added to the provided - * {@code List}. - *

Within a statement, the provided {@code commentPrefix} will be honored; - * any text beginning with the comment prefix and extending to the end of the - * line will be omitted from the statement. In addition, multiple adjacent - * whitespace characters will be collapsed into a single space. - * @param script the SQL script - * @param delim character delimiting each statement — typically a ';' character - * @param commentPrefix the prefix that identifies line comments in the SQL script — typically "--" - * @param statements the List that will contain the individual statements - */ - private static void splitSqlScript(String script, String delim, String commentPrefix, List statements) { - StringBuilder sb = new StringBuilder(); - boolean inLiteral = false; - boolean inEscape = false; - char[] content = script.toCharArray(); - for (int i = 0; i < script.length(); i++) { - char c = content[i]; - if (inEscape) { - inEscape = false; - sb.append(c); - continue; - } - // MySQL style escapes - if (c == '\\') { - inEscape = true; - sb.append(c); - continue; - } - if (c == '\'') { - inLiteral = !inLiteral; - } - if (!inLiteral) { - if (script.startsWith(delim, i)) { - // we've reached the end of the current statement - if (sb.length() > 0) { - statements.add(sb.toString()); - sb = new StringBuilder(); - } - i += delim.length() - 1; - continue; - } - else if (script.startsWith(commentPrefix, i)) { - // skip over any content from the start of the comment to the EOL - int indexOfNextNewline = script.indexOf("\n", i); - if (indexOfNextNewline > i) { - i = indexOfNextNewline; - continue; - } - else { - // if there's no newline after the comment, we must be at the end - // of the script, so stop here. - break; - } - } - else if (c == ' ' || c == '\n' || c == '\t') { - // avoid multiple adjacent whitespace characters - if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ' ') { - c = ' '; - } - else { - continue; - } - } - } - sb.append(c); - } - if (StringUtils.hasText(sb)) { - statements.add(sb.toString()); - } - } + /** + * Split an SQL script into separate statements delimited by the provided + * delimiter string. Each individual statement will be added to the provided + * {@code List}. + *

Within a statement, the provided {@code commentPrefix} will be honored; + * any text beginning with the comment prefix and extending to the end of the + * line will be omitted from the statement. In addition, multiple adjacent + * whitespace characters will be collapsed into a single space. + * @param script the SQL script + * @param delim character delimiting each statement — typically a ';' character + * @param commentPrefix the prefix that identifies line comments in the SQL script — typically "--" + * @param statements the List that will contain the individual statements + */ + private static void splitSqlScript(String script, String delim, String commentPrefix, List statements) { + StringBuilder sb = new StringBuilder(); + boolean inLiteral = false; + boolean inEscape = false; + char[] content = script.toCharArray(); + for (int i = 0; i < script.length(); i++) { + char c = content[i]; + if (inEscape) { + inEscape = false; + sb.append(c); + continue; + } + // MySQL style escapes + if (c == '\\') { + inEscape = true; + sb.append(c); + continue; + } + if (c == '\'') { + inLiteral = !inLiteral; + } + if (!inLiteral) { + if (script.startsWith(delim, i)) { + // we've reached the end of the current statement + if (sb.length() > 0) { + statements.add(sb.toString()); + sb = new StringBuilder(); + } + i += delim.length() - 1; + continue; + } + else if (script.startsWith(commentPrefix, i)) { + // skip over any content from the start of the comment to the EOL + int indexOfNextNewline = script.indexOf("\n", i); + if (indexOfNextNewline > i) { + i = indexOfNextNewline; + continue; + } + else { + // if there's no newline after the comment, we must be at the end + // of the script, so stop here. + break; + } + } + else if (c == ' ' || c == '\n' || c == '\t') { + // avoid multiple adjacent whitespace characters + if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ' ') { + c = ' '; + } + else { + continue; + } + } + } + sb.append(c); + } + if (StringUtils.hasText(sb)) { + statements.add(sb.toString()); + } + } } diff --git a/tigon-codegen/src/test/java/me/chyxion/tigon/codegen/test/package-info.java b/tigon-codegen/src/test/java/me/chyxion/tigon/codegen/test/package-info.java index 6466945..eaade51 100644 --- a/tigon-codegen/src/test/java/me/chyxion/tigon/codegen/test/package-info.java +++ b/tigon-codegen/src/test/java/me/chyxion/tigon/codegen/test/package-info.java @@ -5,4 +5,4 @@ * chyxion@163.com
* Oct 18, 2015 1:09:11 PM */ -package me.chyxion.tigon.codegen.test; \ No newline at end of file +package me.chyxion.tigon.codegen.test; diff --git a/tigon-codegen/src/test/resources/mybatis/mappers/table-test-mapper.xml b/tigon-codegen/src/test/resources/mybatis/mappers/table-test-mapper.xml index a1f2594..eaa4465 100644 --- a/tigon-codegen/src/test/resources/mybatis/mappers/table-test-mapper.xml +++ b/tigon-codegen/src/test/resources/mybatis/mappers/table-test-mapper.xml @@ -9,95 +9,95 @@ */ --> + "-//mybatis.org//DTD Mapper 3.0//EN" + "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > - - - - - - - + + + + + + + - - id, name, date_created, date_updated - - - table_test - - + + id, name, date_created, date_updated + + + table_test + + update name = #{model.name} - + - + insert into () values (#{model.id}, #{model.name}, #{model.dateCreated}, #{model.dateUpdated}) - + - + where id = #{model.id} - + - + - - + + - + - delete from - - + delete from + + - - - + + - - - - + + + - + - + + + - + diff --git a/tigon-codegen/src/test/resources/spring/controller-test.xml b/tigon-codegen/src/test/resources/spring/controller-test.xml index ba4c486..8e212d6 100644 --- a/tigon-codegen/src/test/resources/spring/controller-test.xml +++ b/tigon-codegen/src/test/resources/spring/controller-test.xml @@ -1,13 +1,13 @@ + default-autowire="byName"> diff --git a/tigon-extjs/pom.xml b/tigon-extjs/pom.xml index 79a74ce..5a8116e 100644 --- a/tigon-extjs/pom.xml +++ b/tigon-extjs/pom.xml @@ -4,11 +4,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - 4.0.0 - tigon-extjs - jar - Tigon Ext JS - Tigon Ext JS + 4.0.0 + tigon-extjs + jar + Tigon Ext JS + Tigon Ext JS me.chyxion.tigon diff --git a/tigon-freemarker-support/pom.xml b/tigon-freemarker-support/pom.xml index acc3d8a..253ce73 100644 --- a/tigon-freemarker-support/pom.xml +++ b/tigon-freemarker-support/pom.xml @@ -4,51 +4,51 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - 4.0.0 - tigon-freemarker-support - jar - Tigon FreeMarker Support - Tigon FreeMarker Support + 4.0.0 + tigon-freemarker-support + jar + Tigon FreeMarker Support + Tigon FreeMarker Support - - me.chyxion.tigon - tigon - 0.0.1-SNAPSHOT - ../ - + + me.chyxion.tigon + tigon + 0.0.1-SNAPSHOT + ../ + - - - org.freemarker - freemarker - - + + + org.freemarker + freemarker + + org.slf4j slf4j-api - - org.springframework - spring-webmvc - - - org.springframework - spring-context-support - - - javax.servlet - javax.servlet-api - provided - + + org.springframework + spring-webmvc + + + org.springframework + spring-context-support + + + javax.servlet + javax.servlet-api + provided + - - org.springframework - spring-test - test - - - junit - junit - test - - + + org.springframework + spring-test + test + + + junit + junit + test + + diff --git a/tigon-freemarker-support/src/main/java/me/chyxion/tigon/freemarker/FreeMarkerViewResolverExt.java b/tigon-freemarker-support/src/main/java/me/chyxion/tigon/freemarker/FreeMarkerViewResolverExt.java index e92c3a6..f06fc92 100644 --- a/tigon-freemarker-support/src/main/java/me/chyxion/tigon/freemarker/FreeMarkerViewResolverExt.java +++ b/tigon-freemarker-support/src/main/java/me/chyxion/tigon/freemarker/FreeMarkerViewResolverExt.java @@ -14,16 +14,16 @@ import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; * Dec 5, 2014 2:31:39 PM */ public class FreeMarkerViewResolverExt extends FreeMarkerViewResolver { - private static final Logger log = - LoggerFactory.getLogger(FreeMarkerViewResolverExt.class); + private static final Logger log = + LoggerFactory.getLogger(FreeMarkerViewResolverExt.class); - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ @Override public View resolveViewName(String viewName, Locale locale) - throws Exception { - log.debug("Try To Resolve View Name [{}], Locale [{}] As FreeMarker View.", viewName, locale); - return super.resolveViewName(viewName.replaceAll("(?i)(^\\s*ftl\\:)|(\\.ftl\\s*$)", ""), locale); + throws Exception { + log.debug("Try To Resolve View Name [{}], Locale [{}] As FreeMarker View.", viewName, locale); + return super.resolveViewName(viewName.replaceAll("(?i)(^\\s*ftl\\:)|(\\.ftl\\s*$)", ""), locale); } } diff --git a/tigon-freemarker-support/src/main/resources/spring/spring-freemarker-support.xml b/tigon-freemarker-support/src/main/resources/spring/spring-freemarker-support.xml index 71c10cd..07e090e 100644 --- a/tigon-freemarker-support/src/main/resources/spring/spring-freemarker-support.xml +++ b/tigon-freemarker-support/src/main/resources/spring/spring-freemarker-support.xml @@ -23,7 +23,7 @@ diff --git a/tigon-jsp-support/pom.xml b/tigon-jsp-support/pom.xml index 25bad19..05e97b1 100644 --- a/tigon-jsp-support/pom.xml +++ b/tigon-jsp-support/pom.xml @@ -4,46 +4,46 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - 4.0.0 - tigon-jsp-support - jar - Tigon JSP Support - Tigon JSP Support + 4.0.0 + tigon-jsp-support + jar + Tigon JSP Support + Tigon JSP Support - - me.chyxion.tigon - tigon - 0.0.1-SNAPSHOT - ../ - + + me.chyxion.tigon + tigon + 0.0.1-SNAPSHOT + ../ + - - - org.apache.commons - commons-lang3 - - - javax.servlet - javax.servlet-api - provided - - + + + org.apache.commons + commons-lang3 + + + javax.servlet + javax.servlet-api + provided + + org.slf4j slf4j-api - - org.springframework - spring-webmvc - - - org.springframework - spring-test - provided - - - junit - junit - provided - - + + org.springframework + spring-webmvc + + + org.springframework + spring-test + provided + + + junit + junit + provided + + diff --git a/tigon-jsp-support/src/main/java/me/chyxion/tigon/jsp/InternalResourceViewResolverExt.java b/tigon-jsp-support/src/main/java/me/chyxion/tigon/jsp/InternalResourceViewResolverExt.java index e61ea5c..6cb2cab 100644 --- a/tigon-jsp-support/src/main/java/me/chyxion/tigon/jsp/InternalResourceViewResolverExt.java +++ b/tigon-jsp-support/src/main/java/me/chyxion/tigon/jsp/InternalResourceViewResolverExt.java @@ -17,9 +17,9 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; * Dec 5, 2014 2:33:18 PM */ public class InternalResourceViewResolverExt - extends InternalResourceViewResolver { - private static final Logger log = - LoggerFactory.getLogger(InternalResourceViewResolverExt.class); + extends InternalResourceViewResolver { + private static final Logger log = + LoggerFactory.getLogger(InternalResourceViewResolverExt.class); @Autowired private ServletContext sc; @@ -29,31 +29,31 @@ public class InternalResourceViewResolverExt */ @Override public View resolveViewName(String viewName, Locale locale) - throws Exception { - return super.resolveViewName(viewName(viewName), locale); + throws Exception { + return super.resolveViewName(viewName(viewName), locale); } /** * {@inheritDoc} */ - @Override - protected boolean canHandle(String viewName, Locale locale) { - try { - // avoid 404 - return sc.getResource(getPrefix() + viewName(viewName) + getSuffix()) != null; - } - catch (MalformedURLException e) { - log.warn("InternalResourceViewResolverExt#canHandle Eorror Caused.", e); - return false; - } - } + @Override + protected boolean canHandle(String viewName, Locale locale) { + try { + // avoid 404 + return sc.getResource(getPrefix() + viewName(viewName) + getSuffix()) != null; + } + catch (MalformedURLException e) { + log.warn("InternalResourceViewResolverExt#canHandle Eorror Caused.", e); + return false; + } + } - /** - * Process View Name - * @param name raw name - * @return jsp file name - */ - private String viewName(String name) { - return name.replaceAll("(?i)(^\\s*jsp\\:)|(\\.jsp\\s*$)", ""); - } + /** + * Process View Name + * @param name raw name + * @return jsp file name + */ + private String viewName(String name) { + return name.replaceAll("(?i)(^\\s*jsp\\:)|(\\.jsp\\s*$)", ""); + } } diff --git a/tigon-jsp-support/src/main/resources/spring/spring-jsp-support.xml b/tigon-jsp-support/src/main/resources/spring/spring-jsp-support.xml index 61d12c9..af5da71 100644 --- a/tigon-jsp-support/src/main/resources/spring/spring-jsp-support.xml +++ b/tigon-jsp-support/src/main/resources/spring/spring-jsp-support.xml @@ -6,8 +6,8 @@ http://www.springframework.org/schema/beans/spring-beans.xsd"> diff --git a/tigon-model/pom.xml b/tigon-model/pom.xml index a875528..bb5ed05 100644 --- a/tigon-model/pom.xml +++ b/tigon-model/pom.xml @@ -4,11 +4,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - 4.0.0 - tigon-model - jar - Tigon Model - Tigon Model + 4.0.0 + tigon-model + jar + Tigon Model + Tigon Model me.chyxion.tigon @@ -17,11 +17,11 @@ ../ - - - org.apache.commons - commons-lang3 - + + + org.apache.commons + commons-lang3 + com.alibaba fastjson @@ -40,7 +40,7 @@ commons-beanutils commons-beanutils - + org.slf4j slf4j-api @@ -55,11 +55,11 @@ provided - - junit - junit - test - + + junit + junit + test + org.apache.logging.log4j log4j-slf4j-impl @@ -70,5 +70,5 @@ log4j-core test - + diff --git a/tigon-model/src/main/java/me/chyxion/tigon/exception/BaseException.java b/tigon-model/src/main/java/me/chyxion/tigon/exception/BaseException.java index 38a0c9b..2f3cdf5 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/exception/BaseException.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/exception/BaseException.java @@ -11,37 +11,37 @@ import static org.slf4j.helpers.MessageFormatter.arrayFormat; * Oct 9, 2016 10:04:10 AM */ public class BaseException - extends RuntimeException - implements ErrorCoded { + extends RuntimeException + implements ErrorCoded { private static final long serialVersionUID = 1L; public static final int CODE = 5000; protected Object code = CODE; - public BaseException() { - } + public BaseException() { + } - public BaseException(Object code) { - this.code = code; - } - - public BaseException(Object code, Throwable e) { - super(e); - this.code = code; - } + public BaseException(Object code) { + this.code = code; + } + + public BaseException(Object code, Throwable e) { + super(e); + this.code = code; + } - public BaseException(Object code, String message, Object ... args) { - this(message, args); - this.code = code; - } + public BaseException(Object code, String message, Object ... args) { + this(message, args); + this.code = code; + } - public BaseException(String message, Object ... args) { - super(arrayFormat(message, args).getMessage(), - arrayFormat(null, args).getThrowable()); - } + public BaseException(String message, Object ... args) { + super(arrayFormat(message, args).getMessage(), + arrayFormat(null, args).getThrowable()); + } - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ @Override public Object getCode() { return code; diff --git a/tigon-model/src/main/java/me/chyxion/tigon/exception/ErrorCoded.java b/tigon-model/src/main/java/me/chyxion/tigon/exception/ErrorCoded.java index 2f7da96..c4ee52b 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/exception/ErrorCoded.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/exception/ErrorCoded.java @@ -8,14 +8,14 @@ package me.chyxion.tigon.exception; * Oct 8, 2016 5:54:52 PM */ public interface ErrorCoded { - - /** - * @return error code - */ - T getCode(); - - /** - * @param code error code - */ - void setCode(T code); + + /** + * @return error code + */ + T getCode(); + + /** + * @param code error code + */ + void setCode(T code); } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/exception/InvalidParamException.java b/tigon-model/src/main/java/me/chyxion/tigon/exception/InvalidParamException.java index 993ba55..b941785 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/exception/InvalidParamException.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/exception/InvalidParamException.java @@ -9,10 +9,10 @@ package me.chyxion.tigon.exception; * Oct 26, 2015 12:13:52 PM */ public class InvalidParamException extends BaseException { - private static final long serialVersionUID = 1L; - public static final int CODE = 4001; + private static final long serialVersionUID = 1L; + public static final int CODE = 4001; - public InvalidParamException(String message, Object ... args) { - super(CODE, message, args); - } + public InvalidParamException(String message, Object ... args) { + super(CODE, message, args); + } } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/exception/InvalidStateException.java b/tigon-model/src/main/java/me/chyxion/tigon/exception/InvalidStateException.java index e9bf670..d284d8d 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/exception/InvalidStateException.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/exception/InvalidStateException.java @@ -9,10 +9,10 @@ package me.chyxion.tigon.exception; * Oct 9, 2016 10:05:29 AM */ public class InvalidStateException extends BaseException { - private static final long serialVersionUID = 1L; - public static final int CODE = 4002; + private static final long serialVersionUID = 1L; + public static final int CODE = 4002; - public InvalidStateException(String message, Object ... args) { - super(CODE, message, args); - } + public InvalidStateException(String message, Object ... args) { + super(CODE, message, args); + } } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/form/BaseForm.java b/tigon-model/src/main/java/me/chyxion/tigon/form/BaseForm.java index 05d9cee..c395292 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/form/BaseForm.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/form/BaseForm.java @@ -13,78 +13,78 @@ import org.springframework.beans.BeanUtils; */ @Slf4j public class BaseForm implements BaseFormApi { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * clone to class - * @param clazz copy to class - * @return copy result - */ - @Override - public T copy(Class clazz) { - return copy(clazz, false); - } + /** + * clone to class + * @param clazz copy to class + * @return copy result + */ + @Override + public T copy(Class clazz) { + return copy(clazz, false); + } - /** - * copy to class - * @param clazz copy to class - * @param convert true to convert fields - * @return copy result - */ - @Override - public T copy(Class clazz, boolean convert) { - log.debug("Copy Form [{}] To Class [{}].", this, clazz); - T obj = null; - try { - obj = clazz.newInstance(); - } - catch (Exception e) { - throw new IllegalStateException( - "Create [" + clazz + "] Object Error Caused", e); - } - return copy(obj, convert); - } + /** + * copy to class + * @param clazz copy to class + * @param convert true to convert fields + * @return copy result + */ + @Override + public T copy(Class clazz, boolean convert) { + log.debug("Copy Form [{}] To Class [{}].", this, clazz); + T obj = null; + try { + obj = clazz.newInstance(); + } + catch (Exception e) { + throw new IllegalStateException( + "Create [" + clazz + "] Object Error Caused", e); + } + return copy(obj, convert); + } - /** - * copy to object - * @param obj copy to object - * @return copy result - */ - @Override - public T copy(T obj) { - return copy(obj, false); - } + /** + * copy to object + * @param obj copy to object + * @return copy result + */ + @Override + public T copy(T obj) { + return copy(obj, false); + } - /** - * copy props with converting - * @param obj copy to object - * @param convert true to convert object fields - * @return copy result object - */ - @Override - public T copy(T obj, boolean convert) { - try { - if (convert) { - log.debug("Copy Form [{}] To [{}] With Type Converting.", this, obj); - org.apache.commons.beanutils.BeanUtils.copyProperties(obj, this); - } - else { - log.debug("Copy Form [{}] To [{}].", this, obj); - BeanUtils.copyProperties(this, obj); - } - return obj; - } - catch (Exception e) { - throw new IllegalStateException( - "Copy [" + this + "] Error Caused", e); - } - } + /** + * copy props with converting + * @param obj copy to object + * @param convert true to convert object fields + * @return copy result object + */ + @Override + public T copy(T obj, boolean convert) { + try { + if (convert) { + log.debug("Copy Form [{}] To [{}] With Type Converting.", this, obj); + org.apache.commons.beanutils.BeanUtils.copyProperties(obj, this); + } + else { + log.debug("Copy Form [{}] To [{}].", this, obj); + BeanUtils.copyProperties(this, obj); + } + return obj; + } + catch (Exception e) { + throw new IllegalStateException( + "Copy [" + this + "] Error Caused", e); + } + } - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return JSON.toJSONString(this); - } + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return JSON.toJSONString(this); + } } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/form/BaseFormApi.java b/tigon-model/src/main/java/me/chyxion/tigon/form/BaseFormApi.java index 1770e12..31340fd 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/form/BaseFormApi.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/form/BaseFormApi.java @@ -11,35 +11,35 @@ import java.io.Serializable; */ public interface BaseFormApi extends Serializable { - /** - * copy to class - * @param clazz to class - * @param to class type - * @return copy result - */ - T copy(Class clazz); + /** + * copy to class + * @param clazz to class + * @param to class type + * @return copy result + */ + T copy(Class clazz); - /** - * @param clazz to class - * @param to class type - * @param convert convert prop - * @return copy result - */ - T copy(Class clazz, boolean convert); + /** + * @param clazz to class + * @param to class type + * @param convert convert prop + * @return copy result + */ + T copy(Class clazz, boolean convert); - /** - * @param obj copy to object - * @param to class type - * @return copy result - */ - T copy(T obj); + /** + * @param obj copy to object + * @param to class type + * @return copy result + */ + T copy(T obj); - /** - * copy props with converting - * @param obj copy to object - * @param convert convert prop - * @param to class type - * @return copy result - */ - T copy(T obj, boolean convert); + /** + * copy props with converting + * @param obj copy to object + * @param convert convert prop + * @param to class type + * @return copy result + */ + T copy(T obj, boolean convert); } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/form/BaseFormForUpdateApi.java b/tigon-model/src/main/java/me/chyxion/tigon/form/BaseFormForUpdateApi.java index 1bb771a..97f0295 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/form/BaseFormForUpdateApi.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/form/BaseFormForUpdateApi.java @@ -8,14 +8,14 @@ package me.chyxion.tigon.form; * Oct 8, 2016 6:24:03 PM */ public interface BaseFormForUpdateApi extends BaseFormApi { - - /** - * @return id - */ - Id getId(); - - /** - * @param id id - */ - void setId(Id id); + + /** + * @return id + */ + Id getId(); + + /** + * @param id id + */ + void setId(Id id); } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/form/FC0.java b/tigon-model/src/main/java/me/chyxion/tigon/form/FC0.java index 4eca13f..d6f7352 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/form/FC0.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/form/FC0.java @@ -8,7 +8,7 @@ package me.chyxion.tigon.form; * Oct 8, 2016 6:26:19 PM */ public class FC0 extends BaseForm - implements BaseFormForCreateApi { - private static final long serialVersionUID = 1L; + implements BaseFormForCreateApi { + private static final long serialVersionUID = 1L; } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/form/FC1.java b/tigon-model/src/main/java/me/chyxion/tigon/form/FC1.java index ded67e5..1caa6bf 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/form/FC1.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/form/FC1.java @@ -15,10 +15,10 @@ import me.chyxion.tigon.format.annotation.EmptyToNull; @Getter @Setter public class FC1 extends FC0 { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @NotNull - protected Boolean enabled = true; - @EmptyToNull - protected String note; + @NotNull + protected Boolean enabled = true; + @EmptyToNull + protected String note; } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/form/FC2.java b/tigon-model/src/main/java/me/chyxion/tigon/form/FC2.java index b62b3c5..b6fa0b3 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/form/FC2.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/form/FC2.java @@ -14,8 +14,8 @@ import me.chyxion.tigon.validation.annotation.NotNullOrBlank; @Getter @Setter public class FC2 extends FC1 { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @NotNullOrBlank - protected CreatorId createdBy; + @NotNullOrBlank + protected CreatorId createdBy; } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/form/FU0.java b/tigon-model/src/main/java/me/chyxion/tigon/form/FU0.java index 3ed1717..77145df 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/form/FU0.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/form/FU0.java @@ -14,11 +14,11 @@ import me.chyxion.tigon.validation.annotation.NotNullOrBlank; @Getter @Setter public class FU0 - extends BaseForm - implements BaseFormForUpdateApi { + extends BaseForm + implements BaseFormForUpdateApi { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @NotNullOrBlank - protected Id id; + @NotNullOrBlank + protected Id id; } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/form/FU1.java b/tigon-model/src/main/java/me/chyxion/tigon/form/FU1.java index cfa8bcc..94d2783 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/form/FU1.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/form/FU1.java @@ -15,11 +15,11 @@ import me.chyxion.tigon.format.annotation.EmptyToNull; @Getter @Setter public class FU1 - extends FU0 { - private static final long serialVersionUID = 1L; + extends FU0 { + private static final long serialVersionUID = 1L; - @NotNull - protected Boolean enabled; - @EmptyToNull - protected String note; + @NotNull + protected Boolean enabled; + @EmptyToNull + protected String note; } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/form/FU2.java b/tigon-model/src/main/java/me/chyxion/tigon/form/FU2.java index adc1711..2589e84 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/form/FU2.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/form/FU2.java @@ -14,9 +14,9 @@ import me.chyxion.tigon.validation.annotation.NotNullOrBlank; @Getter @Setter public class FU2 - extends FU1 { - private static final long serialVersionUID = 1L; + extends FU1 { + private static final long serialVersionUID = 1L; - @NotNullOrBlank - private EditorId updatedBy; + @NotNullOrBlank + private EditorId updatedBy; } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/model/ListResult.java b/tigon-model/src/main/java/me/chyxion/tigon/model/ListResult.java index 7ff0841..981ee9f 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/model/ListResult.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/model/ListResult.java @@ -11,7 +11,7 @@ import java.util.List; */ public class ListResult extends ViewModel> - implements ListResultApi { + implements ListResultApi { private static final long serialVersionUID = 1L; private static final String TOTAL_KEY = "total"; diff --git a/tigon-model/src/main/java/me/chyxion/tigon/model/ListResultApi.java b/tigon-model/src/main/java/me/chyxion/tigon/model/ListResultApi.java index 215a098..69da69e 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/model/ListResultApi.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/model/ListResultApi.java @@ -27,4 +27,4 @@ public interface ListResultApi extends ViewModelable> { * @return this */ ListResultApi setTotal(int total); -} \ No newline at end of file +} diff --git a/tigon-model/src/main/java/me/chyxion/tigon/model/M0.java b/tigon-model/src/main/java/me/chyxion/tigon/model/M0.java index 40afc91..9fd0e85 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/model/M0.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/model/M0.java @@ -13,31 +13,31 @@ import lombok.Setter; @Getter @Setter public class M0 extends BaseModel { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - protected Id id; + protected Id id; - /** - * {@inheritDoc} - */ - @Override - public String primaryKeyName() { - return ID; - } + /** + * {@inheritDoc} + */ + @Override + public String primaryKeyName() { + return ID; + } - /** - * {@inheritDoc} - */ - @Override - public Id primaryKeyValue() { - return id; - } + /** + * {@inheritDoc} + */ + @Override + public Id primaryKeyValue() { + return id; + } - /** - * {@inheritDoc} - */ - @Override - public void primaryKeyValue(Id id) { - this.id = id; - } + /** + * {@inheritDoc} + */ + @Override + public void primaryKeyValue(Id id) { + this.id = id; + } } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/model/M1.java b/tigon-model/src/main/java/me/chyxion/tigon/model/M1.java index b4789ee..057dd4d 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/model/M1.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/model/M1.java @@ -15,31 +15,31 @@ import java.util.Date; @Setter public class M1 extends M0 { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public static final String DATE_CREATED = "date_created"; - public static final String DATE_UPDATED = "date_updated"; + public static final String DATE_CREATED = "date_created"; + public static final String DATE_UPDATED = "date_updated"; - protected Date dateCreated; - protected Date dateUpdated; + protected Date dateCreated; + protected Date dateUpdated; - /** - * init date created - */ - @Override - public void beforeInsert() { - super.beforeInsert(); - if (dateCreated == null) { - dateCreated = new Date(); - } - } + /** + * init date created + */ + @Override + public void beforeInsert() { + super.beforeInsert(); + if (dateCreated == null) { + dateCreated = new Date(); + } + } - /** - * update date updated - */ - @Override - public void beforeUpdate() { + /** + * update date updated + */ + @Override + public void beforeUpdate() { super.beforeUpdate(); - dateUpdated = new Date(); - } + dateUpdated = new Date(); + } } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/model/M2.java b/tigon-model/src/main/java/me/chyxion/tigon/model/M2.java index 3b8b96a..c3e066b 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/model/M2.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/model/M2.java @@ -14,11 +14,11 @@ import lombok.Setter; @Setter public class M2 extends M1 { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public static final String ENABLED = "enabled"; - public static final String NOTE = "note"; + public static final String ENABLED = "enabled"; + public static final String NOTE = "note"; - protected boolean enabled; - protected String note; + protected boolean enabled; + protected String note; } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/model/M3.java b/tigon-model/src/main/java/me/chyxion/tigon/model/M3.java index f534489..7116da8 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/model/M3.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/model/M3.java @@ -13,13 +13,13 @@ import lombok.Setter; @Setter @Getter public class M3 - extends M2 { - private static final long serialVersionUID = 1L; + extends M2 { + private static final long serialVersionUID = 1L; - public static final String CREATED_BY = "created_by"; - public static final String UPDATED_BY = "updated_by"; + public static final String CREATED_BY = "created_by"; + public static final String UPDATED_BY = "updated_by"; - // fields - protected UserId createdBy; - protected UserId updatedBy; + // fields + protected UserId createdBy; + protected UserId updatedBy; } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/model/ViewModel.java b/tigon-model/src/main/java/me/chyxion/tigon/model/ViewModel.java index 3069152..9277a15 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/model/ViewModel.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/model/ViewModel.java @@ -15,59 +15,59 @@ import com.alibaba.fastjson.JSONObject; */ @Getter public class ViewModel - implements ViewModelable { - private static final long serialVersionUID = 1L; + implements ViewModelable { + private static final long serialVersionUID = 1L; - private T data; - private Map attrs; + private T data; + private Map attrs; - public ViewModel() { - } + public ViewModel() { + } - /** - * @param data - */ - public ViewModel(T data) { - this.data = data; - } - - /** - * @param data - * @param attrs - */ - public ViewModel(T data, Map attrs) { - this.data = data; - this.attrs = attrs; - } + /** + * @param data + */ + public ViewModel(T data) { + this.data = data; + } + + /** + * @param data + * @param attrs + */ + public ViewModel(T data, Map attrs) { + this.data = data; + this.attrs = attrs; + } - /** - * @param name - * @param value - * @return - */ - @Override - public ViewModel setAttr(String name, Object value) { - if (attrs == null) { - attrs = new HashMap(); - } - attrs.put(name, value); - return this; - } + /** + * @param name + * @param value + * @return + */ + @Override + public ViewModel setAttr(String name, Object value) { + if (attrs == null) { + attrs = new HashMap(); + } + attrs.put(name, value); + return this; + } /** * {@inheritDoc} - */ + */ @Override - public A getAttr(String name) { - return attrs != null ? (A) attrs.get(name) : null; - } + public A getAttr(String name) { + return attrs != null ? (A) attrs.get(name) : null; + } /** * {@inheritDoc} */ @Override public ViewModelable setAttrs(Map attrs) { - this.attrs = attrs; + this.attrs = attrs; return this; } @@ -81,41 +81,41 @@ public class ViewModel } /** - * @return map - */ - @SuppressWarnings("unchecked") - public Map toMap() { - Map mapRtn = null; - if (data != null) { - if (data instanceof Map) { - mapRtn = (Map) data; - } - else { - if (data instanceof ViewModelable) { - mapRtn = new HashMap(); - mapRtn.put("data", ((ViewModelable) data).toMap()); - } - else { - Object jsonData = JSON.toJSON(data); - if (jsonData instanceof JSONObject) { - mapRtn = (Map) jsonData; - } - else { - mapRtn = new HashMap(); - mapRtn.put("data", jsonData); - } - } - } - if (attrs != null && !attrs.isEmpty()) { - mapRtn.putAll(attrs); - } - } - else if (attrs != null) { - mapRtn = attrs; - } - else { - mapRtn = new HashMap(); - } - return mapRtn; - } -} \ No newline at end of file + * @return map + */ + @SuppressWarnings("unchecked") + public Map toMap() { + Map mapRtn = null; + if (data != null) { + if (data instanceof Map) { + mapRtn = (Map) data; + } + else { + if (data instanceof ViewModelable) { + mapRtn = new HashMap(); + mapRtn.put("data", ((ViewModelable) data).toMap()); + } + else { + Object jsonData = JSON.toJSON(data); + if (jsonData instanceof JSONObject) { + mapRtn = (Map) jsonData; + } + else { + mapRtn = new HashMap(); + mapRtn.put("data", jsonData); + } + } + } + if (attrs != null && !attrs.isEmpty()) { + mapRtn.putAll(attrs); + } + } + else if (attrs != null) { + mapRtn = attrs; + } + else { + mapRtn = new HashMap(); + } + return mapRtn; + } +} diff --git a/tigon-model/src/main/java/me/chyxion/tigon/model/ViewModelable.java b/tigon-model/src/main/java/me/chyxion/tigon/model/ViewModelable.java index 1c78698..6947423 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/model/ViewModelable.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/model/ViewModelable.java @@ -11,15 +11,15 @@ import java.util.Map; */ public interface ViewModelable extends Mappable { - /** - * @return data main data - */ - T getData(); + /** + * @return data main data + */ + T getData(); /** - * @param data data to set - */ - ViewModelable setData(T data); + * @param data data to set + */ + ViewModelable setData(T data); /** * @param name attr name diff --git a/tigon-model/src/main/java/me/chyxion/tigon/mybatis/Search.java b/tigon-model/src/main/java/me/chyxion/tigon/mybatis/Search.java index 4e74a84..ca365f0 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/mybatis/Search.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/mybatis/Search.java @@ -13,14 +13,14 @@ import me.chyxion.tigon.model.BaseModel; * May 12, 2015 3:00:40 PM */ public class Search implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private final List criteria = new LinkedList(); private String table; - private Integer offset; - private Integer limit; - private final Map orders = + private Integer offset; + private Integer limit; + private final Map orders = new LinkedHashMap(); /** * extended data @@ -28,53 +28,53 @@ public class Search implements Serializable { private final Map ext = new HashMap(); - private static final List PROCESSORS; - static { - List processors = new LinkedList(); - processors.add(new EqualSearchProcessor()); - processors.add(new IsNullSearchProcessor()); + private static final List PROCESSORS; + static { + List processors = new LinkedList(); + processors.add(new EqualSearchProcessor()); + processors.add(new IsNullSearchProcessor()); - processors.add(new InSearchProcessor()); - processors.add(new NotInSearchProcessor()); + processors.add(new InSearchProcessor()); + processors.add(new NotInSearchProcessor()); - processors.add(new NotEqualSearchProcessor()); - processors.add(new IsNotNullSearchProcessor()); + processors.add(new NotEqualSearchProcessor()); + processors.add(new IsNotNullSearchProcessor()); - processors.add(new GtSearchProcessor()); - processors.add(new GteSearchProcessor()); + processors.add(new GtSearchProcessor()); + processors.add(new GteSearchProcessor()); - processors.add(new LtSearchProcessor()); - processors.add(new LteSearchProcessor()); + processors.add(new LtSearchProcessor()); + processors.add(new LteSearchProcessor()); - processors.add(new BetweenSearchProcessor()); - processors.add(new LikeSearchProcessor()); + processors.add(new BetweenSearchProcessor()); + processors.add(new LikeSearchProcessor()); - processors.add(new AndSearchProcessor()); - processors.add(new OrSearchProcessor()); - PROCESSORS = Collections.unmodifiableList(processors); + processors.add(new AndSearchProcessor()); + processors.add(new OrSearchProcessor()); + PROCESSORS = Collections.unmodifiableList(processors); } - /** - * default construct - */ - public Search() { - } - - /** - * @param value id value - */ - public Search(Object value) { - eq(BaseModel.ID, value); - } + /** + * default construct + */ + public Search() { + } + + /** + * @param value id value + */ + public Search(Object value) { + eq(BaseModel.ID, value); + } - /** - * construct by eq - * @param col col name - * @param value value - */ - public Search(String col, Object value) { - eq(col, value); - } + /** + * construct by eq + * @param col col name + * @param value value + */ + public Search(String col, Object value) { + eq(col, value); + } /** * construct by eq @@ -94,22 +94,22 @@ public class Search implements Serializable { in(col, values); } - /** - * set table - * @param table table - * @return this - */ - public Search table(String table) { - this.table = table; - return this; - } + /** + * set table + * @param table table + * @return this + */ + public Search table(String table) { + this.table = table; + return this; + } /** * clear criteria * @return search */ public Search clearCriteria() { - criteria.clear(); + criteria.clear(); return this; } @@ -122,14 +122,14 @@ public class Search implements Serializable { return this; } - /** + /** * col eq - * @param col col name - * @param value value - * @return this - */ - public Search eq(String col, Object value) { - if (value == null) { + * @param col col name + * @param value value + * @return this + */ + public Search eq(String col, Object value) { + if (value == null) { criteria.add(new Criterion(CriterionType.IS_NULL, col, value)); } else if (value instanceof Collection) { @@ -141,8 +141,8 @@ public class Search implements Serializable { else { criteria.add(new Criterion(CriterionType.EQ, col, value)); } - return this; - } + return this; + } /** * same as #eq(col, null) @@ -150,216 +150,216 @@ public class Search implements Serializable { * @return this */ public Search isNull(String col) { - return eq(col, null); + return eq(col, null); } - /** + /** * col in values array - * @param col col name - * @param values values - * @return this - */ - public Search in(String col, Object[] values) { + * @param col col name + * @param values values + * @return this + */ + public Search in(String col, Object[] values) { criteria.add(new Criterion(CriterionType.IN, col, values)); - return this; - } + return this; + } - /** + /** * col in values list - * @param col col name - * @param values values - * @return this - */ - public Search in(String col, Collection values) { + * @param col col name + * @param values values + * @return this + */ + public Search in(String col, Collection values) { criteria.add(new Criterion(CriterionType.IN, col, values)); - return this; - } + return this; + } - /** + /** * col like value - * @param col col name - * @param value value - * @return this - */ - public Search like(String col, String value) { + * @param col col name + * @param value value + * @return this + */ + public Search like(String col, String value) { criteria.add(new Criterion(CriterionType.LIKE, col, value)); - return this; - } + return this; + } - /** - * @param col col name - * @param value value - * @param wrapValue wrap value with % - * @return this - */ - public Search like(String col, String value, boolean wrapValue) { - return like(col, wrapValue ? "%" + value + "%" : value); - } + /** + * @param col col name + * @param value value + * @param wrapValue wrap value with % + * @return this + */ + public Search like(String col, String value, boolean wrapValue) { + return like(col, wrapValue ? "%" + value + "%" : value); + } - /** - * @param col col name - * @param bottom bottom value - * @param top top value - * @return this - */ - public Search between(String col, Object bottom, Object top) { + /** + * @param col col name + * @param bottom bottom value + * @param top top value + * @return this + */ + public Search between(String col, Object bottom, Object top) { criteria.add(new Criterion( CriterionType.BETWEEN, col, Arrays.asList(bottom, top))); - return this; - } + return this; + } - /** - * @param col col name - * @param value value - * @return this - */ - public Search ne(String col, Object value) { + /** + * @param col col name + * @param value value + * @return this + */ + public Search ne(String col, Object value) { criteria.add(new Criterion( - value != null ? CriterionType.NE : - CriterionType.IS_NOT_NULL, col, value)); - return this; - } + value != null ? CriterionType.NE : + CriterionType.IS_NOT_NULL, col, value)); + return this; + } - /** - * col not null - * @param col col - * @return search - */ - public Search notNull(String col) { - criteria.add(new Criterion( - CriterionType.IS_NOT_NULL, col, (Object) null)); - return this; - } + /** + * col not null + * @param col col + * @return search + */ + public Search notNull(String col) { + criteria.add(new Criterion( + CriterionType.IS_NOT_NULL, col, (Object) null)); + return this; + } - /** - * @param col col name - * @param values values - * @return this - */ - public Search notIn(String col, Object[] values) { + /** + * @param col col name + * @param values values + * @return this + */ + public Search notIn(String col, Object[] values) { return notIn(col, Arrays.asList(values)); - } - - /** - * @param col col name - * @param values values - * @return this - */ - public Search notIn(String col, Collection values) { + } + + /** + * @param col col name + * @param values values + * @return this + */ + public Search notIn(String col, Collection values) { criteria.add(new Criterion(CriterionType.NOT_IN, col, values)); - return this; - } - - /** - * @param col col name - * @param value value - * @return this - */ - public Search lt(String col, Object value) { + return this; + } + + /** + * @param col col name + * @param value value + * @return this + */ + public Search lt(String col, Object value) { criteria.add(new Criterion(CriterionType.LT, col, value)); - return this; - } + return this; + } - /** - * @param col col name - * @param value value - * @return this - */ - public Search lte(String col, Object value) { + /** + * @param col col name + * @param value value + * @return this + */ + public Search lte(String col, Object value) { criteria.add(new Criterion(CriterionType.LTE, col, value)); - return this; - } + return this; + } - /** - * @param col col name - * @param value value - * @return this - */ - public Search gt(String col, Object value) { + /** + * @param col col name + * @param value value + * @return this + */ + public Search gt(String col, Object value) { criteria.add(new Criterion(CriterionType.GT, col, value)); - return this; - } + return this; + } - /** - * @param col col name - * @param value value - * @return this - */ - public Search gte(String col, Object value) { + /** + * @param col col name + * @param value value + * @return this + */ + public Search gte(String col, Object value) { criteria.add(new Criterion(CriterionType.GTE, col, value)); - return this; - } + return this; + } - /** - * @param search search - * @return this - */ - public Search and(Search search) { - Assert.notNull(search, "And Search Could Not Be Null"); - Assert.state(this != search, "And Search Could Not Be Self"); - criteria.add(new Criterion(CriterionType.AND, search)); - return this; - } + /** + * @param search search + * @return this + */ + public Search and(Search search) { + Assert.notNull(search, "And Search Could Not Be Null"); + Assert.state(this != search, "And Search Could Not Be Self"); + criteria.add(new Criterion(CriterionType.AND, search)); + return this; + } - /** - * @param search search - * @return this - */ - public Search or(Search search) { - Assert.notNull(search, "Or Search Could Not Be Null"); - Assert.state(this != search, "Or Search Could Not Be Self"); + /** + * @param search search + * @return this + */ + public Search or(Search search) { + Assert.notNull(search, "Or Search Could Not Be Null"); + Assert.state(this != search, "Or Search Could Not Be Self"); criteria.add(new Criterion(CriterionType.OR, search)); return this; - } + } - /** - * @param col col name - * @param value value - * @return this - */ - public Search or(String col, Object value) { - return or(new Search(col, value)); - } + /** + * @param col col name + * @param value value + * @return this + */ + public Search or(String col, Object value) { + return or(new Search(col, value)); + } - /** - * @param col col name - * @return this - */ - public Search asc(String col) { - return order(col, "asc"); - } + /** + * @param col col name + * @return this + */ + public Search asc(String col) { + return order(col, "asc"); + } - /** - * @param col col name - * @return this - */ - public Search desc(String col) { - return order(col, "desc"); - } - - /** - * @param offset offset - * @return this - */ - public Search offset(Integer offset) { - if (offset != null) { - Assert.state(offset >= 0, "Offset May Not Be Negative"); - } - this.offset = offset; - return this; - } + /** + * @param col col name + * @return this + */ + public Search desc(String col) { + return order(col, "desc"); + } + + /** + * @param offset offset + * @return this + */ + public Search offset(Integer offset) { + if (offset != null) { + Assert.state(offset >= 0, "Offset May Not Be Negative"); + } + this.offset = offset; + return this; + } - /** - * @param offset offset - * @return this - */ - public Search offset(int offset) { - Assert.state(offset >= 0, "Offset May Not Be Negative"); - this.offset = offset; - return this; - } + /** + * @param offset offset + * @return this + */ + public Search offset(int offset) { + Assert.state(offset >= 0, "Offset May Not Be Negative"); + this.offset = offset; + return this; + } /** * @return offset @@ -368,27 +368,27 @@ public class Search implements Serializable { return offset; } - /** - * @param limit limit - * @return this - */ - public Search limit(Integer limit) { - if (limit != null) { - Assert.state(limit > 0, "Limit May Not Be Negative Or Zero"); - } - this.limit = limit; - return this; - } + /** + * @param limit limit + * @return this + */ + public Search limit(Integer limit) { + if (limit != null) { + Assert.state(limit > 0, "Limit May Not Be Negative Or Zero"); + } + this.limit = limit; + return this; + } - /** - * @param limit limit - * @return this - */ - public Search limit(int limit) { - Assert.state(limit > 0, "Limit May Not Be Negative Or Zero"); - this.limit = limit; - return this; - } + /** + * @param limit limit + * @return this + */ + public Search limit(int limit) { + Assert.state(limit > 0, "Limit May Not Be Negative Or Zero"); + this.limit = limit; + return this; + } /** * @return limit @@ -404,13 +404,13 @@ public class Search implements Serializable { return orders; } - /** - * assemble to sql and value list - * @return sql and value list - */ - public List assemble() { - return assemble(false); - } + /** + * assemble to sql and value list + * @return sql and value list + */ + public List assemble() { + return assemble(false); + } /** * @return true if has criterion @@ -419,26 +419,26 @@ public class Search implements Serializable { return !criteria.isEmpty(); } - /** - * @return true if has no criterion - */ - public boolean hasNoCriterion() { - return criteria.isEmpty(); - } + /** + * @return true if has no criterion + */ + public boolean hasNoCriterion() { + return criteria.isEmpty(); + } - /** - * @return true if has order - */ - public boolean hasOrder() { - return !orders.isEmpty(); - } + /** + * @return true if has order + */ + public boolean hasOrder() { + return !orders.isEmpty(); + } - /** - * @return true if has no order - */ - public boolean hasNoOrder() { - return orders.isEmpty(); - } + /** + * @return true if has no order + */ + public boolean hasNoOrder() { + return orders.isEmpty(); + } /** * get ext data @@ -447,7 +447,7 @@ public class Search implements Serializable { * @return data */ @SuppressWarnings("unchecked") - public T getExt(String name) { + public T getExt(String name) { return (T) ext.get(name); } @@ -458,44 +458,44 @@ public class Search implements Serializable { * @return this */ public Search setExt(String name, Object value) { - ext.put(name, value); + ext.put(name, value); return this; } - // -- - // private methods + // -- + // private methods - /** - * @param col col name - * @param direction direction - * @return this - */ - Search order(String col, String direction) { - Assert.hasText(col, "Order Column Could Not Be Blank"); - orders.put(col, direction); - return this; - } + /** + * @param col col name + * @param direction direction + * @return this + */ + Search order(String col, String direction) { + Assert.hasText(col, "Order Column Could Not Be Blank"); + orders.put(col, direction); + return this; + } - List assemble(boolean subSearch) { - List result = new LinkedList(); - SearchProcessArgs args = new SearchProcessArgs(table, result); + List assemble(boolean subSearch) { + List result = new LinkedList(); + SearchProcessArgs args = new SearchProcessArgs(table, result); for (Criterion condition : criteria) { args.setCondition(condition); for (SearchProcessor processor : PROCESSORS) { - if (processor.accept(args)) { - processor.process(args); - break; - } + if (processor.accept(args)) { + processor.process(args); + break; + } } if (!args.isHasPrevCol()) { args.setHasPrevCol(true); } } - if (subSearch && criteria.size() > 1) { - result.add(0, new SqlFragment("(")); - result.add(new SqlFragment(")")); + if (subSearch && criteria.size() > 1) { + result.add(0, new SqlFragment("(")); + result.add(new SqlFragment(")")); } return result; - } + } } diff --git a/tigon-model/src/main/java/me/chyxion/tigon/util/WordUtils.java b/tigon-model/src/main/java/me/chyxion/tigon/util/WordUtils.java index 1af53c2..c7a398d 100644 --- a/tigon-model/src/main/java/me/chyxion/tigon/util/WordUtils.java +++ b/tigon-model/src/main/java/me/chyxion/tigon/util/WordUtils.java @@ -11,10 +11,10 @@ import org.apache.commons.lang3.StringUtils; */ public class WordUtils { - /** - * split Camel Case - *
-	 * nice - [nice]
+    /**
+     * split Camel Case
+     * 
+     * nice - [nice]
      * World - [World]
      * MySQL - [My SQL]
      * HTML - [HTML]
@@ -25,31 +25,31 @@ public class WordUtils {
      * 99Roses - [99 Roses]
      * DO178 - [DO178]
      * Do178 - [Do178]
-	 * 
- * @param str word - * @return split result - */ - public static String[] splitToWords(String str) { - return StringUtils.isNotBlank(str) ? - // JSONObject - JSON Object - str.split(new StringBuilder("(?<=[A-Z])(?=[A-Z][a-z])") - // MySQL - My SQL - .append("|(?<=[a-z])(?=[A-Z])") - // 99Roses -> 99 Roses - .append("|(?<=[^a-zA-Z])(?=[A-Z])") - // .append("|(?<=[^A-Z])(?=[A-Z])") - // 5s - 5 s - // .append("|(?<=[^a-zA-Z])(?=[a-z])") - // A3 - A 3 | a3 - a 3 - // .append("|(?<=[A-Za-z])(?=[^A-Za-z])") - .toString()) : - new String[]{}; - } + *
+ * @param str word + * @return split result + */ + public static String[] splitToWords(String str) { + return StringUtils.isNotBlank(str) ? + // JSONObject - JSON Object + str.split(new StringBuilder("(?<=[A-Z])(?=[A-Z][a-z])") + // MySQL - My SQL + .append("|(?<=[a-z])(?=[A-Z])") + // 99Roses -> 99 Roses + .append("|(?<=[^a-zA-Z])(?=[A-Z])") + // .append("|(?<=[^A-Z])(?=[A-Z])") + // 5s - 5 s + // .append("|(?<=[^a-zA-Z])(?=[a-z])") + // A3 - A 3 | a3 - a 3 + // .append("|(?<=[A-Za-z])(?=[^A-Za-z])") + .toString()) : + new String[]{}; + } - /** - * Join Camel Case Word - *
-	 * #convertCamelCase("nice", "_") - [nice]
+    /**
+     * Join Camel Case Word
+     * 
+     * #convertCamelCase("nice", "_") - [nice]
      * #convertCamelCase("World", "_") - [World]
      * #convertCamelCase("MySQL", "_") - [My_SQL]
      * #convertCamelCase("HTML", "_") - [HTML]
@@ -64,36 +64,36 @@ public class WordUtils {
      * #convertCamelCase("Do178", "_") - [Do_178]
      * #convertCamelCase("Do178", "-") - [Do-178]
      * ...
-	 * 
- * @param str word - * @param separator separator - * @return split result - */ - public static String convertCamelCase(String str, String separator) { - return StringUtils.join(splitToWords(str), separator); - } + *
+ * @param str word + * @param separator separator + * @return split result + */ + public static String convertCamelCase(String str, String separator) { + return StringUtils.join(splitToWords(str), separator); + } - /** - *
-	 * foo_bar - fooBar
-	 * foo,bar - fooBar
-	 * 
- * @param str word - * @param separator separator - * @return split result - */ - public static String convertToCamelCase(String str, String separator) { - String strRtn = null; - if (StringUtils.isNotBlank(str)) { - StringBuilder sbRtn = new StringBuilder(); - for (String s : str.split(separator)) { - sbRtn.append(StringUtils.capitalize(s)); - } - strRtn = sbRtn.toString(); - } - else { - strRtn = str; - } - return strRtn; - } + /** + *
+     * foo_bar - fooBar
+     * foo,bar - fooBar
+     * 
+ * @param str word + * @param separator separator + * @return split result + */ + public static String convertToCamelCase(String str, String separator) { + String strRtn = null; + if (StringUtils.isNotBlank(str)) { + StringBuilder sbRtn = new StringBuilder(); + for (String s : str.split(separator)) { + sbRtn.append(StringUtils.capitalize(s)); + } + strRtn = sbRtn.toString(); + } + else { + strRtn = str; + } + return strRtn; + } } diff --git a/tigon-model/src/test/java/me/chyxion/tigon/test/TestDriver.java b/tigon-model/src/test/java/me/chyxion/tigon/test/TestDriver.java index 498e59f..f09466c 100644 --- a/tigon-model/src/test/java/me/chyxion/tigon/test/TestDriver.java +++ b/tigon-model/src/test/java/me/chyxion/tigon/test/TestDriver.java @@ -18,39 +18,39 @@ import java.util.Arrays; * May 13, 2016 10:45:07 AM */ public class TestDriver { - private static final Logger log = - LoggerFactory.getLogger(TestDriver.class); - - @Test - public void run() { - M3 m3 = new M3(); - log.info("M3 [{}].", m3.updateMap()); - log.info("M3 [{}].", m3.cols()); - } + private static final Logger log = + LoggerFactory.getLogger(TestDriver.class); + + @Test + public void run() { + M3 m3 = new M3(); + log.info("M3 [{}].", m3.updateMap()); + log.info("M3 [{}].", m3.cols()); + } - @Test - public void runSearch() { - Search search = new Search(1).eq("name", 2).or("gender", "F").or("gender", "M"); - System.err.println(StringUtils.join(search.assemble(), "")); - search = new Search().or( - new Search().or("Bar", "Foo") - .eq("foo", "bar") - .ne("ne_col", "1") - .ne("not_null", null) - .notNull("not_null2") + @Test + public void runSearch() { + Search search = new Search(1).eq("name", 2).or("gender", "F").or("gender", "M"); + System.err.println(StringUtils.join(search.assemble(), "")); + search = new Search().or( + new Search().or("Bar", "Foo") + .eq("foo", "bar") + .ne("ne_col", "1") + .ne("not_null", null) + .notNull("not_null2") .or(new Search().eq("sub_or0", 1).eq("sub_or2", 2)) - .in("in_col", new Object[] {"1", 2, 3}) + .in("in_col", new Object[] {"1", 2, 3}) .like("col_like", "%Shaun%") - .or("Or0", "OrValue") - .or("Or2", "OrValue2") - ).eq("name", 2).isNull("gaga"); - System.err.println(StringUtils.join(search.assemble(), "")); - } + .or("Or0", "OrValue") + .or("Or2", "OrValue2") + ).eq("name", 2).isNull("gaga"); + System.err.println(StringUtils.join(search.assemble(), "")); + } - @Test - public void runArray() { - Object array = new String[] {"1", "2"}; - System.err.println(Arrays.asList((Object[]) array)); - new Search().in("foo", new String[]{}); - } + @Test + public void runArray() { + Object array = new String[] {"1", "2"}; + System.err.println(Arrays.asList((Object[]) array)); + new Search().in("foo", new String[]{}); + } } diff --git a/tigon-model/src/test/resources/log4j2.xml b/tigon-model/src/test/resources/log4j2.xml index 9dbb8ec..4332cee 100644 --- a/tigon-model/src/test/resources/log4j2.xml +++ b/tigon-model/src/test/resources/log4j2.xml @@ -1,31 +1,31 @@ - - %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n - .logs - - - - - - + + %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n + .logs + + + - + + + + - - + + - + - - - - - - + + + + + + diff --git a/tigon-mybatis-redis-cache/pom.xml b/tigon-mybatis-redis-cache/pom.xml index 45b939b..e83ca9a 100644 --- a/tigon-mybatis-redis-cache/pom.xml +++ b/tigon-mybatis-redis-cache/pom.xml @@ -1,12 +1,12 @@ - 4.0.0 - tigon-mybatis-redis-cache - jar - Tigon MyBatis Redis Cache + 4.0.0 + tigon-mybatis-redis-cache + jar + Tigon MyBatis Redis Cache Tigon MyBatis Redis Cache @@ -16,7 +16,7 @@ ../ - + org.springframework.data spring-data-redis @@ -25,11 +25,11 @@ org.mybatis mybatis - - - junit - junit - test - - + + + junit + junit + test + + diff --git a/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/CacheTool.java b/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/CacheTool.java index abddaf3..5600134 100644 --- a/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/CacheTool.java +++ b/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/CacheTool.java @@ -11,16 +11,16 @@ import org.apache.ibatis.cache.Cache; */ public interface CacheTool { - /** - * clear cache - * @param mapper mapper - */ - void clearCache(Class mapper); - - /** - * clear cache - * @param mapper mapper - * @return cache of mapper - */ - Cache getCache(Class mapper); + /** + * clear cache + * @param mapper mapper + */ + void clearCache(Class mapper); + + /** + * clear cache + * @param mapper mapper + * @return cache of mapper + */ + Cache getCache(Class mapper); } diff --git a/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/RedisCache.java b/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/RedisCache.java index 097d325..f61ada2 100644 --- a/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/RedisCache.java +++ b/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/RedisCache.java @@ -15,111 +15,111 @@ import org.springframework.data.redis.core.ValueOperations; * Feb 23, 2016 6:03:39 PM */ public final class RedisCache implements Cache { - private static final Logger log = - LoggerFactory.getLogger(RedisCache.class); + private static final Logger log = + LoggerFactory.getLogger(RedisCache.class); - private String id; - private RedisTemplate redisTpl; - private ValueOperations valueOp; - private RedisCacheConfig config; + private String id; + private RedisTemplate redisTpl; + private ValueOperations valueOp; + private RedisCacheConfig config; - /** - * construct cache - * @param id cache id - */ - public RedisCache(String id) { - if (id == null) { - throw new IllegalArgumentException( - "Cache Instance ID Could Not Be Null"); - } - log.info("Create Redis Cache [{}].", id); - this.id = id; - config = RedisCacheConfig.getInstance(); - redisTpl = config.getRedisTpl(); - valueOp = redisTpl.opsForValue(); - } + /** + * construct cache + * @param id cache id + */ + public RedisCache(String id) { + if (id == null) { + throw new IllegalArgumentException( + "Cache Instance ID Could Not Be Null"); + } + log.info("Create Redis Cache [{}].", id); + this.id = id; + config = RedisCacheConfig.getInstance(); + redisTpl = config.getRedisTpl(); + valueOp = redisTpl.opsForValue(); + } - /** - * {@inheritDoc} - */ - public String getId() { - return id; - } + /** + * {@inheritDoc} + */ + public String getId() { + return id; + } - /** - * {@inheritDoc} - */ - public int getSize() { - log.debug("Get Cache [{}] Size.", id); - return redisTpl.keys(prefixedKey("*")).size(); - } + /** + * {@inheritDoc} + */ + public int getSize() { + log.debug("Get Cache [{}] Size.", id); + return redisTpl.keys(prefixedKey("*")).size(); + } - /** - * {@inheritDoc} - */ - public void putObject(final Object key, final Object value) { - log.debug("Put Object Key [{}], Value [{}].", key, value); - valueOp.set(prefixedKey(key), value); - } - - /** - * {@inheritDoc} - */ - public Object getObject(final Object key) { - Object value = valueOp.get(prefixedKey(key)); - log.debug("Get Object Key [{}], Value [{}].", key, value); - return value; - } - - /** - * {@inheritDoc} - */ - public Object removeObject(final Object key) { - log.debug("Remove Object Key [{}].", key); - redisTpl.delete(prefixedKey(key)); - return 1; - } - - /** - * {@inheritDoc} - */ - public void clear() { - log.debug("Clear Cache Key [{}].", id); - redisTpl.delete(redisTpl.keys(prefixedKey("*"))); - } - - /** - * {@inheritDoc} - */ - @Override - public ReadWriteLock getReadWriteLock() { - return null; - } + /** + * {@inheritDoc} + */ + public void putObject(final Object key, final Object value) { + log.debug("Put Object Key [{}], Value [{}].", key, value); + valueOp.set(prefixedKey(key), value); + } + + /** + * {@inheritDoc} + */ + public Object getObject(final Object key) { + Object value = valueOp.get(prefixedKey(key)); + log.debug("Get Object Key [{}], Value [{}].", key, value); + return value; + } + + /** + * {@inheritDoc} + */ + public Object removeObject(final Object key) { + log.debug("Remove Object Key [{}].", key); + redisTpl.delete(prefixedKey(key)); + return 1; + } + + /** + * {@inheritDoc} + */ + public void clear() { + log.debug("Clear Cache Key [{}].", id); + redisTpl.delete(redisTpl.keys(prefixedKey("*"))); + } + + /** + * {@inheritDoc} + */ + @Override + public ReadWriteLock getReadWriteLock() { + return null; + } - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "Redis Cache [" + id + "]"; - } + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "Redis Cache [" + id + "]"; + } - // -- - // private methods + // -- + // private methods - /** - * return prefixed cache key - * @param key cache key - * @return prefixed key - */ - String prefixedKey(Object key) { - return prefix() + String.valueOf(key); - } + /** + * return prefixed cache key + * @param key cache key + * @return prefixed key + */ + String prefixedKey(Object key) { + return prefix() + String.valueOf(key); + } - /** - * @return cache prefix - */ - String prefix() { - return id + ":"; - } + /** + * @return cache prefix + */ + String prefix() { + return id + ":"; + } } diff --git a/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/RedisCacheConfig.java b/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/RedisCacheConfig.java index e7463a4..0305400 100644 --- a/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/RedisCacheConfig.java +++ b/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/RedisCacheConfig.java @@ -12,33 +12,33 @@ import org.springframework.beans.factory.annotation.Autowired; * May 12, 2016 9:02:37 PM */ public class RedisCacheConfig { - @Autowired - private RedisTemplate redisTpl; - private static RedisCacheConfig instance; + @Autowired + private RedisTemplate redisTpl; + private static RedisCacheConfig instance; - @PostConstruct - void init() { - instance = this; - } + @PostConstruct + void init() { + instance = this; + } - /** - * @return cache instance - */ - public static RedisCacheConfig getInstance() { - return instance; - } + /** + * @return cache instance + */ + public static RedisCacheConfig getInstance() { + return instance; + } - /** - * @return the redisTpl - */ - public RedisTemplate getRedisTpl() { - return redisTpl; - } + /** + * @return the redisTpl + */ + public RedisTemplate getRedisTpl() { + return redisTpl; + } - /** - * @param redisTpl the redisTpl to set - */ - public void setRedisTpl(RedisTemplate redisTpl) { - this.redisTpl = redisTpl; - } + /** + * @param redisTpl the redisTpl to set + */ + public void setRedisTpl(RedisTemplate redisTpl) { + this.redisTpl = redisTpl; + } } diff --git a/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/support/CacheToolSupport.java b/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/support/CacheToolSupport.java index 4adfeee..0b5cc39 100644 --- a/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/support/CacheToolSupport.java +++ b/tigon-mybatis-redis-cache/src/main/java/me/chyxion/tigon/mybatis/cache/support/CacheToolSupport.java @@ -17,41 +17,41 @@ import org.springframework.beans.factory.annotation.Autowired; * Aug 26, 2015 10:58:58 AM */ public class CacheToolSupport implements CacheTool { - private static final Logger log = - LoggerFactory.getLogger(CacheToolSupport.class); + private static final Logger log = + LoggerFactory.getLogger(CacheToolSupport.class); - @Autowired - private SqlSessionFactory ssf; - private Configuration configuration; + @Autowired + private SqlSessionFactory ssf; + private Configuration configuration; - /** - * {@inheritDoc} - */ - @Override - public void clearCache(Class mapper) { - log.info("Clear Cache [{}].", mapper); - Cache cache = getCache(mapper); - if (cache != null) { - cache.clear(); - } - else { - log.warn("No Cache [{}] Found.", mapper); - } - } + /** + * {@inheritDoc} + */ + @Override + public void clearCache(Class mapper) { + log.info("Clear Cache [{}].", mapper); + Cache cache = getCache(mapper); + if (cache != null) { + cache.clear(); + } + else { + log.warn("No Cache [{}] Found.", mapper); + } + } - /** - * {@inheritDoc} - */ - @Override - public Cache getCache(Class mapper) { - return configuration.getCache(mapper.getName()); - } + /** + * {@inheritDoc} + */ + @Override + public Cache getCache(Class mapper) { + return configuration.getCache(mapper.getName()); + } - // -- - // private methods + // -- + // private methods - @PostConstruct - void init() { - configuration = ssf.getConfiguration(); - } -} \ No newline at end of file + @PostConstruct + void init() { + configuration = ssf.getConfiguration(); + } +} diff --git a/tigon-mybatis-redis-cache/src/test/resources/log4j2.xml b/tigon-mybatis-redis-cache/src/test/resources/log4j2.xml index 8a544c0..095dc0a 100644 --- a/tigon-mybatis-redis-cache/src/test/resources/log4j2.xml +++ b/tigon-mybatis-redis-cache/src/test/resources/log4j2.xml @@ -1,31 +1,31 @@ - - %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n - ${project.basedir}/.logs - - - - - - + + %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n + ${project.basedir}/.logs + + + - + + + + - - + + - + - - - - - - + + + + + + diff --git a/tigon-mybatis/pom.xml b/tigon-mybatis/pom.xml index 2bc2303..94cb4cd 100644 --- a/tigon-mybatis/pom.xml +++ b/tigon-mybatis/pom.xml @@ -4,11 +4,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - 4.0.0 - tigon-mybatis - jar - Tigon MyBatis - Tigon MyBatis + 4.0.0 + tigon-mybatis + jar + Tigon MyBatis + Tigon MyBatis me.chyxion.tigon @@ -17,20 +17,20 @@ ../ - + me.chyxion.tigon tigon-model - - + + org.mybatis - mybatis - - - org.mybatis - mybatis-spring - + mybatis + + + org.mybatis + mybatis-spring + org.springframework spring-context @@ -42,26 +42,26 @@ provided - - org.springframework - spring-test - test - + + org.springframework + spring-test + test + org.springframework spring-jdbc test - - junit - junit - test - - + + junit + junit + test + + com.alibaba druid test - + mysql mysql-connector-java diff --git a/tigon-mybatis/src/main/java/me/chyxion/tigon/mybatis/BaseMapper.java b/tigon-mybatis/src/main/java/me/chyxion/tigon/mybatis/BaseMapper.java index da1601b..33b6fd3 100644 --- a/tigon-mybatis/src/main/java/me/chyxion/tigon/mybatis/BaseMapper.java +++ b/tigon-mybatis/src/main/java/me/chyxion/tigon/mybatis/BaseMapper.java @@ -25,11 +25,11 @@ public interface BaseMapper> { String PARAM_COL_KEY = "col"; String PARAM_COLS_KEY = "cols"; - /** + /** * insert model - * @param model model - * @return insert result - */ + * @param model model + * @return insert result + */ int insert(@Param(PARAM_MODEL_KEY) Model model); /** diff --git a/tigon-mybatis/src/main/java/me/chyxion/tigon/mybatis/TigonSqlSessionFactoryBean.java b/tigon-mybatis/src/main/java/me/chyxion/tigon/mybatis/TigonSqlSessionFactoryBean.java index f6fb810..889612b 100644 --- a/tigon-mybatis/src/main/java/me/chyxion/tigon/mybatis/TigonSqlSessionFactoryBean.java +++ b/tigon-mybatis/src/main/java/me/chyxion/tigon/mybatis/TigonSqlSessionFactoryBean.java @@ -9,7 +9,6 @@ import java.util.ArrayList; import java.util.LinkedList; import org.w3c.dom.Document; import javax.xml.transform.*; -import java.util.concurrent.*; import org.w3c.dom.DocumentType; import lombok.extern.slf4j.Slf4j; import java.io.ByteArrayOutputStream; @@ -58,96 +57,76 @@ public class TigonSqlSessionFactoryBean extends SqlSessionFactoryBean { /** * {@inheritDoc} */ - @Override - public void setMapperLocations(final Resource[] mapperLocations) { + @Override + public void setMapperLocations(final Resource[] mapperLocations) { if (mapperLocations != null && mapperLocations.length > 0) { - final ExecutorService updateMapperXmlExeService = - Executors.newFixedThreadPool(mapperLocations.length); - final List> updateMapperXmlFutures = - new ArrayList>(mapperLocations.length); - final XMLMapperEntityResolver xmlMapperEntityResolver = new XMLMapperEntityResolver(); + final XMLMapperEntityResolver xmlMapperEntityResolver = + new XMLMapperEntityResolver(); + final List updatedMapperLocations = + new ArrayList(mapperLocations.length); // update mapper xml in thread for (final Resource mapperLocation : mapperLocations) { - updateMapperXmlFutures.add(updateMapperXmlExeService.submit(new Callable() { - @Override - public Resource call() throws Exception { - return updateMapperXml(xmlMapperEntityResolver, mapperLocation); - } - })); + updatedMapperLocations.add(updateMapperXml(xmlMapperEntityResolver, mapperLocation)); } - - final List updatedMapperLocations = - new ArrayList(mapperLocations.length); - try { - for (Future future : updateMapperXmlFutures) { - updatedMapperLocations.add(future.get()); - } - } - catch (Exception e) { - throw new IllegalStateException( - "Update MyBatis Mapper Error Caused", e); - } - updateMapperXmlExeService.shutdown(); super.setMapperLocations(updatedMapperLocations.toArray(mapperLocations)); } - } + } - /** - * {@inheritDoc} - */ - @Override - protected SqlSessionFactory buildSqlSessionFactory() throws IOException { - // this.setMapperLocations(); - SqlSessionFactory ssf = super.buildSqlSessionFactory(); - Configuration config = ssf.getConfiguration(); - config.setMapUnderscoreToCamelCase(true); - config.addInterceptor(new KeyGenInterceptor()); - // tigon mapper - Resource mapperLocation = - findResource("classpath*:__tigon_mybatis__.xml"); - XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), - config, mapperLocation.toString(), config.getSqlFragments()); - xmlMapperBuilder.parse(); + /** + * {@inheritDoc} + */ + @Override + protected SqlSessionFactory buildSqlSessionFactory() throws IOException { + SqlSessionFactory ssf = super.buildSqlSessionFactory(); + Configuration config = ssf.getConfiguration(); + config.setMapUnderscoreToCamelCase(true); + config.addInterceptor(new KeyGenInterceptor()); + // tigon mapper + Resource mapperLocation = + findResource("classpath*:__tigon_mybatis__.xml"); + XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), + config, mapperLocation.toString(), config.getSqlFragments()); + xmlMapperBuilder.parse(); return ssf; } - // -- - // private methods + // -- + // private methods - /** - * find resource by path - * @param path path - * @return resource - */ - private Resource findResource(String path) { - Resource resource = null; - Resource[] resources = null; - try { - resources = new PathMatchingResourcePatternResolver() - .getResources(path); - } - catch (Exception e) { - throw new IllegalStateException( - "Find Resource [" + path + "] Error Caused", e); - } - if (resources.length == 0) { - throw new IllegalStateException( - "No Resource [" + path + "] Found"); - } - else if (resources.length == 1) { - resource = resources[0]; - log.info("Resource [{}] Of Path [{}] Found.", resource, path); - } - else { - throw new IllegalStateException("Multiple Resources [" - + org.apache.commons.lang3.StringUtils.join(resources, ", ") - + "] Of Path [" + path + "] Found"); - } - return resource; - } + /** + * find resource by path + * @param path path + * @return resource + */ + private Resource findResource(String path) { + Resource resource = null; + Resource[] resources = null; + try { + resources = new PathMatchingResourcePatternResolver() + .getResources(path); + } + catch (Exception e) { + throw new IllegalStateException( + "Find Resource [" + path + "] Error Caused", e); + } + if (resources.length == 0) { + throw new IllegalStateException( + "No Resource [" + path + "] Found"); + } + else if (resources.length == 1) { + resource = resources[0]; + log.info("Resource [{}] Of Path [{}] Found.", resource, path); + } + else { + throw new IllegalStateException("Multiple Resources [" + + org.apache.commons.lang3.StringUtils.join(resources, ", ") + + "] Of Path [" + path + "] Found"); + } + return resource; + } - private Class getMapperClass(String name) { - Class mapperClassRtn = null; + private Class getMapperClass(String name) { + Class mapperClassRtn = null; try { Class classFound = ClassUtils.forName(name, ClassUtils.getDefaultClassLoader()); @@ -161,128 +140,128 @@ public class TigonSqlSessionFactoryBean extends SqlSessionFactoryBean { return mapperClassRtn; } - private Transformer newTransformer() { - try { - return TransformerFactory.newInstance().newTransformer(); - } - catch (TransformerConfigurationException e) { - throw new IllegalStateException( - "Create XML Transformer Error Caused", e); - } - } + private Transformer newTransformer() { + try { + return TransformerFactory.newInstance().newTransformer(); + } + catch (TransformerConfigurationException e) { + throw new IllegalStateException( + "Create XML Transformer Error Caused", e); + } + } - private Resource updateMapperXml( + private Resource updateMapperXml( final XMLMapperEntityResolver xmlMapperEntityResolver, final Resource mapperLocation) { - InputStream inputStream = null; - try { - Resource mapperResourceUpdated = null; - inputStream = mapperLocation.getInputStream(); - final XPathParser xPathParser = + InputStream inputStream = null; + try { + Resource mapperResourceUpdated = null; + inputStream = mapperLocation.getInputStream(); + final XPathParser xPathParser = new XPathParser(inputStream, false, null, xmlMapperEntityResolver); - final String mapperNamespace = + final String mapperNamespace = xPathParser.evalString("/mapper/@namespace"); - if (StringUtils.isNotBlank(mapperNamespace)) { - final Class mapperClass = + if (StringUtils.isNotBlank(mapperNamespace)) { + final Class mapperClass = getMapperClass(mapperNamespace); - if (mapperClass != null) { - MetaObject metaXpp = SystemMetaObject.forObject(xPathParser); - Document doc = (Document) metaXpp.getValue("document"); - boolean updated = false; - for (MapperXmlProcessor mapperXmlProcessor : MAPPER_XML_PROCESSORS) { - if (mapperXmlProcessor.accept(mapperClass, xPathParser)) { - mapperXmlProcessor.process(mapperClass, doc); - updated = true; - } - } - if (updated) { - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final DocumentType docType = doc.getDoctype(); - final Transformer transformer = newTransformer(); - transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, + if (mapperClass != null) { + MetaObject metaXpp = SystemMetaObject.forObject(xPathParser); + Document doc = (Document) metaXpp.getValue("document"); + boolean updated = false; + for (MapperXmlProcessor mapperXmlProcessor : MAPPER_XML_PROCESSORS) { + if (mapperXmlProcessor.accept(mapperClass, xPathParser)) { + mapperXmlProcessor.process(mapperClass, doc); + updated = true; + } + } + if (updated) { + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final DocumentType docType = doc.getDoctype(); + final Transformer transformer = newTransformer(); + transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId()); - transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, + transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId()); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.transform(new DOMSource(doc), new StreamResult(baos)); - mapperResourceUpdated = new TigonMapperResource(baos.toByteArray(), mapperLocation); - log.info("Tigon MyBatis Mapper [{}] Updated Result [{}].", mapperResourceUpdated, baos); - } - } - } - return mapperResourceUpdated != null ? mapperResourceUpdated : mapperLocation; - } - catch (IOException e) { - throw new IllegalStateException( - "Read MyBatis Mapper Resource [" + mapperLocation + "] Error Caused", e); - } - catch (TransformerException e) { - throw new IllegalStateException( - "Transform MyBatis Mapper Resource [" + mapperLocation + "] Error Caused", e); - } - finally { - if (inputStream != null) { - try { - inputStream.close(); - } - catch (IOException e) { - log.warn("Close MyBatis Mapper Resource [{}] Input Stream Error Caused.", - mapperLocation, e); - } - } - } - } + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.transform(new DOMSource(doc), new StreamResult(baos)); + mapperResourceUpdated = new TigonMapperResource(baos.toByteArray(), mapperLocation); + log.info("Tigon MyBatis Mapper [{}] Updated Result [{}].", mapperResourceUpdated, baos); + } + } + } + return mapperResourceUpdated != null ? mapperResourceUpdated : mapperLocation; + } + catch (IOException e) { + throw new IllegalStateException( + "Read MyBatis Mapper Resource [" + mapperLocation + "] Error Caused", e); + } + catch (TransformerException e) { + throw new IllegalStateException( + "Transform MyBatis Mapper Resource [" + mapperLocation + "] Error Caused", e); + } + finally { + if (inputStream != null) { + try { + inputStream.close(); + } + catch (IOException e) { + log.warn("Close MyBatis Mapper Resource [{}] Input Stream Error Caused.", + mapperLocation, e); + } + } + } + } - static class TigonMapperResource extends ByteArrayResource { - private final Resource originResource; + static class TigonMapperResource extends ByteArrayResource { + private final Resource originResource; - public TigonMapperResource(byte[] byteArray, Resource originResource) { - super(byteArray); - this.originResource = originResource; - } + public TigonMapperResource(byte[] byteArray, Resource originResource) { + super(byteArray); + this.originResource = originResource; + } - /** - * {@inheritDoc} - * for JRebel monitor file - */ - @Override - public URL getURL() throws IOException { - return originResource.getURL(); - } + /** + * {@inheritDoc} + * for JRebel monitor file + */ + @Override + public URL getURL() throws IOException { + return originResource.getURL(); + } - /** - * {@inheritDoc} - * for JRebel monitor file - */ - @Override - public File getFile() throws IOException { - return originResource.getFile(); - } + /** + * {@inheritDoc} + * for JRebel monitor file + */ + @Override + public File getFile() throws IOException { + return originResource.getFile(); + } - /** - * {@inheritDoc} - */ - @Override - public String getFilename() { - return originResource.getFilename(); - } + /** + * {@inheritDoc} + */ + @Override + public String getFilename() { + return originResource.getFilename(); + } - /** - * {@inheritDoc} - */ - @Override - public String getDescription() { - return "[TIGON] " + originResource.getDescription(); - } + /** + * {@inheritDoc} + */ + @Override + public String getDescription() { + return "[TIGON] " + originResource.getDescription(); + } - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "[TIGON] " + originResource.toString(); - } - } + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "[TIGON] " + originResource.toString(); + } + } } diff --git a/tigon-mybatis/src/main/resources/__tigon_mybatis__.xml b/tigon-mybatis/src/main/resources/__tigon_mybatis__.xml index 7ee1e40..d14ddf4 100644 --- a/tigon-mybatis/src/main/resources/__tigon_mybatis__.xml +++ b/tigon-mybatis/src/main/resources/__tigon_mybatis__.xml @@ -1,12 +1,12 @@ + "-//mybatis.org//DTD Mapper 3.0//EN" + "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > - - + + where @@ -21,7 +21,7 @@ where = #{s} - + @@ -75,7 +75,7 @@ - + insert into @@ -122,11 +122,11 @@ - + - + update @@ -153,7 +153,7 @@ where = #{__primary_key_value__} - + @@ -176,31 +176,31 @@ - - delete from + + delete from - - + + - + select from - - + + - + select from - - + + diff --git a/tigon-mybatis/src/test/java/me/chyxion/tigon/mybatis/test/AppMapperTest.java b/tigon-mybatis/src/test/java/me/chyxion/tigon/mybatis/test/AppMapperTest.java index ea318cd..b6ae0ba 100644 --- a/tigon-mybatis/src/test/java/me/chyxion/tigon/mybatis/test/AppMapperTest.java +++ b/tigon-mybatis/src/test/java/me/chyxion/tigon/mybatis/test/AppMapperTest.java @@ -27,50 +27,50 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration("classpath*:spring/spring-*.xml") public class AppMapperTest // extends AbstractTransactionalJUnit4SpringContextTests { - @Autowired - private AppMapper mapper; + @Autowired + private AppMapper mapper; @Autowired private ActivityMapper activityMapper; - @Test - public void mapperTest() { - // String id = String.valueOf(new Date().getTime()); - // init model + @Test + public void mapperTest() { + // String id = String.valueOf(new Date().getTime()); + // init model - App m = newApp(); - App m2 = newApp(); - // m.setCreatedBy("chyxion"); - // mapper.insertApp(Arrays.asList(m, m2)); - mapper.insert(Arrays.asList(m, m2)); - App m3 = newApp(); - mapper.insert(m3); - App m4 = newApp(); - App m5 = newApp(); - mapper.insert(new App[] {m4, m5}); - // Assert.assertTrue(mapper.list(null).size() > 0); - System.err.println(m); - System.err.println(m2); - System.err.println(m3); - System.err.println(m4); - System.err.println(m5); + App m = newApp(); + App m2 = newApp(); + // m.setCreatedBy("chyxion"); + // mapper.insertApp(Arrays.asList(m, m2)); + mapper.insert(Arrays.asList(m, m2)); + App m3 = newApp(); + mapper.insert(m3); + App m4 = newApp(); + App m5 = newApp(); + mapper.insert(new App[] {m4, m5}); + // Assert.assertTrue(mapper.list(null).size() > 0); + System.err.println(m); + System.err.println(m2); + System.err.println(m3); + System.err.println(m4); + System.err.println(m5); for (App app : mapper.list(null)) { System.err.println(app); } } - App newApp() { - App m = new App(); - m.setCreatedBy("donghuang"); - m.setDateCreated(new Date()); - m.setName("s"); - m.setHoldingDate(new Date()); - m.setEnabled(true); - m.setHoldingPlace("s"); - return m; - } + App newApp() { + App m = new App(); + m.setCreatedBy("donghuang"); + m.setDateCreated(new Date()); + m.setName("s"); + m.setHoldingDate(new Date()); + m.setEnabled(true); + m.setHoldingPlace("s"); + return m; + } - @Test - public void testFind() { + @Test + public void testFind() { App app = mapper.find(1L); System.err.println(app); app = mapper.find(new Search().eq(App.NAME, "s1").desc(App.NAME).offset(0).limit(1)); @@ -84,7 +84,7 @@ public class AppMapperTest // extends AbstractTransactionalJUnit4SpringContextTe @Test public void testCount() { - // System.err.println(mapper.count(null)); + // System.err.println(mapper.count(null)); System.err.println(activityMapper.count(new Search(3))); System.err.println(mapper.count(new Search(3))); System.err.println(mapper.count(new Search().gt(App.ID, 1).limit(3).desc(App.NAME))); diff --git a/tigon-mybatis/src/test/java/me/chyxion/tigon/mybatis/test/model/Activity.java b/tigon-mybatis/src/test/java/me/chyxion/tigon/mybatis/test/model/Activity.java index 9005977..225a23d 100644 --- a/tigon-mybatis/src/test/java/me/chyxion/tigon/mybatis/test/model/Activity.java +++ b/tigon-mybatis/src/test/java/me/chyxion/tigon/mybatis/test/model/Activity.java @@ -28,7 +28,7 @@ public class Activity extends M3 { public static final String HOLDING_PLACE = "holding_place"; // Properties - private String name; - private Date holdingDate; - private String holdingPlace; + private String name; + private Date holdingDate; + private String holdingPlace; } diff --git a/tigon-mybatis/src/test/java/me/chyxion/tigon/mybatis/test/model/App.java b/tigon-mybatis/src/test/java/me/chyxion/tigon/mybatis/test/model/App.java index c42f569..8e14d04 100644 --- a/tigon-mybatis/src/test/java/me/chyxion/tigon/mybatis/test/model/App.java +++ b/tigon-mybatis/src/test/java/me/chyxion/tigon/mybatis/test/model/App.java @@ -27,7 +27,7 @@ public class App extends M3 { public static final String HOLDING_PLACE = "holding_place"; // Properties - private String name; - private Date holdingDate; - private String holdingPlace; + private String name; + private Date holdingDate; + private String holdingPlace; } diff --git a/tigon-mybatis/src/test/resources/log4j2.xml b/tigon-mybatis/src/test/resources/log4j2.xml index 56a323c..f1cc9d1 100644 --- a/tigon-mybatis/src/test/resources/log4j2.xml +++ b/tigon-mybatis/src/test/resources/log4j2.xml @@ -1,31 +1,31 @@ - - %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n - .logs - - - - - - + + %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n + .logs + + + - + + + + - - + + - + - - - - - - + + + + + + diff --git a/tigon-mybatis/src/test/resources/mybatis/mybatis-config.xml b/tigon-mybatis/src/test/resources/mybatis/mybatis-config.xml index 5e6851f..80a6ddd 100644 --- a/tigon-mybatis/src/test/resources/mybatis/mybatis-config.xml +++ b/tigon-mybatis/src/test/resources/mybatis/mybatis-config.xml @@ -1,6 +1,6 @@ + "http://mybatis.org/dtd/mybatis-3-config.dtd"> diff --git a/tigon-mybatis/src/test/resources/spring/spring-mybatis.xml b/tigon-mybatis/src/test/resources/spring/spring-mybatis.xml index f36adc7..1fd9784 100644 --- a/tigon-mybatis/src/test/resources/spring/spring-mybatis.xml +++ b/tigon-mybatis/src/test/resources/spring/spring-mybatis.xml @@ -1,8 +1,8 @@ - - + - - - \ No newline at end of file + p:dataSource-ref="dataSource" + p:mapperLocations="classpath*:mybatis/mappers/*-mapper.xml" /> + + + diff --git a/tigon-mybatis/src/test/resources/spring/spring-test.xml b/tigon-mybatis/src/test/resources/spring/spring-test.xml index 7817720..7b07bdc 100644 --- a/tigon-mybatis/src/test/resources/spring/spring-test.xml +++ b/tigon-mybatis/src/test/resources/spring/spring-test.xml @@ -1,11 +1,11 @@ - + diff --git a/tigon-props-config/pom.xml b/tigon-props-config/pom.xml index 5dacc91..6ae3051 100644 --- a/tigon-props-config/pom.xml +++ b/tigon-props-config/pom.xml @@ -1,50 +1,50 @@ - 4.0.0 - tigon-props-config - jar - Tigon Props Config + 4.0.0 + tigon-props-config + jar + Tigon Props Config - - me.chyxion.tigon - tigon - 0.0.1-SNAPSHOT - ../ - + + me.chyxion.tigon + tigon + 0.0.1-SNAPSHOT + ../ + - - + + org.slf4j slf4j-api - - - org.springframework - spring-context - - - javax.servlet - javax.servlet-api - provided - - - - javax.el - javax.el-api - test - - - org.springframework - spring-test - test - - - junit - junit - test - - + + + org.springframework + spring-context + + + javax.servlet + javax.servlet-api + provided + + + + javax.el + javax.el-api + test + + + org.springframework + spring-test + test + + + junit + junit + test + + diff --git a/tigon-props-config/src/main/java/me/chyxion/tigon/propsconfig/PropsConfig.java b/tigon-props-config/src/main/java/me/chyxion/tigon/propsconfig/PropsConfig.java index f56f389..8ed0e63 100644 --- a/tigon-props-config/src/main/java/me/chyxion/tigon/propsconfig/PropsConfig.java +++ b/tigon-props-config/src/main/java/me/chyxion/tigon/propsconfig/PropsConfig.java @@ -16,105 +16,105 @@ import org.slf4j.LoggerFactory; * Oct 13, 2015 11:25:55 AM */ public class PropsConfig { - private static final Logger log = - LoggerFactory.getLogger(PropsConfig.class); - public static final Properties CONFIG_PROPS = - new Properties(); - static { load(); } + private static final Logger log = + LoggerFactory.getLogger(PropsConfig.class); + public static final Properties CONFIG_PROPS = + new Properties(); + static { load(); } - /** - * get app (container/tomcat) dir - * @return app dir - */ - public static File getAppDir() { - File file = new File( - // classes - PropsConfig.class.getResource("/").getFile()) - // WEB-INF - .getParentFile() - // WebApp - .getParentFile() - // WebApps - .getParentFile() - // App - .getParentFile(); - log.info("Get App Dir [{}].", file.getAbsolutePath()); - return file; - } + /** + * get app (container/tomcat) dir + * @return app dir + */ + public static File getAppDir() { + File file = new File( + // classes + PropsConfig.class.getResource("/").getFile()) + // WEB-INF + .getParentFile() + // WebApp + .getParentFile() + // WebApps + .getParentFile() + // App + .getParentFile(); + log.info("Get App Dir [{}].", file.getAbsolutePath()); + return file; + } - // -- - // private methods + // -- + // private methods - /** - * load system config - */ - static void load() { - InputStream configIn = null; - String configPath = "/spring/config.properties"; - try { - log.info("Load Classpath Config [{}].", configPath); - configIn = PropsConfig.class - .getResourceAsStream(configPath); - if (configIn != null) { - log.info("Classpath Config [{}] Found.", configPath); - CONFIG_PROPS.load(configIn); - } - else { - log.warn("No Classpath Config [{}] Found.", configPath); - } - } - catch (Exception e) { - log.error("Load Classpath Config [{}] Error Caused.", configPath, e); - } - finally { - if (configIn != null) { - try { - configIn.close(); - } - catch (IOException e) { - log.warn("Config Input Stream Close Eroror Caused."); - } - } - } - File appDir = getAppDir(); - // load global config - load(appDir.getParentFile()); - // load app config - load(appDir); - log.debug("Config Props [{}] Loaded.", CONFIG_PROPS); - } + /** + * load system config + */ + static void load() { + InputStream configIn = null; + String configPath = "/spring/config.properties"; + try { + log.info("Load Classpath Config [{}].", configPath); + configIn = PropsConfig.class + .getResourceAsStream(configPath); + if (configIn != null) { + log.info("Classpath Config [{}] Found.", configPath); + CONFIG_PROPS.load(configIn); + } + else { + log.warn("No Classpath Config [{}] Found.", configPath); + } + } + catch (Exception e) { + log.error("Load Classpath Config [{}] Error Caused.", configPath, e); + } + finally { + if (configIn != null) { + try { + configIn.close(); + } + catch (IOException e) { + log.warn("Config Input Stream Close Eroror Caused."); + } + } + } + File appDir = getAppDir(); + // load global config + load(appDir.getParentFile()); + // load app config + load(appDir); + log.debug("Config Props [{}] Loaded.", CONFIG_PROPS); + } - static void load(File dir) { - // load from custom file - File configFile = new File(dir, "config/config.properties"); - String configPath = configFile.getAbsolutePath(); - log.info("Load Config From Path [{}].", configPath); - if (configFile.exists()) { - log.info("Config File [{}] Exists.", configPath); - InputStream configIn = null; - try { - configIn = new FileInputStream(configFile); - Properties props = new Properties(); - props.load(configIn); - log.debug("Config Props [{}] Found.", props); - CONFIG_PROPS.putAll(props); - } - catch (Exception e) { - log.error("Load Config [{}] Error Caused.", configPath, e); - } - finally { - if (configIn != null) { - try { - configIn.close(); - } - catch (IOException e) { - log.warn("Config Input Stream Close Error Caused."); - } - } - } - } - else { - log.info("Config File [{}] Does Not Exist, Ignore.", configPath); - } - } -} \ No newline at end of file + static void load(File dir) { + // load from custom file + File configFile = new File(dir, "config/config.properties"); + String configPath = configFile.getAbsolutePath(); + log.info("Load Config From Path [{}].", configPath); + if (configFile.exists()) { + log.info("Config File [{}] Exists.", configPath); + InputStream configIn = null; + try { + configIn = new FileInputStream(configFile); + Properties props = new Properties(); + props.load(configIn); + log.debug("Config Props [{}] Found.", props); + CONFIG_PROPS.putAll(props); + } + catch (Exception e) { + log.error("Load Config [{}] Error Caused.", configPath, e); + } + finally { + if (configIn != null) { + try { + configIn.close(); + } + catch (IOException e) { + log.warn("Config Input Stream Close Error Caused."); + } + } + } + } + else { + log.info("Config File [{}] Does Not Exist, Ignore.", configPath); + } + } +} diff --git a/tigon-props-config/src/main/resources/spring/servlet-spring-summer-props-config.xml b/tigon-props-config/src/main/resources/spring/servlet-spring-summer-props-config.xml index 5fe7de7..8fd7424 100644 --- a/tigon-props-config/src/main/resources/spring/servlet-spring-summer-props-config.xml +++ b/tigon-props-config/src/main/resources/spring/servlet-spring-summer-props-config.xml @@ -7,4 +7,4 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> - \ No newline at end of file + diff --git a/tigon-props-config/src/main/resources/spring/spring-summer-props-config.xml b/tigon-props-config/src/main/resources/spring/spring-summer-props-config.xml index 0b4fa4e..ada0c89 100644 --- a/tigon-props-config/src/main/resources/spring/spring-summer-props-config.xml +++ b/tigon-props-config/src/main/resources/spring/spring-summer-props-config.xml @@ -12,4 +12,4 @@ - \ No newline at end of file + diff --git a/tigon-props-config/src/test/resources/log4j.xml b/tigon-props-config/src/test/resources/log4j.xml index 3db98dd..ce75e3e 100644 --- a/tigon-props-config/src/test/resources/log4j.xml +++ b/tigon-props-config/src/test/resources/log4j.xml @@ -1,22 +1,22 @@ - - - - - - + + + + + + - - - - - - - - - + + + + + + + + + @@ -28,9 +28,9 @@ - - + + - - + + diff --git a/tigon-props-config/src/test/resources/spring/dao.xml b/tigon-props-config/src/test/resources/spring/dao.xml index dab1188..9ffa409 100644 --- a/tigon-props-config/src/test/resources/spring/dao.xml +++ b/tigon-props-config/src/test/resources/spring/dao.xml @@ -16,7 +16,7 @@ - + - - + - - - + + + - - + diff --git a/tigon-redis/pom.xml b/tigon-redis/pom.xml index 3e3720a..e8a00fa 100644 --- a/tigon-redis/pom.xml +++ b/tigon-redis/pom.xml @@ -7,7 +7,7 @@ tigon-redis jar Tigon Redis - Tigon Redis + Tigon Redis me.chyxion.tigon @@ -16,7 +16,7 @@ ../ - + org.apache.commons commons-lang3 @@ -45,22 +45,22 @@ log4j-core test - - org.springframework - spring-context + + org.springframework + spring-context ${spring.version} - test - - - org.springframework - spring-test + test + + + org.springframework + spring-test ${spring.version} - test - - - junit - junit - test - - + test + + + junit + junit + test + + diff --git a/tigon-redis/src/main/java/me/chyxion/tigon/redis/pub/PubProducer.java b/tigon-redis/src/main/java/me/chyxion/tigon/redis/pub/PubProducer.java index ed1f33c..72b19a6 100644 --- a/tigon-redis/src/main/java/me/chyxion/tigon/redis/pub/PubProducer.java +++ b/tigon-redis/src/main/java/me/chyxion/tigon/redis/pub/PubProducer.java @@ -8,18 +8,18 @@ package me.chyxion.tigon.redis.pub; * Nov 7, 2015 5:32:36 PM */ public interface PubProducer { - String PUB_QUEUE_SUFFIX = "_QUEUE"; - String MESSAGE_CHANEL = "__PUBLICATION__"; + String PUB_QUEUE_SUFFIX = "_QUEUE"; + String MESSAGE_CHANEL = "__PUBLICATION__"; - /** - * @param topic topic - * @param message message - */ - void publish(String topic, Object message); + /** + * @param topic topic + * @param message message + */ + void publish(String topic, Object message); - /** - * @param topic topic - * @param message message - */ - void publish(String topic, String message); + /** + * @param topic topic + * @param message message + */ + void publish(String topic, String message); } diff --git a/tigon-redis/src/main/java/me/chyxion/tigon/redis/pub/support/PubProducerSupport.java b/tigon-redis/src/main/java/me/chyxion/tigon/redis/pub/support/PubProducerSupport.java index 9335b54..b5b4e85 100644 --- a/tigon-redis/src/main/java/me/chyxion/tigon/redis/pub/support/PubProducerSupport.java +++ b/tigon-redis/src/main/java/me/chyxion/tigon/redis/pub/support/PubProducerSupport.java @@ -14,34 +14,34 @@ import org.springframework.data.redis.core.StringRedisTemplate; * Nov 7, 2015 5:07:50 PM */ public class PubProducerSupport - implements PubProducer { - @Autowired - private RedisTemplate redisTpl; - @Autowired - private StringRedisTemplate strRedisTpl; + implements PubProducer { + @Autowired + private RedisTemplate redisTpl; + @Autowired + private StringRedisTemplate strRedisTpl; - /** - * {@inheritDoc} - */ - @Override - public void publish(String topic, Object message) { - publish(redisTpl, topic, message); - } + /** + * {@inheritDoc} + */ + @Override + public void publish(String topic, Object message) { + publish(redisTpl, topic, message); + } - /** - * {@inheritDoc} - */ - @Override - public void publish(String topic, String message) { - publish(strRedisTpl, topic, message); - } + /** + * {@inheritDoc} + */ + @Override + public void publish(String topic, String message) { + publish(strRedisTpl, topic, message); + } - // -- - // private methods - - private void publish( - RedisTemplate redisTpl, String topic, T message) { - redisTpl.opsForList().rightPush(topic + PUB_QUEUE_SUFFIX, message); - strRedisTpl.convertAndSend(MESSAGE_CHANEL, topic); - } + // -- + // private methods + + private void publish( + RedisTemplate redisTpl, String topic, T message) { + redisTpl.opsForList().rightPush(topic + PUB_QUEUE_SUFFIX, message); + strRedisTpl.convertAndSend(MESSAGE_CHANEL, topic); + } } diff --git a/tigon-redis/src/test/java/cn/com/flaginfo/echat/redis/TestDriver.java b/tigon-redis/src/test/java/cn/com/flaginfo/echat/redis/TestDriver.java index ee82b3f..c1bec82 100644 --- a/tigon-redis/src/test/java/cn/com/flaginfo/echat/redis/TestDriver.java +++ b/tigon-redis/src/test/java/cn/com/flaginfo/echat/redis/TestDriver.java @@ -11,8 +11,8 @@ import org.junit.Test; */ public class TestDriver { - @Test - public void testHash() { - // System.err.println(new AuthConfig().hashPassword("123", "456")); - } + @Test + public void testHash() { + // System.err.println(new AuthConfig().hashPassword("123", "456")); + } } diff --git a/tigon-redis/src/test/java/cn/com/flaginfo/echat/redis/test/TestPub.java b/tigon-redis/src/test/java/cn/com/flaginfo/echat/redis/test/TestPub.java index e595a0c..b01c89a 100644 --- a/tigon-redis/src/test/java/cn/com/flaginfo/echat/redis/test/TestPub.java +++ b/tigon-redis/src/test/java/cn/com/flaginfo/echat/redis/test/TestPub.java @@ -19,15 +19,15 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ - "classpath:spring/spring-echat-redis.xml", - "classpath:spring/spring-redis-test.xml", + "classpath:spring/spring-echat-redis.xml", + "classpath:spring/spring-redis-test.xml", }) public class TestPub { - @Autowired - private PubProducer pp; + @Autowired + private PubProducer pp; - @Test - public void testRun() { - pp.publish("MESSAGE", "Hello, Redis Pub!" + new Date()); - } + @Test + public void testRun() { + pp.publish("MESSAGE", "Hello, Redis Pub!" + new Date()); + } } diff --git a/tigon-redis/src/test/java/cn/com/flaginfo/echat/redis/test/TestSub.java b/tigon-redis/src/test/java/cn/com/flaginfo/echat/redis/test/TestSub.java index 2359f5e..e62036b 100644 --- a/tigon-redis/src/test/java/cn/com/flaginfo/echat/redis/test/TestSub.java +++ b/tigon-redis/src/test/java/cn/com/flaginfo/echat/redis/test/TestSub.java @@ -15,14 +15,14 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ - "classpath:spring/spring-echat-redis.xml", - "classpath:spring/spring-redis-test.xml", - "classpath:spring/spring-redis-sub-test.xml", + "classpath:spring/spring-echat-redis.xml", + "classpath:spring/spring-redis-test.xml", + "classpath:spring/spring-redis-sub-test.xml", }) public class TestSub { - - @Test - public void testRun() { - new Scanner(System.in).next(); - } + + @Test + public void testRun() { + new Scanner(System.in).next(); + } } diff --git a/tigon-sequence/pom.xml b/tigon-sequence/pom.xml index cf1868e..a405861 100644 --- a/tigon-sequence/pom.xml +++ b/tigon-sequence/pom.xml @@ -1,43 +1,43 @@ - 4.0.0 - tigon-sequence - jar - Tigon Sequence - Tigon Sequence + 4.0.0 + tigon-sequence + jar + Tigon Sequence + Tigon Sequence - - me.chyxion.tigon - tigon - 0.0.1-SNAPSHOT - ../ - + + me.chyxion.tigon + tigon + 0.0.1-SNAPSHOT + ../ + - + org.mongodb bson - - - org.springframework - spring-test - test - - - org.springframework - spring-context - test - - - junit - junit - test - + + + org.springframework + spring-test + test + + + org.springframework + spring-context + test + + + junit + junit + test + org.apache.logging.log4j log4j-slf4j-impl @@ -48,5 +48,5 @@ log4j-core test - + diff --git a/tigon-sequence/src/main/java/me/chyxion/tigon/sequence/IdSequence.java b/tigon-sequence/src/main/java/me/chyxion/tigon/sequence/IdSequence.java index ed03d29..347a600 100644 --- a/tigon-sequence/src/main/java/me/chyxion/tigon/sequence/IdSequence.java +++ b/tigon-sequence/src/main/java/me/chyxion/tigon/sequence/IdSequence.java @@ -8,9 +8,9 @@ package me.chyxion.tigon.sequence; * Nov 23, 2016 3:01:53 PM */ public interface IdSequence { - - /** - * @return id - */ - String get(); + + /** + * @return id + */ + String get(); } diff --git a/tigon-sequence/src/main/java/me/chyxion/tigon/sequence/support/IdSequenceSupport.java b/tigon-sequence/src/main/java/me/chyxion/tigon/sequence/support/IdSequenceSupport.java index dc52143..67e64ae 100644 --- a/tigon-sequence/src/main/java/me/chyxion/tigon/sequence/support/IdSequenceSupport.java +++ b/tigon-sequence/src/main/java/me/chyxion/tigon/sequence/support/IdSequenceSupport.java @@ -12,10 +12,10 @@ import me.chyxion.tigon.sequence.IdSequence; */ public class IdSequenceSupport implements IdSequence { - /** - * {@inheritDoc} - */ - public String get() { - return ObjectId.get().toHexString(); - } + /** + * {@inheritDoc} + */ + public String get() { + return ObjectId.get().toHexString(); + } } diff --git a/tigon-sequence/src/main/resources/spring/spring-summer-sequence.xml b/tigon-sequence/src/main/resources/spring/spring-summer-sequence.xml index 56f2fc2..e3f5f08 100644 --- a/tigon-sequence/src/main/resources/spring/spring-summer-sequence.xml +++ b/tigon-sequence/src/main/resources/spring/spring-summer-sequence.xml @@ -3,5 +3,5 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - - \ No newline at end of file + + diff --git a/tigon-sequence/src/test/java/me/chyxion/tigon/sequence/TestDriver.java b/tigon-sequence/src/test/java/me/chyxion/tigon/sequence/TestDriver.java index d9b5745..f43dce7 100644 --- a/tigon-sequence/src/test/java/me/chyxion/tigon/sequence/TestDriver.java +++ b/tigon-sequence/src/test/java/me/chyxion/tigon/sequence/TestDriver.java @@ -15,16 +15,16 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ - "classpath*:spring/spring-*.xml", - // "classpath*:spring/servlet-spring-*.xml" + "classpath*:spring/spring-*.xml", + // "classpath*:spring/servlet-spring-*.xml" }) public class TestDriver { - @Autowired - private IdSequence idSeq; + @Autowired + private IdSequence idSeq; - @Test - public void testIdSequence() { - System.err.println(idSeq.get()); - } + @Test + public void testIdSequence() { + System.err.println(idSeq.get()); + } } diff --git a/tigon-sequence/src/test/resources/log4j2.xml b/tigon-sequence/src/test/resources/log4j2.xml index 9dbb8ec..4332cee 100644 --- a/tigon-sequence/src/test/resources/log4j2.xml +++ b/tigon-sequence/src/test/resources/log4j2.xml @@ -1,31 +1,31 @@ - - %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n - .logs - - - - - - + + %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n + .logs + + + - + + + + - - + + - + - - - - - - + + + + + + diff --git a/tigon-service-api/pom.xml b/tigon-service-api/pom.xml index 0ca1005..3698f70 100644 --- a/tigon-service-api/pom.xml +++ b/tigon-service-api/pom.xml @@ -7,7 +7,7 @@ tigon-service-api jar Tigon Service API - Tigon Servic API + Tigon Servic API me.chyxion.tigon @@ -16,20 +16,20 @@ ../ - + me.chyxion.tigon tigon-model - - org.springframework - spring-context - + + org.springframework + spring-context + - - junit - junit - test - - + + junit + junit + test + + diff --git a/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseCrudByFormService.java b/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseCrudByFormService.java index e44720c..8165761 100644 --- a/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseCrudByFormService.java +++ b/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseCrudByFormService.java @@ -16,23 +16,23 @@ import javax.validation.constraints.NotNull; * Jun 21, 2016 10:02:10 AM */ public interface BaseCrudByFormService - , - FormForCreate extends BaseFormForCreateApi, - FormForUpdate extends BaseFormForUpdateApi> - extends BaseCrudService, - BaseQueryService, - BaseDeleteService { + , + FormForCreate extends BaseFormForCreateApi, + FormForUpdate extends BaseFormForUpdateApi> + extends BaseCrudService, + BaseQueryService, + BaseDeleteService { - /** - * @param form form - * @return view model - */ - @NotNull ViewModel create(@NotNull @Valid FormForCreate form); + /** + * @param form form + * @return view model + */ + @NotNull ViewModel create(@NotNull @Valid FormForCreate form); - /** - * @param form form - * @return view model - */ - @NotNull ViewModel update(@NotNull @Valid FormForUpdate form); + /** + * @param form form + * @return view model + */ + @NotNull ViewModel update(@NotNull @Valid FormForUpdate form); } diff --git a/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseCrudService.java b/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseCrudService.java index ef32645..f933d0d 100644 --- a/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseCrudService.java +++ b/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseCrudService.java @@ -18,35 +18,35 @@ import org.hibernate.validator.constraints.NotEmpty; * Jun 21, 2016 10:02:10 AM */ public interface BaseCrudService - > - extends BaseQueryService, - BaseDeleteService { + > + extends BaseQueryService, + BaseDeleteService { - /** - * @param model form - * @return view model - */ - @NotNull ViewModel create(@NotNull Model model); + /** + * @param model form + * @return view model + */ + @NotNull ViewModel create(@NotNull Model model); - /** - * create model - * @param models model - */ - Collection> create(@NotEmpty Collection models); + /** + * create model + * @param models model + */ + Collection> create(@NotEmpty Collection models); - /** - * @param model model - * @return view model - */ - @NotNull ViewModel update(@NotNull Model model); + /** + * @param model model + * @return view model + */ + @NotNull ViewModel update(@NotNull Model model); - /** - * update model by search - * @param model model sample - * @param search search - * @return updated rows - */ - int update(@NotNull Model model, @NotNull Search search); + /** + * update model by search + * @param model model sample + * @param search search + * @return updated rows + */ + int update(@NotNull Model model, @NotNull Search search); /** * update model by primary key @@ -56,11 +56,11 @@ public interface BaseCrudService */ int update(@NotEmpty Map model, @NotNullOrBlank PrimaryKey primaryKey); - /** - * update model by search - * @param model update map - * @param search search - * @return updated rows - */ - int update(@NotEmpty Map model, @NotNull Search search); + /** + * update model by search + * @param model update map + * @param search search + * @return updated rows + */ + int update(@NotEmpty Map model, @NotNull Search search); } diff --git a/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseDeleteService.java b/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseDeleteService.java index a1a44e9..3037e2d 100644 --- a/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseDeleteService.java +++ b/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseDeleteService.java @@ -15,15 +15,15 @@ import me.chyxion.tigon.validation.annotation.NotNullOrBlank; @Validated public interface BaseDeleteService { - /** - * delete by search - * @param search search - */ - int delete(@NotNull Search search); - - /** - * delete by primaryKey - * @param primaryKey primaryKey - */ - int delete(@NotNullOrBlank PrimaryKey primaryKey); + /** + * delete by search + * @param search search + */ + int delete(@NotNull Search search); + + /** + * delete by primaryKey + * @param primaryKey primaryKey + */ + int delete(@NotNullOrBlank PrimaryKey primaryKey); } diff --git a/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseQueryService.java b/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseQueryService.java index 20ebf61..5261dd7 100644 --- a/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseQueryService.java +++ b/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseQueryService.java @@ -19,100 +19,100 @@ import me.chyxion.tigon.validation.annotation.NotNullOrBlank; */ @Validated public interface BaseQueryService> - extends BaseService { + Model extends BaseModel> + extends BaseService { - /** - * find view model by search - * @param search search - * @return view model - */ - ViewModel findViewModel(@NotNull Search search); + /** + * find view model by search + * @param search search + * @return view model + */ + ViewModel findViewModel(@NotNull Search search); - /** - * find view model by primaryKey - * @param primaryKey primaryKey - * @return view model - */ - ViewModel findViewModel(@NotNull PrimaryKey primaryKey); + /** + * find view model by primaryKey + * @param primaryKey primaryKey + * @return view model + */ + ViewModel findViewModel(@NotNull PrimaryKey primaryKey); - /** - * list view model - * @param search search - * @return view model - */ - @NotNull List> listViewModels(@NotNull Search search); + /** + * list view model + * @param search search + * @return view model + */ + @NotNull List> listViewModels(@NotNull Search search); - /** - * list view model page - * @param search search - * @return view model page - */ - @NotNull ListResult> listViewModelsPage(@NotNull Search search); - - /** - * find model by primaryKey - * @param primaryKey model primaryKey - * @return model - */ - Model find(@NotNullOrBlank PrimaryKey primaryKey); + /** + * list view model page + * @param search search + * @return view model page + */ + @NotNull ListResult> listViewModelsPage(@NotNull Search search); + + /** + * find model by primaryKey + * @param primaryKey model primaryKey + * @return model + */ + Model find(@NotNullOrBlank PrimaryKey primaryKey); - /** - * find model by search - * @param search search - * @return result - */ - Model find(@NotNull Search search); + /** + * find model by search + * @param search search + * @return result + */ + Model find(@NotNull Search search); - /** - * list by search - * @param search search - * @return list result - */ - @NotNull List list(Search search); + /** + * list by search + * @param search search + * @return list result + */ + @NotNull List list(Search search); - /** - * list page by search - * @param search search - * @return list result - */ - @NotNull ListResult listPage(@NotNull Search search); + /** + * list page by search + * @param search search + * @return list result + */ + @NotNull ListResult listPage(@NotNull Search search); - /** - * count by search - * @param search search - * @return count - */ - int count(Search search); - - /** - * scan model of all - * @param scanner scanner - */ - Model scan(@NotNull Scanner scanner); - - /** - * scan model by search - * @param search search - * @param scanner scanner - */ - Model scan(Search search, @NotNull Scanner scanner); - - /** - * scan model by search - * @param batchSize fetch model batch size - * @param search search - * @param scanner scanner - */ - Model scan(@Min(1) int batchSize, Search search, @NotNull Scanner scanner); + /** + * count by search + * @param search search + * @return count + */ + int count(Search search); + + /** + * scan model of all + * @param scanner scanner + */ + Model scan(@NotNull Scanner scanner); + + /** + * scan model by search + * @param search search + * @param scanner scanner + */ + Model scan(Search search, @NotNull Scanner scanner); + + /** + * scan model by search + * @param batchSize fetch model batch size + * @param search search + * @param scanner scanner + */ + Model scan(@Min(1) int batchSize, Search search, @NotNull Scanner scanner); - interface Scanner { - - /** - * scan model - * @param model model - * @return false to break - */ - boolean run(T model); - } + interface Scanner { + + /** + * scan model + * @param model model + * @return false to break + */ + boolean run(T model); + } } diff --git a/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseService.java b/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseService.java index bd888a9..3281e8f 100644 --- a/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseService.java +++ b/tigon-service-api/src/main/java/me/chyxion/tigon/service/BaseService.java @@ -15,17 +15,17 @@ import org.hibernate.validator.constraints.NotEmpty; */ public interface BaseService> { - /** - * model to view model - * @param model db model - * @return view model - */ - ViewModel toViewModel(@NotNull Model model); + /** + * model to view model + * @param model db model + * @return view model + */ + ViewModel toViewModel(@NotNull Model model); - /** - * model to view model - * @param models model - * @return view model - */ - List> toViewModel(@NotEmpty List models); + /** + * model to view model + * @param models model + * @return view model + */ + List> toViewModel(@NotEmpty List models); } diff --git a/tigon-service-support/pom.xml b/tigon-service-support/pom.xml index 6069459..29a9d5c 100644 --- a/tigon-service-support/pom.xml +++ b/tigon-service-support/pom.xml @@ -7,7 +7,7 @@ tigon-service-support jar Tigon Service Support - Tigon Service Support + Tigon Service Support me.chyxion.tigon @@ -16,7 +16,7 @@ ../ - + me.chyxion.tigon tigon-service-api @@ -79,5 +79,5 @@ javax.el-api test - + diff --git a/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseCrudByFormServiceSupport.java b/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseCrudByFormServiceSupport.java index 6c37cc1..9731b99 100644 --- a/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseCrudByFormServiceSupport.java +++ b/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseCrudByFormServiceSupport.java @@ -18,52 +18,52 @@ import me.chyxion.tigon.service.BaseCrudByFormService; */ @Slf4j public class BaseCrudByFormServiceSupport - , - FormForCreate extends BaseFormForCreateApi, - FormForUpdate extends BaseFormForUpdateApi, - Mapper extends BaseMapper> - extends BaseCrudServiceSupport - implements BaseCrudByFormService { + , + FormForCreate extends BaseFormForCreateApi, + FormForUpdate extends BaseFormForUpdateApi, + Mapper extends BaseMapper> + extends BaseCrudServiceSupport + implements BaseCrudByFormService { /** * {@inheritDoc} */ - @Override - public ViewModel create(FormForCreate form) { - log.debug("Create Form [{}].", form); - validate(form); - return create(form.copy(modelType)); - } + @Override + public ViewModel create(FormForCreate form) { + log.debug("Create Form [{}].", form); + validate(form); + return create(form.copy(modelType)); + } - /** - * {@inheritDoc} - */ - @Override - public ViewModel update(FormForUpdate form) { - validate(form); - PrimaryKey primaryKey = form.getId(); - Model model = find(primaryKey); - Assert.state(model != null, "No Model [" + primaryKey + "] Found"); - return update(form.copy(model)); - } - + /** + * {@inheritDoc} + */ + @Override + public ViewModel update(FormForUpdate form) { + validate(form); + PrimaryKey primaryKey = form.getId(); + Model model = find(primaryKey); + Assert.state(model != null, "No Model [" + primaryKey + "] Found"); + return update(form.copy(model)); + } + - // -- - // private methods + // -- + // private methods - /** - * validate create form - * @param form create form - */ - protected void validate(FormForCreate form) { - // For Override - } - - /** - * validate update form - * @param form update form - */ - protected void validate(FormForUpdate form) { - // For Override - } + /** + * validate create form + * @param form create form + */ + protected void validate(FormForCreate form) { + // For Override + } + + /** + * validate update form + * @param form update form + */ + protected void validate(FormForUpdate form) { + // For Override + } } diff --git a/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseCrudServiceSupport.java b/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseCrudServiceSupport.java index 6800ff3..0214e8a 100644 --- a/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseCrudServiceSupport.java +++ b/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseCrudServiceSupport.java @@ -25,38 +25,38 @@ import org.springframework.transaction.annotation.Transactional; */ @Slf4j public class BaseCrudServiceSupport - , - Mapper extends BaseMapper> - extends BaseQueryServiceSupport - implements BaseCrudService { + , + Mapper extends BaseMapper> + extends BaseQueryServiceSupport + implements BaseCrudService { - /** - * {@inheritDoc} - */ - @Override + /** + * {@inheritDoc} + */ + @Override @Transactional - public int delete(Search search) { - return mapper.delete(search); - } + public int delete(Search search) { + return mapper.delete(search); + } - /** - * {@inheritDoc} - */ - @Override - public int delete(PrimaryKey primaryKey) { - return mapper.delete(primaryKey); - } + /** + * {@inheritDoc} + */ + @Override + public int delete(PrimaryKey primaryKey) { + return mapper.delete(primaryKey); + } - /** - * {@inheritDoc} - */ - @Override - public ViewModel create(Model model) { - beforeInsert(model); - mapper.insert(model); - afterInsert(model); - return toViewModel(model); - } + /** + * {@inheritDoc} + */ + @Override + public ViewModel create(Model model) { + beforeInsert(model); + mapper.insert(model); + afterInsert(model); + return toViewModel(model); + } /** * {@inheritDoc} @@ -72,15 +72,15 @@ public class BaseCrudServiceSupport } /** - * {@inheritDoc} - */ - @Override - public ViewModel update(Model model) { - beforeUpdate(model); - mapper.update(model); - afterUpdate(model); - return toViewModel(model); - } + * {@inheritDoc} + */ + @Override + public ViewModel update(Model model) { + beforeUpdate(model); + mapper.update(model); + afterUpdate(model); + return toViewModel(model); + } /** * {@inheritDoc} @@ -88,7 +88,7 @@ public class BaseCrudServiceSupport @Override @Transactional public int update(@NotNull Model model, @NotNull Search search) { - return mapper.update(model, search); + return mapper.update(model, search); } /** @@ -109,28 +109,28 @@ public class BaseCrudServiceSupport } // -- - // private methods + // private methods - protected void beforeInsert(Model model) { - if (idType.equals(String.class) && - StringUtils.isBlank((String) model.primaryKeyValue())) { - final String id = idSeq.get(); - log.debug("Insert Model [{}] Id Is Blank, Generate [{}].", model, id); - model.primaryKeyValue((PrimaryKey) id); - } - // Hook - } + protected void beforeInsert(Model model) { + if (idType.equals(String.class) && + StringUtils.isBlank((String) model.primaryKeyValue())) { + final String id = idSeq.get(); + log.debug("Insert Model [{}] Id Is Blank, Generate [{}].", model, id); + model.primaryKeyValue((PrimaryKey) id); + } + // Hook + } - protected void afterInsert(Model model) { - // Hook - } + protected void afterInsert(Model model) { + // Hook + } - protected void beforeUpdate(Model model) { - // Hook - } + protected void beforeUpdate(Model model) { + // Hook + } - protected void afterUpdate(Model model) { - // Hook - } + protected void afterUpdate(Model model) { + // Hook + } } diff --git a/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseQueryServiceSupport.java b/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseQueryServiceSupport.java index 0045377..602ce64 100644 --- a/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseQueryServiceSupport.java +++ b/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseQueryServiceSupport.java @@ -19,13 +19,13 @@ import org.springframework.beans.factory.annotation.Value; */ @Slf4j public class BaseQueryServiceSupport - , - Mapper extends BaseMapper> - extends BaseServiceSupport + , + Mapper extends BaseMapper> + extends BaseServiceSupport implements BaseQueryService { - @Value("${default.query.batch.size:32}") - private int scanBatchSize; + @Value("${default.query.batch.size:32}") + private int scanBatchSize; /** * {@inheritDoc} @@ -36,15 +36,15 @@ public class BaseQueryServiceSupport return mapper.list(search); } - /** - * {@inheritDoc} - */ - @Override - public ListResult listPage(Search search) { + /** + * {@inheritDoc} + */ + @Override + public ListResult listPage(Search search) { log.debug("List Models Page By Search [{}], Using Mapper [{}].", search, mapper); - return new ListResult(mapper.list(search), - mapper.count(search)); - } + return new ListResult(mapper.list(search), + mapper.count(search)); + } /** * {@inheritDoc} @@ -78,101 +78,101 @@ public class BaseQueryServiceSupport this.mapper = mapper; } - /** - * {@inheritDoc} - */ - @Override - public ViewModel findViewModel(Search search) { + /** + * {@inheritDoc} + */ + @Override + public ViewModel findViewModel(Search search) { log.debug("Find View Model By Search [{}] Using Mapper [{}].", search, mapper); - Model model = mapper.find(search); - return model != null ? toViewModel(model) : null; - } + Model model = mapper.find(search); + return model != null ? toViewModel(model) : null; + } - /** - * {@inheritDoc} - */ - @Override - public ListResult> listViewModelsPage( - Search search) { + /** + * {@inheritDoc} + */ + @Override + public ListResult> listViewModelsPage( + Search search) { log.debug("List View Models Page By Search [{}] Using Mapper [{}].", search, mapper); - return new ListResult>( - listViewModels(search), - mapper.count(search)); - } + return new ListResult>( + listViewModels(search), + mapper.count(search)); + } - /** - * {@inheritDoc} - */ - @Override - public List> listViewModels(Search search) { + /** + * {@inheritDoc} + */ + @Override + public List> listViewModels(Search search) { log.debug("List View Models By Search [{}] Using Mapper [{}].", search, mapper); - return toViewModel(mapper.list(search)); - } + return toViewModel(mapper.list(search)); + } - /** - * {@inheritDoc} - */ - @Override - public ViewModel findViewModel(PrimaryKey primaryKey) { - Model model = mapper.find(primaryKey); - return model != null ? toViewModel(model) : null; - } + /** + * {@inheritDoc} + */ + @Override + public ViewModel findViewModel(PrimaryKey primaryKey) { + Model model = mapper.find(primaryKey); + return model != null ? toViewModel(model) : null; + } - /** - * {@inheritDoc} - */ - @Override - public Model find(PrimaryKey primaryKey) { - return mapper.find(primaryKey); - } + /** + * {@inheritDoc} + */ + @Override + public Model find(PrimaryKey primaryKey) { + return mapper.find(primaryKey); + } - /** - * {@inheritDoc} - */ - @Override - public Model scan(Scanner scanner) { - return scan(null, scanner); - } + /** + * {@inheritDoc} + */ + @Override + public Model scan(Scanner scanner) { + return scan(null, scanner); + } - /** - * {@inheritDoc} - */ - @Override - public Model scan(Search search, Scanner scanner) { - return scan(scanBatchSize(), search, scanner); - } + /** + * {@inheritDoc} + */ + @Override + public Model scan(Search search, Scanner scanner) { + return scan(scanBatchSize(), search, scanner); + } - /** - * {@inheritDoc} - */ - @Override - public Model scan(int batchSize, Search search, Scanner scanner) { - log.info("Scan Model By Search [{}].", search); - int total = mapper.count(search); - if (total > 0) { - if (search == null) { - log.debug("Scan Search Is Null, Use Default."); - search = new Search(); - } - for (int start = 0; start < total; start += batchSize) { - for (Model model : mapper.list( - search.offset(start) - .limit(Math.min(batchSize, total - start)))) { - if (scanner.run(model)) { - log.info("Model [{}] Found By Scanner.", model); - return model; - } - } - } - log.debug("No Matched Model Found By Scanner."); - } - else { - log.info("No Model To Scan By Search [{}].", search); - } - return null; - } + /** + * {@inheritDoc} + */ + @Override + public Model scan(int batchSize, Search search, Scanner scanner) { + log.info("Scan Model By Search [{}].", search); + int total = mapper.count(search); + if (total > 0) { + if (search == null) { + log.debug("Scan Search Is Null, Use Default."); + search = new Search(); + } + for (int start = 0; start < total; start += batchSize) { + for (Model model : mapper.list( + search.offset(start) + .limit(Math.min(batchSize, total - start)))) { + if (scanner.run(model)) { + log.info("Model [{}] Found By Scanner.", model); + return model; + } + } + } + log.debug("No Matched Model Found By Scanner."); + } + else { + log.info("No Model To Scan By Search [{}].", search); + } + return null; + } - protected int scanBatchSize() { - return scanBatchSize; - } -} \ No newline at end of file + protected int scanBatchSize() { + return scanBatchSize; + } +} diff --git a/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseServiceSupport.java b/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseServiceSupport.java index 961d071..1f3404a 100644 --- a/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseServiceSupport.java +++ b/tigon-service-support/src/main/java/me/chyxion/tigon/service/support/BaseServiceSupport.java @@ -27,76 +27,76 @@ import org.springframework.beans.factory.annotation.Autowired; @Getter @Setter public class BaseServiceSupport - , - Mapper extends BaseMapper> - implements BaseService { + , + Mapper extends BaseMapper> + implements BaseService { @Autowired protected Mapper mapper; - @Autowired - protected IdSequence idSeq; - protected Class idType; - protected Class modelType; + @Autowired + protected IdSequence idSeq; + protected Class idType; + protected Class modelType; - /** - * constructor - */ - @SuppressWarnings("unchecked") - public BaseServiceSupport() { - Class[] clazzArr = - GenericTypeResolver.resolveTypeArguments( - getClass(), - BaseServiceSupport.class); - idType = (Class) clazzArr[0]; - modelType = (Class) clazzArr[1]; - } + /** + * constructor + */ + @SuppressWarnings("unchecked") + public BaseServiceSupport() { + Class[] clazzArr = + GenericTypeResolver.resolveTypeArguments( + getClass(), + BaseServiceSupport.class); + idType = (Class) clazzArr[0]; + modelType = (Class) clazzArr[1]; + } - /** - * {@inheritDoc} - */ - @Override - public ViewModel toViewModel(Model model) { - ViewModel viewModel = - new ViewModel(model); - log.debug("Model [{}] To View Model.", model); - processViewModel(viewModel, model); - return viewModel; - } + /** + * {@inheritDoc} + */ + @Override + public ViewModel toViewModel(Model model) { + ViewModel viewModel = + new ViewModel(model); + log.debug("Model [{}] To View Model.", model); + processViewModel(viewModel, model); + return viewModel; + } - /** - * {@inheritDoc} - */ - @Override - public List> toViewModel(List models) { - List> viewModels = null; - if (models != null && !models.isEmpty()) { - viewModels = new ArrayList>(models.size()); - for (Model model : models) { - viewModels.add(toViewModel(model)); - } - } - else { - viewModels = Collections.emptyList(); - } - return viewModels; - } + /** + * {@inheritDoc} + */ + @Override + public List> toViewModel(List models) { + List> viewModels = null; + if (models != null && !models.isEmpty()) { + viewModels = new ArrayList>(models.size()); + for (Model model : models) { + viewModels.add(toViewModel(model)); + } + } + else { + viewModels = Collections.emptyList(); + } + return viewModels; + } - /** - * @param model model - * @param url url - * @return url - */ - protected String urlCacheClear(M1 model, String url) { - Date dateUpdated = model.getDateUpdated(); - return dateUpdated != null ? - url + "?_d=" + dateUpdated.getTime() : url; - } + /** + * @param model model + * @param url url + * @return url + */ + protected String urlCacheClear(M1 model, String url) { + Date dateUpdated = model.getDateUpdated(); + return dateUpdated != null ? + url + "?_d=" + dateUpdated.getTime() : url; + } - /** - * @param viewModel view model - * @param model model - */ - protected void processViewModel(ViewModel viewModel, Model model) { - // For Subclass Override - } -} \ No newline at end of file + /** + * @param viewModel view model + * @param model model + */ + protected void processViewModel(ViewModel viewModel, Model model) { + // For Subclass Override + } +} diff --git a/tigon-service-support/src/test/resources/spring/spring-mybatis.xml b/tigon-service-support/src/test/resources/spring/spring-mybatis.xml index 460444f..eed4317 100644 --- a/tigon-service-support/src/test/resources/spring/spring-mybatis.xml +++ b/tigon-service-support/src/test/resources/spring/spring-mybatis.xml @@ -1,8 +1,8 @@ - - + - - - \ No newline at end of file + p:dataSource-ref="dataSource" + p:typeAliasesPackage="me.chyxion.tigon.model" + p:mapperLocations="classpath*:mybatis/mapper/*-mapper.xml" /> + + + diff --git a/tigon-service-support/src/test/resources/spring/spring-test.xml b/tigon-service-support/src/test/resources/spring/spring-test.xml index dbfda4c..ff57710 100644 --- a/tigon-service-support/src/test/resources/spring/spring-test.xml +++ b/tigon-service-support/src/test/resources/spring/spring-test.xml @@ -1,11 +1,11 @@ - - + + diff --git a/tigon-shiro-core/pom.xml b/tigon-shiro-core/pom.xml index 8990124..5c51ddf 100644 --- a/tigon-shiro-core/pom.xml +++ b/tigon-shiro-core/pom.xml @@ -16,7 +16,7 @@ ../ - + me.chyxion.tigon tigon-sequence @@ -44,15 +44,15 @@ provided - - org.springframework - spring-test - test - - - junit - junit - test - - + + org.springframework + spring-test + test + + + junit + junit + test + + diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthCallback.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthCallback.java index 5e2915f..62b5caf 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthCallback.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthCallback.java @@ -14,11 +14,11 @@ import org.apache.shiro.authc.AuthenticationException; */ public interface AuthCallback { - /** - * @param token token - * @param info info - * @param subject subject - */ + /** + * @param token token + * @param info info + * @param subject subject + */ void onSuccessfulLogin(AuthenticationToken token, AuthenticationInfo info, Subject subject); /** diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthConfig.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthConfig.java index 4414dde..cb3a327 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthConfig.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthConfig.java @@ -11,12 +11,12 @@ import javax.servlet.Filter; * Apr 7, 2015 4:44:25 PM */ public interface AuthConfig { - String FILTER_USER = "user"; - String FILTER_FORM = "form"; - String FILTER_ANON = "anon"; - - /** - * @param filters - */ - void customizeFilters(Map filters); + String FILTER_USER = "user"; + String FILTER_FORM = "form"; + String FILTER_ANON = "anon"; + + /** + * @param filters + */ + void customizeFilters(Map filters); } diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthConfigFactory.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthConfigFactory.java index fb23b21..bc3cdab 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthConfigFactory.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthConfigFactory.java @@ -24,92 +24,92 @@ import org.springframework.beans.factory.annotation.Autowired; * Apr 7, 2015 4:44:04 PM */ public class AuthConfigFactory { - private static final Logger log = - LoggerFactory.getLogger(AuthConfigFactory.class); - @Autowired(required = false) - private AuthConfig authConfig; - @Autowired - private ResponseTool responseTool; - @Autowired - private JSONViewConfig viewConfig; - @Autowired(required = false) - private ExceptionMessage exceptionMessage; + private static final Logger log = + LoggerFactory.getLogger(AuthConfigFactory.class); + @Autowired(required = false) + private AuthConfig authConfig; + @Autowired + private ResponseTool responseTool; + @Autowired + private JSONViewConfig viewConfig; + @Autowired(required = false) + private ExceptionMessage exceptionMessage; - private UserFilterExt userFilter; + private UserFilterExt userFilter; - /** - * @return filters - */ - public Map filters() { - Map filters = new LinkedHashMap(); - filters.put(AuthConfig.FILTER_USER, userFilter); - if (authConfig != null) { - authConfig.customizeFilters(filters); - } - log.info("Auth Filters [{}].", filters); - return filters; - } + /** + * @return filters + */ + public Map filters() { + Map filters = new LinkedHashMap(); + filters.put(AuthConfig.FILTER_USER, userFilter); + if (authConfig != null) { + authConfig.customizeFilters(filters); + } + log.info("Auth Filters [{}].", filters); + return filters; + } - /** - * @return filter routings - */ - public Map filterRoutings() { - Map routings = new LinkedHashMap(); - routings.put("/assets/**", AuthConfig.FILTER_ANON); - InputStream authIn = AuthConfigFactory.class - .getResourceAsStream("/shiro/auth.properties"); - if (authIn != null) { - Properties props = new OrderedProperties(); - try { - props.load(authIn); - } - catch (IOException e) { - throw new IllegalStateException( - "Load Auth Config Error Caused", e); - } - finally { - if (authIn != null) { - try { - authIn.close(); - } - catch (IOException e) { - // ignore - } - } - } - for (String name : props.stringPropertyNames()) { - routings.put(name, props.getProperty(name)); - } - } - log.info("Auth Filter Routings [{}].", routings); - return routings; - } + /** + * @return filter routings + */ + public Map filterRoutings() { + Map routings = new LinkedHashMap(); + routings.put("/assets/**", AuthConfig.FILTER_ANON); + InputStream authIn = AuthConfigFactory.class + .getResourceAsStream("/shiro/auth.properties"); + if (authIn != null) { + Properties props = new OrderedProperties(); + try { + props.load(authIn); + } + catch (IOException e) { + throw new IllegalStateException( + "Load Auth Config Error Caused", e); + } + finally { + if (authIn != null) { + try { + authIn.close(); + } + catch (IOException e) { + // ignore + } + } + } + for (String name : props.stringPropertyNames()) { + routings.put(name, props.getProperty(name)); + } + } + log.info("Auth Filter Routings [{}].", routings); + return routings; + } /** * init */ - @PostConstruct - void init() { - userFilter = new UserFilterExt( - responseTool, viewConfig, exceptionMessage); - } + @PostConstruct + void init() { + userFilter = new UserFilterExt( + responseTool, viewConfig, exceptionMessage); + } - static class OrderedProperties extends Properties { - private static final long serialVersionUID = 1L; - private final Set keys = new LinkedHashSet(); + static class OrderedProperties extends Properties { + private static final long serialVersionUID = 1L; + private final Set keys = new LinkedHashSet(); - public Object put(Object key, Object value) { - keys.add((String) key); - return super.put(key, value); - } + public Object put(Object key, Object value) { + keys.add((String) key); + return super.put(key, value); + } - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Set keySet() { - return keys; - } + @SuppressWarnings({ "rawtypes", "unchecked" }) + public Set keySet() { + return keys; + } - public Set stringPropertyNames() { - return keys; - } - } + public Set stringPropertyNames() { + return keys; + } + } } diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthExceptionResolver.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthExceptionResolver.java index 993acd8..9068f78 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthExceptionResolver.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthExceptionResolver.java @@ -24,60 +24,60 @@ import me.chyxion.tigon.webmvc.exception.DefaultExceptionResolver; */ @Order(8) public class AuthExceptionResolver extends DefaultExceptionResolver { - - private static final Map, Pair> - EXCEPTIONS_MAP = - new HashMap, Pair>() { - private static final long serialVersionUID = 1L; - { - put(AuthenticationException.class, - pair(4010, "Authentication Exception")); - put(AuthorizationException.class, - pair(4010, "Authorization Exception")); - put(UnauthenticatedException.class, - pair(4011, "Unauthenticated")); - put(UnknownAccountException.class, - pair(4012, "Unknown Account")); - put(IncorrectCredentialsException.class, - pair(4013, "Incorrect Credentials")); - put(ExpiredCredentialsException.class, - pair(4014, "Expired Credentials")); - put(LockedAccountException.class, - pair(4015, "Locked Account")); - } + + private static final Map, Pair> + EXCEPTIONS_MAP = + new HashMap, Pair>() { + private static final long serialVersionUID = 1L; + { + put(AuthenticationException.class, + pair(4010, "Authentication Exception")); + put(AuthorizationException.class, + pair(4010, "Authorization Exception")); + put(UnauthenticatedException.class, + pair(4011, "Unauthenticated")); + put(UnknownAccountException.class, + pair(4012, "Unknown Account")); + put(IncorrectCredentialsException.class, + pair(4013, "Incorrect Credentials")); + put(ExpiredCredentialsException.class, + pair(4014, "Expired Credentials")); + put(LockedAccountException.class, + pair(4015, "Locked Account")); + } - /** - * new code msg pair - * @param code - * @param msg - * @return - */ - private Pair pair(Integer code, String msg) { - return ImmutablePair.of(code, msg); - } - }; + /** + * new code msg pair + * @param code + * @param msg + * @return + */ + private Pair pair(Integer code, String msg) { + return ImmutablePair.of(code, msg); + } + }; - /** - * {@inheritDoc} - */ - @Override - public boolean accept(Throwable ex) { - return EXCEPTIONS_MAP.containsKey(ex.getClass()); - } + /** + * {@inheritDoc} + */ + @Override + public boolean accept(Throwable ex) { + return EXCEPTIONS_MAP.containsKey(ex.getClass()); + } - /** - * {@inheritDoc} - */ - @Override - protected Object getErrorCode(Throwable ex) { - return EXCEPTIONS_MAP.get(ex.getClass()).getKey(); - } + /** + * {@inheritDoc} + */ + @Override + protected Object getErrorCode(Throwable ex) { + return EXCEPTIONS_MAP.get(ex.getClass()).getKey(); + } - /** - * {@inheritDoc} - */ - @Override - protected Object getErrorMessage(Throwable ex, Object code) { - return EXCEPTIONS_MAP.get(ex.getClass()).getValue(); - } + /** + * {@inheritDoc} + */ + @Override + protected Object getErrorMessage(Throwable ex, Object code) { + return EXCEPTIONS_MAP.get(ex.getClass()).getValue(); + } } diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthRealm.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthRealm.java index 02b956b..c262a57 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthRealm.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthRealm.java @@ -14,43 +14,43 @@ import org.apache.shiro.authc.AuthenticationToken; */ public abstract class AuthRealm { - /** - * @param principal principal - * @return roles - */ - public Collection roles(Object principal) { - return Collections.emptyList(); - } + /** + * @param principal principal + * @return roles + */ + public Collection roles(Object principal) { + return Collections.emptyList(); + } - /** - * @param principal principal - * @return permissions - */ - public Collection permissions(Object principal) { - return Collections.emptyList(); - } + /** + * @param principal principal + * @return permissions + */ + public Collection permissions(Object principal) { + return Collections.emptyList(); + } - /** - * @param principal principal - * @return credential - */ - public abstract Credential credential(Object principal); + /** + * @param principal principal + * @return credential + */ + public abstract Credential credential(Object principal); - /** + /** * for override - * @param principal principal - * @param authToken auth token - * @return credential - */ - public Credential credential(Object principal, AuthenticationToken authToken) { - return credential(principal); - } + * @param principal principal + * @param authToken auth token + * @return credential + */ + public Credential credential(Object principal, AuthenticationToken authToken) { + return credential(principal); + } - /** - * @param password password - * @param credential credential - * @return true if credential matched - */ - public abstract boolean credentialMatch(Object password, Credential credential); + /** + * @param password password + * @param credential credential + * @return true if credential matched + */ + public abstract boolean credentialMatch(Object password, Credential credential); } diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthorizingRealmSupport.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthorizingRealmSupport.java index 587079a..9e5ce4e 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthorizingRealmSupport.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/AuthorizingRealmSupport.java @@ -27,71 +27,71 @@ import org.apache.shiro.authc.credential.SimpleCredentialsMatcher; * Apr 7, 2015 3:19:12 PM */ public class AuthorizingRealmSupport extends AuthorizingRealm { - private static final Logger log = - LoggerFactory.getLogger(AuthorizingRealmSupport.class); + private static final Logger log = + LoggerFactory.getLogger(AuthorizingRealmSupport.class); - @Autowired(required = false) - private AuthRealm authRealm; + @Autowired(required = false) + private AuthRealm authRealm; - public AuthorizingRealmSupport() { - setCredentialsMatcher(new SimpleCredentialsMatcher() { - @Override - public boolean doCredentialsMatch( - AuthenticationToken authcToken, AuthenticationInfo info) { - AuthInfo authInfo = (AuthInfo) info; - return authRealm.credentialMatch( - authcToken.getCredentials(), - new Credential(authInfo.getCredentials(), - authInfo.getCredentialsSalt(), - authInfo.getExtra())); - } - }); - } + public AuthorizingRealmSupport() { + setCredentialsMatcher(new SimpleCredentialsMatcher() { + @Override + public boolean doCredentialsMatch( + AuthenticationToken authcToken, AuthenticationInfo info) { + AuthInfo authInfo = (AuthInfo) info; + return authRealm.credentialMatch( + authcToken.getCredentials(), + new Credential(authInfo.getCredentials(), + authInfo.getCredentialsSalt(), + authInfo.getExtra())); + } + }); + } - /** - * Login - * {@inheritDoc} - */ - @Override - protected AuthenticationInfo doGetAuthenticationInfo( - AuthenticationToken authToken) - throws AuthenticationException { - Object principal = authToken.getPrincipal(); + /** + * Login + * {@inheritDoc} + */ + @Override + protected AuthenticationInfo doGetAuthenticationInfo( + AuthenticationToken authToken) + throws AuthenticationException { + Object principal = authToken.getPrincipal(); Assert.state(principal != null, "Null Username Is Not Allowed"); - log.info("Login [{}].", principal); + log.info("Login [{}].", principal); - Credential credential = authRealm.credential(principal, authToken); - if (credential == null) { - throw new UnknownAccountException( - "No Account [" + principal + "] Found"); - } - return new AuthInfo(principal, credential.getCredential(), - new SerializableByteSource( - ByteSource.Util.bytes(credential.getSalt())), - getName()).setExtra(credential.getExtra()); - } + Credential credential = authRealm.credential(principal, authToken); + if (credential == null) { + throw new UnknownAccountException( + "No Account [" + principal + "] Found"); + } + return new AuthInfo(principal, credential.getCredential(), + new SerializableByteSource( + ByteSource.Util.bytes(credential.getSalt())), + getName()).setExtra(credential.getExtra()); + } - /** - * Get Permissions - * {@inheritDoc} - */ - @Override - protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { - Assert.state(principals != null, "Principals Could Not Be Null"); + /** + * Get Permissions + * {@inheritDoc} + */ + @Override + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { + Assert.state(principals != null, "Principals Could Not Be Null"); Object principal = getAvailablePrincipal(principals); - SimpleAuthorizationInfo authInfo = null; - if (principal != null) { - authInfo = new SimpleAuthorizationInfo( - new HashSet(authRealm.roles(principal))); - authInfo.addStringPermissions(authRealm.permissions(principal)); - } - return authInfo; - } + SimpleAuthorizationInfo authInfo = null; + if (principal != null) { + authInfo = new SimpleAuthorizationInfo( + new HashSet(authRealm.roles(principal))); + authInfo.addStringPermissions(authRealm.permissions(principal)); + } + return authInfo; + } - /** - * {@inheritDoc} - */ - @Override + /** + * {@inheritDoc} + */ + @Override protected Object getAuthorizationCacheKey(PrincipalCollection principals) { return getAvailablePrincipal(principals); } diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/DefaultWebSecurityManagerExt.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/DefaultWebSecurityManagerExt.java index d81e02a..8284366 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/DefaultWebSecurityManagerExt.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/DefaultWebSecurityManagerExt.java @@ -15,41 +15,41 @@ import org.springframework.beans.factory.annotation.Autowired; * Mar 12, 2015 1:18:00 PM */ public class DefaultWebSecurityManagerExt extends DefaultWebSecurityManager { - @Autowired(required = false) - private AuthCallback authCallback; + @Autowired(required = false) + private AuthCallback authCallback; - /** - * {@inheritDoc} - */ - @Override - protected void onSuccessfulLogin(AuthenticationToken token, - AuthenticationInfo info, Subject subject) { - if (authCallback != null) { - authCallback.onSuccessfulLogin(token, info, subject); - } - super.onSuccessfulLogin(token, info, subject); - } + /** + * {@inheritDoc} + */ + @Override + protected void onSuccessfulLogin(AuthenticationToken token, + AuthenticationInfo info, Subject subject) { + if (authCallback != null) { + authCallback.onSuccessfulLogin(token, info, subject); + } + super.onSuccessfulLogin(token, info, subject); + } - /** - * {@inheritDoc} - */ - @Override - protected void onFailedLogin(AuthenticationToken token, - AuthenticationException ae, Subject subject) { - if (authCallback != null) { - authCallback.onFailedLogin(token, ae, subject); - } - super.onFailedLogin(token, ae, subject); - } - - /** - * {@inheritDoc} - */ - @Override - protected void beforeLogout(Subject subject) { - if (authCallback != null) { - authCallback.beforeLogout(subject); - } - super.beforeLogout(subject); - } + /** + * {@inheritDoc} + */ + @Override + protected void onFailedLogin(AuthenticationToken token, + AuthenticationException ae, Subject subject) { + if (authCallback != null) { + authCallback.onFailedLogin(token, ae, subject); + } + super.onFailedLogin(token, ae, subject); + } + + /** + * {@inheritDoc} + */ + @Override + protected void beforeLogout(Subject subject) { + if (authCallback != null) { + authCallback.beforeLogout(subject); + } + super.beforeLogout(subject); + } } diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/DefaultWebSessionManagerExt.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/DefaultWebSessionManagerExt.java index c7ef920..576205d 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/DefaultWebSessionManagerExt.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/DefaultWebSessionManagerExt.java @@ -29,30 +29,30 @@ import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; * Apr 7, 2015 2:54:25 PM */ public class DefaultWebSessionManagerExt extends DefaultWebSessionManager { - private static final Logger log = LoggerFactory.getLogger(DefaultWebSessionManagerExt.class); - @Autowired(required = false) - private SessionIdManager sessionIdManager; - @Autowired(required = false) - private List sessionListeners; + private static final Logger log = LoggerFactory.getLogger(DefaultWebSessionManagerExt.class); + @Autowired(required = false) + private SessionIdManager sessionIdManager; + @Autowired(required = false) + private List sessionListeners; - /** - * init - */ - @PostConstruct - void init() { - if (sessionListeners == null) { - sessionListeners = new LinkedList(); - } - else { - log.info("SessionListeners [{}] Found.", sessionListeners); - } - setSessionListeners(sessionListeners); - } + /** + * init + */ + @PostConstruct + void init() { + if (sessionListeners == null) { + sessionListeners = new LinkedList(); + } + else { + log.info("SessionListeners [{}] Found.", sessionListeners); + } + setSessionListeners(sessionListeners); + } - /** - * {@inheritDoc} - */ - @Override + /** + * {@inheritDoc} + */ + @Override protected void onStart(Session session, SessionContext context) { if (!WebUtils.isHttp(context)) { log.debug("SessionContext argument is not HTTP compatible or does not have an HTTP request/response " + @@ -77,17 +77,17 @@ public class DefaultWebSessionManagerExt extends DefaultWebSessionManager { */ @Override protected Serializable getSessionId(ServletRequest request, ServletResponse response) { - Serializable sessionId = null; + Serializable sessionId = null; if (sessionIdManager != null) { - log.debug("Get Custom Session ID From Custom Session Manager."); - sessionId = sessionIdManager.read( - (HttpServletRequest) request, - (HttpServletResponse) response, - new SimpleCookie(getSessionIdCookie())); + log.debug("Get Custom Session ID From Custom Session Manager."); + sessionId = sessionIdManager.read( + (HttpServletRequest) request, + (HttpServletResponse) response, + new SimpleCookie(getSessionIdCookie())); } if (sessionId == null) { - log.debug("No Custom Session ID Found From Custom Session Manager, Get Session Id From Cookie."); - sessionId = super.getSessionId(request, response); + log.debug("No Custom Session ID Found From Custom Session Manager, Get Session Id From Cookie."); + sessionId = super.getSessionId(request, response); } return sessionId; } @@ -95,20 +95,20 @@ public class DefaultWebSessionManagerExt extends DefaultWebSessionManager { // -- // private methods - void writeSessionIdCookie(Serializable currentId, HttpServletRequest request, HttpServletResponse response) { + void writeSessionIdCookie(Serializable currentId, HttpServletRequest request, HttpServletResponse response) { Assert.notNull(currentId, "sessionId Cannot Be Null When Persisting For Subsequent Requests"); String sessionId = currentId.toString(); // copy cookie template Cookie cookie = new SimpleCookie(getSessionIdCookie()); cookie.setValue(sessionId); if (sessionIdManager != null) { - if (sessionIdManager.write(request, response, cookie)) { - log.info("Custom Session ID Mananger Write Session ID Cookie [{}] For Session [{}].", cookie, sessionId); - return; - } - else { - log.info("Custom Session ID Mananger Dose Not Write Session ID Cookie [{}] For Session [{}].", cookie, sessionId); - } + if (sessionIdManager.write(request, response, cookie)) { + log.info("Custom Session ID Mananger Write Session ID Cookie [{}] For Session [{}].", cookie, sessionId); + return; + } + else { + log.info("Custom Session ID Mananger Dose Not Write Session ID Cookie [{}] For Session [{}].", cookie, sessionId); + } } log.info("Default Write Session ID Cookie [{}] For Session [{}].", cookie, sessionId); cookie.saveTo(request, response); diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/SessionDAOSupport.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/SessionDAOSupport.java index 47284dd..047552d 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/SessionDAOSupport.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/SessionDAOSupport.java @@ -24,45 +24,45 @@ import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; * Sep 8, 2014 7:43:05 PM */ public class SessionDAOSupport extends EnterpriseCacheSessionDAO { - private static final Logger log = LoggerFactory.getLogger(SessionDAOSupport.class); - @Autowired(required = false) - private Cache sessionCache; - @Autowired - private IdSequence idSeq; + private static final Logger log = LoggerFactory.getLogger(SessionDAOSupport.class); + @Autowired(required = false) + private Cache sessionCache; + @Autowired + private IdSequence idSeq; - /** - * init session dao - */ - @PostConstruct - void init() { - if (sessionCache == null) { - log.info("No Custom Session Store Found, Use Map Cache."); - sessionCache = new MapCache( - CachingSessionDAO.ACTIVE_SESSION_CACHE_NAME, - new ConcurrentHashMap()); - } - else { - log.info("Use Custom Session Cache [{}].", sessionCache); - } + /** + * init session dao + */ + @PostConstruct + void init() { + if (sessionCache == null) { + log.info("No Custom Session Store Found, Use Map Cache."); + sessionCache = new MapCache( + CachingSessionDAO.ACTIVE_SESSION_CACHE_NAME, + new ConcurrentHashMap()); + } + else { + log.info("Use Custom Session Cache [{}].", sessionCache); + } setCacheManager(new AbstractCacheManager() { - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ @Override protected Cache createCache(String name) - throws CacheException { - log.info("Create Session Cache [{}] Result [{}].", name, sessionCache); + throws CacheException { + log.info("Create Session Cache [{}] Result [{}].", name, sessionCache); return sessionCache; } }); setSessionIdGenerator(new SessionIdGenerator() { - /** - * {@inheritDoc} - */ - @Override - public Serializable generateId(Session session) { - return idSeq.get(); - } - }); - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @Override + public Serializable generateId(Session session) { + return idSeq.get(); + } + }); + } +} diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/SessionIdManager.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/SessionIdManager.java index be5fde6..ed490e7 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/SessionIdManager.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/SessionIdManager.java @@ -13,26 +13,26 @@ import javax.servlet.http.HttpServletResponse; * Apr 7, 2015 3:34:48 PM */ public interface SessionIdManager { - - /** - * read session id from request - * @param request http request - * @param response http response - * @param cookieTpl cookie template - * @return session id - */ - Serializable read(HttpServletRequest request, - HttpServletResponse response, - Cookie cookieTpl); - - /** - * write session id to http response - * @param request http request - * @param response http response - * @param cookie cookie - * @return true if do write - */ - boolean write(HttpServletRequest request, - HttpServletResponse response, - Cookie cookie); + + /** + * read session id from request + * @param request http request + * @param response http response + * @param cookieTpl cookie template + * @return session id + */ + Serializable read(HttpServletRequest request, + HttpServletResponse response, + Cookie cookieTpl); + + /** + * write session id to http response + * @param request http request + * @param response http response + * @param cookie cookie + * @return true if do write + */ + boolean write(HttpServletRequest request, + HttpServletResponse response, + Cookie cookie); } diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/SessionListenerExt.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/SessionListenerExt.java index 948cf62..c11c478 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/SessionListenerExt.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/SessionListenerExt.java @@ -12,10 +12,10 @@ import org.apache.shiro.session.SessionListener; */ public interface SessionListenerExt extends SessionListener { - /** - * on session validation - * @param session session - * @return returns true if session has been changed - */ - boolean onValidation(Session session); + /** + * on session validation + * @param session session + * @return returns true if session has been changed + */ + boolean onValidation(Session session); } diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/UserFilterExt.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/UserFilterExt.java index f21d0c1..f79e691 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/UserFilterExt.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/UserFilterExt.java @@ -21,79 +21,79 @@ import me.chyxion.tigon.webmvc.exception.ExceptionMessage; */ @Slf4j public class UserFilterExt extends UserFilter { - protected final ResponseTool responseTool; - protected final JSONViewConfig viewConfig; - protected final ExceptionMessage exceptionMessage; + protected final ResponseTool responseTool; + protected final JSONViewConfig viewConfig; + protected final ExceptionMessage exceptionMessage; - /** - * construct user filter ext - * @param responseTool response tool - * @param viewConfig view config - * @param exceptionMessage exception message - */ - public UserFilterExt(ResponseTool responseTool, - JSONViewConfig viewConfig, ExceptionMessage exceptionMessage) { - this.responseTool = responseTool; - this.viewConfig = viewConfig; - this.exceptionMessage = exceptionMessage; - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { - try { - return super.isAccessAllowed(request, response, mappedValue); - } - catch (UnknownSessionException e) { - log.warn("Unknown Session Exception Caused.", e); - return false; - } + /** + * construct user filter ext + * @param responseTool response tool + * @param viewConfig view config + * @param exceptionMessage exception message + */ + public UserFilterExt(ResponseTool responseTool, + JSONViewConfig viewConfig, ExceptionMessage exceptionMessage) { + this.responseTool = responseTool; + this.viewConfig = viewConfig; + this.exceptionMessage = exceptionMessage; } - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ + @Override + protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { + try { + return super.isAccessAllowed(request, response, mappedValue); + } + catch (UnknownSessionException e) { + log.warn("Unknown Session Exception Caused.", e); + return false; + } + } + + /** + * {@inheritDoc} + */ @Override protected void redirectToLogin(ServletRequest request, ServletResponse response) { - log.info("Access Denied, Redirect To Login."); - if (!response.isCommitted()) { - int code = 4011; - Object message = null; - if (exceptionMessage != null) { - message = exceptionMessage.get(code); - } - if (message == null) { - message = "Access Denied, You May Need Login"; - } - JSONViewDataModel dataModel = new JSONViewDataModel() - .setSuccess(false) - .setCode(code) - .setMessage(message); - processAccessDeniedDataModel((HttpServletRequest) request, - (HttpServletResponse) response, dataModel); - if (!doRedirectToLogin(request, response, dataModel)) { - responseTool.writeJSON(response, - dataModel.toMap(viewConfig.getSuccessKey(), - viewConfig.getDataKey(), - viewConfig.getCodeKey(), - viewConfig.getMessageKey())); - } - } + log.info("Access Denied, Redirect To Login."); + if (!response.isCommitted()) { + int code = 4011; + Object message = null; + if (exceptionMessage != null) { + message = exceptionMessage.get(code); + } + if (message == null) { + message = "Access Denied, You May Need Login"; + } + JSONViewDataModel dataModel = new JSONViewDataModel() + .setSuccess(false) + .setCode(code) + .setMessage(message); + processAccessDeniedDataModel((HttpServletRequest) request, + (HttpServletResponse) response, dataModel); + if (!doRedirectToLogin(request, response, dataModel)) { + responseTool.writeJSON(response, + dataModel.toMap(viewConfig.getSuccessKey(), + viewConfig.getDataKey(), + viewConfig.getCodeKey(), + viewConfig.getMessageKey())); + } + } } - /** - * Process Access Denied Model - * @param request request - * @param response response - * @param dataModel data model - */ - protected void processAccessDeniedDataModel( - HttpServletRequest request, - HttpServletResponse response, - JSONViewDataModel dataModel) { - // For Override + /** + * Process Access Denied Model + * @param request request + * @param response response + * @param dataModel data model + */ + protected void processAccessDeniedDataModel( + HttpServletRequest request, + HttpServletResponse response, + JSONViewDataModel dataModel) { + // For Override } /** @@ -104,10 +104,10 @@ public class UserFilterExt extends UserFilter { * @return true if redirected */ protected boolean doRedirectToLogin( - ServletRequest request, - ServletResponse response, - JSONViewDataModel dataModel) { - // For Override - return false; + ServletRequest request, + ServletResponse response, + JSONViewDataModel dataModel) { + // For Override + return false; } -} \ No newline at end of file +} diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/model/AuthInfo.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/model/AuthInfo.java index 729b95c..f52fb2e 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/model/AuthInfo.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/model/AuthInfo.java @@ -12,60 +12,60 @@ import org.apache.shiro.authc.SimpleAuthenticationInfo; * Apr 8, 2015 1:02:32 PM */ public class AuthInfo extends SimpleAuthenticationInfo { - private static final long serialVersionUID = 1L; - private Object extra; + private static final long serialVersionUID = 1L; + private Object extra; - /** - * @param principal principal - * @param hashedCredentials hashedCredentials - * @param credentialsSalt credentialsSalt - * @param realmName realmName - */ - public AuthInfo(Object principal, Object hashedCredentials, - ByteSource credentialsSalt, String realmName) { - super(principal, hashedCredentials, credentialsSalt, realmName); - } + /** + * @param principal principal + * @param hashedCredentials hashedCredentials + * @param credentialsSalt credentialsSalt + * @param realmName realmName + */ + public AuthInfo(Object principal, Object hashedCredentials, + ByteSource credentialsSalt, String realmName) { + super(principal, hashedCredentials, credentialsSalt, realmName); + } - /** - * @param principal principal - * @param credentials credentials - * @param realmName realmName - */ - public AuthInfo(Object principal, Object credentials, String realmName) { - super(principal, credentials, realmName); - } + /** + * @param principal principal + * @param credentials credentials + * @param realmName realmName + */ + public AuthInfo(Object principal, Object credentials, String realmName) { + super(principal, credentials, realmName); + } - /** - * @param principals principals - * @param hashedCredentials hashedCredentials - * @param credentialsSalt credentialsSalt - */ - public AuthInfo(PrincipalCollection principals, Object hashedCredentials, - ByteSource credentialsSalt) { - super(principals, hashedCredentials, credentialsSalt); - } + /** + * @param principals principals + * @param hashedCredentials hashedCredentials + * @param credentialsSalt credentialsSalt + */ + public AuthInfo(PrincipalCollection principals, Object hashedCredentials, + ByteSource credentialsSalt) { + super(principals, hashedCredentials, credentialsSalt); + } - /** - * @param principals principals - * @param credentials credentials - */ - public AuthInfo(PrincipalCollection principals, Object credentials) { - super(principals, credentials); - } + /** + * @param principals principals + * @param credentials credentials + */ + public AuthInfo(PrincipalCollection principals, Object credentials) { + super(principals, credentials); + } - /** - * @return the extra - */ - public Object getExtra() { - return extra; - } + /** + * @return the extra + */ + public Object getExtra() { + return extra; + } - /** - * @param extra the extra to set - * @return this - */ - public AuthInfo setExtra(Object extra) { - this.extra = extra; - return this; - } + /** + * @param extra the extra to set + * @return this + */ + public AuthInfo setExtra(Object extra) { + this.extra = extra; + return this; + } } diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/model/Credential.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/model/Credential.java index d80c17e..682f67f 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/model/Credential.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/model/Credential.java @@ -8,78 +8,78 @@ package me.chyxion.tigon.shiro.model; * Apr 7, 2015 3:13:16 PM */ public class Credential { - private Object credential; - private Object salt; - private Object extra; + private Object credential; + private Object salt; + private Object extra; - /** - * @param credential credential - * @param salt salt - */ - public Credential(Object credential, Object salt) { - this.credential = credential; - this.salt = salt; - } - - /** - * @param credential credential - * @param salt salt - * @param extra extra - */ - public Credential(Object credential, Object salt, Object extra) { - super(); - this.credential = credential; - this.salt = salt; - this.extra = extra; - } + /** + * @param credential credential + * @param salt salt + */ + public Credential(Object credential, Object salt) { + this.credential = credential; + this.salt = salt; + } + + /** + * @param credential credential + * @param salt salt + * @param extra extra + */ + public Credential(Object credential, Object salt, Object extra) { + super(); + this.credential = credential; + this.salt = salt; + this.extra = extra; + } - /** - * @return the credential - */ - public Object getCredential() { - return credential; - } + /** + * @return the credential + */ + public Object getCredential() { + return credential; + } - /** - * @param credential the credential to set - * @return this - */ - public Credential setCredential(Object credential) { - this.credential = credential; - return this; - } + /** + * @param credential the credential to set + * @return this + */ + public Credential setCredential(Object credential) { + this.credential = credential; + return this; + } - /** - * @return the salt - */ - public Object getSalt() { - return salt; - } + /** + * @return the salt + */ + public Object getSalt() { + return salt; + } - /** - * @param salt the solt to set - * @return this - */ - public Credential setSalt(Object salt) { - this.salt = salt; - return this; - } + /** + * @param salt the solt to set + * @return this + */ + public Credential setSalt(Object salt) { + this.salt = salt; + return this; + } - /** - * @param extra type - * @return the extra - */ - @SuppressWarnings("unchecked") - public T getExtra() { - return (T) extra; - } + /** + * @param extra type + * @return the extra + */ + @SuppressWarnings("unchecked") + public T getExtra() { + return (T) extra; + } - /** - * @param extra the extra to set - * @return this - */ - public Credential setExtra(Object extra) { - this.extra = extra; - return this; - } + /** + * @param extra the extra to set + * @return this + */ + public Credential setExtra(Object extra) { + this.extra = extra; + return this; + } } diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/model/SerializableByteSource.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/model/SerializableByteSource.java index cceb6b4..efc2399 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/model/SerializableByteSource.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/model/SerializableByteSource.java @@ -14,7 +14,7 @@ import org.apache.shiro.util.ByteSource; * May 12, 2016 1:52:00 PM */ public class SerializableByteSource implements ByteSource, Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private byte[] bytes; private transient String cachedHex; @@ -34,7 +34,7 @@ public class SerializableByteSource implements ByteSource, Serializable { * @param source the source to use to populate the underlying byte array. */ public SerializableByteSource(ByteSource source) { - this(source.getBytes()); + this(source.getBytes()); } /** @@ -48,15 +48,15 @@ public class SerializableByteSource implements ByteSource, Serializable { /** * @param bytes bytes */ - public void setBytes(byte[] bytes) { - this.bytes = bytes; - } + public void setBytes(byte[] bytes) { + this.bytes = bytes; + } - /** - * {@inheritDoc} - */ + /** + * {@inheritDoc} + */ @Override - public boolean isEmpty() { + public boolean isEmpty() { return this.bytes == null || this.bytes.length == 0; } @@ -115,4 +115,4 @@ public class SerializableByteSource implements ByteSource, Serializable { } return false; } -} \ No newline at end of file +} diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/service/AuthService.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/service/AuthService.java index 8150dc1..8a3f0c2 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/service/AuthService.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/service/AuthService.java @@ -11,44 +11,44 @@ import me.chyxion.tigon.shiro.model.AuthUser; * May 12, 2016 2:21:40 PM */ public interface AuthService { - - /** - * login with loginId and password - * @param loginId login id - * @param password password - * @return auth user - */ - AuthUser login(String loginId, String password); + + /** + * login with loginId and password + * @param loginId login id + * @param password password + * @return auth user + */ + AuthUser login(String loginId, String password); - /** - * @param loginId login id - * @param password password - * @param rememberMe remember me - * @return auth user - */ - AuthUser login(String loginId, String password, boolean rememberMe); - - /** - * logout current user - */ - void logout(); - - /** - * get auth user from session - * @param auth user data type - * @return auth user or null - */ - AuthUser getAuthUser(); - - /** - * check if authenticated - * @return true if authenticated - */ - boolean isAuthenticated(); - - /** - * get current session - * @return session - */ - Session getSession(); + /** + * @param loginId login id + * @param password password + * @param rememberMe remember me + * @return auth user + */ + AuthUser login(String loginId, String password, boolean rememberMe); + + /** + * logout current user + */ + void logout(); + + /** + * get auth user from session + * @param auth user data type + * @return auth user or null + */ + AuthUser getAuthUser(); + + /** + * check if authenticated + * @return true if authenticated + */ + boolean isAuthenticated(); + + /** + * get current session + * @return session + */ + Session getSession(); } diff --git a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/service/support/AuthServiceSupport.java b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/service/support/AuthServiceSupport.java index 6fb2f75..aeb92bd 100644 --- a/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/service/support/AuthServiceSupport.java +++ b/tigon-shiro-core/src/main/java/me/chyxion/tigon/shiro/service/support/AuthServiceSupport.java @@ -16,66 +16,66 @@ import org.apache.shiro.authz.UnauthenticatedException; */ public class AuthServiceSupport implements AuthService { - /** - * {@inheritDoc} - */ - @Override - public void logout() { - SecurityUtils.getSubject().logout(); - } + /** + * {@inheritDoc} + */ + @Override + public void logout() { + SecurityUtils.getSubject().logout(); + } - /** - * {@inheritDoc} - */ - @Override - public AuthUser getAuthUser() { - Session session = getSession(); - if (session == null) { - throw new UnauthenticatedException(); - } - AuthUser user = AuthUser.get(session); - if (user == null) { - throw new UnauthenticatedException(); - } - return user; - } + /** + * {@inheritDoc} + */ + @Override + public AuthUser getAuthUser() { + Session session = getSession(); + if (session == null) { + throw new UnauthenticatedException(); + } + AuthUser user = AuthUser.get(session); + if (user == null) { + throw new UnauthenticatedException(); + } + return user; + } - /** - * {@inheritDoc} - */ - @Override - public boolean isAuthenticated() { - Session session = getSession(); - AuthUser user = null; - if (session != null) { - user = AuthUser.get(session); - } - return user != null; - } + /** + * {@inheritDoc} + */ + @Override + public boolean isAuthenticated() { + Session session = getSession(); + AuthUser user = null; + if (session != null) { + user = AuthUser.get(session); + } + return user != null; + } - /** - * {@inheritDoc} - */ - @Override - public Session getSession() { - return SecurityUtils.getSubject().getSession(false); - } + /** + * {@inheritDoc} + */ + @Override + public Session getSession() { + return SecurityUtils.getSubject().getSession(false); + } - /** - * {@inheritDoc} - */ - @Override - public AuthUser login(String loginId, String password) { - return login(loginId, password, false); - } + /** + * {@inheritDoc} + */ + @Override + public AuthUser login(String loginId, String password) { + return login(loginId, password, false); + } - /** - * {@inheritDoc} - */ - @Override - public AuthUser login(String loginId, String password, - boolean rememberMe) { - SecurityUtils.getSubject().login(new UsernamePasswordToken(loginId, password, rememberMe)); - return getAuthUser(); - } + /** + * {@inheritDoc} + */ + @Override + public AuthUser login(String loginId, String password, + boolean rememberMe) { + SecurityUtils.getSubject().login(new UsernamePasswordToken(loginId, password, rememberMe)); + return getAuthUser(); + } } diff --git a/tigon-shiro-core/src/main/resources/spring/spring-summer-shiro.xml b/tigon-shiro-core/src/main/resources/spring/spring-summer-shiro.xml index 9fddd3f..8b855aa 100644 --- a/tigon-shiro-core/src/main/resources/spring/spring-summer-shiro.xml +++ b/tigon-shiro-core/src/main/resources/spring/spring-summer-shiro.xml @@ -4,7 +4,7 @@ xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - Tigon Shiro Configuration + Tigon Shiro Configuration @@ -13,7 +13,7 @@ p:proxyTargetClass="true" /> - + @@ -47,7 +47,7 @@ - + diff --git a/tigon-shiro-core/src/test/java/me/chyxion/tigon/shiro/TestDriver.java b/tigon-shiro-core/src/test/java/me/chyxion/tigon/shiro/TestDriver.java index 8865570..4acf7d8 100644 --- a/tigon-shiro-core/src/test/java/me/chyxion/tigon/shiro/TestDriver.java +++ b/tigon-shiro-core/src/test/java/me/chyxion/tigon/shiro/TestDriver.java @@ -11,7 +11,7 @@ import org.junit.Test; */ public class TestDriver { - @Test - public void test() { - } + @Test + public void test() { + } } diff --git a/tigon-shiro-redis-cache/pom.xml b/tigon-shiro-redis-cache/pom.xml index 31b9c66..93e123c 100644 --- a/tigon-shiro-redis-cache/pom.xml +++ b/tigon-shiro-redis-cache/pom.xml @@ -15,15 +15,15 @@ ../ - - - org.springframework - spring-context - - - org.apache.commons - commons-lang3 - + + + org.springframework + spring-context + + + org.apache.commons + commons-lang3 + com.alibaba fastjson @@ -47,15 +47,15 @@ lombok provided - - org.springframework - spring-test - test - - - junit - junit - test - - + + org.springframework + spring-test + test + + + junit + junit + test + + diff --git a/tigon-shiro-redis-cache/src/main/java/me/chyxion/tigon/shiro/cache/SessionCache.java b/tigon-shiro-redis-cache/src/main/java/me/chyxion/tigon/shiro/cache/SessionCache.java index 84c53fa..6da3e8e 100644 --- a/tigon-shiro-redis-cache/src/main/java/me/chyxion/tigon/shiro/cache/SessionCache.java +++ b/tigon-shiro-redis-cache/src/main/java/me/chyxion/tigon/shiro/cache/SessionCache.java @@ -16,24 +16,24 @@ import org.springframework.validation.annotation.Validated; */ @Validated public interface SessionCache extends Cache { - - /** - * find sessions by user id - * @param userId user id - * @return sessions - */ - Session findByUserId(@NotBlank Serializable userId); - - /** - * put user session - * @param session - * @return - */ - @NotNull Session putUserSession(@NotNull Session session); + + /** + * find sessions by user id + * @param userId user id + * @return sessions + */ + Session findByUserId(@NotBlank Serializable userId); + + /** + * put user session + * @param session + * @return + */ + @NotNull Session putUserSession(@NotNull Session session); - /** - * @param session - * @return - */ - @NotNull Session put(@NotNull Session session); + /** + * @param session + * @return + */ + @NotNull Session put(@NotNull Session session); } diff --git a/tigon-shiro-redis-cache/src/main/java/me/chyxion/tigon/shiro/cache/support/UserIdKeyRedisSessionCache.java b/tigon-shiro-redis-cache/src/main/java/me/chyxion/tigon/shiro/cache/support/UserIdKeyRedisSessionCache.java index ebb7c90..926b50d 100644 --- a/tigon-shiro-redis-cache/src/main/java/me/chyxion/tigon/shiro/cache/support/UserIdKeyRedisSessionCache.java +++ b/tigon-shiro-redis-cache/src/main/java/me/chyxion/tigon/shiro/cache/support/UserIdKeyRedisSessionCache.java @@ -26,146 +26,146 @@ import org.springframework.beans.factory.annotation.Autowired; * May 12, 2016 1:25:02 PM */ public class UserIdKeyRedisSessionCache implements SessionCache { - private static final Logger log = - LoggerFactory.getLogger(UserIdKeyRedisSessionCache.class); + private static final Logger log = + LoggerFactory.getLogger(UserIdKeyRedisSessionCache.class); - @Autowired - protected RedisTemplate redisTpl; - @Value("${shiro.session.redis.prefix:AUTH_SESSION}") - protected String prefix; - protected String userIdSessionPrefix; + @Autowired + protected RedisTemplate redisTpl; + @Value("${shiro.session.redis.prefix:AUTH_SESSION}") + protected String prefix; + protected String userIdSessionPrefix; - /** - * init - */ - @PostConstruct - void init() { - userIdSessionPrefix = prefix + ":USER"; - } + /** + * init + */ + @PostConstruct + void init() { + userIdSessionPrefix = prefix + ":USER"; + } - /** - * {@inheritDoc} - */ - @Override - public Session get(Serializable sessionId) { - log.info("Redis Session Cache Get [{}].", sessionId); - Session session = (Session) valueOp().get(prefix + ":" + sessionId); - log.debug("Session [{}] Found.", session); - return session; - } + /** + * {@inheritDoc} + */ + @Override + public Session get(Serializable sessionId) { + log.info("Redis Session Cache Get [{}].", sessionId); + Session session = (Session) valueOp().get(prefix + ":" + sessionId); + log.debug("Session [{}] Found.", session); + return session; + } - /** - * {@inheritDoc} - */ - @Override - public Session put(Session session) { - return put(session.getId(), session); - } + /** + * {@inheritDoc} + */ + @Override + public Session put(Session session) { + return put(session.getId(), session); + } - /** - * {@inheritDoc} - */ - @Override - public Session put(Serializable sessionId, Session session) { - log.info("Redis Session Cache Put [{}:{}:{}].", prefix, sessionId, session); - valueOp().set(prefix + ":" + sessionId, - (Serializable) session, - session.getTimeout(), - TimeUnit.MILLISECONDS); - return session; - } + /** + * {@inheritDoc} + */ + @Override + public Session put(Serializable sessionId, Session session) { + log.info("Redis Session Cache Put [{}:{}:{}].", prefix, sessionId, session); + valueOp().set(prefix + ":" + sessionId, + (Serializable) session, + session.getTimeout(), + TimeUnit.MILLISECONDS); + return session; + } - /** - * {@inheritDoc} - */ - @Override - public Session remove(Serializable sessionId) { - log.info("Redis Session Cache Remove [{}].", sessionId); - Session session = get(sessionId); - if (session != null) { - log.info("Redis Session Cache Remove [{}].", session); - redisTpl.delete(prefix + ":" + sessionId); - } - return session; - } + /** + * {@inheritDoc} + */ + @Override + public Session remove(Serializable sessionId) { + log.info("Redis Session Cache Remove [{}].", sessionId); + Session session = get(sessionId); + if (session != null) { + log.info("Redis Session Cache Remove [{}].", session); + redisTpl.delete(prefix + ":" + sessionId); + } + return session; + } - /** - * {@inheritDoc} - */ - @Override - public void clear() throws CacheException { - log.warn("Redis Session Cache #clear Not Supported"); - } + /** + * {@inheritDoc} + */ + @Override + public void clear() throws CacheException { + log.warn("Redis Session Cache #clear Not Supported"); + } - /** - * {@inheritDoc} - */ - @Override - public int size() { - Long size = hashOp().size(userIdSessionPrefix); - return size != null ? size.intValue() : 0; - } + /** + * {@inheritDoc} + */ + @Override + public int size() { + Long size = hashOp().size(userIdSessionPrefix); + return size != null ? size.intValue() : 0; + } - /** - * {@inheritDoc} - */ - @Override - public Set keys() { - log.warn("Redis Session Cache #keys Not Supported"); - return Collections.emptySet(); - } + /** + * {@inheritDoc} + */ + @Override + public Set keys() { + log.warn("Redis Session Cache #keys Not Supported"); + return Collections.emptySet(); + } - /** - * {@inheritDoc} - */ - @Override - public Collection values() { - log.warn("Redis Session Cache #values Not Supported"); - return Collections.emptyList(); - } + /** + * {@inheritDoc} + */ + @Override + public Collection values() { + log.warn("Redis Session Cache #values Not Supported"); + return Collections.emptyList(); + } - /** - * {@inheritDoc} - */ - @Override - public Session findByUserId(final Serializable userId) { - log.debug("Find Session By User Id [{}].", userId); - Serializable sessionId = hashOp().get(userIdSessionPrefix, userId); - Session session = null; - if (sessionId != null) { - log.debug("User [{}] Session Id [{}] Found.", userId, sessionId); - session = get(sessionId); - log.info("User [{}] Session [{}] Found.", userId, session); - if (session == null) { - log.info("No User [{}] Session Found, Remove."); - hashOp().delete(userIdSessionPrefix, userId); - } - } - return session; - } + /** + * {@inheritDoc} + */ + @Override + public Session findByUserId(final Serializable userId) { + log.debug("Find Session By User Id [{}].", userId); + Serializable sessionId = hashOp().get(userIdSessionPrefix, userId); + Session session = null; + if (sessionId != null) { + log.debug("User [{}] Session Id [{}] Found.", userId, sessionId); + session = get(sessionId); + log.info("User [{}] Session [{}] Found.", userId, session); + if (session == null) { + log.info("No User [{}] Session Found, Remove."); + hashOp().delete(userIdSessionPrefix, userId); + } + } + return session; + } - /** - * {@inheritDoc} - */ - @Override - public Session putUserSession(Session session) { - log.info("Put User Session [{}].", session); - AuthUser authUser = AuthUser.get(session); - Assert.state(authUser != null, "Auth User Not Found In Session"); - final Serializable userId = authUser.getUserId(); - Assert.state(userId != null, "Session Auth User Id Could Not Be Null"); - log.info("Put User [{}] Session [{}].", userId, session); - hashOp().put(userIdSessionPrefix, userId, session.getId()); - return session; - } + /** + * {@inheritDoc} + */ + @Override + public Session putUserSession(Session session) { + log.info("Put User Session [{}].", session); + AuthUser authUser = AuthUser.get(session); + Assert.state(authUser != null, "Auth User Not Found In Session"); + final Serializable userId = authUser.getUserId(); + Assert.state(userId != null, "Session Auth User Id Could Not Be Null"); + log.info("Put User [{}] Session [{}].", userId, session); + hashOp().put(userIdSessionPrefix, userId, session.getId()); + return session; + } - // -- - // private methods - protected HashOperations hashOp() { - return redisTpl.opsForHash(); - } + // -- + // private methods + protected HashOperations hashOp() { + return redisTpl.opsForHash(); + } - protected ValueOperations valueOp() { - return redisTpl.opsForValue(); - } + protected ValueOperations valueOp() { + return redisTpl.opsForValue(); + } } diff --git a/tigon-shiro-redis-cache/src/main/java/me/chyxion/tigon/shiro/model/AuthUser.java b/tigon-shiro-redis-cache/src/main/java/me/chyxion/tigon/shiro/model/AuthUser.java index 62eb34d..f63d3c2 100644 --- a/tigon-shiro-redis-cache/src/main/java/me/chyxion/tigon/shiro/model/AuthUser.java +++ b/tigon-shiro-redis-cache/src/main/java/me/chyxion/tigon/shiro/model/AuthUser.java @@ -20,106 +20,106 @@ import org.apache.shiro.session.Session; @Getter @Setter public class AuthUser implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public static final String SESSION_AUTH_USER_KEY = "__AUTH_USER__"; - public static final String OFFLINE = "__OFFLINE__"; - public static final String OFFLINE_MSG = "__OFFLINE_MSG__"; + public static final String SESSION_AUTH_USER_KEY = "__AUTH_USER__"; + public static final String OFFLINE = "__OFFLINE__"; + public static final String OFFLINE_MSG = "__OFFLINE_MSG__"; - protected Serializable userId; - protected U user; - protected Map attrs; - - /** - * save this to session - * @param session - */ - public void save(Session session) { - save(session, this); - } + protected Serializable userId; + protected U user; + protected Map attrs; + + /** + * save this to session + * @param session + */ + public void save(Session session) { + save(session, this); + } - /** - * put this to session - */ - public void save() { - save(SecurityUtils.getSubject().getSession(false)); - } + /** + * put this to session + */ + public void save() { + save(SecurityUtils.getSubject().getSession(false)); + } - /** - * get auth user from session - * @param session session - * @param auth user data type - * @return auth user - */ - @SuppressWarnings("unchecked") - public static AuthUser get(Session session) { - return (AuthUser) session.getAttribute(SESSION_AUTH_USER_KEY); - } + /** + * get auth user from session + * @param session session + * @param auth user data type + * @return auth user + */ + @SuppressWarnings("unchecked") + public static AuthUser get(Session session) { + return (AuthUser) session.getAttribute(SESSION_AUTH_USER_KEY); + } - /** - * get auth user from current session - * @param auth user data type - * @return auth user - */ - public static AuthUser get() { - return get(SecurityUtils.getSubject().getSession(false)); - } + /** + * get auth user from current session + * @param auth user data type + * @return auth user + */ + public static AuthUser get() { + return get(SecurityUtils.getSubject().getSession(false)); + } - /** - * put auth user to session - * @param session session - * @param authUser auth user - */ - public static void save(Session session, AuthUser authUser) { - Assert.notNull(session); - Assert.notNull(authUser); - Assert.state(authUser.getUserId() != null, "User Id Is Null"); - session.setAttribute(SESSION_AUTH_USER_KEY, authUser); - session.touch(); - } + /** + * put auth user to session + * @param session session + * @param authUser auth user + */ + public static void save(Session session, AuthUser authUser) { + Assert.notNull(session); + Assert.notNull(authUser); + Assert.state(authUser.getUserId() != null, "User Id Is Null"); + session.setAttribute(SESSION_AUTH_USER_KEY, authUser); + session.touch(); + } - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return JSON.toJSONString(this); - } + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return JSON.toJSONString(this); + } - /** - * @param name attr name - * @param value attr value - * @return auth user - */ - public AuthUser setAttr(String name, Serializable value) { - if (attrs == null) { - attrs = new HashMap(); - } - attrs.put(name, value); - return this; - } + /** + * @param name attr name + * @param value attr value + * @return auth user + */ + public AuthUser setAttr(String name, Serializable value) { + if (attrs == null) { + attrs = new HashMap(); + } + attrs.put(name, value); + return this; + } - /** - * @param name attr name - * @param attr type - * @return attr value - */ - @SuppressWarnings("unchecked") - public T removeAttr(String name) { - return attrs != null ? (T) attrs.remove(name) : null; - } - - /** - * @param name attr name - * @param attr type - * @return attr value - */ - @SuppressWarnings("unchecked") - public T getAttr(String name) { - T value = null; - if (attrs != null) { - value = (T) attrs.get(name); - } - return value; - } + /** + * @param name attr name + * @param attr type + * @return attr value + */ + @SuppressWarnings("unchecked") + public T removeAttr(String name) { + return attrs != null ? (T) attrs.remove(name) : null; + } + + /** + * @param name attr name + * @param attr type + * @return attr value + */ + @SuppressWarnings("unchecked") + public T getAttr(String name) { + T value = null; + if (attrs != null) { + value = (T) attrs.get(name); + } + return value; + } } diff --git a/tigon-shiro-redis-cache/src/main/resources/spring/spring-summer-shiro-redis-cache.xml b/tigon-shiro-redis-cache/src/main/resources/spring/spring-summer-shiro-redis-cache.xml index f9e4de6..47bb9cc 100644 --- a/tigon-shiro-redis-cache/src/main/resources/spring/spring-summer-shiro-redis-cache.xml +++ b/tigon-shiro-redis-cache/src/main/resources/spring/spring-summer-shiro-redis-cache.xml @@ -3,6 +3,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - Tigon Shiro Redis Cache + Tigon Shiro Redis Cache diff --git a/tigon-shiro-redis-cache/src/test/java/me/chyxion/tigon/shiro/TestDriver.java b/tigon-shiro-redis-cache/src/test/java/me/chyxion/tigon/shiro/TestDriver.java index 8865570..4acf7d8 100644 --- a/tigon-shiro-redis-cache/src/test/java/me/chyxion/tigon/shiro/TestDriver.java +++ b/tigon-shiro-redis-cache/src/test/java/me/chyxion/tigon/shiro/TestDriver.java @@ -11,7 +11,7 @@ import org.junit.Test; */ public class TestDriver { - @Test - public void test() { - } + @Test + public void test() { + } } diff --git a/tigon-shiro-spring-boot/pom.xml b/tigon-shiro-spring-boot/pom.xml index b64cc75..142f961 100644 --- a/tigon-shiro-spring-boot/pom.xml +++ b/tigon-shiro-spring-boot/pom.xml @@ -15,7 +15,7 @@ ../ - + me.chyxion.tigon tigon-shiro-core @@ -30,11 +30,11 @@ provided - - org.springframework - spring-test - test - + + org.springframework + spring-test + test + me.chyxion.tigon tigon-webmvc-spring-boot @@ -45,11 +45,11 @@ spring-boot-test test - - junit - junit - test - + + junit + junit + test + org.apache.logging.log4j log4j-slf4j-impl @@ -60,5 +60,5 @@ log4j-core test - + diff --git a/tigon-shiro-spring-boot/src/test/java/me/chyxion/tigon/shiro/SiteControllerTest.java b/tigon-shiro-spring-boot/src/test/java/me/chyxion/tigon/shiro/SiteControllerTest.java index 0ee30d7..2684ee1 100644 --- a/tigon-shiro-spring-boot/src/test/java/me/chyxion/tigon/shiro/SiteControllerTest.java +++ b/tigon-shiro-spring-boot/src/test/java/me/chyxion/tigon/shiro/SiteControllerTest.java @@ -27,32 +27,32 @@ import java.util.Map; @SpringBootTest public class SiteControllerTest { - @Autowired - private ControllerTestTool t; - @Autowired - private UserFilter userFilter; + @Autowired + private ControllerTestTool t; + @Autowired + private UserFilter userFilter; - @Test - public void testIndex() { - t.print(t.get("/")); - } + @Test + public void testIndex() { + t.print(t.get("/")); + } - @Test - public void testRaw() { - t.print(t.get("/raw")); - } + @Test + public void testRaw() { + t.print(t.get("/raw")); + } - @Test - public void testInt() { - t.print(t.get("/int")); - } + @Test + public void testInt() { + t.print(t.get("/int")); + } - @Test - public void testPost() { - Map params = new HashMap(); - params.put("id", "id"); - params.put("name", "Shaun Chyxion"); - params.put("gender", ""); - t.print(t.post("/post", params)); - } + @Test + public void testPost() { + Map params = new HashMap(); + params.put("id", "id"); + params.put("name", "Shaun Chyxion"); + params.put("gender", ""); + t.print(t.post("/post", params)); + } } diff --git a/tigon-shiro-spring-boot/src/test/java/me/chyxion/tigon/shiro/TestDriver.java b/tigon-shiro-spring-boot/src/test/java/me/chyxion/tigon/shiro/TestDriver.java index 8865570..4acf7d8 100644 --- a/tigon-shiro-spring-boot/src/test/java/me/chyxion/tigon/shiro/TestDriver.java +++ b/tigon-shiro-spring-boot/src/test/java/me/chyxion/tigon/shiro/TestDriver.java @@ -11,7 +11,7 @@ import org.junit.Test; */ public class TestDriver { - @Test - public void test() { - } + @Test + public void test() { + } } diff --git a/tigon-shiro-spring-boot/src/test/resources/log4j2.xml b/tigon-shiro-spring-boot/src/test/resources/log4j2.xml index 08c2ae6..166de45 100644 --- a/tigon-shiro-spring-boot/src/test/resources/log4j2.xml +++ b/tigon-shiro-spring-boot/src/test/resources/log4j2.xml @@ -1,38 +1,38 @@ - - %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n - .logs - DEBUG - - - - - - + + %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n + .logs + DEBUG + + + - + + + + - - + + - + - - - - - - - - - + + + + + + + + + - - + + diff --git a/tigon-shiro-spring-boot/src/test/resources/spring/spring-test.xml b/tigon-shiro-spring-boot/src/test/resources/spring/spring-test.xml index d4db2ce..7aa0615 100644 --- a/tigon-shiro-spring-boot/src/test/resources/spring/spring-test.xml +++ b/tigon-shiro-spring-boot/src/test/resources/spring/spring-test.xml @@ -1,8 +1,8 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans.xsd"> diff --git a/tigon-shiro-war/pom.xml b/tigon-shiro-war/pom.xml index 9b81ac7..e47cc24 100644 --- a/tigon-shiro-war/pom.xml +++ b/tigon-shiro-war/pom.xml @@ -15,7 +15,7 @@ ../ - + me.chyxion.tigon tigon-shiro-core @@ -26,15 +26,15 @@ provided - - org.springframework - spring-test - test - - - junit - junit - test - - + + org.springframework + spring-test + test + + + junit + junit + test + + diff --git a/tigon-shiro-war/src/main/java/me/chyxion/tigon/shiro/package-info.java b/tigon-shiro-war/src/main/java/me/chyxion/tigon/shiro/package-info.java index f685714..57af8d9 100644 --- a/tigon-shiro-war/src/main/java/me/chyxion/tigon/shiro/package-info.java +++ b/tigon-shiro-war/src/main/java/me/chyxion/tigon/shiro/package-info.java @@ -3,4 +3,4 @@ * donghuang@wacai.com
* Mar 07, 2017 13:35 */ -package me.chyxion.tigon.shiro; \ No newline at end of file +package me.chyxion.tigon.shiro; diff --git a/tigon-shiro-war/src/main/resources/META-INF/web-fragment.xml b/tigon-shiro-war/src/main/resources/META-INF/web-fragment.xml index 144f048..5d89e1b 100644 --- a/tigon-shiro-war/src/main/resources/META-INF/web-fragment.xml +++ b/tigon-shiro-war/src/main/resources/META-INF/web-fragment.xml @@ -26,4 +26,4 @@ INCLUDE ERROR - \ No newline at end of file + diff --git a/tigon-shiro-war/src/test/java/me/chyxion/tigon/shiro/TestDriver.java b/tigon-shiro-war/src/test/java/me/chyxion/tigon/shiro/TestDriver.java index 8865570..4acf7d8 100644 --- a/tigon-shiro-war/src/test/java/me/chyxion/tigon/shiro/TestDriver.java +++ b/tigon-shiro-war/src/test/java/me/chyxion/tigon/shiro/TestDriver.java @@ -11,7 +11,7 @@ import org.junit.Test; */ public class TestDriver { - @Test - public void test() { - } + @Test + public void test() { + } } diff --git a/tigon-shiro-war/src/test/java/me/chyxion/tigon/shiro/controller/SiteController.java b/tigon-shiro-war/src/test/java/me/chyxion/tigon/shiro/controller/SiteController.java index 9d3b79a..b142b7d 100644 --- a/tigon-shiro-war/src/test/java/me/chyxion/tigon/shiro/controller/SiteController.java +++ b/tigon-shiro-war/src/test/java/me/chyxion/tigon/shiro/controller/SiteController.java @@ -21,83 +21,83 @@ import java.util.Map; @Controller public class SiteController { - @RequestMapping("/") - public void index() { - - } + @RequestMapping("/") + public void index() { + + } - @RequestMapping("/v") - public String index(@RequestParam("v") + @RequestMapping("/v") + public String index(@RequestParam("v") // @EmptyToNull String validate) { - return validate; - } + return validate; + } - @RequestMapping("/raw") - public Map raw() { - Map mapRaw = new HashMap(); - mapRaw.put("data", "Hello!"); - return mapRaw; - } + @RequestMapping("/raw") + public Map raw() { + Map mapRaw = new HashMap(); + mapRaw.put("data", "Hello!"); + return mapRaw; + } - @RequestMapping("/int") - public int integer() { - return 99; - } + @RequestMapping("/int") + public int integer() { + return 99; + } - @RequestMapping("/post") - public String post(@Validated Form form) { - return form.getId(); - } - - public static class Form { - @NotBlank - private String id; - @NotBlank + @RequestMapping("/post") + public String post(@Validated Form form) { + return form.getId(); + } + + public static class Form { + @NotBlank + private String id; + @NotBlank private String name; - @EmptyToNull - private String gender; + @EmptyToNull + private String gender; - /** - * @return the id - */ - public String getId() { - return id; - } + /** + * @return the id + */ + public String getId() { + return id; + } - /** - * @param id the id to set - */ - public void setId(String id) { - this.id = id; - } + /** + * @param id the id to set + */ + public void setId(String id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the gender - */ - public String getGender() { - return gender; - } + /** + * @return the gender + */ + public String getGender() { + return gender; + } - /** - * @param gender the gender to set - */ - public void setGender(String gender) { - this.gender = gender; - } - } + /** + * @param gender the gender to set + */ + public void setGender(String gender) { + this.gender = gender; + } + } } diff --git a/tigon-shiro-war/src/test/resources/log4j2.xml b/tigon-shiro-war/src/test/resources/log4j2.xml index 27958bb..c7486b5 100644 --- a/tigon-shiro-war/src/test/resources/log4j2.xml +++ b/tigon-shiro-war/src/test/resources/log4j2.xml @@ -1,37 +1,37 @@ - - %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n - .logs - DEBUG - - - - - - + + %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n + .logs + DEBUG + + + - + + + + - - + + - + - - - - - - - - - + + + + + + + + + - - + + diff --git a/tigon-shiro-war/src/test/resources/spring/servlet-spring-test.xml b/tigon-shiro-war/src/test/resources/spring/servlet-spring-test.xml index 6dd4589..4ca575e 100644 --- a/tigon-shiro-war/src/test/resources/spring/servlet-spring-test.xml +++ b/tigon-shiro-war/src/test/resources/spring/servlet-spring-test.xml @@ -1,9 +1,9 @@ diff --git a/tigon-webmvc-core/pom.xml b/tigon-webmvc-core/pom.xml index 18032e9..0214f9e 100644 --- a/tigon-webmvc-core/pom.xml +++ b/tigon-webmvc-core/pom.xml @@ -4,11 +4,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - 4.0.0 - tigon-webmvc-core - jar - Tigon Web MVC Core - Tigon Web MVC Core + 4.0.0 + tigon-webmvc-core + jar + Tigon Web MVC Core + Tigon Web MVC Core me.chyxion.tigon @@ -17,11 +17,11 @@ ../ - - - me.chyxion.tigon - tigon-model - + + + me.chyxion.tigon + tigon-model + org.aspectj aspectjrt @@ -35,35 +35,35 @@ cglib - org.springframework - spring-webmvc - + org.springframework + spring-webmvc + org.projectlombok lombok provided - - javax.servlet - javax.servlet-api - provided - - - org.springframework - spring-test - provided - + + javax.servlet + javax.servlet-api + provided + + + org.springframework + spring-test + provided + javax.el javax.el-api test - - junit - junit - test - + + junit + junit + test + org.apache.logging.log4j log4j-slf4j-impl @@ -74,5 +74,5 @@ log4j-core test - + diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/DefaultViewResolver.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/DefaultViewResolver.java index e063679..d01c27d 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/DefaultViewResolver.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/DefaultViewResolver.java @@ -17,11 +17,11 @@ import org.springframework.beans.factory.annotation.Autowired; * Mar 19, 2017 11:23:01 */ public class DefaultViewResolver implements ViewResolver, Ordered { - private static final Logger log = - LoggerFactory.getLogger(DefaultViewResolver.class); + private static final Logger log = + LoggerFactory.getLogger(DefaultViewResolver.class); - @Autowired - private JSONViewConfig jsonViewConfig; + @Autowired + private JSONViewConfig jsonViewConfig; /** * view resolver order @@ -35,18 +35,18 @@ public class DefaultViewResolver implements ViewResolver, Ordered { */ @Override public View resolveViewName(String rawViewName, Locale locale) throws Exception { - log.debug("Base View Resolver Resolve View Name [{}].", rawViewName); + log.debug("Base View Resolver Resolve View Name [{}].", rawViewName); // parse view name View view = null; if (rawViewName.startsWith(ResponseTool.PREFIX_DATA)) { - String viewName = rawViewName.substring(ResponseTool.PREFIX_DATA.length()); - log.debug("Resolve View Name [{}] As JSON Data.", viewName); - view = new JSONView(new JSONViewDataModel(viewName), jsonViewConfig); + String viewName = rawViewName.substring(ResponseTool.PREFIX_DATA.length()); + log.debug("Resolve View Name [{}] As JSON Data.", viewName); + view = new JSONView(new JSONViewDataModel(viewName), jsonViewConfig); } if (view == null) { - log.debug("No View Type Found, Render As JSON View [{}].", rawViewName); - view = new JSONView(rawViewName, jsonViewConfig); + log.debug("No View Type Found, Render As JSON View [{}].", rawViewName); + view = new JSONView(rawViewName, jsonViewConfig); } return view; } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONView.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONView.java index 69a20bd..c132d31 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONView.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONView.java @@ -103,4 +103,4 @@ public class JSONView extends FastJsonJsonView { } return new JSONViewDataModel(objData); } -} \ No newline at end of file +} diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONViewConfig.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONViewConfig.java index d3366c7..87fff22 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONViewConfig.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONViewConfig.java @@ -38,4 +38,4 @@ public class JSONViewConfig { serializeConfig.put(ViewModel.class, viewModelableSerializer); serializeConfig.put(ListResult.class, viewModelableSerializer); } -} \ No newline at end of file +} diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONViewDataModel.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONViewDataModel.java index 93b67d1..eae7e7b 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONViewDataModel.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONViewDataModel.java @@ -15,173 +15,173 @@ import me.chyxion.tigon.model.Mappable; public class JSONViewDataModel { @Getter - private boolean success = true; - /** - * error code - */ + private boolean success = true; + /** + * error code + */ @Getter - private Object code = 0; + private Object code = 0; @Getter - private Object message; + private Object message; @Getter - private Object data; + private Object data; @Getter - private Map attrs; + private Map attrs; @Getter - private Throwable exception; + private Throwable exception; - /** - * @since 0.0.3 - */ + /** + * @since 0.0.3 + */ public JSONViewDataModel() { } - /** - * @param data - */ + /** + * @param data + */ public JSONViewDataModel(Object data) { - this.data = data; + this.data = data; } - /** - * @since 0.0.3 - * @param exception - */ + /** + * @since 0.0.3 + * @param exception + */ public JSONViewDataModel(Throwable exception) { - this.exception = exception; + this.exception = exception; } - /** - * @param success the success to set - * @return this - */ - public JSONViewDataModel setSuccess(boolean success) { - this.success = success; - return this; - } + /** + * @param success the success to set + * @return this + */ + public JSONViewDataModel setSuccess(boolean success) { + this.success = success; + return this; + } - /** - * @param code the code to set - * @return - */ - public JSONViewDataModel setCode(Object code) { - this.code = code; - return this; - } + /** + * @param code the code to set + * @return + */ + public JSONViewDataModel setCode(Object code) { + this.code = code; + return this; + } - /** - * @param message the message to set - * @return this - */ - public JSONViewDataModel setMessage(Object message) { - this.message = message; - return this; - } + /** + * @param message the message to set + * @return this + */ + public JSONViewDataModel setMessage(Object message) { + this.message = message; + return this; + } - /** - * @param data the data to set - */ - public JSONViewDataModel setData(Object data) { - this.data = data; - return this; - } + /** + * @param data the data to set + */ + public JSONViewDataModel setData(Object data) { + this.data = data; + return this; + } - /** - * @return formatted data map - */ - @SuppressWarnings("unchecked") - public Map toMap( - final String successKey, + /** + * @return formatted data map + */ + @SuppressWarnings("unchecked") + public Map toMap( + final String successKey, final String dataKey, - final String codeKey, - final String messageKey) { + final String codeKey, + final String messageKey) { - Map mapData = null; - if (data instanceof Map) { - mapData = (Map) data; - } - else if (data instanceof Mappable) { - mapData = ((Mappable) data).toMap(); - } - else { - mapData = new HashMap(); - if (data != null) { - mapData.put(dataKey, data); - } - } - // attrs - if (attrs != null) { - mapData.putAll(attrs); - } - // success - if (!mapData.containsKey(successKey)) { - mapData.put(successKey, success); - if (!success) { - mapData.put(messageKey, getMessageOrExceptionMessage()); - } - } - // code - if (!mapData.containsKey(codeKey)) { - mapData.put(codeKey, code); - } - return mapData; - } + Map mapData = null; + if (data instanceof Map) { + mapData = (Map) data; + } + else if (data instanceof Mappable) { + mapData = ((Mappable) data).toMap(); + } + else { + mapData = new HashMap(); + if (data != null) { + mapData.put(dataKey, data); + } + } + // attrs + if (attrs != null) { + mapData.putAll(attrs); + } + // success + if (!mapData.containsKey(successKey)) { + mapData.put(successKey, success); + if (!success) { + mapData.put(messageKey, getMessageOrExceptionMessage()); + } + } + // code + if (!mapData.containsKey(codeKey)) { + mapData.put(codeKey, code); + } + return mapData; + } - /** - * @param exception the exception to set - */ - public void setException(Throwable exception) { - this.exception = exception; - } + /** + * @param exception the exception to set + */ + public void setException(Throwable exception) { + this.exception = exception; + } - /** - * @param attrs the attrs to set - * @return this - */ - public JSONViewDataModel setAttrs(Map attrs) { - this.attrs = attrs; - return this; - } - - /** - * set attr - * @param name attr name - * @param value attr value - * @return this - */ - public JSONViewDataModel setAttr(String name, Object value) { - if (attrs == null) { - attrs = new HashMap(); - } - attrs.put(name, value); - return this; - } + /** + * @param attrs the attrs to set + * @return this + */ + public JSONViewDataModel setAttrs(Map attrs) { + this.attrs = attrs; + return this; + } + + /** + * set attr + * @param name attr name + * @param value attr value + * @return this + */ + public JSONViewDataModel setAttr(String name, Object value) { + if (attrs == null) { + attrs = new HashMap(); + } + attrs.put(name, value); + return this; + } - /** - * get attr - * @param name attr name - * @return attr value - */ - @SuppressWarnings("unchecked") - public T getAttr(String name) { - return attrs != null ? (T) attrs.get(name) : null; - } + /** + * get attr + * @param name attr name + * @return attr value + */ + @SuppressWarnings("unchecked") + public T getAttr(String name) { + return attrs != null ? (T) attrs.get(name) : null; + } - /** - * get attr - * @param name attr name - * @return attr value - */ - @SuppressWarnings("unchecked") - public T removeAttr(String name) { - return attrs != null ? (T) attrs.remove(name) : null; - } + /** + * get attr + * @param name attr name + * @return attr value + */ + @SuppressWarnings("unchecked") + public T removeAttr(String name) { + return attrs != null ? (T) attrs.remove(name) : null; + } - /** - * @return the message - */ - protected Object getMessageOrExceptionMessage() { - return message != null ? message : - exception != null ? exception.getMessage() : null; - } + /** + * @return the message + */ + protected Object getMessageOrExceptionMessage() { + return message != null ? message : + exception != null ? exception.getMessage() : null; + } } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONViewDataModelAssembler.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONViewDataModelAssembler.java index 9092906..45d2b75 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONViewDataModelAssembler.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/JSONViewDataModelAssembler.java @@ -10,10 +10,10 @@ package me.chyxion.tigon.webmvc; */ public interface JSONViewDataModelAssembler { - /** - * custom json data model assemble, return your custom data model - * @param model - * @return - */ - Object assemble(JSONViewDataModel model); -} \ No newline at end of file + /** + * custom json data model assemble, return your custom data model + * @param model + * @return + */ + Object assemble(JSONViewDataModel model); +} diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/ResourceModel.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/ResourceModel.java index 31ed68f..ebda0b5 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/ResourceModel.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/ResourceModel.java @@ -22,118 +22,118 @@ import org.springframework.core.io.InputStreamResource; * Jan 16, 2015 5:33:30 PM */ public class ResourceModel { - private static final Logger log = - LoggerFactory.getLogger(ResourceModel.class); + private static final Logger log = + LoggerFactory.getLogger(ResourceModel.class); - private String contentType; - private long contentLength; - private String name; - private Resource resource; + private String contentType; + private long contentLength; + private String name; + private Resource resource; - public ResourceModel(Resource resource, - String contentType, long contentLength, String name) throws IOException { - Assert.notNull(resource); - Assert.state(!(InputStreamResource.class == - resource.getClass() && contentLength <= 0), - "Input Stream Resource Content Length Must Provide."); - this.resource = resource; - this.contentType = contentType; - this.contentLength = contentLength > 0 ? - contentLength : resource.contentLength(); - this.name = name; - } + public ResourceModel(Resource resource, + String contentType, long contentLength, String name) throws IOException { + Assert.notNull(resource); + Assert.state(!(InputStreamResource.class == + resource.getClass() && contentLength <= 0), + "Input Stream Resource Content Length Must Provide."); + this.resource = resource; + this.contentType = contentType; + this.contentLength = contentLength > 0 ? + contentLength : resource.contentLength(); + this.name = name; + } - public ResourceModel(File file, String contentType, String name) { - this.resource = new FileSystemResource(file); - this.contentType = contentType; - this.contentLength = file.length(); - this.name = StringUtils.defaultIfBlank(name, file.getName()); - } - - public ResourceModel(InputStream inputStream, - String contentType, long contentLength, String name) { - Assert.notNull(inputStream); - Assert.state(contentLength > 0, - "Input Stream Resource Content Length Must Provide."); - this.contentType = contentType; - this.contentLength = contentLength; - this.resource = new InputStreamResource(inputStream); - } + public ResourceModel(File file, String contentType, String name) { + this.resource = new FileSystemResource(file); + this.contentType = contentType; + this.contentLength = file.length(); + this.name = StringUtils.defaultIfBlank(name, file.getName()); + } + + public ResourceModel(InputStream inputStream, + String contentType, long contentLength, String name) { + Assert.notNull(inputStream); + Assert.state(contentLength > 0, + "Input Stream Resource Content Length Must Provide."); + this.contentType = contentType; + this.contentLength = contentLength; + this.resource = new InputStreamResource(inputStream); + } - public ResourceModel(byte[] data, String contentType, String name) { - Assert.notNull(data); - this.resource = new ByteArrayResource(data); - this.contentType = contentType; - this.contentLength = data.length; - this.name = name; - } + public ResourceModel(byte[] data, String contentType, String name) { + Assert.notNull(data); + this.resource = new ByteArrayResource(data); + this.contentType = contentType; + this.contentLength = data.length; + this.name = name; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name the name to set - * @return - */ - public ResourceModel setName(String name) { - this.name = name; - return this; - } + /** + * @param name the name to set + * @return + */ + public ResourceModel setName(String name) { + this.name = name; + return this; + } - /** - * @return the resource - */ - public Resource getResource() { - return resource; - } + /** + * @return the resource + */ + public Resource getResource() { + return resource; + } - /** - * @param resource the resource to set - * @return - */ - public ResourceModel setResource(Resource resource) { - this.resource = resource; - return this; - } + /** + * @param resource the resource to set + * @return + */ + public ResourceModel setResource(Resource resource) { + this.resource = resource; + return this; + } - /** - * @return the contentType - */ - public String getContentType() { - if (StringUtils.isBlank(contentType)) { - log.debug("Resource Content Type Is Blank, Try To Guess From Name [{}].", name); - // from file name - if (StringUtils.isNotBlank(name)) { - contentType = URLConnection.guessContentTypeFromName(name); - log.debug("Guess Content Type [{}] From File Name [{}].", contentType, name); - } - // use default - if (StringUtils.isBlank(contentType)) { - contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE; - log.debug("Use Default Content Type [{}].", contentType); - } - } - return contentType; - } + /** + * @return the contentType + */ + public String getContentType() { + if (StringUtils.isBlank(contentType)) { + log.debug("Resource Content Type Is Blank, Try To Guess From Name [{}].", name); + // from file name + if (StringUtils.isNotBlank(name)) { + contentType = URLConnection.guessContentTypeFromName(name); + log.debug("Guess Content Type [{}] From File Name [{}].", contentType, name); + } + // use default + if (StringUtils.isBlank(contentType)) { + contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE; + log.debug("Use Default Content Type [{}].", contentType); + } + } + return contentType; + } - /** - * @param contentType the contentType to set - * @return - */ - public ResourceModel setContentType(String contentType) { - this.contentType = contentType; - return this; - } + /** + * @param contentType the contentType to set + * @return + */ + public ResourceModel setContentType(String contentType) { + this.contentType = contentType; + return this; + } - /** - * @return the contentLength - * @throws IOException - */ - public long getContentLength() throws IOException { - return contentLength; - } + /** + * @return the contentLength + * @throws IOException + */ + public long getContentLength() throws IOException { + return contentLength; + } } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/TigonControllerAdvice.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/TigonControllerAdvice.java index 7e00f62..e94c044 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/TigonControllerAdvice.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/TigonControllerAdvice.java @@ -24,26 +24,26 @@ import java.util.List; @ControllerAdvice(annotations = {Controller.class, RestController.class}) public class TigonControllerAdvice { - @Autowired - private JSONViewConfig jsonViewConfig; - @Autowired - private List exceptionResolvers; + @Autowired + private JSONViewConfig jsonViewConfig; + @Autowired + private List exceptionResolvers; - @ExceptionHandler(Throwable.class) - public ModelAndView handleThrowable(Throwable ex) { - log.warn("Exception [{}] [{}] Caused.", ex.getClass(), ex.getMessage()); - JSONViewDataModel model = new JSONViewDataModel(ex).setSuccess(false); - // custom exception resolvers - for (ExceptionResolver er : exceptionResolvers) { - if (log.isInfoEnabled()) { - log.info("Exception Resolver [{}] Found.", er.getClass()); - } - if (er.accept(ex)) { - log.info("Exception Has Been Accepted By [{}].", er); - model = er.process(model); - break; - } - } - return new ModelAndView(new JSONView(model, jsonViewConfig)); - } + @ExceptionHandler(Throwable.class) + public ModelAndView handleThrowable(Throwable ex) { + log.warn("Exception [{}] [{}] Caused.", ex.getClass(), ex.getMessage()); + JSONViewDataModel model = new JSONViewDataModel(ex).setSuccess(false); + // custom exception resolvers + for (ExceptionResolver er : exceptionResolvers) { + if (log.isInfoEnabled()) { + log.info("Exception Resolver [{}] Found.", er.getClass()); + } + if (er.accept(ex)) { + log.info("Exception Has Been Accepted By [{}].", er); + model = er.process(model); + break; + } + } + return new ModelAndView(new JSONView(model, jsonViewConfig)); + } } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/TigonControllerAspect.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/TigonControllerAspect.java index 23dffd3..db93966 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/TigonControllerAspect.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/TigonControllerAspect.java @@ -27,9 +27,9 @@ public class TigonControllerAspect { * And Without @ResponseBody */ @Pointcut("(@target(org.springframework.stereotype.Controller) || " + - "@within(org.springframework.stereotype.Controller)) && " + - "!@target(org.springframework.web.bind.annotation.ResponseBody) && " + - "!@within(org.springframework.web.bind.annotation.ResponseBody)") + "@within(org.springframework.stereotype.Controller)) && " + + "!@target(org.springframework.web.bind.annotation.ResponseBody) && " + + "!@within(org.springframework.web.bind.annotation.ResponseBody)") public void controllerBean() {} /** @@ -38,15 +38,15 @@ public class TigonControllerAspect { * Without @ResponseBody */ @Pointcut("execution(@org.springframework.web.bind.annotation.RequestMapping public * *(..)) && " + - "!@annotation(org.springframework.web.bind.annotation.ResponseBody)") + "!@annotation(org.springframework.web.bind.annotation.ResponseBody)") public void methodPointcut() {} @AfterReturning(pointcut = "controllerBean() && methodPointcut()", returning = "result") public void afterReturning(JoinPoint jp, Object result) { if (result instanceof Map) { - if (log.isDebugEnabled()) { - log.debug("Controller Aspect After Returning, Return Map [{}].", JSON.toJSON(result)); - } + if (log.isDebugEnabled()) { + log.debug("Controller Aspect After Returning, Return Map [{}].", JSON.toJSON(result)); + } @SuppressWarnings("unchecked") Map mapRtn = (Map) result; Map mapData = new HashMap(mapRtn); diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/TigonReturnValueHandler.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/TigonReturnValueHandler.java index 53f44e5..20dc884 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/TigonReturnValueHandler.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/TigonReturnValueHandler.java @@ -24,19 +24,19 @@ import org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodPro * Mar 19, 2017 11:32:22 */ public class TigonReturnValueHandler - implements HandlerMethodReturnValueHandler { - private static final Logger log = - LoggerFactory.getLogger(TigonReturnValueHandler.class); + implements HandlerMethodReturnValueHandler { + private static final Logger log = + LoggerFactory.getLogger(TigonReturnValueHandler.class); - @Autowired - private JSONViewConfig jsonViewConfig; - private HttpEntityMethodProcessor httpEntityProcessor = - new HttpEntityMethodProcessor(Arrays.>asList( - new ResourceHttpMessageConverter())); - - /** - * {@inheritDoc} - */ + @Autowired + private JSONViewConfig jsonViewConfig; + private HttpEntityMethodProcessor httpEntityProcessor = + new HttpEntityMethodProcessor(Arrays.>asList( + new ResourceHttpMessageConverter())); + + /** + * {@inheritDoc} + */ @Override public boolean supportsReturnType(MethodParameter returnType) { return true; @@ -50,21 +50,21 @@ public class TigonReturnValueHandler MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { - log.debug("Return Value Handler, Handle Return Value [{}], Return Type [{}].", - returnValue, returnType); - if (!handleResource(returnValue, - returnType, mavContainer, webRequest)) { - JSONViewDataModel model = null; - if (returnValue instanceof JSONViewDataModel) { - log.debug("Controller Return Value Is JSONViewDataModel, Return."); - model = (JSONViewDataModel) returnValue; - } - else { - log.debug("Wrap Controller Return Value To Data Model."); - model = new JSONViewDataModel(returnValue); - } - mavContainer.setView(new JSONView(model, jsonViewConfig)); - } + log.debug("Return Value Handler, Handle Return Value [{}], Return Type [{}].", + returnValue, returnType); + if (!handleResource(returnValue, + returnType, mavContainer, webRequest)) { + JSONViewDataModel model = null; + if (returnValue instanceof JSONViewDataModel) { + log.debug("Controller Return Value Is JSONViewDataModel, Return."); + model = (JSONViewDataModel) returnValue; + } + else { + log.debug("Wrap Controller Return Value To Data Model."); + model = new JSONViewDataModel(returnValue); + } + mavContainer.setView(new JSONView(model, jsonViewConfig)); + } } /** @@ -77,59 +77,59 @@ public class TigonReturnValueHandler * @throws Exception on error caused */ private boolean handleResource(Object returnValue, - MethodParameter returnType, - ModelAndViewContainer mavContainer, - NativeWebRequest webRequest) throws Exception { + MethodParameter returnType, + ModelAndViewContainer mavContainer, + NativeWebRequest webRequest) throws Exception { - ResourceModel resourceModel = null; - HttpEntity entity = null; + ResourceModel resourceModel = null; + HttpEntity entity = null; if (returnValue instanceof ResourceModel) { - log.debug("Found Download Model Return."); - resourceModel = (ResourceModel) returnValue; + log.debug("Found Download Model Return."); + resourceModel = (ResourceModel) returnValue; } else if (returnValue instanceof HttpEntity) { - log.debug("Found HttpEntity Return."); - entity = (HttpEntity) returnValue; + log.debug("Found HttpEntity Return."); + entity = (HttpEntity) returnValue; } else if (returnValue instanceof File) { - log.debug("Found File [{}] Return.", returnValue); - resourceModel = new ResourceModel((File) returnValue, null, null); + log.debug("Found File [{}] Return.", returnValue); + resourceModel = new ResourceModel((File) returnValue, null, null); } - else if (returnValue instanceof Resource) { - log.debug("Found Resouce [{}] Return.", returnValue); - resourceModel = new ResourceModel((Resource) returnValue, null, 0, null); + else if (returnValue instanceof Resource) { + log.debug("Found Resouce [{}] Return.", returnValue); + resourceModel = new ResourceModel((Resource) returnValue, null, 0, null); } else if (returnValue instanceof byte[]) { - log.debug("Found Byte Array Return."); - resourceModel = new ResourceModel((byte[]) returnValue, null, null); + log.debug("Found Byte Array Return."); + resourceModel = new ResourceModel((byte[]) returnValue, null, null); } // assemble http entity if (resourceModel != null) { - HttpHeaders headers = new HttpHeaders(); - String name = resourceModel.getName(); - if (StringUtils.isNotBlank(name)) { - log.info("Found Resource Name [{}], Set Content-Disposition Header.", name); - name = URLEncoder.encode(name, CharEncoding.UTF_8); - StringBuilder sbDispo = - new StringBuilder("attachment; filename=\"") - .append(name) - .append("\"; filename*=utf-8''") - .append(name); - headers.set(HttpHeaders.CONTENT_DISPOSITION, - sbDispo.toString()); - } - headers.setContentType( - MediaType.valueOf(resourceModel.getContentType())); - headers.setContentLength(resourceModel.getContentLength()); - entity = new ResponseEntity( - resourceModel.getResource(), headers, HttpStatus.OK); + HttpHeaders headers = new HttpHeaders(); + String name = resourceModel.getName(); + if (StringUtils.isNotBlank(name)) { + log.info("Found Resource Name [{}], Set Content-Disposition Header.", name); + name = URLEncoder.encode(name, CharEncoding.UTF_8); + StringBuilder sbDispo = + new StringBuilder("attachment; filename=\"") + .append(name) + .append("\"; filename*=utf-8''") + .append(name); + headers.set(HttpHeaders.CONTENT_DISPOSITION, + sbDispo.toString()); + } + headers.setContentType( + MediaType.valueOf(resourceModel.getContentType())); + headers.setContentLength(resourceModel.getContentLength()); + entity = new ResponseEntity( + resourceModel.getResource(), headers, HttpStatus.OK); } - boolean handled = false; + boolean handled = false; if (entity != null) { - httpEntityProcessor.handleReturnValue(entity, - returnType, mavContainer, webRequest); - handled = true; + httpEntityProcessor.handleReturnValue(entity, + returnType, mavContainer, webRequest); + handled = true; } - return handled; + return handled; } } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/converter/StringToDateTypeConverter.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/converter/StringToDateTypeConverter.java index 9c008e5..b4d20df 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/converter/StringToDateTypeConverter.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/converter/StringToDateTypeConverter.java @@ -12,20 +12,20 @@ import org.springframework.core.convert.converter.Converter; * Oct 19, 2015 7:45:36 PM */ public class StringToDateTypeConverter - implements Converter { + implements Converter { - /** - * {@inheritDoc} - */ - @Override - public Date convert(String text) { - try { - return StringUtils.isNotBlank(text) ? - new Date(Long.parseLong(text.trim())) : null; - } - catch (NumberFormatException e) { - throw new IllegalArgumentException( - "Invalid Date [" + text + "] Param", e); - } - } + /** + * {@inheritDoc} + */ + @Override + public Date convert(String text) { + try { + return StringUtils.isNotBlank(text) ? + new Date(Long.parseLong(text.trim())) : null; + } + catch (NumberFormatException e) { + throw new IllegalArgumentException( + "Invalid Date [" + text + "] Param", e); + } + } } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/converter/StringToJSONArrayTypeConverter.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/converter/StringToJSONArrayTypeConverter.java index f40397c..34c2271 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/converter/StringToJSONArrayTypeConverter.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/converter/StringToJSONArrayTypeConverter.java @@ -14,20 +14,20 @@ import org.springframework.core.convert.converter.Converter; * Oct 27, 2015 7:57:53 PM */ public class StringToJSONArrayTypeConverter - implements Converter { + implements Converter { - /** - * {@inheritDoc} - */ - @Override - public JSONArray convert(String text) { - try { - return StringUtils.isNotBlank(text) ? - JSON.parseArray(text) : null; - } - catch (JSONException e) { - throw new IllegalArgumentException( - "Invalid JSONArray [" + text + "] Param", e); - } - } + /** + * {@inheritDoc} + */ + @Override + public JSONArray convert(String text) { + try { + return StringUtils.isNotBlank(text) ? + JSON.parseArray(text) : null; + } + catch (JSONException e) { + throw new IllegalArgumentException( + "Invalid JSONArray [" + text + "] Param", e); + } + } } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/converter/StringToJSONObjectTypeConverter.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/converter/StringToJSONObjectTypeConverter.java index 560197d..df8b00b 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/converter/StringToJSONObjectTypeConverter.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/converter/StringToJSONObjectTypeConverter.java @@ -14,20 +14,20 @@ import org.springframework.core.convert.converter.Converter; * Oct 27, 2015 7:58:13 PM */ public class StringToJSONObjectTypeConverter - implements Converter { + implements Converter { - /** - * {@inheritDoc} - */ - @Override - public JSONObject convert(String text) { - try { - return StringUtils.isNotBlank(text) ? - JSON.parseObject(text) : null; - } - catch (JSONException e) { - throw new IllegalArgumentException( - "Invalid JSONObject [" + text + "] Param", e); - } - } + /** + * {@inheritDoc} + */ + @Override + public JSONObject convert(String text) { + try { + return StringUtils.isNotBlank(text) ? + JSON.parseObject(text) : null; + } + catch (JSONException e) { + throw new IllegalArgumentException( + "Invalid JSONObject [" + text + "] Param", e); + } + } } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/BaseExceptionResolver.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/BaseExceptionResolver.java index 933bbb9..858c3bb 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/BaseExceptionResolver.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/BaseExceptionResolver.java @@ -13,19 +13,19 @@ import org.springframework.core.annotation.Order; @Order(32) public class BaseExceptionResolver extends DefaultExceptionResolver { - /** - * {@inheritDoc} - */ - @Override - public boolean accept(Throwable ex) { - return ex instanceof BaseException; - } + /** + * {@inheritDoc} + */ + @Override + public boolean accept(Throwable ex) { + return ex instanceof BaseException; + } - /** - * {@inheritDoc} - */ - @Override - protected Object getErrorCode(Throwable ex) { - return ((BaseException) ex).getCode(); - } + /** + * {@inheritDoc} + */ + @Override + protected Object getErrorCode(Throwable ex) { + return ((BaseException) ex).getCode(); + } } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/BindingResultResolver.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/BindingResultResolver.java index e48f15c..b87a91c 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/BindingResultResolver.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/BindingResultResolver.java @@ -20,37 +20,37 @@ import org.springframework.web.bind.MethodArgumentNotValidException; @Order(8) public class BindingResultResolver implements ExceptionResolver { - /** - * {@inheritDoc} - */ - @Override - public boolean accept(Throwable ex) { - return ex instanceof MethodArgumentNotValidException || - ex instanceof BindException; - } + /** + * {@inheritDoc} + */ + @Override + public boolean accept(Throwable ex) { + return ex instanceof MethodArgumentNotValidException || + ex instanceof BindException; + } - /** - * {@inheritDoc} - */ - @Override - public JSONViewDataModel process(JSONViewDataModel model) { - Throwable e = model.getException(); - BindingResult br = null; - if (e instanceof MethodArgumentNotValidException) { - br = ((MethodArgumentNotValidException) e).getBindingResult(); - } - else if (e instanceof BindException) { - br = ((BindException) e).getBindingResult(); - } - if (br != null) { - List fieldErrors = br.getFieldErrors(); - final List messages = new ArrayList(fieldErrors.size()); - for (FieldError er : fieldErrors) { - messages.add("'" + er.getField() + "' " + er.getDefaultMessage()); - } - model.setMessage(messages); - } - model.setCode(InvalidParamException.CODE); - return model; - } + /** + * {@inheritDoc} + */ + @Override + public JSONViewDataModel process(JSONViewDataModel model) { + Throwable e = model.getException(); + BindingResult br = null; + if (e instanceof MethodArgumentNotValidException) { + br = ((MethodArgumentNotValidException) e).getBindingResult(); + } + else if (e instanceof BindException) { + br = ((BindException) e).getBindingResult(); + } + if (br != null) { + List fieldErrors = br.getFieldErrors(); + final List messages = new ArrayList(fieldErrors.size()); + for (FieldError er : fieldErrors) { + messages.add("'" + er.getField() + "' " + er.getDefaultMessage()); + } + model.setMessage(messages); + } + model.setCode(InvalidParamException.CODE); + return model; + } } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/ConstraintViolationExceptionResolver.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/ConstraintViolationExceptionResolver.java index 7ad4ae8..a7879fa 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/ConstraintViolationExceptionResolver.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/ConstraintViolationExceptionResolver.java @@ -20,31 +20,31 @@ import me.chyxion.tigon.exception.InvalidParamException; */ @Order(10) public class ConstraintViolationExceptionResolver implements ExceptionResolver { - private static final Logger log = - LoggerFactory.getLogger(ConstraintViolationExceptionResolver.class); + private static final Logger log = + LoggerFactory.getLogger(ConstraintViolationExceptionResolver.class); - /** - * {@inheritDoc} - */ - @Override - public boolean accept(Throwable ex) { - return ex instanceof ConstraintViolationException; - } + /** + * {@inheritDoc} + */ + @Override + public boolean accept(Throwable ex) { + return ex instanceof ConstraintViolationException; + } - /** - * {@inheritDoc} - */ - @Override - public JSONViewDataModel process(final JSONViewDataModel model) { - final Set> cvs = + /** + * {@inheritDoc} + */ + @Override + public JSONViewDataModel process(final JSONViewDataModel model) { + final Set> cvs = ((ConstraintViolationException) model.getException()).getConstraintViolations(); - final List messages = new ArrayList(cvs.size()); - for (ConstraintViolation cv : cvs) { - log.info("Constraint Violation [{}] Caused.", cv); - messages.add("'" + cv.getPropertyPath() + "' " + cv.getMessage()); - } - model.setCode(InvalidParamException.CODE); - model.setMessage(messages); - return model; - } + final List messages = new ArrayList(cvs.size()); + for (ConstraintViolation cv : cvs) { + log.info("Constraint Violation [{}] Caused.", cv); + messages.add("'" + cv.getPropertyPath() + "' " + cv.getMessage()); + } + model.setCode(InvalidParamException.CODE); + model.setMessage(messages); + return model; + } } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/DefaultExceptionResolver.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/DefaultExceptionResolver.java index 044a1aa..b2c7c06 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/DefaultExceptionResolver.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/DefaultExceptionResolver.java @@ -25,113 +25,113 @@ import org.springframework.web.bind.MissingServletRequestParameterException; @Order(64) @Slf4j public class DefaultExceptionResolver implements ExceptionResolver { - @Autowired(required = false) - private ExceptionMessage exceptionMessage; + @Autowired(required = false) + private ExceptionMessage exceptionMessage; - private static final Map, Integer> EXCEPTIONS_MAP = - new HashMap, Integer>() { - private static final long serialVersionUID = 1L; - { - // Database Exceptions -// put(CannotAcquireLockException.class, 5030); -// put(CannotSerializeTransactionException.class, 5031); -// put(CleanupFailureDataAccessException.class, 5032); -// put(ConcurrencyFailureException.class, 5033); -// put(DataAccessException.class, 5034); -// put(DataAccessResourceFailureException.class, 5035); -// put(DataIntegrityViolationException.class, 5036); -// put(DataRetrievalFailureException.class, 5037); -// put(DeadlockLoserDataAccessException.class, 5038); -// put(DuplicateKeyException.class, 5039); -// put(EmptyResultDataAccessException.class, 5040); -// put(IncorrectResultSizeDataAccessException.class, 5041); -// put(IncorrectUpdateSemanticsDataAccessException.class, 5042); -// put(InvalidDataAccessApiUsageException.class, 5043); -// put(InvalidDataAccessResourceUsageException.class, 5044); -// put(NonTransientDataAccessException.class, 5045); -// put(NonTransientDataAccessResourceException.class, 5046); -// put(OptimisticLockingFailureException.class, 5047); -// put(PermissionDeniedDataAccessException.class, 5048); -// put(PessimisticLockingFailureException.class, 5049); -// put(QueryTimeoutException.class, 5050); -// put(RecoverableDataAccessException.class, 5051); -// put(TransientDataAccessException.class, 5052); -// put(TransientDataAccessResourceException.class, 5053); -// put(TypeMismatchDataAccessException.class, 5054); -// put(UncategorizedDataAccessException.class, 5055); - // 4002 - put(IllegalStateException.class, InvalidStateException.CODE); - put(ConversionFailedException.class, InvalidStateException.CODE); - put(IllegalArgumentException.class, InvalidStateException.CODE); - // 4001 - put(InvalidParamException.class, InvalidParamException.CODE); + private static final Map, Integer> EXCEPTIONS_MAP = + new HashMap, Integer>() { + private static final long serialVersionUID = 1L; + { + // Database Exceptions +// put(CannotAcquireLockException.class, 5030); +// put(CannotSerializeTransactionException.class, 5031); +// put(CleanupFailureDataAccessException.class, 5032); +// put(ConcurrencyFailureException.class, 5033); +// put(DataAccessException.class, 5034); +// put(DataAccessResourceFailureException.class, 5035); +// put(DataIntegrityViolationException.class, 5036); +// put(DataRetrievalFailureException.class, 5037); +// put(DeadlockLoserDataAccessException.class, 5038); +// put(DuplicateKeyException.class, 5039); +// put(EmptyResultDataAccessException.class, 5040); +// put(IncorrectResultSizeDataAccessException.class, 5041); +// put(IncorrectUpdateSemanticsDataAccessException.class, 5042); +// put(InvalidDataAccessApiUsageException.class, 5043); +// put(InvalidDataAccessResourceUsageException.class, 5044); +// put(NonTransientDataAccessException.class, 5045); +// put(NonTransientDataAccessResourceException.class, 5046); +// put(OptimisticLockingFailureException.class, 5047); +// put(PermissionDeniedDataAccessException.class, 5048); +// put(PessimisticLockingFailureException.class, 5049); +// put(QueryTimeoutException.class, 5050); +// put(RecoverableDataAccessException.class, 5051); +// put(TransientDataAccessException.class, 5052); +// put(TransientDataAccessResourceException.class, 5053); +// put(TypeMismatchDataAccessException.class, 5054); +// put(UncategorizedDataAccessException.class, 5055); + // 4002 + put(IllegalStateException.class, InvalidStateException.CODE); + put(ConversionFailedException.class, InvalidStateException.CODE); + put(IllegalArgumentException.class, InvalidStateException.CODE); + // 4001 + put(InvalidParamException.class, InvalidParamException.CODE); put(MissingServletRequestParameterException.class, InvalidParamException.CODE); put(ServletRequestBindingException.class, InvalidParamException.CODE); - } - }; + } + }; - /** - * {@inheritDoc} - */ - @Override - public boolean accept(Throwable ex) { - return true; - } + /** + * {@inheritDoc} + */ + @Override + public boolean accept(Throwable ex) { + return true; + } - /** - * {@inheritDoc} - */ - @Override - public JSONViewDataModel process(JSONViewDataModel model) { - Throwable ex = model.getException(); - log.error("Exception [{}] [{}] Caused.", ex.getClass(), ex.getMessage(), ex); - Object code = model.getCode(); - if (code == null || - (code instanceof Number && ((Number) code).intValue() == 0) || - (code instanceof String && StringUtils.isBlank((String) code))) { - code = getErrorCode(ex); - if (code == null) { - code = BaseException.CODE; - } - model.setCode(code); - } - if (model.getMessage() == null) { - Object message = null; - if (exceptionMessage != null) { - message = exceptionMessage.get(code); - log.info("Get Custom Error Message [{}] By Code [{}].", message, code); - } - if (message == null) { - message = getErrorMessage(ex, code); - } - model.setMessage(message); - } - return model; - } + /** + * {@inheritDoc} + */ + @Override + public JSONViewDataModel process(JSONViewDataModel model) { + Throwable ex = model.getException(); + log.error("Exception [{}] [{}] Caused.", ex.getClass(), ex.getMessage(), ex); + Object code = model.getCode(); + if (code == null || + (code instanceof Number && ((Number) code).intValue() == 0) || + (code instanceof String && StringUtils.isBlank((String) code))) { + code = getErrorCode(ex); + if (code == null) { + code = BaseException.CODE; + } + model.setCode(code); + } + if (model.getMessage() == null) { + Object message = null; + if (exceptionMessage != null) { + message = exceptionMessage.get(code); + log.info("Get Custom Error Message [{}] By Code [{}].", message, code); + } + if (message == null) { + message = getErrorMessage(ex, code); + } + model.setMessage(message); + } + return model; + } - /** - * @param ex exception - * @return error code - */ - protected Object getErrorCode(Throwable ex) { - return EXCEPTIONS_MAP.get(ex.getClass()); - } + /** + * @param ex exception + * @return error code + */ + protected Object getErrorCode(Throwable ex) { + return EXCEPTIONS_MAP.get(ex.getClass()); + } - /** - * @param ex exception - * @param code error code - * @return error message - */ - protected Object getErrorMessage(Throwable ex, Object code) { - Object message = null; - for (Throwable e : ExceptionUtils.getThrowableList(ex)) { - String msg = e.getMessage(); - if (StringUtils.isNotBlank(msg)) { - message = msg; - break; - } - } - log.info("No Custom Error Message Found, Get Message [{}] From Exception.", message); - return message; - } + /** + * @param ex exception + * @param code error code + * @return error message + */ + protected Object getErrorMessage(Throwable ex, Object code) { + Object message = null; + for (Throwable e : ExceptionUtils.getThrowableList(ex)) { + String msg = e.getMessage(); + if (StringUtils.isNotBlank(msg)) { + message = msg; + break; + } + } + log.info("No Custom Error Message Found, Get Message [{}] From Exception.", message); + return message; + } } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/ExceptionMessage.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/ExceptionMessage.java index 3af4e8f..b6a0a47 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/ExceptionMessage.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/ExceptionMessage.java @@ -8,11 +8,11 @@ package me.chyxion.tigon.webmvc.exception; * Jul 21, 2015 11:14:29 AM */ public interface ExceptionMessage { - - /** - * get exception message by code - * @param code exception code - * @return exception message - */ - T get(Object code); + + /** + * get exception message by code + * @param code exception code + * @return exception message + */ + T get(Object code); } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/ExceptionResolver.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/ExceptionResolver.java index 322dcee..bc5dd88 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/ExceptionResolver.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/exception/ExceptionResolver.java @@ -11,17 +11,17 @@ import me.chyxion.tigon.webmvc.JSONViewDataModel; */ public interface ExceptionResolver { - /** - * decide exception to process - * @param ex - * @return - */ - boolean accept(Throwable ex); + /** + * decide exception to process + * @param ex + * @return + */ + boolean accept(Throwable ex); - /** - * process model - * @param model - * @return - */ - JSONViewDataModel process(JSONViewDataModel model); + /** + * process model + * @param model + * @return + */ + JSONViewDataModel process(JSONViewDataModel model); } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/formatter/EmptyToNullAnnotationFormatterFactory.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/formatter/EmptyToNullAnnotationFormatterFactory.java index e276de2..238593d 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/formatter/EmptyToNullAnnotationFormatterFactory.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/formatter/EmptyToNullAnnotationFormatterFactory.java @@ -17,40 +17,40 @@ import org.springframework.context.support.EmbeddedValueResolutionSupport; * Jun 15, 2016 11:23:03 AM */ public class EmptyToNullAnnotationFormatterFactory - extends EmbeddedValueResolutionSupport - implements AnnotationFormatterFactory { + extends EmbeddedValueResolutionSupport + implements AnnotationFormatterFactory { - private static final Set> FIELD_TYPES; + private static final Set> FIELD_TYPES; - static { - Set> fieldTypes = new HashSet>(1); - fieldTypes.add(String.class); - FIELD_TYPES = Collections.unmodifiableSet(fieldTypes); - } + static { + Set> fieldTypes = new HashSet>(1); + fieldTypes.add(String.class); + FIELD_TYPES = Collections.unmodifiableSet(fieldTypes); + } - /** - * {@inheritDoc} - */ - @Override - public Set> getFieldTypes() { - return FIELD_TYPES; - } + /** + * {@inheritDoc} + */ + @Override + public Set> getFieldTypes() { + return FIELD_TYPES; + } - /** - * {@inheritDoc} - */ - @Override - public Printer getPrinter(EmptyToNull annotation, - Class fieldType) { - return new EmptyToNullFormatter(); - } + /** + * {@inheritDoc} + */ + @Override + public Printer getPrinter(EmptyToNull annotation, + Class fieldType) { + return new EmptyToNullFormatter(); + } - /** - * {@inheritDoc} - */ - @Override - public Parser getParser(EmptyToNull annotation, - Class fieldType) { - return new EmptyToNullFormatter(); - } + /** + * {@inheritDoc} + */ + @Override + public Parser getParser(EmptyToNull annotation, + Class fieldType) { + return new EmptyToNullFormatter(); + } } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/formatter/EmptyToNullFormatter.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/formatter/EmptyToNullFormatter.java index 19dda64..363c109 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/formatter/EmptyToNullFormatter.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/formatter/EmptyToNullFormatter.java @@ -14,19 +14,19 @@ import org.springframework.format.Formatter; */ public class EmptyToNullFormatter implements Formatter { - /** - * {@inheritDoc} - */ - @Override - public String print(String text, Locale locale) { - return text; - } + /** + * {@inheritDoc} + */ + @Override + public String print(String text, Locale locale) { + return text; + } - /** - * {@inheritDoc} - */ - @Override - public String parse(String text, Locale locale) throws ParseException { - return StringUtils.isNotEmpty(text) ? text : null; - } + /** + * {@inheritDoc} + */ + @Override + public String parse(String text, Locale locale) throws ParseException { + return StringUtils.isNotEmpty(text) ? text : null; + } } diff --git a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/util/ResponseTool.java b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/util/ResponseTool.java index e8f2fdb..e91f6d7 100644 --- a/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/util/ResponseTool.java +++ b/tigon-webmvc-core/src/main/java/me/chyxion/tigon/webmvc/util/ResponseTool.java @@ -16,15 +16,15 @@ import org.springframework.web.servlet.ModelAndView; @Slf4j public class ResponseTool { - public static final String PREFIX_DATA = "data:"; - public static final String PREFIX_REDIRECT = "redirect:"; - public static final String PREFIX_FORWARD = "forward:"; - public static final String PREFIX_JSP = "jsp:"; - public static final String PREFIX_FTL = "ftl:"; + public static final String PREFIX_DATA = "data:"; + public static final String PREFIX_REDIRECT = "redirect:"; + public static final String PREFIX_FORWARD = "forward:"; + public static final String PREFIX_JSP = "jsp:"; + public static final String PREFIX_FTL = "ftl:"; public String data(CharSequence data) { - log.debug("Build Data Response [{}:{}].", PREFIX_DATA, data); - return PREFIX_DATA + data; + log.debug("Build Data Response [{}:{}].", PREFIX_DATA, data); + return PREFIX_DATA + data; } /** @@ -33,8 +33,8 @@ public class ResponseTool { * @return */ public String jsp(CharSequence jsp) { - log.debug("Build JSP Response [{}:{}].", PREFIX_JSP, jsp); - return PREFIX_JSP + jsp; + log.debug("Build JSP Response [{}:{}].", PREFIX_JSP, jsp); + return PREFIX_JSP + jsp; } /** @@ -43,8 +43,8 @@ public class ResponseTool { * @return */ public ModelAndView jsp(ModelAndView mv) { - mv.setViewName(PREFIX_JSP + mv.getViewName()); - return mv; + mv.setViewName(PREFIX_JSP + mv.getViewName()); + return mv; } /** @@ -53,8 +53,8 @@ public class ResponseTool { * @return */ public ModelAndView ftl(ModelAndView mv) { - mv.setViewName(PREFIX_FTL + mv.getViewName()); - return mv; + mv.setViewName(PREFIX_FTL + mv.getViewName()); + return mv; } /** @@ -63,8 +63,8 @@ public class ResponseTool { * @return */ public String ftl(CharSequence ftl) { - log.debug("Build FreeMarker Response [{}:{}].", PREFIX_FTL, ftl); - return PREFIX_FTL + ftl; + log.debug("Build FreeMarker Response [{}:{}].", PREFIX_FTL, ftl); + return PREFIX_FTL + ftl; } /** @@ -73,8 +73,8 @@ public class ResponseTool { * @return */ public String redirect(String redirect) { - log.debug("Build Redirect Response [{}:{}].", PREFIX_REDIRECT, redirect); - return PREFIX_REDIRECT + redirect; + log.debug("Build Redirect Response [{}:{}].", PREFIX_REDIRECT, redirect); + return PREFIX_REDIRECT + redirect; } /** @@ -83,48 +83,48 @@ public class ResponseTool { * @return */ public String forward(String forward) { - log.debug("Build Forward Response [{}:{}].", PREFIX_FORWARD, forward); - return PREFIX_FORWARD + forward; + log.debug("Build Forward Response [{}:{}].", PREFIX_FORWARD, forward); + return PREFIX_FORWARD + forward; } - public void write(ServletResponse response, String data, String contentType, String encoding) { - response.setContentType(contentType); - response.setCharacterEncoding(encoding); - PrintWriter writer = null; - try { - writer = response.getWriter(); - writer.write(data); - writer.flush(); - } - catch (Exception e) { - throw new IllegalStateException( - "Write Response Error Caused", e); - } - finally { - closeQuietly(writer); - } - } + public void write(ServletResponse response, String data, String contentType, String encoding) { + response.setContentType(contentType); + response.setCharacterEncoding(encoding); + PrintWriter writer = null; + try { + writer = response.getWriter(); + writer.write(data); + writer.flush(); + } + catch (Exception e) { + throw new IllegalStateException( + "Write Response Error Caused", e); + } + finally { + closeQuietly(writer); + } + } - public void writeJSON(ServletResponse response, String data) { - write(response, data, "application/json;charset=utf-8", "utf-8"); - } + public void writeJSON(ServletResponse response, String data) { + write(response, data, "application/json;charset=utf-8", "utf-8"); + } - public void writeJSON(ServletResponse response, Object data) { - writeJSON(response, JSON.toJSONString(data)); - } + public void writeJSON(ServletResponse response, Object data) { + writeJSON(response, JSON.toJSONString(data)); + } - public void writeText(ServletResponse response, String data) { - write(response, data, "text/plain;charset=utf-8", "utf-8"); - } + public void writeText(ServletResponse response, String data) { + write(response, data, "text/plain;charset=utf-8", "utf-8"); + } - void closeQuietly(Closeable closeable) { - if (closeable != null) { - try { - closeable.close(); - } - catch (IOException e) { - log.warn("IO Close Error Caused.", e); - } - } - } + void closeQuietly(Closeable closeable) { + if (closeable != null) { + try { + closeable.close(); + } + catch (IOException e) { + log.warn("IO Close Error Caused.", e); + } + } + } } diff --git a/tigon-webmvc-core/src/main/resources/spring/spring-summer-webmvc-core.xml b/tigon-webmvc-core/src/main/resources/spring/spring-summer-webmvc-core.xml index de5ec9b..8e3ac9d 100644 --- a/tigon-webmvc-core/src/main/resources/spring/spring-summer-webmvc-core.xml +++ b/tigon-webmvc-core/src/main/resources/spring/spring-summer-webmvc-core.xml @@ -30,4 +30,4 @@
- \ No newline at end of file + diff --git a/tigon-webmvc-core/src/test/resources/log4j2.xml b/tigon-webmvc-core/src/test/resources/log4j2.xml index 08c2ae6..166de45 100644 --- a/tigon-webmvc-core/src/test/resources/log4j2.xml +++ b/tigon-webmvc-core/src/test/resources/log4j2.xml @@ -1,38 +1,38 @@ - - %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n - .logs - DEBUG - - - - - - + + %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n + .logs + DEBUG + + + - + + + + - - + + - + - - - - - - - - - + + + + + + + + + - - + + diff --git a/tigon-webmvc-spring-boot/pom.xml b/tigon-webmvc-spring-boot/pom.xml index b4fcb71..944212e 100644 --- a/tigon-webmvc-spring-boot/pom.xml +++ b/tigon-webmvc-spring-boot/pom.xml @@ -4,11 +4,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - 4.0.0 - tigon-webmvc-spring-boot - jar - Tigon Web MVC Spring Boot - Tigon Web MVC Spring Boot + 4.0.0 + tigon-webmvc-spring-boot + jar + Tigon Web MVC Spring Boot + Tigon Web MVC Spring Boot me.chyxion.tigon @@ -17,56 +17,56 @@ ../ - - - org.springframework.boot - spring-boot-starter-web - - - me.chyxion.tigon - tigon-webmvc-core - - - org.projectlombok - lombok - provided - - - javax.servlet - javax.servlet-api - provided - - - - me.chyxion.tigon - tigon-freemarker-support - test - + + + org.springframework.boot + spring-boot-starter-web + + + me.chyxion.tigon + tigon-webmvc-core + + + org.projectlombok + lombok + provided + + + javax.servlet + javax.servlet-api + provided + + + + me.chyxion.tigon + tigon-freemarker-support + test + me.chyxion.tigon tigon-extjs test - - org.springframework - spring-test - test - - - org.springframework.boot - spring-boot-test - test - + + org.springframework + spring-test + test + + + org.springframework.boot + spring-boot-test + test + javax.el javax.el-api test - - junit - junit - test - + + junit + junit + test + org.apache.logging.log4j log4j-slf4j-impl @@ -77,5 +77,5 @@ log4j-core test - + diff --git a/tigon-webmvc-spring-boot/src/test/java/me/chyxion/tigon/webmvc/test/SiteControllerTest.java b/tigon-webmvc-spring-boot/src/test/java/me/chyxion/tigon/webmvc/test/SiteControllerTest.java index edc3cba..f1e3d92 100644 --- a/tigon-webmvc-spring-boot/src/test/java/me/chyxion/tigon/webmvc/test/SiteControllerTest.java +++ b/tigon-webmvc-spring-boot/src/test/java/me/chyxion/tigon/webmvc/test/SiteControllerTest.java @@ -23,55 +23,55 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @SpringBootTest public class SiteControllerTest { - @Autowired - private ControllerTestTool t; + @Autowired + private ControllerTestTool t; - @Test - public void testIndex() { - t.print(t.get("/")); - } + @Test + public void testIndex() { + t.print(t.get("/")); + } - @Test - public void testRaw() { - t.print(t.get("/raw")); - } + @Test + public void testRaw() { + t.print(t.get("/raw")); + } - @Test - public void testInt() { - t.print(t.get("/int")); - } + @Test + public void testInt() { + t.print(t.get("/int")); + } - @Test - public void testFtl() { - t.print(t.get("/test")); - } + @Test + public void testFtl() { + t.print(t.get("/test")); + } - @Test - public void testViewModels() { - t.print(t.get("/view-model")); - } + @Test + public void testViewModels() { + t.print(t.get("/view-model")); + } - @Test - public void testListResult() { - t.print(t.get("/list-result")); - } + @Test + public void testListResult() { + t.print(t.get("/list-result")); + } - @Test - public void testListResult1() { - t.print(t.get("/list-result1")); - } + @Test + public void testListResult1() { + t.print(t.get("/list-result1")); + } - @Test - public void testExtJsCommon() { - t.print(t.get("/assets/js/extjs-commons.js")); - } + @Test + public void testExtJsCommon() { + t.print(t.get("/assets/js/extjs-commons.js")); + } - @Test - public void testPost() { - Map params = new HashMap(); - params.put("id", "id"); - params.put("name", "Shaun Chyxion"); - params.put("gender", ""); - t.print(t.post("/post", params)); - } + @Test + public void testPost() { + Map params = new HashMap(); + params.put("id", "id"); + params.put("name", "Shaun Chyxion"); + params.put("gender", ""); + t.print(t.post("/post", params)); + } } diff --git a/tigon-webmvc-spring-boot/src/test/java/me/chyxion/tigon/webmvc/test/controller/SiteController.java b/tigon-webmvc-spring-boot/src/test/java/me/chyxion/tigon/webmvc/test/controller/SiteController.java index f0af1ec..35d7b24 100644 --- a/tigon-webmvc-spring-boot/src/test/java/me/chyxion/tigon/webmvc/test/controller/SiteController.java +++ b/tigon-webmvc-spring-boot/src/test/java/me/chyxion/tigon/webmvc/test/controller/SiteController.java @@ -24,106 +24,106 @@ import org.springframework.web.servlet.ModelAndView; @Controller public class SiteController { - @RequestMapping("/") - public void index() { - - } + @RequestMapping("/") + public void index() { + + } - @RequestMapping("/raw") - public Map raw() { - Map mapRaw = new HashMap(); - mapRaw.put("data", "Hello!"); - return mapRaw; - } + @RequestMapping("/raw") + public Map raw() { + Map mapRaw = new HashMap(); + mapRaw.put("data", "Hello!"); + return mapRaw; + } - @RequestMapping("/int") - public int integer() { - return 99; - } + @RequestMapping("/int") + public int integer() { + return 99; + } - @RequestMapping("/test") - public ModelAndView test() { - return new ModelAndView("test").addObject("name", "FreeMarker"); - } + @RequestMapping("/test") + public ModelAndView test() { + return new ModelAndView("test").addObject("name", "FreeMarker"); + } - @RequestMapping("/view-models") - public List> viewModels() { - return Arrays.asList( - new ViewModel(1) - .setAttr("name", "foo"), - new ViewModel(2) - .setAttr("name", "bar") + @RequestMapping("/view-models") + public List> viewModels() { + return Arrays.asList( + new ViewModel(1) + .setAttr("name", "foo"), + new ViewModel(2) + .setAttr("name", "bar") .setAttr("other", new ViewModel(3) .setAttr("name", "foobar"))); - } + } - @RequestMapping("/list-result") - public ViewModelable> listResult() { - return new ListResult().setTotal(10).setData(Arrays.asList(1, 2, 3)).setAttr("attr", "foo"); - } + @RequestMapping("/list-result") + public ViewModelable> listResult() { + return new ListResult().setTotal(10).setData(Arrays.asList(1, 2, 3)).setAttr("attr", "foo"); + } - @RequestMapping("/list-result1") - public List>> listResult1() { - return Arrays.asList( - new ListResult() - .setTotal(10) - .setData(Arrays.asList(1, 2, 3)) - .setAttr("attr", "foo")); - } + @RequestMapping("/list-result1") + public List>> listResult1() { + return Arrays.asList( + new ListResult() + .setTotal(10) + .setData(Arrays.asList(1, 2, 3)) + .setAttr("attr", "foo")); + } - @RequestMapping("/post") - public String post(@Validated Form form) { - return form.getId(); - } - - public static class Form { - @NotBlank - private String id; - @NotBlank + @RequestMapping("/post") + public String post(@Validated Form form) { + return form.getId(); + } + + public static class Form { + @NotBlank + private String id; + @NotBlank private String name; - private String gender; + private String gender; - /** - * @return the id - */ - public String getId() { - return id; - } + /** + * @return the id + */ + public String getId() { + return id; + } - /** - * @param id the id to set - */ - public void setId(String id) { - this.id = id; - } + /** + * @param id the id to set + */ + public void setId(String id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the gender - */ - public String getGender() { - return gender; - } + /** + * @return the gender + */ + public String getGender() { + return gender; + } - /** - * @param gender the gender to set - */ - public void setGender(String gender) { - this.gender = gender; - } - } + /** + * @param gender the gender to set + */ + public void setGender(String gender) { + this.gender = gender; + } + } } diff --git a/tigon-webmvc-spring-boot/src/test/resources/log4j2.xml b/tigon-webmvc-spring-boot/src/test/resources/log4j2.xml index 08c2ae6..166de45 100644 --- a/tigon-webmvc-spring-boot/src/test/resources/log4j2.xml +++ b/tigon-webmvc-spring-boot/src/test/resources/log4j2.xml @@ -1,38 +1,38 @@ - - %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n - .logs - DEBUG - - - - - - + + %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n + .logs + DEBUG + + + - + + + + - - + + - + - - - - - - - - - + + + + + + + + + - - + + diff --git a/tigon-webmvc-spring-boot/src/test/resources/spring/spring-test.xml b/tigon-webmvc-spring-boot/src/test/resources/spring/spring-test.xml index d4db2ce..7aa0615 100644 --- a/tigon-webmvc-spring-boot/src/test/resources/spring/spring-test.xml +++ b/tigon-webmvc-spring-boot/src/test/resources/spring/spring-test.xml @@ -1,8 +1,8 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans.xsd"> diff --git a/tigon-webmvc-war/pom.xml b/tigon-webmvc-war/pom.xml index 07705af..3bbec9f 100644 --- a/tigon-webmvc-war/pom.xml +++ b/tigon-webmvc-war/pom.xml @@ -4,11 +4,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - 4.0.0 - tigon-webmvc-war - jar - Tigon Web MVC WAR - Tigon Web MVC WAR + 4.0.0 + tigon-webmvc-war + jar + Tigon Web MVC WAR + Tigon Web MVC WAR me.chyxion.tigon @@ -17,25 +17,25 @@ ../ - - - me.chyxion.tigon - tigon-webmvc-core - + + + me.chyxion.tigon + tigon-webmvc-core + commons-fileupload commons-fileupload - - javax.servlet - javax.servlet-api - provided - - - org.springframework - spring-test - test - + + javax.servlet + javax.servlet-api + provided + + + org.springframework + spring-test + test + javax.el @@ -49,10 +49,10 @@ test - junit - junit - test - + junit + junit + test + org.apache.logging.log4j log4j-slf4j-impl @@ -63,5 +63,5 @@ log4j-core test - + diff --git a/tigon-webmvc-war/src/main/java/me/chyxion/tigon/webmvc/war/AppContextInitializer.java b/tigon-webmvc-war/src/main/java/me/chyxion/tigon/webmvc/war/AppContextInitializer.java index d981450..7c41905 100644 --- a/tigon-webmvc-war/src/main/java/me/chyxion/tigon/webmvc/war/AppContextInitializer.java +++ b/tigon-webmvc-war/src/main/java/me/chyxion/tigon/webmvc/war/AppContextInitializer.java @@ -13,16 +13,16 @@ import org.springframework.context.support.AbstractRefreshableApplicationContext * Jan 23, 2015 12:19:07 PM */ public class AppContextInitializer - implements ApplicationContextInitializer { + implements ApplicationContextInitializer { - /** - * {@inheritDoc} - */ - @Override - public void initialize(ConfigurableApplicationContext appContext) { - if (appContext instanceof AbstractRefreshableApplicationContext) { + /** + * {@inheritDoc} + */ + @Override + public void initialize(ConfigurableApplicationContext appContext) { + if (appContext instanceof AbstractRefreshableApplicationContext) { ((AbstractRefreshableApplicationContext) appContext) - .setAllowBeanDefinitionOverriding(false); + .setAllowBeanDefinitionOverriding(false); } - } + } } diff --git a/tigon-webmvc-war/src/main/resources/META-INF/web-fragment.xml b/tigon-webmvc-war/src/main/resources/META-INF/web-fragment.xml index 85e4ef3..232a30b 100644 --- a/tigon-webmvc-war/src/main/resources/META-INF/web-fragment.xml +++ b/tigon-webmvc-war/src/main/resources/META-INF/web-fragment.xml @@ -15,11 +15,11 @@ spring.profiles.active profile_active - - contextConfigLocation - classpath*:spring/**/spring-*.xml - - + + contextConfigLocation + classpath*:spring/**/spring-*.xml + + contextInitializerClasses me.chyxion.tigon.webmvc.war.AppContextInitializer @@ -27,12 +27,12 @@ org.springframework.web.context.ContextLoaderListener - + encoding org.springframework.web.filter.CharacterEncodingFilter - encoding - UTF-8 + encoding + UTF-8 forceEncoding @@ -58,8 +58,8 @@ spring-mvc org.springframework.web.servlet.DispatcherServlet - contextConfigLocation - classpath*:spring/**/servlet-spring-*.xml + contextConfigLocation + classpath*:spring/**/servlet-spring-*.xml true 1 diff --git a/tigon-webmvc-war/src/main/resources/spring/spring-summer-webmvc.xml b/tigon-webmvc-war/src/main/resources/spring/spring-summer-webmvc.xml index f15238f..c2ca0da 100644 --- a/tigon-webmvc-war/src/main/resources/spring/spring-summer-webmvc.xml +++ b/tigon-webmvc-war/src/main/resources/spring/spring-summer-webmvc.xml @@ -11,4 +11,4 @@ http://www.springframework.org/schema/context/spring-context.xsd"> - \ No newline at end of file + diff --git a/tigon-webmvc-war/src/test/java/me/chyxion/tigon/webmvc/test/SiteControllerTest.java b/tigon-webmvc-war/src/test/java/me/chyxion/tigon/webmvc/test/SiteControllerTest.java index 48a0b17..ff4545e 100644 --- a/tigon-webmvc-war/src/test/java/me/chyxion/tigon/webmvc/test/SiteControllerTest.java +++ b/tigon-webmvc-war/src/test/java/me/chyxion/tigon/webmvc/test/SiteControllerTest.java @@ -25,75 +25,75 @@ import org.springframework.validation.annotation.Validated; @WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ - "classpath*:spring/spring-*.xml", - "classpath*:spring/servlet-spring-*.xml" + "classpath*:spring/spring-*.xml", + "classpath*:spring/servlet-spring-*.xml" }) @Validated public class SiteControllerTest { - @Autowired - private ControllerTestTool t; - @Autowired - private Validator v; + @Autowired + private ControllerTestTool t; + @Autowired + private Validator v; - @Test - public void testIndex() { - t.print(t.get("/")); - } + @Test + public void testIndex() { + t.print(t.get("/")); + } - @Test - public void testV() { - t.print(t.get("/v?v=")); - } + @Test + public void testV() { + t.print(t.get("/v?v=")); + } - @Test - public void testValidation() { - testValidation(""); - } + @Test + public void testValidation() { + testValidation(""); + } - public void testValidation(@NotBlank String foo) { + public void testValidation(@NotBlank String foo) { - } + } - @Test - public void testRaw() { - t.print(t.get("/raw")); - } + @Test + public void testRaw() { + t.print(t.get("/raw")); + } - @Test - public void testInt() { - t.print(t.get("/int")); - } + @Test + public void testInt() { + t.print(t.get("/int")); + } - @Test - public void testPost() { - Map params = new HashMap(); - params.put("id", ""); - params.put("name", "Shaun Chyxion"); - params.put("gender", ""); - t.print(t.post("/post", params)); - } + @Test + public void testPost() { + Map params = new HashMap(); + params.put("id", ""); + params.put("name", "Shaun Chyxion"); + params.put("gender", ""); + t.print(t.post("/post", params)); + } - @Test - public void testValidate() { - Set> result = v.validate(new Form()); - for (ConstraintViolation
vv : result) { - System.err.println("[" + - vv.getPropertyPath() + "] " + vv.getMessage()); - } - } - - @Test - public void testValidate1() { - Form form = new Form(); - form.setId("chyxion"); - form.setName("chyxion"); - form.setGender(""); + @Test + public void testValidate() { + Set> result = v.validate(new Form()); + for (ConstraintViolation vv : result) { + System.err.println("[" + + vv.getPropertyPath() + "] " + vv.getMessage()); + } + } + + @Test + public void testValidate1() { + Form form = new Form(); + form.setId("chyxion"); + form.setName("chyxion"); + form.setGender(""); - Set> result = v.validate(form); - for (ConstraintViolation vv : result) { - System.err.println(vv.getMessage()); - System.err.println(vv.getPropertyPath().toString()); - } - } + Set> result = v.validate(form); + for (ConstraintViolation vv : result) { + System.err.println(vv.getMessage()); + System.err.println(vv.getPropertyPath().toString()); + } + } } diff --git a/tigon-webmvc-war/src/test/java/me/chyxion/tigon/webmvc/test/controller/SiteController.java b/tigon-webmvc-war/src/test/java/me/chyxion/tigon/webmvc/test/controller/SiteController.java index b2ab6a2..48921b8 100644 --- a/tigon-webmvc-war/src/test/java/me/chyxion/tigon/webmvc/test/controller/SiteController.java +++ b/tigon-webmvc-war/src/test/java/me/chyxion/tigon/webmvc/test/controller/SiteController.java @@ -21,83 +21,83 @@ import org.springframework.web.bind.annotation.RequestParam; @Controller public class SiteController { - @RequestMapping("/") - public void index() { - - } + @RequestMapping("/") + public void index() { + + } - @RequestMapping("/v") - public String index(@RequestParam("v") + @RequestMapping("/v") + public String index(@RequestParam("v") // @EmptyToNull String validate) { - return validate; - } + return validate; + } - @RequestMapping("/raw") - public Map raw() { - Map mapRaw = new HashMap(); - mapRaw.put("data", "Hello!"); - return mapRaw; - } + @RequestMapping("/raw") + public Map raw() { + Map mapRaw = new HashMap(); + mapRaw.put("data", "Hello!"); + return mapRaw; + } - @RequestMapping("/int") - public int integer() { - return 99; - } + @RequestMapping("/int") + public int integer() { + return 99; + } - @RequestMapping("/post") - public String post(@Validated Form form) { - return form.getId(); - } - - public static class Form { - @NotBlank - private String id; - @NotBlank + @RequestMapping("/post") + public String post(@Validated Form form) { + return form.getId(); + } + + public static class Form { + @NotBlank + private String id; + @NotBlank private String name; - @EmptyToNull - private String gender; + @EmptyToNull + private String gender; - /** - * @return the id - */ - public String getId() { - return id; - } + /** + * @return the id + */ + public String getId() { + return id; + } - /** - * @param id the id to set - */ - public void setId(String id) { - this.id = id; - } + /** + * @param id the id to set + */ + public void setId(String id) { + this.id = id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the gender - */ - public String getGender() { - return gender; - } + /** + * @return the gender + */ + public String getGender() { + return gender; + } - /** - * @param gender the gender to set - */ - public void setGender(String gender) { - this.gender = gender; - } - } + /** + * @param gender the gender to set + */ + public void setGender(String gender) { + this.gender = gender; + } + } } diff --git a/tigon-webmvc-war/src/test/resources/log4j2.xml b/tigon-webmvc-war/src/test/resources/log4j2.xml index 27958bb..c7486b5 100644 --- a/tigon-webmvc-war/src/test/resources/log4j2.xml +++ b/tigon-webmvc-war/src/test/resources/log4j2.xml @@ -1,37 +1,37 @@ - - %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n - .logs - DEBUG - - - - - - + + %-d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t][%c{1}] %m%n + .logs + DEBUG + + + - + + + + - - + + - + - - - - - - - - - + + + + + + + + + - - + +