repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
fireshort/spring-boot-quickstart
src/test/functional/org/springside/examples/quickstart/functional/gui/TaskGuiFT.java
// Path: src/test/java/org/springside/examples/quickstart/data/TaskData.java // public class TaskData { // // public static Task randomTask() { // Task task = new Task(); // task.setTitle(randomTitle()); // User user = new User(1L); // task.setUser(user); // return task; // } // // public static String randomTitle() { // return RandomData.randomName("Task"); // } // } // // Path: src/main/java/org/springside/examples/quickstart/entity/Task.java // @Entity // @Table(name = "ss_task") // public class Task extends IdEntity { // // private String title; // private String description; // private User user; // // // JSR303 BeanValidator的校验规则 // @NotBlank // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // // JPA 基于USER_ID列的多对一关系定义 // @ManyToOne // @JoinColumn(name = "user_id") // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this); // } // } // // Path: src/test/functional/org/springside/examples/quickstart/functional/BaseSeleniumTestCase.java // public class BaseSeleniumTestCase extends BaseFunctionalTestCase { // // protected static Selenium2 s; // // // 出错时截屏的规则 // @Rule // public TestRule snapshotRule = new SeleniumSnapshotRule(s); // // @BeforeClass // public static void initSelenium() throws Exception { // createSeleniumOnce(); // loginAsUserIfNecessary(); // } // // /** // * 创建Selenium,仅创建一次. // */ // protected static void createSeleniumOnce() throws Exception { // if (s == null) { // // 根据配置创建Selenium driver. // String driverName = propertiesLoader.getProperty("selenium.driver"); // // WebDriver driver = WebDriverFactory.createDriver(driverName); // // s = new Selenium2(driver, baseUrl); // s.setStopAtShutdown(); // } // } // // /** // * 登录管理员, 如果用户还没有登录. // */ // protected static void loginAsUserIfNecessary() { // s.open("/task"); // // if (s.getTitle().contains("登录页")) { // s.type(By.name("username"), "user"); // s.type(By.name("password"), "user"); // s.check(By.name("rememberMe")); // s.click(By.id("submit_btn")); // s.waitForTitleContains("任务管理"); // } // } // }
import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.junit.experimental.categories.Category; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.springside.examples.quickstart.data.TaskData; import org.springside.examples.quickstart.entity.Task; import org.springside.examples.quickstart.functional.BaseSeleniumTestCase; import org.springside.modules.test.category.Smoke;
/******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.quickstart.functional.gui; /** * 任务管理的功能测试, 测试页面JavaScript及主要用户故事流程. * * @author calvin */ public class TaskGuiFT extends BaseSeleniumTestCase { /** * 浏览任务列表. */ @Test @Category(Smoke.class) public void viewTaskList() { s.open("/task/"); WebElement table = s.findElement(By.id("contentTable")); assertThat(s.getTable(table, 0, 0)).isEqualTo("Release SpringSide 4.0"); } /** * 创建/更新/搜索/删除任务. */ @Test @Category(Smoke.class) public void crudTask() { s.open("/task/"); // create s.click(By.linkText("创建任务"));
// Path: src/test/java/org/springside/examples/quickstart/data/TaskData.java // public class TaskData { // // public static Task randomTask() { // Task task = new Task(); // task.setTitle(randomTitle()); // User user = new User(1L); // task.setUser(user); // return task; // } // // public static String randomTitle() { // return RandomData.randomName("Task"); // } // } // // Path: src/main/java/org/springside/examples/quickstart/entity/Task.java // @Entity // @Table(name = "ss_task") // public class Task extends IdEntity { // // private String title; // private String description; // private User user; // // // JSR303 BeanValidator的校验规则 // @NotBlank // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // // JPA 基于USER_ID列的多对一关系定义 // @ManyToOne // @JoinColumn(name = "user_id") // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this); // } // } // // Path: src/test/functional/org/springside/examples/quickstart/functional/BaseSeleniumTestCase.java // public class BaseSeleniumTestCase extends BaseFunctionalTestCase { // // protected static Selenium2 s; // // // 出错时截屏的规则 // @Rule // public TestRule snapshotRule = new SeleniumSnapshotRule(s); // // @BeforeClass // public static void initSelenium() throws Exception { // createSeleniumOnce(); // loginAsUserIfNecessary(); // } // // /** // * 创建Selenium,仅创建一次. // */ // protected static void createSeleniumOnce() throws Exception { // if (s == null) { // // 根据配置创建Selenium driver. // String driverName = propertiesLoader.getProperty("selenium.driver"); // // WebDriver driver = WebDriverFactory.createDriver(driverName); // // s = new Selenium2(driver, baseUrl); // s.setStopAtShutdown(); // } // } // // /** // * 登录管理员, 如果用户还没有登录. // */ // protected static void loginAsUserIfNecessary() { // s.open("/task"); // // if (s.getTitle().contains("登录页")) { // s.type(By.name("username"), "user"); // s.type(By.name("password"), "user"); // s.check(By.name("rememberMe")); // s.click(By.id("submit_btn")); // s.waitForTitleContains("任务管理"); // } // } // } // Path: src/test/functional/org/springside/examples/quickstart/functional/gui/TaskGuiFT.java import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.junit.experimental.categories.Category; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.springside.examples.quickstart.data.TaskData; import org.springside.examples.quickstart.entity.Task; import org.springside.examples.quickstart.functional.BaseSeleniumTestCase; import org.springside.modules.test.category.Smoke; /******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.quickstart.functional.gui; /** * 任务管理的功能测试, 测试页面JavaScript及主要用户故事流程. * * @author calvin */ public class TaskGuiFT extends BaseSeleniumTestCase { /** * 浏览任务列表. */ @Test @Category(Smoke.class) public void viewTaskList() { s.open("/task/"); WebElement table = s.findElement(By.id("contentTable")); assertThat(s.getTable(table, 0, 0)).isEqualTo("Release SpringSide 4.0"); } /** * 创建/更新/搜索/删除任务. */ @Test @Category(Smoke.class) public void crudTask() { s.open("/task/"); // create s.click(By.linkText("创建任务"));
Task task = TaskData.randomTask();
fireshort/spring-boot-quickstart
src/test/functional/org/springside/examples/quickstart/functional/gui/TaskGuiFT.java
// Path: src/test/java/org/springside/examples/quickstart/data/TaskData.java // public class TaskData { // // public static Task randomTask() { // Task task = new Task(); // task.setTitle(randomTitle()); // User user = new User(1L); // task.setUser(user); // return task; // } // // public static String randomTitle() { // return RandomData.randomName("Task"); // } // } // // Path: src/main/java/org/springside/examples/quickstart/entity/Task.java // @Entity // @Table(name = "ss_task") // public class Task extends IdEntity { // // private String title; // private String description; // private User user; // // // JSR303 BeanValidator的校验规则 // @NotBlank // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // // JPA 基于USER_ID列的多对一关系定义 // @ManyToOne // @JoinColumn(name = "user_id") // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this); // } // } // // Path: src/test/functional/org/springside/examples/quickstart/functional/BaseSeleniumTestCase.java // public class BaseSeleniumTestCase extends BaseFunctionalTestCase { // // protected static Selenium2 s; // // // 出错时截屏的规则 // @Rule // public TestRule snapshotRule = new SeleniumSnapshotRule(s); // // @BeforeClass // public static void initSelenium() throws Exception { // createSeleniumOnce(); // loginAsUserIfNecessary(); // } // // /** // * 创建Selenium,仅创建一次. // */ // protected static void createSeleniumOnce() throws Exception { // if (s == null) { // // 根据配置创建Selenium driver. // String driverName = propertiesLoader.getProperty("selenium.driver"); // // WebDriver driver = WebDriverFactory.createDriver(driverName); // // s = new Selenium2(driver, baseUrl); // s.setStopAtShutdown(); // } // } // // /** // * 登录管理员, 如果用户还没有登录. // */ // protected static void loginAsUserIfNecessary() { // s.open("/task"); // // if (s.getTitle().contains("登录页")) { // s.type(By.name("username"), "user"); // s.type(By.name("password"), "user"); // s.check(By.name("rememberMe")); // s.click(By.id("submit_btn")); // s.waitForTitleContains("任务管理"); // } // } // }
import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.junit.experimental.categories.Category; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.springside.examples.quickstart.data.TaskData; import org.springside.examples.quickstart.entity.Task; import org.springside.examples.quickstart.functional.BaseSeleniumTestCase; import org.springside.modules.test.category.Smoke;
/******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.quickstart.functional.gui; /** * 任务管理的功能测试, 测试页面JavaScript及主要用户故事流程. * * @author calvin */ public class TaskGuiFT extends BaseSeleniumTestCase { /** * 浏览任务列表. */ @Test @Category(Smoke.class) public void viewTaskList() { s.open("/task/"); WebElement table = s.findElement(By.id("contentTable")); assertThat(s.getTable(table, 0, 0)).isEqualTo("Release SpringSide 4.0"); } /** * 创建/更新/搜索/删除任务. */ @Test @Category(Smoke.class) public void crudTask() { s.open("/task/"); // create s.click(By.linkText("创建任务"));
// Path: src/test/java/org/springside/examples/quickstart/data/TaskData.java // public class TaskData { // // public static Task randomTask() { // Task task = new Task(); // task.setTitle(randomTitle()); // User user = new User(1L); // task.setUser(user); // return task; // } // // public static String randomTitle() { // return RandomData.randomName("Task"); // } // } // // Path: src/main/java/org/springside/examples/quickstart/entity/Task.java // @Entity // @Table(name = "ss_task") // public class Task extends IdEntity { // // private String title; // private String description; // private User user; // // // JSR303 BeanValidator的校验规则 // @NotBlank // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // // JPA 基于USER_ID列的多对一关系定义 // @ManyToOne // @JoinColumn(name = "user_id") // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this); // } // } // // Path: src/test/functional/org/springside/examples/quickstart/functional/BaseSeleniumTestCase.java // public class BaseSeleniumTestCase extends BaseFunctionalTestCase { // // protected static Selenium2 s; // // // 出错时截屏的规则 // @Rule // public TestRule snapshotRule = new SeleniumSnapshotRule(s); // // @BeforeClass // public static void initSelenium() throws Exception { // createSeleniumOnce(); // loginAsUserIfNecessary(); // } // // /** // * 创建Selenium,仅创建一次. // */ // protected static void createSeleniumOnce() throws Exception { // if (s == null) { // // 根据配置创建Selenium driver. // String driverName = propertiesLoader.getProperty("selenium.driver"); // // WebDriver driver = WebDriverFactory.createDriver(driverName); // // s = new Selenium2(driver, baseUrl); // s.setStopAtShutdown(); // } // } // // /** // * 登录管理员, 如果用户还没有登录. // */ // protected static void loginAsUserIfNecessary() { // s.open("/task"); // // if (s.getTitle().contains("登录页")) { // s.type(By.name("username"), "user"); // s.type(By.name("password"), "user"); // s.check(By.name("rememberMe")); // s.click(By.id("submit_btn")); // s.waitForTitleContains("任务管理"); // } // } // } // Path: src/test/functional/org/springside/examples/quickstart/functional/gui/TaskGuiFT.java import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.junit.experimental.categories.Category; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.springside.examples.quickstart.data.TaskData; import org.springside.examples.quickstart.entity.Task; import org.springside.examples.quickstart.functional.BaseSeleniumTestCase; import org.springside.modules.test.category.Smoke; /******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.quickstart.functional.gui; /** * 任务管理的功能测试, 测试页面JavaScript及主要用户故事流程. * * @author calvin */ public class TaskGuiFT extends BaseSeleniumTestCase { /** * 浏览任务列表. */ @Test @Category(Smoke.class) public void viewTaskList() { s.open("/task/"); WebElement table = s.findElement(By.id("contentTable")); assertThat(s.getTable(table, 0, 0)).isEqualTo("Release SpringSide 4.0"); } /** * 创建/更新/搜索/删除任务. */ @Test @Category(Smoke.class) public void crudTask() { s.open("/task/"); // create s.click(By.linkText("创建任务"));
Task task = TaskData.randomTask();
fireshort/spring-boot-quickstart
src/main/java/org/springside/examples/quickstart/rest/TaskRestController.java
// Path: src/main/java/org/springside/examples/quickstart/entity/Task.java // @Entity // @Table(name = "ss_task") // public class Task extends IdEntity { // // private String title; // private String description; // private User user; // // // JSR303 BeanValidator的校验规则 // @NotBlank // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // // JPA 基于USER_ID列的多对一关系定义 // @ManyToOne // @JoinColumn(name = "user_id") // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this); // } // } // // Path: src/main/java/org/springside/examples/quickstart/service/task/TaskService.java // @Component // // 类中所有public函数都纳入事务管理的标识. // @Transactional // public class TaskService { // // private TaskDao taskDao; // // public Task getTask(Long id) { // return taskDao.findOne(id); // } // // public void saveTask(Task entity) { // taskDao.save(entity); // } // // public void deleteTask(Long id) { // taskDao.delete(id); // } // // public List<Task> getAllTask() { // return (List<Task>) taskDao.findAll(); // } // // public Page<Task> getUserTask(Long userId, Map<String, Object> searchParams, int pageNumber, int pageSize, // String sortType) { // PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType); // Specification<Task> spec = buildSpecification(userId, searchParams); // // return taskDao.findAll(spec, pageRequest); // } // // /** // * 创建分页请求. // */ // private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) { // Sort sort = null; // if ("auto".equals(sortType)) { // sort = new Sort(Direction.DESC, "id"); // } else if ("title".equals(sortType)) { // sort = new Sort(Direction.ASC, "title"); // } // // return new PageRequest(pageNumber - 1, pagzSize, sort); // } // // /** // * 创建动态查询条件组合. // */ // private Specification<Task> buildSpecification(Long userId, Map<String, Object> searchParams) { // Map<String, SearchFilter> filters = SearchFilter.parse(searchParams); // filters.put("user.id", new SearchFilter("user.id", Operator.EQ, userId)); // Specification<Task> spec = DynamicSpecifications.bySearchFilter(filters.values(), Task.class); // return spec; // } // // @Autowired // public void setTaskDao(TaskDao taskDao) { // this.taskDao = taskDao; // } // }
import org.springside.examples.quickstart.entity.Task; import org.springside.examples.quickstart.service.task.TaskService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import org.springside.modules.beanvalidator.BeanValidators; import org.springside.modules.web.MediaTypes; import javax.validation.Validator; import java.net.URI; import java.util.List;
/******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.quickstart.rest; /** * Task的Restful API的Controller. * * @author calvin */ @RestController @RequestMapping(value = "/api/v1/task") public class TaskRestController { private static Logger logger = LoggerFactory.getLogger(TaskRestController.class); @Autowired
// Path: src/main/java/org/springside/examples/quickstart/entity/Task.java // @Entity // @Table(name = "ss_task") // public class Task extends IdEntity { // // private String title; // private String description; // private User user; // // // JSR303 BeanValidator的校验规则 // @NotBlank // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // // JPA 基于USER_ID列的多对一关系定义 // @ManyToOne // @JoinColumn(name = "user_id") // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this); // } // } // // Path: src/main/java/org/springside/examples/quickstart/service/task/TaskService.java // @Component // // 类中所有public函数都纳入事务管理的标识. // @Transactional // public class TaskService { // // private TaskDao taskDao; // // public Task getTask(Long id) { // return taskDao.findOne(id); // } // // public void saveTask(Task entity) { // taskDao.save(entity); // } // // public void deleteTask(Long id) { // taskDao.delete(id); // } // // public List<Task> getAllTask() { // return (List<Task>) taskDao.findAll(); // } // // public Page<Task> getUserTask(Long userId, Map<String, Object> searchParams, int pageNumber, int pageSize, // String sortType) { // PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType); // Specification<Task> spec = buildSpecification(userId, searchParams); // // return taskDao.findAll(spec, pageRequest); // } // // /** // * 创建分页请求. // */ // private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) { // Sort sort = null; // if ("auto".equals(sortType)) { // sort = new Sort(Direction.DESC, "id"); // } else if ("title".equals(sortType)) { // sort = new Sort(Direction.ASC, "title"); // } // // return new PageRequest(pageNumber - 1, pagzSize, sort); // } // // /** // * 创建动态查询条件组合. // */ // private Specification<Task> buildSpecification(Long userId, Map<String, Object> searchParams) { // Map<String, SearchFilter> filters = SearchFilter.parse(searchParams); // filters.put("user.id", new SearchFilter("user.id", Operator.EQ, userId)); // Specification<Task> spec = DynamicSpecifications.bySearchFilter(filters.values(), Task.class); // return spec; // } // // @Autowired // public void setTaskDao(TaskDao taskDao) { // this.taskDao = taskDao; // } // } // Path: src/main/java/org/springside/examples/quickstart/rest/TaskRestController.java import org.springside.examples.quickstart.entity.Task; import org.springside.examples.quickstart.service.task.TaskService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import org.springside.modules.beanvalidator.BeanValidators; import org.springside.modules.web.MediaTypes; import javax.validation.Validator; import java.net.URI; import java.util.List; /******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.quickstart.rest; /** * Task的Restful API的Controller. * * @author calvin */ @RestController @RequestMapping(value = "/api/v1/task") public class TaskRestController { private static Logger logger = LoggerFactory.getLogger(TaskRestController.class); @Autowired
private TaskService taskService;
fireshort/spring-boot-quickstart
src/main/java/org/springside/examples/quickstart/rest/TaskRestController.java
// Path: src/main/java/org/springside/examples/quickstart/entity/Task.java // @Entity // @Table(name = "ss_task") // public class Task extends IdEntity { // // private String title; // private String description; // private User user; // // // JSR303 BeanValidator的校验规则 // @NotBlank // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // // JPA 基于USER_ID列的多对一关系定义 // @ManyToOne // @JoinColumn(name = "user_id") // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this); // } // } // // Path: src/main/java/org/springside/examples/quickstart/service/task/TaskService.java // @Component // // 类中所有public函数都纳入事务管理的标识. // @Transactional // public class TaskService { // // private TaskDao taskDao; // // public Task getTask(Long id) { // return taskDao.findOne(id); // } // // public void saveTask(Task entity) { // taskDao.save(entity); // } // // public void deleteTask(Long id) { // taskDao.delete(id); // } // // public List<Task> getAllTask() { // return (List<Task>) taskDao.findAll(); // } // // public Page<Task> getUserTask(Long userId, Map<String, Object> searchParams, int pageNumber, int pageSize, // String sortType) { // PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType); // Specification<Task> spec = buildSpecification(userId, searchParams); // // return taskDao.findAll(spec, pageRequest); // } // // /** // * 创建分页请求. // */ // private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) { // Sort sort = null; // if ("auto".equals(sortType)) { // sort = new Sort(Direction.DESC, "id"); // } else if ("title".equals(sortType)) { // sort = new Sort(Direction.ASC, "title"); // } // // return new PageRequest(pageNumber - 1, pagzSize, sort); // } // // /** // * 创建动态查询条件组合. // */ // private Specification<Task> buildSpecification(Long userId, Map<String, Object> searchParams) { // Map<String, SearchFilter> filters = SearchFilter.parse(searchParams); // filters.put("user.id", new SearchFilter("user.id", Operator.EQ, userId)); // Specification<Task> spec = DynamicSpecifications.bySearchFilter(filters.values(), Task.class); // return spec; // } // // @Autowired // public void setTaskDao(TaskDao taskDao) { // this.taskDao = taskDao; // } // }
import org.springside.examples.quickstart.entity.Task; import org.springside.examples.quickstart.service.task.TaskService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import org.springside.modules.beanvalidator.BeanValidators; import org.springside.modules.web.MediaTypes; import javax.validation.Validator; import java.net.URI; import java.util.List;
/******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.quickstart.rest; /** * Task的Restful API的Controller. * * @author calvin */ @RestController @RequestMapping(value = "/api/v1/task") public class TaskRestController { private static Logger logger = LoggerFactory.getLogger(TaskRestController.class); @Autowired private TaskService taskService; @Autowired private Validator validator; @RequestMapping(method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
// Path: src/main/java/org/springside/examples/quickstart/entity/Task.java // @Entity // @Table(name = "ss_task") // public class Task extends IdEntity { // // private String title; // private String description; // private User user; // // // JSR303 BeanValidator的校验规则 // @NotBlank // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // // JPA 基于USER_ID列的多对一关系定义 // @ManyToOne // @JoinColumn(name = "user_id") // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this); // } // } // // Path: src/main/java/org/springside/examples/quickstart/service/task/TaskService.java // @Component // // 类中所有public函数都纳入事务管理的标识. // @Transactional // public class TaskService { // // private TaskDao taskDao; // // public Task getTask(Long id) { // return taskDao.findOne(id); // } // // public void saveTask(Task entity) { // taskDao.save(entity); // } // // public void deleteTask(Long id) { // taskDao.delete(id); // } // // public List<Task> getAllTask() { // return (List<Task>) taskDao.findAll(); // } // // public Page<Task> getUserTask(Long userId, Map<String, Object> searchParams, int pageNumber, int pageSize, // String sortType) { // PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType); // Specification<Task> spec = buildSpecification(userId, searchParams); // // return taskDao.findAll(spec, pageRequest); // } // // /** // * 创建分页请求. // */ // private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) { // Sort sort = null; // if ("auto".equals(sortType)) { // sort = new Sort(Direction.DESC, "id"); // } else if ("title".equals(sortType)) { // sort = new Sort(Direction.ASC, "title"); // } // // return new PageRequest(pageNumber - 1, pagzSize, sort); // } // // /** // * 创建动态查询条件组合. // */ // private Specification<Task> buildSpecification(Long userId, Map<String, Object> searchParams) { // Map<String, SearchFilter> filters = SearchFilter.parse(searchParams); // filters.put("user.id", new SearchFilter("user.id", Operator.EQ, userId)); // Specification<Task> spec = DynamicSpecifications.bySearchFilter(filters.values(), Task.class); // return spec; // } // // @Autowired // public void setTaskDao(TaskDao taskDao) { // this.taskDao = taskDao; // } // } // Path: src/main/java/org/springside/examples/quickstart/rest/TaskRestController.java import org.springside.examples.quickstart.entity.Task; import org.springside.examples.quickstart.service.task.TaskService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import org.springside.modules.beanvalidator.BeanValidators; import org.springside.modules.web.MediaTypes; import javax.validation.Validator; import java.net.URI; import java.util.List; /******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.quickstart.rest; /** * Task的Restful API的Controller. * * @author calvin */ @RestController @RequestMapping(value = "/api/v1/task") public class TaskRestController { private static Logger logger = LoggerFactory.getLogger(TaskRestController.class); @Autowired private TaskService taskService; @Autowired private Validator validator; @RequestMapping(method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public List<Task> list() {
fireshort/spring-boot-quickstart
src/test/functional/org/springside/examples/quickstart/functional/BaseFunctionalTestCase.java
// Path: src/test/java/org/springside/modules/test/spring/Profiles.java // public class Profiles { // // public static final String ACTIVE_PROFILE = "spring.profiles.active"; // public static final String DEFAULT_PROFILE = "spring.profiles.default"; // // public static final String PRODUCTION = "production"; // public static final String DEVELOPMENT = "development"; // public static final String UNIT_TEST = "test"; // public static final String FUNCTIONAL_TEST = "functional"; // // /** // * 在Spring启动前,设置profile的环境变量。 // */ // public static void setProfileAsSystemProperty(String profile) { // System.setProperty(ACTIVE_PROFILE, profile); // } // }
import java.net.URL; import java.sql.Driver; import org.eclipse.jetty.server.Server; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.datasource.SimpleDriverDataSource; import org.springside.examples.quickstart.QuickStartServer; import org.springside.modules.test.data.DataFixtures; import org.springside.modules.test.jetty.JettyFactory; import org.springside.modules.test.spring.Profiles; import org.springside.modules.utils.PropertiesLoader;
/******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.quickstart.functional; /** * 功能测试基类. * * 在整个测试期间启动一次Jetty Server和 Selenium,在JVM退出时关闭两者。 * 在每个TestCase Class执行前重新载入默认数据. * * @author calvin */ public class BaseFunctionalTestCase { protected static String baseUrl; protected static Server jettyServer; protected static SimpleDriverDataSource dataSource; protected static PropertiesLoader propertiesLoader = new PropertiesLoader("classpath:/application.properties", "classpath:/application.functional.properties", "classpath:/application.functional-local.properties"); private static Logger logger = LoggerFactory.getLogger(BaseFunctionalTestCase.class); @BeforeClass public static void initFunctionalTestEnv() throws Exception { baseUrl = propertiesLoader.getProperty("baseUrl"); // 如果是目标地址是localhost,则启动嵌入式jetty。如果指向远程地址,则不需要启动Jetty. boolean isEmbedded = new URL(baseUrl).getHost().equals("localhost") && propertiesLoader.getBoolean("embeddedForLocal"); if (isEmbedded) { startJettyOnce(); } buildDataSourceOnce(); reloadSampleData(); } /** * 启动Jetty服务器, 仅启动一次. */ protected static void startJettyOnce() throws Exception { if (jettyServer == null) { // 设定Spring的profile
// Path: src/test/java/org/springside/modules/test/spring/Profiles.java // public class Profiles { // // public static final String ACTIVE_PROFILE = "spring.profiles.active"; // public static final String DEFAULT_PROFILE = "spring.profiles.default"; // // public static final String PRODUCTION = "production"; // public static final String DEVELOPMENT = "development"; // public static final String UNIT_TEST = "test"; // public static final String FUNCTIONAL_TEST = "functional"; // // /** // * 在Spring启动前,设置profile的环境变量。 // */ // public static void setProfileAsSystemProperty(String profile) { // System.setProperty(ACTIVE_PROFILE, profile); // } // } // Path: src/test/functional/org/springside/examples/quickstart/functional/BaseFunctionalTestCase.java import java.net.URL; import java.sql.Driver; import org.eclipse.jetty.server.Server; import org.junit.BeforeClass; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.datasource.SimpleDriverDataSource; import org.springside.examples.quickstart.QuickStartServer; import org.springside.modules.test.data.DataFixtures; import org.springside.modules.test.jetty.JettyFactory; import org.springside.modules.test.spring.Profiles; import org.springside.modules.utils.PropertiesLoader; /******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.quickstart.functional; /** * 功能测试基类. * * 在整个测试期间启动一次Jetty Server和 Selenium,在JVM退出时关闭两者。 * 在每个TestCase Class执行前重新载入默认数据. * * @author calvin */ public class BaseFunctionalTestCase { protected static String baseUrl; protected static Server jettyServer; protected static SimpleDriverDataSource dataSource; protected static PropertiesLoader propertiesLoader = new PropertiesLoader("classpath:/application.properties", "classpath:/application.functional.properties", "classpath:/application.functional-local.properties"); private static Logger logger = LoggerFactory.getLogger(BaseFunctionalTestCase.class); @BeforeClass public static void initFunctionalTestEnv() throws Exception { baseUrl = propertiesLoader.getProperty("baseUrl"); // 如果是目标地址是localhost,则启动嵌入式jetty。如果指向远程地址,则不需要启动Jetty. boolean isEmbedded = new URL(baseUrl).getHost().equals("localhost") && propertiesLoader.getBoolean("embeddedForLocal"); if (isEmbedded) { startJettyOnce(); } buildDataSourceOnce(); reloadSampleData(); } /** * 启动Jetty服务器, 仅启动一次. */ protected static void startJettyOnce() throws Exception { if (jettyServer == null) { // 设定Spring的profile
Profiles.setProfileAsSystemProperty(Profiles.FUNCTIONAL_TEST);
fireshort/spring-boot-quickstart
src/main/java/org/springside/examples/quickstart/jms/NotifyMessageProducer.java
// Path: src/main/java/org/springside/examples/quickstart/entity/User.java // @Entity // @Table(name = "ss_user") // public class User extends IdEntity implements Serializable { // private String loginName; // private String name; // private String plainPassword; // private String password; // private String salt; // private String roles; // private Date registerDate; // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // private String email; // // public User() { // } // // public User(Long id) { // this.id = id; // } // // @NotBlank // public String getLoginName() { // return loginName; // } // // public void setLoginName(String loginName) { // this.loginName = loginName; // } // // @NotBlank // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // 不持久化到数据库,也不显示在Restful接口的属性. // @Transient // @JsonIgnore // public String getPlainPassword() { // return plainPassword; // } // // public void setPlainPassword(String plainPassword) { // this.plainPassword = plainPassword; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getRoles() { // return roles; // } // // public void setRoles(String roles) { // this.roles = roles; // } // // @Transient // @JsonIgnore // public List<String> getRoleList() { // // 角色列表在数据库中实际以逗号分隔字符串存储,因此返回不能修改的List. // return ImmutableList.copyOf(StringUtils.split(roles, ",")); // } // // // 设定JSON序列化时的日期格式 // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00") // public Date getRegisterDate() { // return registerDate; // } // // public void setRegisterDate(Date registerDate) { // this.registerDate = registerDate; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this); // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Component; import org.springside.examples.quickstart.entity.User; import javax.annotation.Resource; import javax.jms.Destination; import java.util.HashMap; import java.util.Map;
/******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.quickstart.jms; /** * JMS用户变更消息生产者. * <p/> * 使用jmsTemplate将用户变更消息分别发送到queue与topic. * * @author calvin */ @Component public class NotifyMessageProducer { @Resource private JmsTemplate jmsTemplate; @Resource private Destination notifyQueue; @Resource private Destination notifyTopic;
// Path: src/main/java/org/springside/examples/quickstart/entity/User.java // @Entity // @Table(name = "ss_user") // public class User extends IdEntity implements Serializable { // private String loginName; // private String name; // private String plainPassword; // private String password; // private String salt; // private String roles; // private Date registerDate; // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // private String email; // // public User() { // } // // public User(Long id) { // this.id = id; // } // // @NotBlank // public String getLoginName() { // return loginName; // } // // public void setLoginName(String loginName) { // this.loginName = loginName; // } // // @NotBlank // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // // 不持久化到数据库,也不显示在Restful接口的属性. // @Transient // @JsonIgnore // public String getPlainPassword() { // return plainPassword; // } // // public void setPlainPassword(String plainPassword) { // this.plainPassword = plainPassword; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getSalt() { // return salt; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getRoles() { // return roles; // } // // public void setRoles(String roles) { // this.roles = roles; // } // // @Transient // @JsonIgnore // public List<String> getRoleList() { // // 角色列表在数据库中实际以逗号分隔字符串存储,因此返回不能修改的List. // return ImmutableList.copyOf(StringUtils.split(roles, ",")); // } // // // 设定JSON序列化时的日期格式 // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00") // public Date getRegisterDate() { // return registerDate; // } // // public void setRegisterDate(Date registerDate) { // this.registerDate = registerDate; // } // // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this); // } // } // Path: src/main/java/org/springside/examples/quickstart/jms/NotifyMessageProducer.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Component; import org.springside.examples.quickstart.entity.User; import javax.annotation.Resource; import javax.jms.Destination; import java.util.HashMap; import java.util.Map; /******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.examples.quickstart.jms; /** * JMS用户变更消息生产者. * <p/> * 使用jmsTemplate将用户变更消息分别发送到queue与topic. * * @author calvin */ @Component public class NotifyMessageProducer { @Resource private JmsTemplate jmsTemplate; @Resource private Destination notifyQueue; @Resource private Destination notifyTopic;
public void sendQueue(final User user) {
gunblues/strophe-openfire-websocket
openfire-websockets/src/com/ifsoft/websockets/servlet/XMPPServlet.java
// Path: openfire-websockets/src/com/ifsoft/websockets/plugin/WebSocketsPlugin.java // public class WebSocketsPlugin implements Plugin { // // private static Logger Log = LoggerFactory.getLogger("WebSocketsPlugin"); // private static final String NAME = "ws"; // private static final String DESCRIPTION = "WebSockets Plugin for Openfire"; // // private PluginManager manager; // private File pluginDirectory; // // private ConcurrentHashMap<String, XMPPServlet.XMPPWebSocket> sockets = new ConcurrentHashMap<String, XMPPServlet.XMPPWebSocket>(); // // // //------------------------------------------------------- // // // // // // // //------------------------------------------------------- // // public void initializePlugin(PluginManager manager, File pluginDirectory) { // Log.info( "["+ NAME + "] initialize " + NAME + " plugin resources"); // // String appName = JiveGlobals.getProperty("websockets.webapp.name", NAME); // // try { // // ContextHandlerCollection contexts = HttpBindManager.getInstance().getContexts(); // // try { // Log.info( "["+ NAME + "] initialize " + NAME + " initialize Websockets " + appName); // ServletContextHandler context = new ServletContextHandler(contexts, "/" + appName, ServletContextHandler.SESSIONS); // context.addServlet(new ServletHolder(new XMPPServlet()),"/server"); // // WebAppContext context2 = new WebAppContext(contexts, pluginDirectory.getPath(), "/websockets"); // context.setWelcomeFiles(new String[]{"index.html"}); // // } // catch(Exception e) { // Log.error( "An error has occurred", e ); // } // } // catch (Exception e) { // Log.error("Error initializing WebSockets Plugin", e); // } // } // // public void destroyPlugin() { // Log.info( "["+ NAME + "] destroy " + NAME + " plugin resources"); // // try { // // for (XMPPServlet.XMPPWebSocket socket : sockets.values()) // { // try { // LocalClientSession session = socket.getSession(); // session.close(); // SessionManager.getInstance().removeSession( session ); // session = null; // // } catch ( Exception e ) { } // } // // sockets.clear(); // // } // catch (Exception e) { // Log.error("["+ NAME + "] destroyPlugin exception " + e); // } // } // // public String getName() { // return NAME; // } // // public String getDescription() { // return DESCRIPTION; // } // // public int getCount() { // return this.sockets.size(); // } // // public ConcurrentHashMap<String, XMPPServlet.XMPPWebSocket> getSockets() { // return sockets; // } // }
import org.jivesoftware.util.JiveGlobals; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.security.*; import java.util.*; import java.text.*; import java.net.*; import java.security.cert.Certificate; import java.util.concurrent.ConcurrentHashMap; import java.math.BigInteger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.websocket.servlet.WebSocketServlet; import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; import org.eclipse.jetty.websocket.servlet.WebSocketCreator; import org.eclipse.jetty.util.FutureCallback; import org.eclipse.jetty.websocket.api.annotations.*; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.RemoteEndpoint; import org.jivesoftware.util.ParamUtils; import org.jivesoftware.openfire.SessionManager; import org.jivesoftware.openfire.StreamID; import org.jivesoftware.openfire.session.ClientSession; import org.jivesoftware.openfire.session.LocalClientSession; import org.jivesoftware.openfire.net.VirtualConnection; import org.jivesoftware.openfire.auth.UnauthorizedException; import org.jivesoftware.openfire.auth.AuthToken; import org.jivesoftware.openfire.auth.AuthFactory; import org.jivesoftware.openfire.user.User; import org.jivesoftware.openfire.user.UserAlreadyExistsException; import org.jivesoftware.openfire.user.UserManager; import org.jivesoftware.openfire.user.UserNotFoundException; import org.jivesoftware.openfire.SessionPacketRouter; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.database.SequenceManager; import org.jivesoftware.openfire.component.InternalComponentManager; import com.ifsoft.websockets.plugin.WebSocketsPlugin; import com.ifsoft.websockets.*; import org.xmpp.packet.*; import org.dom4j.*;
package com.ifsoft.websockets.servlet; public final class XMPPServlet extends WebSocketServlet { private static Logger Log = LoggerFactory.getLogger( "XMPPServlet" ); private ConcurrentHashMap<String, XMPPServlet.XMPPWebSocket> sockets; private String remoteAddr;
// Path: openfire-websockets/src/com/ifsoft/websockets/plugin/WebSocketsPlugin.java // public class WebSocketsPlugin implements Plugin { // // private static Logger Log = LoggerFactory.getLogger("WebSocketsPlugin"); // private static final String NAME = "ws"; // private static final String DESCRIPTION = "WebSockets Plugin for Openfire"; // // private PluginManager manager; // private File pluginDirectory; // // private ConcurrentHashMap<String, XMPPServlet.XMPPWebSocket> sockets = new ConcurrentHashMap<String, XMPPServlet.XMPPWebSocket>(); // // // //------------------------------------------------------- // // // // // // // //------------------------------------------------------- // // public void initializePlugin(PluginManager manager, File pluginDirectory) { // Log.info( "["+ NAME + "] initialize " + NAME + " plugin resources"); // // String appName = JiveGlobals.getProperty("websockets.webapp.name", NAME); // // try { // // ContextHandlerCollection contexts = HttpBindManager.getInstance().getContexts(); // // try { // Log.info( "["+ NAME + "] initialize " + NAME + " initialize Websockets " + appName); // ServletContextHandler context = new ServletContextHandler(contexts, "/" + appName, ServletContextHandler.SESSIONS); // context.addServlet(new ServletHolder(new XMPPServlet()),"/server"); // // WebAppContext context2 = new WebAppContext(contexts, pluginDirectory.getPath(), "/websockets"); // context.setWelcomeFiles(new String[]{"index.html"}); // // } // catch(Exception e) { // Log.error( "An error has occurred", e ); // } // } // catch (Exception e) { // Log.error("Error initializing WebSockets Plugin", e); // } // } // // public void destroyPlugin() { // Log.info( "["+ NAME + "] destroy " + NAME + " plugin resources"); // // try { // // for (XMPPServlet.XMPPWebSocket socket : sockets.values()) // { // try { // LocalClientSession session = socket.getSession(); // session.close(); // SessionManager.getInstance().removeSession( session ); // session = null; // // } catch ( Exception e ) { } // } // // sockets.clear(); // // } // catch (Exception e) { // Log.error("["+ NAME + "] destroyPlugin exception " + e); // } // } // // public String getName() { // return NAME; // } // // public String getDescription() { // return DESCRIPTION; // } // // public int getCount() { // return this.sockets.size(); // } // // public ConcurrentHashMap<String, XMPPServlet.XMPPWebSocket> getSockets() { // return sockets; // } // } // Path: openfire-websockets/src/com/ifsoft/websockets/servlet/XMPPServlet.java import org.jivesoftware.util.JiveGlobals; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.security.*; import java.util.*; import java.text.*; import java.net.*; import java.security.cert.Certificate; import java.util.concurrent.ConcurrentHashMap; import java.math.BigInteger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.websocket.servlet.WebSocketServlet; import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; import org.eclipse.jetty.websocket.servlet.WebSocketCreator; import org.eclipse.jetty.util.FutureCallback; import org.eclipse.jetty.websocket.api.annotations.*; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.RemoteEndpoint; import org.jivesoftware.util.ParamUtils; import org.jivesoftware.openfire.SessionManager; import org.jivesoftware.openfire.StreamID; import org.jivesoftware.openfire.session.ClientSession; import org.jivesoftware.openfire.session.LocalClientSession; import org.jivesoftware.openfire.net.VirtualConnection; import org.jivesoftware.openfire.auth.UnauthorizedException; import org.jivesoftware.openfire.auth.AuthToken; import org.jivesoftware.openfire.auth.AuthFactory; import org.jivesoftware.openfire.user.User; import org.jivesoftware.openfire.user.UserAlreadyExistsException; import org.jivesoftware.openfire.user.UserManager; import org.jivesoftware.openfire.user.UserNotFoundException; import org.jivesoftware.openfire.SessionPacketRouter; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.database.SequenceManager; import org.jivesoftware.openfire.component.InternalComponentManager; import com.ifsoft.websockets.plugin.WebSocketsPlugin; import com.ifsoft.websockets.*; import org.xmpp.packet.*; import org.dom4j.*; package com.ifsoft.websockets.servlet; public final class XMPPServlet extends WebSocketServlet { private static Logger Log = LoggerFactory.getLogger( "XMPPServlet" ); private ConcurrentHashMap<String, XMPPServlet.XMPPWebSocket> sockets; private String remoteAddr;
private WebSocketsPlugin plugin;
harryaskham/Twitter-L-LDA
liwc/LIWCWord.java
// Path: types/Category.java // public class Category implements Serializable { // // private static final long serialVersionUID = -3033274268834147218L; // private String title; // private Set<String> words; // private int LIWCID; // // public Category(String title) { // this.title = title; // words = new HashSet<String>(); // LIWCID = -1; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public Set<String> getWords() { // return words; // } // // public void addWord(String word) { // words.add(word); // } // // public int getLIWCID() { // return LIWCID; // } // // public void setLIWCID(int LIWCID) { // this.LIWCID = LIWCID; // } // // public void print() { // System.out.println("Category: "+title); // System.out.println("Words: "); // for(String word : words) { // System.out.print(word+" "); // } // System.out.println(); // } // }
import java.io.Serializable; import java.util.HashSet; import java.util.Set; import uk.ac.cam.ha293.tweetlabel.types.Category;
package uk.ac.cam.ha293.tweetlabel.liwc; public class LIWCWord implements Serializable, Comparable<LIWCWord> { private static final long serialVersionUID = 1226473677648649283L; private String word;
// Path: types/Category.java // public class Category implements Serializable { // // private static final long serialVersionUID = -3033274268834147218L; // private String title; // private Set<String> words; // private int LIWCID; // // public Category(String title) { // this.title = title; // words = new HashSet<String>(); // LIWCID = -1; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public Set<String> getWords() { // return words; // } // // public void addWord(String word) { // words.add(word); // } // // public int getLIWCID() { // return LIWCID; // } // // public void setLIWCID(int LIWCID) { // this.LIWCID = LIWCID; // } // // public void print() { // System.out.println("Category: "+title); // System.out.println("Words: "); // for(String word : words) { // System.out.print(word+" "); // } // System.out.println(); // } // } // Path: liwc/LIWCWord.java import java.io.Serializable; import java.util.HashSet; import java.util.Set; import uk.ac.cam.ha293.tweetlabel.types.Category; package uk.ac.cam.ha293.tweetlabel.liwc; public class LIWCWord implements Serializable, Comparable<LIWCWord> { private static final long serialVersionUID = 1226473677648649283L; private String word;
private Set<Category> categories;
harryaskham/Twitter-L-LDA
twitter/RawProfile.java
// Path: types/Document.java // public class Document implements Serializable { // // private static final long serialVersionUID = -3396519504581827961L; // // private long id; //ie twitter user id! duh // private String documentString; // private Set<String> topics; // // public Document() { // documentString = new String(); // topics = null; // id = -1; // } // // public Document(String documentString) { // this.documentString = documentString; // topics = null; // } // // public Document(String documentString, long id) { // this.documentString = documentString; // this.id = id; // topics = null; // } // // public Document(String documentString, long id, Set<String> topics) { // this.documentString = documentString; // this.id = id; // this.topics = topics; // } // // public String getDocumentString() { // return documentString; // } // // public Set<String> getTopics() { // return topics; // } // // public void setId(long id) { // this.id = id; // } // // public long getId() { // return id; // } // // public void setTopics(Set<String> topics) { // this.topics = topics; // } // // public void setDocumentString(String documentString) { // this.documentString = documentString; // } // // //TODO: A method for returning a word count vector based on an alphabet Map maybe? // // public void print() { // System.out.println(documentString); // } // // }
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import twitter4j.Status; import uk.ac.cam.ha293.tweetlabel.types.Document;
e.printStackTrace(); } } public void saveAsSimpleProfile() { if(userID == -1) { System.err.println("Cannot save as simple profile, no UID set for RawProfile"); return; } SimpleProfile simple = new SimpleProfile(userID); for(Status tweet : tweets) { SimpleTweet simpleTweet = new SimpleTweet(userID,tweet.getId(),tweet.getText()); simple.addTweet(simpleTweet); } simple.save(); } public SimpleProfile asSimpleProfile() { if(userID == -1) { System.err.println("Cannot convert to simple profile, no UID set for RawProfile"); return null; } SimpleProfile simple = new SimpleProfile(userID); for(Status tweet : tweets) { SimpleTweet simpleTweet = new SimpleTweet(userID,tweet.getId(),tweet.getText()); simple.addTweet(simpleTweet); } return simple; }
// Path: types/Document.java // public class Document implements Serializable { // // private static final long serialVersionUID = -3396519504581827961L; // // private long id; //ie twitter user id! duh // private String documentString; // private Set<String> topics; // // public Document() { // documentString = new String(); // topics = null; // id = -1; // } // // public Document(String documentString) { // this.documentString = documentString; // topics = null; // } // // public Document(String documentString, long id) { // this.documentString = documentString; // this.id = id; // topics = null; // } // // public Document(String documentString, long id, Set<String> topics) { // this.documentString = documentString; // this.id = id; // this.topics = topics; // } // // public String getDocumentString() { // return documentString; // } // // public Set<String> getTopics() { // return topics; // } // // public void setId(long id) { // this.id = id; // } // // public long getId() { // return id; // } // // public void setTopics(Set<String> topics) { // this.topics = topics; // } // // public void setDocumentString(String documentString) { // this.documentString = documentString; // } // // //TODO: A method for returning a word count vector based on an alphabet Map maybe? // // public void print() { // System.out.println(documentString); // } // // } // Path: twitter/RawProfile.java import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import twitter4j.Status; import uk.ac.cam.ha293.tweetlabel.types.Document; e.printStackTrace(); } } public void saveAsSimpleProfile() { if(userID == -1) { System.err.println("Cannot save as simple profile, no UID set for RawProfile"); return; } SimpleProfile simple = new SimpleProfile(userID); for(Status tweet : tweets) { SimpleTweet simpleTweet = new SimpleTweet(userID,tweet.getId(),tweet.getText()); simple.addTweet(simpleTweet); } simple.save(); } public SimpleProfile asSimpleProfile() { if(userID == -1) { System.err.println("Cannot convert to simple profile, no UID set for RawProfile"); return null; } SimpleProfile simple = new SimpleProfile(userID); for(Status tweet : tweets) { SimpleTweet simpleTweet = new SimpleTweet(userID,tweet.getId(),tweet.getText()); simple.addTweet(simpleTweet); } return simple; }
public Set<Document> asDocumentSet() {
dwdyer/uncommons-maths
demo/src/java/main/org/uncommons/maths/demo/UniformDistribution.java
// Path: core/src/java/main/org/uncommons/maths/random/DiscreteUniformGenerator.java // public class DiscreteUniformGenerator implements NumberGenerator<Integer> // { // private final Random rng; // private final int range; // private final int minimumValue; // // public DiscreteUniformGenerator(int minimumValue, // int maximumValue, // Random rng) // { // this.rng = rng; // this.minimumValue = minimumValue; // this.range = maximumValue - minimumValue + 1; // } // // // /** // * {@inheritDoc} // */ // public Integer nextValue() // { // return rng.nextInt(range) + minimumValue; // } // }
import java.util.HashMap; import java.util.Map; import java.util.Random; import org.uncommons.maths.random.DiscreteUniformGenerator;
// ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.demo; /** * @author Daniel Dyer */ class UniformDistribution extends ProbabilityDistribution { private final int min; private final int max; public UniformDistribution(int min, int max) { this.min = min; this.max = max; } public Map<Double, Double> getExpectedValues() { Map<Double, Double> values = new HashMap<Double, Double>(); for (int i = min; i <= max; i++) { values.put((double) i, 1d / ((max - min) + 1)); } return values; }
// Path: core/src/java/main/org/uncommons/maths/random/DiscreteUniformGenerator.java // public class DiscreteUniformGenerator implements NumberGenerator<Integer> // { // private final Random rng; // private final int range; // private final int minimumValue; // // public DiscreteUniformGenerator(int minimumValue, // int maximumValue, // Random rng) // { // this.rng = rng; // this.minimumValue = minimumValue; // this.range = maximumValue - minimumValue + 1; // } // // // /** // * {@inheritDoc} // */ // public Integer nextValue() // { // return rng.nextInt(range) + minimumValue; // } // } // Path: demo/src/java/main/org/uncommons/maths/demo/UniformDistribution.java import java.util.HashMap; import java.util.Map; import java.util.Random; import org.uncommons.maths.random.DiscreteUniformGenerator; // ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.demo; /** * @author Daniel Dyer */ class UniformDistribution extends ProbabilityDistribution { private final int min; private final int max; public UniformDistribution(int min, int max) { this.min = min; this.max = max; } public Map<Double, Double> getExpectedValues() { Map<Double, Double> values = new HashMap<Double, Double>(); for (int i = min; i <= max; i++) { values.put((double) i, 1d / ((max - min) + 1)); } return values; }
protected DiscreteUniformGenerator createValueGenerator(Random rng)
dwdyer/uncommons-maths
core/src/java/main/org/uncommons/maths/random/ExponentialGenerator.java
// Path: core/src/java/main/org/uncommons/maths/number/ConstantGenerator.java // public class ConstantGenerator<T extends Number> implements NumberGenerator<T> // { // private final T constant; // // /** // * Creates a number generator that always returns the same // * values. // * @param constant The value to be returned by all invocations // * of the {@link #nextValue()} method. // */ // public ConstantGenerator(T constant) // { // this.constant = constant; // } // // /** // * @return The constant value specified when the generator was constructed. // */ // public T nextValue() // { // return constant; // } // } // // Path: core/src/java/main/org/uncommons/maths/number/NumberGenerator.java // public interface NumberGenerator<T extends Number> // { // /** // * @return The next value from the generator. // */ // T nextValue(); // }
import java.util.Random; import org.uncommons.maths.number.ConstantGenerator; import org.uncommons.maths.number.NumberGenerator;
// ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.random; /** * Continuous random sequence that follows an * <a href="http://en.wikipedia.org/wiki/Exponential_distribution" target="_top">exponential * distribution</a>. * @author Daniel Dyer * @since 1.0.2 */ public class ExponentialGenerator implements NumberGenerator<Double> { private final NumberGenerator<Double> rate; private final Random rng; /** * Creates a generator of exponentially-distributed values from a distribution * with a rate controlled by the specified generator parameter. The mean of * this distribution is {@literal 1 / rate} * and the variance is {@literal 1 / rate^2}. * @param rate A number generator that provides values to use as the rate for * the exponential distribution. This generator must only return non-zero, positive * values. * @param rng The source of randomness used to generate the exponential values. */ public ExponentialGenerator(NumberGenerator<Double> rate, Random rng) { this.rate = rate; this.rng = rng; } /** * Creates a generator of exponentially-distributed values from a distribution * with the specified rate. The mean of this distribution is {@literal 1 / rate} * and the variance is {@literal 1 / rate^2}. * @param rate The rate (lamda) of the exponential distribution. * @param rng The source of randomness used to generate the exponential values. */ public ExponentialGenerator(double rate, Random rng) {
// Path: core/src/java/main/org/uncommons/maths/number/ConstantGenerator.java // public class ConstantGenerator<T extends Number> implements NumberGenerator<T> // { // private final T constant; // // /** // * Creates a number generator that always returns the same // * values. // * @param constant The value to be returned by all invocations // * of the {@link #nextValue()} method. // */ // public ConstantGenerator(T constant) // { // this.constant = constant; // } // // /** // * @return The constant value specified when the generator was constructed. // */ // public T nextValue() // { // return constant; // } // } // // Path: core/src/java/main/org/uncommons/maths/number/NumberGenerator.java // public interface NumberGenerator<T extends Number> // { // /** // * @return The next value from the generator. // */ // T nextValue(); // } // Path: core/src/java/main/org/uncommons/maths/random/ExponentialGenerator.java import java.util.Random; import org.uncommons.maths.number.ConstantGenerator; import org.uncommons.maths.number.NumberGenerator; // ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.random; /** * Continuous random sequence that follows an * <a href="http://en.wikipedia.org/wiki/Exponential_distribution" target="_top">exponential * distribution</a>. * @author Daniel Dyer * @since 1.0.2 */ public class ExponentialGenerator implements NumberGenerator<Double> { private final NumberGenerator<Double> rate; private final Random rng; /** * Creates a generator of exponentially-distributed values from a distribution * with a rate controlled by the specified generator parameter. The mean of * this distribution is {@literal 1 / rate} * and the variance is {@literal 1 / rate^2}. * @param rate A number generator that provides values to use as the rate for * the exponential distribution. This generator must only return non-zero, positive * values. * @param rng The source of randomness used to generate the exponential values. */ public ExponentialGenerator(NumberGenerator<Double> rate, Random rng) { this.rate = rate; this.rng = rng; } /** * Creates a generator of exponentially-distributed values from a distribution * with the specified rate. The mean of this distribution is {@literal 1 / rate} * and the variance is {@literal 1 / rate^2}. * @param rate The rate (lamda) of the exponential distribution. * @param rng The source of randomness used to generate the exponential values. */ public ExponentialGenerator(double rate, Random rng) {
this(new ConstantGenerator<Double>(rate), rng);
dwdyer/uncommons-maths
demo/src/java/main/org/uncommons/maths/demo/RandomDemo.java
// Path: demo/src/java/main/org/uncommons/swing/SwingBackgroundTask.java // public abstract class SwingBackgroundTask<V> // { // // Used to assign thread IDs to make threads easier to identify when debugging. // private static int instanceCount = 0; // // private final CountDownLatch latch = new CountDownLatch(1); // private final int id; // // protected SwingBackgroundTask() // { // synchronized (SwingBackgroundTask.class) // { // this.id = instanceCount; // ++instanceCount; // } // } // // // /** // * Asynchronous call that begins execution of the task // * and returns immediately. // */ // public void execute() // { // Runnable task = new Runnable() // { // public void run() // { // final V result = performTask(); // SwingUtilities.invokeLater(new Runnable() // { // public void run() // { // postProcessing(result); // latch.countDown(); // } // }); // } // }; // new Thread(task, "SwingBackgroundTask-" + id).start(); // } // // // /** // * Waits for the execution of this task to complete. If the {@link #execute()} // * method has not yet been invoked, this method will block indefinitely. // * @throws InterruptedException If the thread executing the task // * is interrupted. // */ // public void waitForCompletion() throws InterruptedException // { // latch.await(); // } // // // /** // * Performs the processing of the task and returns a result. // * Implement in sub-classes to provide the task logic. This method will // * run on a background thread and not on the Event Dispatch Thread and // * therefore should not manipulate any Swing components. // * @return The result of executing this task. // */ // protected abstract V performTask(); // // // /** // * This method is invoked, on the Event Dispatch Thread, after the task // * has been executed. // * This should be implemented in sub-classes in order to provide GUI // * updates that should occur following task completion. // * @param result The result from the {@link #performTask()} method. // */ // protected abstract void postProcessing(V result); // }
import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Map; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.SwingUtilities; import org.uncommons.swing.SwingBackgroundTask;
// ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.demo; /** * Demo application that demonstrates the generation of random values using * different probability distributions. * @author Daniel Dyer */ public class RandomDemo extends JFrame { private final DistributionPanel distributionPanel = new DistributionPanel(); private final RNGPanel rngPanel = new RNGPanel(); private final GraphPanel graphPanel = new GraphPanel(); public RandomDemo() { super("Uncommons Maths - Random Numbers Demo"); setLayout(new BorderLayout()); add(createControls(), BorderLayout.WEST); add(graphPanel, BorderLayout.CENTER); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(700, 500); setMinimumSize(new Dimension(500, 250)); validate(); } private JComponent createControls() { Box controls = new Box(BoxLayout.Y_AXIS); controls.add(distributionPanel); controls.add(rngPanel); JButton executeButton = new JButton("Go"); executeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { RandomDemo.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// Path: demo/src/java/main/org/uncommons/swing/SwingBackgroundTask.java // public abstract class SwingBackgroundTask<V> // { // // Used to assign thread IDs to make threads easier to identify when debugging. // private static int instanceCount = 0; // // private final CountDownLatch latch = new CountDownLatch(1); // private final int id; // // protected SwingBackgroundTask() // { // synchronized (SwingBackgroundTask.class) // { // this.id = instanceCount; // ++instanceCount; // } // } // // // /** // * Asynchronous call that begins execution of the task // * and returns immediately. // */ // public void execute() // { // Runnable task = new Runnable() // { // public void run() // { // final V result = performTask(); // SwingUtilities.invokeLater(new Runnable() // { // public void run() // { // postProcessing(result); // latch.countDown(); // } // }); // } // }; // new Thread(task, "SwingBackgroundTask-" + id).start(); // } // // // /** // * Waits for the execution of this task to complete. If the {@link #execute()} // * method has not yet been invoked, this method will block indefinitely. // * @throws InterruptedException If the thread executing the task // * is interrupted. // */ // public void waitForCompletion() throws InterruptedException // { // latch.await(); // } // // // /** // * Performs the processing of the task and returns a result. // * Implement in sub-classes to provide the task logic. This method will // * run on a background thread and not on the Event Dispatch Thread and // * therefore should not manipulate any Swing components. // * @return The result of executing this task. // */ // protected abstract V performTask(); // // // /** // * This method is invoked, on the Event Dispatch Thread, after the task // * has been executed. // * This should be implemented in sub-classes in order to provide GUI // * updates that should occur following task completion. // * @param result The result from the {@link #performTask()} method. // */ // protected abstract void postProcessing(V result); // } // Path: demo/src/java/main/org/uncommons/maths/demo/RandomDemo.java import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Map; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.SwingUtilities; import org.uncommons.swing.SwingBackgroundTask; // ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.demo; /** * Demo application that demonstrates the generation of random values using * different probability distributions. * @author Daniel Dyer */ public class RandomDemo extends JFrame { private final DistributionPanel distributionPanel = new DistributionPanel(); private final RNGPanel rngPanel = new RNGPanel(); private final GraphPanel graphPanel = new GraphPanel(); public RandomDemo() { super("Uncommons Maths - Random Numbers Demo"); setLayout(new BorderLayout()); add(createControls(), BorderLayout.WEST); add(graphPanel, BorderLayout.CENTER); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(700, 500); setMinimumSize(new Dimension(500, 250)); validate(); } private JComponent createControls() { Box controls = new Box(BoxLayout.Y_AXIS); controls.add(distributionPanel); controls.add(rngPanel); JButton executeButton = new JButton("Go"); executeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { RandomDemo.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
new SwingBackgroundTask<GraphData>()
dwdyer/uncommons-maths
demo/src/java/main/org/uncommons/maths/demo/GaussianDistribution.java
// Path: core/src/java/main/org/uncommons/maths/random/GaussianGenerator.java // public class GaussianGenerator implements NumberGenerator<Double> // { // private final Random rng; // private final NumberGenerator<Double> mean; // private final NumberGenerator<Double> standardDeviation; // // // /** // * <p>Creates a generator of normally-distributed values. The mean and // * standard deviation are determined by the provided // * {@link NumberGenerator}s. This means that the statistical parameters // * of this generator may change over time. One example of where this // * is useful is if the mean and standard deviation generators are attached // * to GUI controls that allow a user to tweak the parameters while a // * program is running.</p> // * <p>To create a Gaussian generator with a constant mean and standard // * deviation, use the {@link #GaussianGenerator(double, double, Random)} // * constructor instead.</p> // * @param mean A {@link NumberGenerator} that provides the mean of the // * Gaussian distribution used for the next generated value. // * @param standardDeviation A {@link NumberGenerator} that provides the // * standard deviation of the Gaussian distribution used for the next // * generated value. // * @param rng The source of randomness. // */ // public GaussianGenerator(NumberGenerator<Double> mean, // NumberGenerator<Double> standardDeviation, // Random rng) // { // this.mean = mean; // this.standardDeviation = standardDeviation; // this.rng = rng; // } // // // /** // * Creates a generator of normally-distributed values from a distribution // * with the specified mean and standard deviation. // * @param mean The mean of the values generated. // * @param standardDeviation The standard deviation of the values generated. // * @param rng The source of randomness. // */ // public GaussianGenerator(double mean, // double standardDeviation, // Random rng) // { // this(new ConstantGenerator<Double>(mean), // new ConstantGenerator<Double>(standardDeviation), // rng); // } // // // /** // * {@inheritDoc} // */ // public Double nextValue() // { // return rng.nextGaussian() * standardDeviation.nextValue() + mean.nextValue(); // } // }
import java.util.HashMap; import java.util.Map; import java.util.Random; import org.uncommons.maths.random.GaussianGenerator;
// ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.demo; /** * @author Daniel Dyer */ class GaussianDistribution extends ProbabilityDistribution { private final double mean; private final double standardDeviation; public GaussianDistribution(double mean, double standardDeviation) { this.mean = mean; this.standardDeviation = standardDeviation; }
// Path: core/src/java/main/org/uncommons/maths/random/GaussianGenerator.java // public class GaussianGenerator implements NumberGenerator<Double> // { // private final Random rng; // private final NumberGenerator<Double> mean; // private final NumberGenerator<Double> standardDeviation; // // // /** // * <p>Creates a generator of normally-distributed values. The mean and // * standard deviation are determined by the provided // * {@link NumberGenerator}s. This means that the statistical parameters // * of this generator may change over time. One example of where this // * is useful is if the mean and standard deviation generators are attached // * to GUI controls that allow a user to tweak the parameters while a // * program is running.</p> // * <p>To create a Gaussian generator with a constant mean and standard // * deviation, use the {@link #GaussianGenerator(double, double, Random)} // * constructor instead.</p> // * @param mean A {@link NumberGenerator} that provides the mean of the // * Gaussian distribution used for the next generated value. // * @param standardDeviation A {@link NumberGenerator} that provides the // * standard deviation of the Gaussian distribution used for the next // * generated value. // * @param rng The source of randomness. // */ // public GaussianGenerator(NumberGenerator<Double> mean, // NumberGenerator<Double> standardDeviation, // Random rng) // { // this.mean = mean; // this.standardDeviation = standardDeviation; // this.rng = rng; // } // // // /** // * Creates a generator of normally-distributed values from a distribution // * with the specified mean and standard deviation. // * @param mean The mean of the values generated. // * @param standardDeviation The standard deviation of the values generated. // * @param rng The source of randomness. // */ // public GaussianGenerator(double mean, // double standardDeviation, // Random rng) // { // this(new ConstantGenerator<Double>(mean), // new ConstantGenerator<Double>(standardDeviation), // rng); // } // // // /** // * {@inheritDoc} // */ // public Double nextValue() // { // return rng.nextGaussian() * standardDeviation.nextValue() + mean.nextValue(); // } // } // Path: demo/src/java/main/org/uncommons/maths/demo/GaussianDistribution.java import java.util.HashMap; import java.util.Map; import java.util.Random; import org.uncommons.maths.random.GaussianGenerator; // ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.demo; /** * @author Daniel Dyer */ class GaussianDistribution extends ProbabilityDistribution { private final double mean; private final double standardDeviation; public GaussianDistribution(double mean, double standardDeviation) { this.mean = mean; this.standardDeviation = standardDeviation; }
protected GaussianGenerator createValueGenerator(Random rng)
dwdyer/uncommons-maths
core/src/java/main/org/uncommons/maths/random/PoissonGenerator.java
// Path: core/src/java/main/org/uncommons/maths/number/ConstantGenerator.java // public class ConstantGenerator<T extends Number> implements NumberGenerator<T> // { // private final T constant; // // /** // * Creates a number generator that always returns the same // * values. // * @param constant The value to be returned by all invocations // * of the {@link #nextValue()} method. // */ // public ConstantGenerator(T constant) // { // this.constant = constant; // } // // /** // * @return The constant value specified when the generator was constructed. // */ // public T nextValue() // { // return constant; // } // } // // Path: core/src/java/main/org/uncommons/maths/number/NumberGenerator.java // public interface NumberGenerator<T extends Number> // { // /** // * @return The next value from the generator. // */ // T nextValue(); // }
import java.util.Random; import org.uncommons.maths.number.ConstantGenerator; import org.uncommons.maths.number.NumberGenerator;
// ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.random; /** * Discrete random sequence that follows a * <a href="http://en.wikipedia.org/wiki/Poisson_distribution" target="_top">Poisson * distribution</a>. * @author Daniel Dyer */ public class PoissonGenerator implements NumberGenerator<Integer> { private final Random rng; private final NumberGenerator<Double> mean; /** * <p>Creates a generator of Poisson-distributed values. The mean is * determined by the provided {@link org.uncommons.maths.number.NumberGenerator}. This means that * the statistical parameters of this generator may change over time. * One example of where this is useful is if the mean generator is attached * to a GUI control that allows a user to tweak the parameters while a * program is running.</p> * <p>To create a Poisson generator with a constant mean, use the * {@link #PoissonGenerator(double, Random)} constructor instead.</p> * @param mean A {@link NumberGenerator} that provides the mean of the * Poisson distribution used for the next generated value. * @param rng The source of randomness. */ public PoissonGenerator(NumberGenerator<Double> mean, Random rng) { this.mean = mean; this.rng = rng; } /** * Creates a generator of Poisson-distributed values from a distribution * with the specified mean. * @param mean The mean of the values generated. * @param rng The source of randomness. */ public PoissonGenerator(double mean, Random rng) {
// Path: core/src/java/main/org/uncommons/maths/number/ConstantGenerator.java // public class ConstantGenerator<T extends Number> implements NumberGenerator<T> // { // private final T constant; // // /** // * Creates a number generator that always returns the same // * values. // * @param constant The value to be returned by all invocations // * of the {@link #nextValue()} method. // */ // public ConstantGenerator(T constant) // { // this.constant = constant; // } // // /** // * @return The constant value specified when the generator was constructed. // */ // public T nextValue() // { // return constant; // } // } // // Path: core/src/java/main/org/uncommons/maths/number/NumberGenerator.java // public interface NumberGenerator<T extends Number> // { // /** // * @return The next value from the generator. // */ // T nextValue(); // } // Path: core/src/java/main/org/uncommons/maths/random/PoissonGenerator.java import java.util.Random; import org.uncommons.maths.number.ConstantGenerator; import org.uncommons.maths.number.NumberGenerator; // ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.random; /** * Discrete random sequence that follows a * <a href="http://en.wikipedia.org/wiki/Poisson_distribution" target="_top">Poisson * distribution</a>. * @author Daniel Dyer */ public class PoissonGenerator implements NumberGenerator<Integer> { private final Random rng; private final NumberGenerator<Double> mean; /** * <p>Creates a generator of Poisson-distributed values. The mean is * determined by the provided {@link org.uncommons.maths.number.NumberGenerator}. This means that * the statistical parameters of this generator may change over time. * One example of where this is useful is if the mean generator is attached * to a GUI control that allows a user to tweak the parameters while a * program is running.</p> * <p>To create a Poisson generator with a constant mean, use the * {@link #PoissonGenerator(double, Random)} constructor instead.</p> * @param mean A {@link NumberGenerator} that provides the mean of the * Poisson distribution used for the next generated value. * @param rng The source of randomness. */ public PoissonGenerator(NumberGenerator<Double> mean, Random rng) { this.mean = mean; this.rng = rng; } /** * Creates a generator of Poisson-distributed values from a distribution * with the specified mean. * @param mean The mean of the values generated. * @param rng The source of randomness. */ public PoissonGenerator(double mean, Random rng) {
this(new ConstantGenerator<Double>(mean), rng);
dwdyer/uncommons-maths
core/src/java/main/org/uncommons/maths/random/AESCounterRNG.java
// Path: core/src/java/main/org/uncommons/maths/binary/BinaryUtils.java // public final class BinaryUtils // { // // Mask for casting a byte to an int, bit-by-bit (with // // bitwise AND) with no special consideration for the sign bit. // private static final int BITWISE_BYTE_TO_INT = 0x000000FF; // // private static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', // '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // // private BinaryUtils() // { // // Prevents instantiation of utility class. // } // // // /** // * Converts an array of bytes in to a String of hexadecimal characters (0 - F). // * @param data An array of bytes to convert to a String. // * @return A hexadecimal String representation of the data. // */ // public static String convertBytesToHexString(byte[] data) // { // StringBuilder buffer = new StringBuilder(data.length * 2); // for (byte b : data) // { // buffer.append(HEX_CHARS[(b >>> 4) & 0x0F]); // buffer.append(HEX_CHARS[b & 0x0F]); // } // return buffer.toString(); // } // // // /** // * Converts a hexadecimal String (such as one generated by the // * {@link #convertBytesToHexString(byte[])} method) into an array of bytes. // * @param hex The hexadecimal String to be converted into an array of bytes. // * @return An array of bytes that. // */ // public static byte[] convertHexStringToBytes(String hex) // { // if (hex.length() % 2 != 0) // { // throw new IllegalArgumentException("Hex string must have even number of characters."); // } // byte[] seed = new byte[hex.length() / 2]; // for (int i = 0; i < seed.length; i++) // { // int index = i * 2; // seed[i] = (byte) Integer.parseInt(hex.substring(index, index + 2), 16); // } // return seed; // } // // // // /** // * Take four bytes from the specified position in the specified // * block and convert them into a 32-bit int, using the big-endian // * convention. // * @param bytes The data to read from. // * @param offset The position to start reading the 4-byte int from. // * @return The 32-bit integer represented by the four bytes. // */ // public static int convertBytesToInt(byte[] bytes, int offset) // { // return (BITWISE_BYTE_TO_INT & bytes[offset + 3]) // | ((BITWISE_BYTE_TO_INT & bytes[offset + 2]) << 8) // | ((BITWISE_BYTE_TO_INT & bytes[offset + 1]) << 16) // | ((BITWISE_BYTE_TO_INT & bytes[offset]) << 24); // } // // // /** // * Convert an array of bytes into an array of ints. 4 bytes from the // * input data map to a single int in the output data. // * @param bytes The data to read from. // * @return An array of 32-bit integers constructed from the data. // * @since 1.1 // */ // public static int[] convertBytesToInts(byte[] bytes) // { // if (bytes.length % 4 != 0) // { // throw new IllegalArgumentException("Number of input bytes must be a multiple of 4."); // } // int[] ints = new int[bytes.length / 4]; // for (int i = 0; i < ints.length; i++) // { // ints[i] = convertBytesToInt(bytes, i * 4); // } // return ints; // } // // // /** // * Utility method to convert an array of bytes into a long. Byte ordered is // * assumed to be big-endian. // * @param bytes The data to read from. // * @param offset The position to start reading the 8-byte long from. // * @return The 64-bit integer represented by the eight bytes. // * @since 1.1 // */ // public static long convertBytesToLong(byte[] bytes, int offset) // { // long value = 0; // for (int i = offset; i < offset + 8; i++) // { // byte b = bytes[i]; // value <<= 8; // value |= b; // } // return value; // // } // // // /** // * Converts a floating point value in the range 0 - 1 into a fixed // * point bit string (where the most significant bit has a value of 0.5). // * @param value The value to convert (must be between zero and one). // * @return A bit string representing the value in fixed-point format. // */ // public static BitString convertDoubleToFixedPointBits(double value) // { // if (value < 0.0d || value >= 1.0d) // { // throw new IllegalArgumentException("Value must be between 0 and 1."); // } // StringBuilder bits = new StringBuilder(64); // double bitValue = 0.5d; // double d = value; // while (d > 0) // { // if (d >= bitValue) // { // bits.append('1'); // d -= bitValue; // } // else // { // bits.append('0'); // } // bitValue /= 2; // } // return new BitString(bits.toString()); // } // }
import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.Random; import java.util.concurrent.locks.ReentrantLock; import javax.crypto.Cipher; import javax.crypto.SecretKey; import org.uncommons.maths.binary.BinaryUtils;
{ incrementCounter(); return cipher.doFinal(counter); } /** * {@inheritDoc} */ @Override protected final int next(int bits) { int result; try { lock.lock(); if (currentBlock == null || currentBlock.length - index < 4) { try { currentBlock = nextBlock(); index = 0; } catch (GeneralSecurityException ex) { // Should never happen. If initialisation succeeds without exceptions // we should be able to proceed indefinitely without exceptions. throw new IllegalStateException("Failed creating next random block.", ex); } }
// Path: core/src/java/main/org/uncommons/maths/binary/BinaryUtils.java // public final class BinaryUtils // { // // Mask for casting a byte to an int, bit-by-bit (with // // bitwise AND) with no special consideration for the sign bit. // private static final int BITWISE_BYTE_TO_INT = 0x000000FF; // // private static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', // '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // // private BinaryUtils() // { // // Prevents instantiation of utility class. // } // // // /** // * Converts an array of bytes in to a String of hexadecimal characters (0 - F). // * @param data An array of bytes to convert to a String. // * @return A hexadecimal String representation of the data. // */ // public static String convertBytesToHexString(byte[] data) // { // StringBuilder buffer = new StringBuilder(data.length * 2); // for (byte b : data) // { // buffer.append(HEX_CHARS[(b >>> 4) & 0x0F]); // buffer.append(HEX_CHARS[b & 0x0F]); // } // return buffer.toString(); // } // // // /** // * Converts a hexadecimal String (such as one generated by the // * {@link #convertBytesToHexString(byte[])} method) into an array of bytes. // * @param hex The hexadecimal String to be converted into an array of bytes. // * @return An array of bytes that. // */ // public static byte[] convertHexStringToBytes(String hex) // { // if (hex.length() % 2 != 0) // { // throw new IllegalArgumentException("Hex string must have even number of characters."); // } // byte[] seed = new byte[hex.length() / 2]; // for (int i = 0; i < seed.length; i++) // { // int index = i * 2; // seed[i] = (byte) Integer.parseInt(hex.substring(index, index + 2), 16); // } // return seed; // } // // // // /** // * Take four bytes from the specified position in the specified // * block and convert them into a 32-bit int, using the big-endian // * convention. // * @param bytes The data to read from. // * @param offset The position to start reading the 4-byte int from. // * @return The 32-bit integer represented by the four bytes. // */ // public static int convertBytesToInt(byte[] bytes, int offset) // { // return (BITWISE_BYTE_TO_INT & bytes[offset + 3]) // | ((BITWISE_BYTE_TO_INT & bytes[offset + 2]) << 8) // | ((BITWISE_BYTE_TO_INT & bytes[offset + 1]) << 16) // | ((BITWISE_BYTE_TO_INT & bytes[offset]) << 24); // } // // // /** // * Convert an array of bytes into an array of ints. 4 bytes from the // * input data map to a single int in the output data. // * @param bytes The data to read from. // * @return An array of 32-bit integers constructed from the data. // * @since 1.1 // */ // public static int[] convertBytesToInts(byte[] bytes) // { // if (bytes.length % 4 != 0) // { // throw new IllegalArgumentException("Number of input bytes must be a multiple of 4."); // } // int[] ints = new int[bytes.length / 4]; // for (int i = 0; i < ints.length; i++) // { // ints[i] = convertBytesToInt(bytes, i * 4); // } // return ints; // } // // // /** // * Utility method to convert an array of bytes into a long. Byte ordered is // * assumed to be big-endian. // * @param bytes The data to read from. // * @param offset The position to start reading the 8-byte long from. // * @return The 64-bit integer represented by the eight bytes. // * @since 1.1 // */ // public static long convertBytesToLong(byte[] bytes, int offset) // { // long value = 0; // for (int i = offset; i < offset + 8; i++) // { // byte b = bytes[i]; // value <<= 8; // value |= b; // } // return value; // // } // // // /** // * Converts a floating point value in the range 0 - 1 into a fixed // * point bit string (where the most significant bit has a value of 0.5). // * @param value The value to convert (must be between zero and one). // * @return A bit string representing the value in fixed-point format. // */ // public static BitString convertDoubleToFixedPointBits(double value) // { // if (value < 0.0d || value >= 1.0d) // { // throw new IllegalArgumentException("Value must be between 0 and 1."); // } // StringBuilder bits = new StringBuilder(64); // double bitValue = 0.5d; // double d = value; // while (d > 0) // { // if (d >= bitValue) // { // bits.append('1'); // d -= bitValue; // } // else // { // bits.append('0'); // } // bitValue /= 2; // } // return new BitString(bits.toString()); // } // } // Path: core/src/java/main/org/uncommons/maths/random/AESCounterRNG.java import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.Random; import java.util.concurrent.locks.ReentrantLock; import javax.crypto.Cipher; import javax.crypto.SecretKey; import org.uncommons.maths.binary.BinaryUtils; { incrementCounter(); return cipher.doFinal(counter); } /** * {@inheritDoc} */ @Override protected final int next(int bits) { int result; try { lock.lock(); if (currentBlock == null || currentBlock.length - index < 4) { try { currentBlock = nextBlock(); index = 0; } catch (GeneralSecurityException ex) { // Should never happen. If initialisation succeeds without exceptions // we should be able to proceed indefinitely without exceptions. throw new IllegalStateException("Failed creating next random block.", ex); } }
result = BinaryUtils.convertBytesToInt(currentBlock, index);
dwdyer/uncommons-maths
demo/src/java/main/org/uncommons/maths/demo/ProbabilityDistribution.java
// Path: core/src/java/main/org/uncommons/maths/number/NumberGenerator.java // public interface NumberGenerator<T extends Number> // { // /** // * @return The next value from the generator. // */ // T nextValue(); // }
import java.util.HashMap; import java.util.Map; import java.util.Random; import org.uncommons.maths.number.NumberGenerator;
// ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.demo; /** * Encapsulates a probability distribution. Provides both theoretical * values for the distribution as well as a way of randomly generating * values that follow this distribution. * @author Daniel Dyer */ abstract class ProbabilityDistribution {
// Path: core/src/java/main/org/uncommons/maths/number/NumberGenerator.java // public interface NumberGenerator<T extends Number> // { // /** // * @return The next value from the generator. // */ // T nextValue(); // } // Path: demo/src/java/main/org/uncommons/maths/demo/ProbabilityDistribution.java import java.util.HashMap; import java.util.Map; import java.util.Random; import org.uncommons.maths.number.NumberGenerator; // ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.demo; /** * Encapsulates a probability distribution. Provides both theoretical * values for the distribution as well as a way of randomly generating * values that follow this distribution. * @author Daniel Dyer */ abstract class ProbabilityDistribution {
protected abstract NumberGenerator<?> createValueGenerator(Random rng);
dwdyer/uncommons-maths
core/src/java/main/org/uncommons/maths/random/GaussianGenerator.java
// Path: core/src/java/main/org/uncommons/maths/number/ConstantGenerator.java // public class ConstantGenerator<T extends Number> implements NumberGenerator<T> // { // private final T constant; // // /** // * Creates a number generator that always returns the same // * values. // * @param constant The value to be returned by all invocations // * of the {@link #nextValue()} method. // */ // public ConstantGenerator(T constant) // { // this.constant = constant; // } // // /** // * @return The constant value specified when the generator was constructed. // */ // public T nextValue() // { // return constant; // } // } // // Path: core/src/java/main/org/uncommons/maths/number/NumberGenerator.java // public interface NumberGenerator<T extends Number> // { // /** // * @return The next value from the generator. // */ // T nextValue(); // }
import java.util.Random; import org.uncommons.maths.number.ConstantGenerator; import org.uncommons.maths.number.NumberGenerator;
// ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.random; /** * <a href="http://en.wikipedia.org/wiki/Normal_distribution" target="_top">Normally distributed</a> * random sequence. * @author Daniel Dyer */ public class GaussianGenerator implements NumberGenerator<Double> { private final Random rng; private final NumberGenerator<Double> mean; private final NumberGenerator<Double> standardDeviation; /** * <p>Creates a generator of normally-distributed values. The mean and * standard deviation are determined by the provided * {@link NumberGenerator}s. This means that the statistical parameters * of this generator may change over time. One example of where this * is useful is if the mean and standard deviation generators are attached * to GUI controls that allow a user to tweak the parameters while a * program is running.</p> * <p>To create a Gaussian generator with a constant mean and standard * deviation, use the {@link #GaussianGenerator(double, double, Random)} * constructor instead.</p> * @param mean A {@link NumberGenerator} that provides the mean of the * Gaussian distribution used for the next generated value. * @param standardDeviation A {@link NumberGenerator} that provides the * standard deviation of the Gaussian distribution used for the next * generated value. * @param rng The source of randomness. */ public GaussianGenerator(NumberGenerator<Double> mean, NumberGenerator<Double> standardDeviation, Random rng) { this.mean = mean; this.standardDeviation = standardDeviation; this.rng = rng; } /** * Creates a generator of normally-distributed values from a distribution * with the specified mean and standard deviation. * @param mean The mean of the values generated. * @param standardDeviation The standard deviation of the values generated. * @param rng The source of randomness. */ public GaussianGenerator(double mean, double standardDeviation, Random rng) {
// Path: core/src/java/main/org/uncommons/maths/number/ConstantGenerator.java // public class ConstantGenerator<T extends Number> implements NumberGenerator<T> // { // private final T constant; // // /** // * Creates a number generator that always returns the same // * values. // * @param constant The value to be returned by all invocations // * of the {@link #nextValue()} method. // */ // public ConstantGenerator(T constant) // { // this.constant = constant; // } // // /** // * @return The constant value specified when the generator was constructed. // */ // public T nextValue() // { // return constant; // } // } // // Path: core/src/java/main/org/uncommons/maths/number/NumberGenerator.java // public interface NumberGenerator<T extends Number> // { // /** // * @return The next value from the generator. // */ // T nextValue(); // } // Path: core/src/java/main/org/uncommons/maths/random/GaussianGenerator.java import java.util.Random; import org.uncommons.maths.number.ConstantGenerator; import org.uncommons.maths.number.NumberGenerator; // ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.random; /** * <a href="http://en.wikipedia.org/wiki/Normal_distribution" target="_top">Normally distributed</a> * random sequence. * @author Daniel Dyer */ public class GaussianGenerator implements NumberGenerator<Double> { private final Random rng; private final NumberGenerator<Double> mean; private final NumberGenerator<Double> standardDeviation; /** * <p>Creates a generator of normally-distributed values. The mean and * standard deviation are determined by the provided * {@link NumberGenerator}s. This means that the statistical parameters * of this generator may change over time. One example of where this * is useful is if the mean and standard deviation generators are attached * to GUI controls that allow a user to tweak the parameters while a * program is running.</p> * <p>To create a Gaussian generator with a constant mean and standard * deviation, use the {@link #GaussianGenerator(double, double, Random)} * constructor instead.</p> * @param mean A {@link NumberGenerator} that provides the mean of the * Gaussian distribution used for the next generated value. * @param standardDeviation A {@link NumberGenerator} that provides the * standard deviation of the Gaussian distribution used for the next * generated value. * @param rng The source of randomness. */ public GaussianGenerator(NumberGenerator<Double> mean, NumberGenerator<Double> standardDeviation, Random rng) { this.mean = mean; this.standardDeviation = standardDeviation; this.rng = rng; } /** * Creates a generator of normally-distributed values from a distribution * with the specified mean and standard deviation. * @param mean The mean of the values generated. * @param standardDeviation The standard deviation of the values generated. * @param rng The source of randomness. */ public GaussianGenerator(double mean, double standardDeviation, Random rng) {
this(new ConstantGenerator<Double>(mean),
dwdyer/uncommons-maths
demo/src/java/main/org/uncommons/maths/demo/ExponentialDistribution.java
// Path: core/src/java/main/org/uncommons/maths/random/ExponentialGenerator.java // public class ExponentialGenerator implements NumberGenerator<Double> // { // private final NumberGenerator<Double> rate; // private final Random rng; // // // /** // * Creates a generator of exponentially-distributed values from a distribution // * with a rate controlled by the specified generator parameter. The mean of // * this distribution is {@literal 1 / rate} // * and the variance is {@literal 1 / rate^2}. // * @param rate A number generator that provides values to use as the rate for // * the exponential distribution. This generator must only return non-zero, positive // * values. // * @param rng The source of randomness used to generate the exponential values. // */ // public ExponentialGenerator(NumberGenerator<Double> rate, // Random rng) // { // this.rate = rate; // this.rng = rng; // } // // // /** // * Creates a generator of exponentially-distributed values from a distribution // * with the specified rate. The mean of this distribution is {@literal 1 / rate} // * and the variance is {@literal 1 / rate^2}. // * @param rate The rate (lamda) of the exponential distribution. // * @param rng The source of randomness used to generate the exponential values. // */ // public ExponentialGenerator(double rate, // Random rng) // { // this(new ConstantGenerator<Double>(rate), rng); // } // // // /** // * Generate the next exponential value from the current value of // * {@literal rate}. // * @return The next exponentially-distributed value. // */ // public Double nextValue() // { // double u; // do // { // // Get a uniformly-distributed random double between // // zero (inclusive) and 1 (exclusive) // u = rng.nextDouble(); // } while (u == 0d); // Reject zero, u must be positive for this to work. // return (-Math.log(u)) / rate.nextValue(); // } // }
import java.util.HashMap; import java.util.Map; import java.util.Random; import org.uncommons.maths.random.ExponentialGenerator;
// ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.demo; /** * @author Daniel Dyer */ class ExponentialDistribution extends ProbabilityDistribution { private final double rate; public ExponentialDistribution(double rate) { this.rate = rate; }
// Path: core/src/java/main/org/uncommons/maths/random/ExponentialGenerator.java // public class ExponentialGenerator implements NumberGenerator<Double> // { // private final NumberGenerator<Double> rate; // private final Random rng; // // // /** // * Creates a generator of exponentially-distributed values from a distribution // * with a rate controlled by the specified generator parameter. The mean of // * this distribution is {@literal 1 / rate} // * and the variance is {@literal 1 / rate^2}. // * @param rate A number generator that provides values to use as the rate for // * the exponential distribution. This generator must only return non-zero, positive // * values. // * @param rng The source of randomness used to generate the exponential values. // */ // public ExponentialGenerator(NumberGenerator<Double> rate, // Random rng) // { // this.rate = rate; // this.rng = rng; // } // // // /** // * Creates a generator of exponentially-distributed values from a distribution // * with the specified rate. The mean of this distribution is {@literal 1 / rate} // * and the variance is {@literal 1 / rate^2}. // * @param rate The rate (lamda) of the exponential distribution. // * @param rng The source of randomness used to generate the exponential values. // */ // public ExponentialGenerator(double rate, // Random rng) // { // this(new ConstantGenerator<Double>(rate), rng); // } // // // /** // * Generate the next exponential value from the current value of // * {@literal rate}. // * @return The next exponentially-distributed value. // */ // public Double nextValue() // { // double u; // do // { // // Get a uniformly-distributed random double between // // zero (inclusive) and 1 (exclusive) // u = rng.nextDouble(); // } while (u == 0d); // Reject zero, u must be positive for this to work. // return (-Math.log(u)) / rate.nextValue(); // } // } // Path: demo/src/java/main/org/uncommons/maths/demo/ExponentialDistribution.java import java.util.HashMap; import java.util.Map; import java.util.Random; import org.uncommons.maths.random.ExponentialGenerator; // ============================================================================ // Copyright 2006-2012 Daniel W. Dyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================ package org.uncommons.maths.demo; /** * @author Daniel Dyer */ class ExponentialDistribution extends ProbabilityDistribution { private final double rate; public ExponentialDistribution(double rate) { this.rate = rate; }
protected ExponentialGenerator createValueGenerator(Random rng)
strassl/Lampshade
lampshade/src/main/java/eu/prismsw/lampshade/providers/ArticleProvider.java
// Path: lampshade/src/main/java/eu/prismsw/lampshade/database/SavedArticlesHelper.java // public class SavedArticlesHelper extends SQLiteOpenHelper { // // public static final String TABLE_SAVED = "saved"; // public static final String TABLE_RECENT = "recent"; // public static final String TABLE_FAVORITE = "favorite"; // // public static final String ARTICLES_COLUMN_ID = "_id"; // public static final String ARTICLES_COLUMN_TITLE = "title"; // public static final String ARTICLES_COLUMN_URL = "url"; // // protected static final String DATABASE_NAME = "saved_articles.db"; // protected static final int DATABASE_VERSION = 2; // // public SavedArticlesHelper(Context context) { // super(context, DATABASE_NAME, null, DATABASE_VERSION); // } // // public SavedArticlesHelper(Context context, String name, CursorFactory factory, int version) { // super(context, name, factory, version); // } // // @Override // public void onCreate(SQLiteDatabase db) { // createTable(db, TABLE_SAVED); // createTable(db, TABLE_RECENT); // createTable(db, TABLE_FAVORITE); // } // // private void createTable (SQLiteDatabase db, String table) { // db.execSQL("create table " + table + "( " // + ARTICLES_COLUMN_ID + " integer primary key autoincrement, " // + ARTICLES_COLUMN_TITLE + " text not null, " // + ARTICLES_COLUMN_URL + " text not null" + ");"); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // db.execSQL("DROP TABLE IF EXISTS " + TABLE_SAVED); // db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECENT); // db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITE); // onCreate(db); // } // }
import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import eu.prismsw.lampshade.database.SavedArticlesHelper;
package eu.prismsw.lampshade.providers; public class ArticleProvider extends ContentProvider { private static final String AUTHORITY = "eu.prismsw.lampshade.providers.articleprovider"; private static final String ARTICLES_BASE_PATH = "articles"; public static final int ARTICLES_SAVED = 10; public static final int ARTICLES_SAVED_ID = 11; public static final int ARTICLES_SAVED_TITLE = 12; public static final int ARTICLES_FAV = 20; public static final int ARTICLES_FAV_ID = 21; public static final int ARTICLES_FAV_TITLE = 22; public static final int ARTICLES_RECENT = 30; public static final int ARTICLES_RECENT_ID = 31; public static final int ARTICLES_RECENT_TITLE = 32; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + ARTICLES_BASE_PATH); public static final Uri SAVED_URI = CONTENT_URI.buildUpon().appendPath("saved").build(); public static final Uri FAV_URI = CONTENT_URI.buildUpon().appendPath("favorites").build(); public static final Uri RECENT_URI = CONTENT_URI.buildUpon().appendPath("recent").build(); private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); static { matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/saved", ARTICLES_SAVED); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/saved/id/#", ARTICLES_SAVED_ID); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/saved/title/*", ARTICLES_SAVED_TITLE); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/favorites", ARTICLES_FAV); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/favorites/id/#", ARTICLES_FAV_ID); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/favorites/title/*", ARTICLES_FAV_TITLE); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/recent", ARTICLES_RECENT); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/recent/id/#", ARTICLES_RECENT_ID); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/favorites/title/*", ARTICLES_RECENT_TITLE); }
// Path: lampshade/src/main/java/eu/prismsw/lampshade/database/SavedArticlesHelper.java // public class SavedArticlesHelper extends SQLiteOpenHelper { // // public static final String TABLE_SAVED = "saved"; // public static final String TABLE_RECENT = "recent"; // public static final String TABLE_FAVORITE = "favorite"; // // public static final String ARTICLES_COLUMN_ID = "_id"; // public static final String ARTICLES_COLUMN_TITLE = "title"; // public static final String ARTICLES_COLUMN_URL = "url"; // // protected static final String DATABASE_NAME = "saved_articles.db"; // protected static final int DATABASE_VERSION = 2; // // public SavedArticlesHelper(Context context) { // super(context, DATABASE_NAME, null, DATABASE_VERSION); // } // // public SavedArticlesHelper(Context context, String name, CursorFactory factory, int version) { // super(context, name, factory, version); // } // // @Override // public void onCreate(SQLiteDatabase db) { // createTable(db, TABLE_SAVED); // createTable(db, TABLE_RECENT); // createTable(db, TABLE_FAVORITE); // } // // private void createTable (SQLiteDatabase db, String table) { // db.execSQL("create table " + table + "( " // + ARTICLES_COLUMN_ID + " integer primary key autoincrement, " // + ARTICLES_COLUMN_TITLE + " text not null, " // + ARTICLES_COLUMN_URL + " text not null" + ");"); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // db.execSQL("DROP TABLE IF EXISTS " + TABLE_SAVED); // db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECENT); // db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITE); // onCreate(db); // } // } // Path: lampshade/src/main/java/eu/prismsw/lampshade/providers/ArticleProvider.java import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import eu.prismsw.lampshade.database.SavedArticlesHelper; package eu.prismsw.lampshade.providers; public class ArticleProvider extends ContentProvider { private static final String AUTHORITY = "eu.prismsw.lampshade.providers.articleprovider"; private static final String ARTICLES_BASE_PATH = "articles"; public static final int ARTICLES_SAVED = 10; public static final int ARTICLES_SAVED_ID = 11; public static final int ARTICLES_SAVED_TITLE = 12; public static final int ARTICLES_FAV = 20; public static final int ARTICLES_FAV_ID = 21; public static final int ARTICLES_FAV_TITLE = 22; public static final int ARTICLES_RECENT = 30; public static final int ARTICLES_RECENT_ID = 31; public static final int ARTICLES_RECENT_TITLE = 32; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + ARTICLES_BASE_PATH); public static final Uri SAVED_URI = CONTENT_URI.buildUpon().appendPath("saved").build(); public static final Uri FAV_URI = CONTENT_URI.buildUpon().appendPath("favorites").build(); public static final Uri RECENT_URI = CONTENT_URI.buildUpon().appendPath("recent").build(); private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); static { matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/saved", ARTICLES_SAVED); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/saved/id/#", ARTICLES_SAVED_ID); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/saved/title/*", ARTICLES_SAVED_TITLE); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/favorites", ARTICLES_FAV); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/favorites/id/#", ARTICLES_FAV_ID); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/favorites/title/*", ARTICLES_FAV_TITLE); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/recent", ARTICLES_RECENT); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/recent/id/#", ARTICLES_RECENT_ID); matcher.addURI(AUTHORITY, ARTICLES_BASE_PATH + "/favorites/title/*", ARTICLES_RECENT_TITLE); }
private SavedArticlesHelper helper;
strassl/Lampshade
lampshade/src/main/java/eu/prismsw/lampshade/fragments/IndexFragment.java
// Path: lampshade/src/main/java/eu/prismsw/lampshade/BaseActivity.java // public class BaseActivity extends FragmentActivity { // TropesApplication application; // // @Override // public void onCreate(Bundle savedInstanceState) { // this.application = (TropesApplication) getApplication(); // this.switchTheme(); // // super.onCreate(savedInstanceState); // } // // public void switchTheme() { // String theme = getThemeName(); // // if(theme.equalsIgnoreCase("HoloDark")) { // setTheme(R.style.LampshadeDark); // } // else if(theme.equalsIgnoreCase("HoloDarkActionBar")) { // setTheme(R.style.LampshadeLightDarkActionBar); // } // } // // public Boolean isDarkActionBar() { // Boolean darkAB = false; // darkAB = getThemeName().contains("Dark"); // // return darkAB; // } // // public Boolean isDarkTheme() { // Boolean isDark = false; // isDark = getThemeName().equalsIgnoreCase("HoloDark"); // // return isDark; // } // // public String getThemeName() { // SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); // String theme = preferences.getString("preference_theme", "HoloLight"); // return theme; // } // // public void showDialogFragment(DialogFragment fragment) { // FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); // Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog"); // if (prev != null) { // ft.remove(prev); // } // ft.addToBackStack(null); // // fragment.show(ft, "dialog"); // } // // public boolean isTablet() { // boolean xlarge = ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE); // boolean large = ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE); // return (xlarge || large); // } // // public void loadPage(Uri url) { // if(TropesHelper.isTropesLink(url)) { // String page = TropesHelper.titleFromUrl(url); // // if(TropesHelper.isIndex(page)) { // loadIndex(url); // } // else { // loadArticle(url); // } // } // else { // loadWebsite(url); // } // } // // /** Opens a page as an article, and only as an article **/ // public void loadArticle(Uri url) { // Intent articleIntent = new Intent(getApplicationContext(), ArticleActivity.class); // articleIntent.putExtra(TropesApplication.loadAsArticle, true); // articleIntent.setData(url); // articleIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // startActivity(articleIntent); // } // // public void loadIndex(Uri url) { // Intent indexIntent = new Intent(getApplicationContext(), ArticleActivity.class); // indexIntent.setData(url); // indexIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // startActivity(indexIntent); // } // // public void loadWebsite(Uri url) { // Intent websiteIntent = new Intent(Intent.ACTION_VIEW); // websiteIntent.setData(url); // websiteIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // startActivity(websiteIntent); // } // // }
import android.net.Uri; import android.os.Bundle; import android.view.*; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ShareActionProvider; import com.koushikdutta.async.future.Future; import com.koushikdutta.async.future.FutureCallback; import com.koushikdutta.ion.Ion; import com.koushikdutta.ion.Response; import eu.prismsw.lampshade.BaseActivity; import eu.prismsw.lampshade.R; import eu.prismsw.tropeswrapper.*;
package eu.prismsw.lampshade.fragments; public class IndexFragment extends TropesFragment { public static IndexFragment newInstance(Uri url) { IndexFragment f = new IndexFragment(); Bundle bundle = new Bundle(2); bundle.putParcelable(PASSED_URL, url); bundle.putParcelable(TRUE_URL, url); f.setArguments(bundle); return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle bundle) { return inflater.inflate(R.layout.index_fragment, group, false); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.tropes_fragment_menu, menu); inflater.inflate(R.menu.index_fragment_menu, menu); MenuItem shareItem = menu.findItem(R.id.share_article); shareProvider = (ShareActionProvider) shareItem.getActionProvider(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(!loadingIsFinished()) { return true; } else if (item.getItemId() == R.id.index_as_article) {
// Path: lampshade/src/main/java/eu/prismsw/lampshade/BaseActivity.java // public class BaseActivity extends FragmentActivity { // TropesApplication application; // // @Override // public void onCreate(Bundle savedInstanceState) { // this.application = (TropesApplication) getApplication(); // this.switchTheme(); // // super.onCreate(savedInstanceState); // } // // public void switchTheme() { // String theme = getThemeName(); // // if(theme.equalsIgnoreCase("HoloDark")) { // setTheme(R.style.LampshadeDark); // } // else if(theme.equalsIgnoreCase("HoloDarkActionBar")) { // setTheme(R.style.LampshadeLightDarkActionBar); // } // } // // public Boolean isDarkActionBar() { // Boolean darkAB = false; // darkAB = getThemeName().contains("Dark"); // // return darkAB; // } // // public Boolean isDarkTheme() { // Boolean isDark = false; // isDark = getThemeName().equalsIgnoreCase("HoloDark"); // // return isDark; // } // // public String getThemeName() { // SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); // String theme = preferences.getString("preference_theme", "HoloLight"); // return theme; // } // // public void showDialogFragment(DialogFragment fragment) { // FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); // Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog"); // if (prev != null) { // ft.remove(prev); // } // ft.addToBackStack(null); // // fragment.show(ft, "dialog"); // } // // public boolean isTablet() { // boolean xlarge = ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE); // boolean large = ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE); // return (xlarge || large); // } // // public void loadPage(Uri url) { // if(TropesHelper.isTropesLink(url)) { // String page = TropesHelper.titleFromUrl(url); // // if(TropesHelper.isIndex(page)) { // loadIndex(url); // } // else { // loadArticle(url); // } // } // else { // loadWebsite(url); // } // } // // /** Opens a page as an article, and only as an article **/ // public void loadArticle(Uri url) { // Intent articleIntent = new Intent(getApplicationContext(), ArticleActivity.class); // articleIntent.putExtra(TropesApplication.loadAsArticle, true); // articleIntent.setData(url); // articleIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // startActivity(articleIntent); // } // // public void loadIndex(Uri url) { // Intent indexIntent = new Intent(getApplicationContext(), ArticleActivity.class); // indexIntent.setData(url); // indexIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // startActivity(indexIntent); // } // // public void loadWebsite(Uri url) { // Intent websiteIntent = new Intent(Intent.ACTION_VIEW); // websiteIntent.setData(url); // websiteIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // startActivity(websiteIntent); // } // // } // Path: lampshade/src/main/java/eu/prismsw/lampshade/fragments/IndexFragment.java import android.net.Uri; import android.os.Bundle; import android.view.*; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ShareActionProvider; import com.koushikdutta.async.future.Future; import com.koushikdutta.async.future.FutureCallback; import com.koushikdutta.ion.Ion; import com.koushikdutta.ion.Response; import eu.prismsw.lampshade.BaseActivity; import eu.prismsw.lampshade.R; import eu.prismsw.tropeswrapper.*; package eu.prismsw.lampshade.fragments; public class IndexFragment extends TropesFragment { public static IndexFragment newInstance(Uri url) { IndexFragment f = new IndexFragment(); Bundle bundle = new Bundle(2); bundle.putParcelable(PASSED_URL, url); bundle.putParcelable(TRUE_URL, url); f.setArguments(bundle); return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle bundle) { return inflater.inflate(R.layout.index_fragment, group, false); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.tropes_fragment_menu, menu); inflater.inflate(R.menu.index_fragment_menu, menu); MenuItem shareItem = menu.findItem(R.id.share_article); shareProvider = (ShareActionProvider) shareItem.getActionProvider(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(!loadingIsFinished()) { return true; } else if (item.getItemId() == R.id.index_as_article) {
((BaseActivity) getActivity()).loadArticle(trueUrl);
strassl/Lampshade
lampshade/src/main/java/eu/prismsw/lampshade/DebugActivity.java
// Path: lampshade/src/main/java/eu/prismsw/lampshade/fragments/SyncDialogFragment.java // public class SyncDialogFragment extends DialogFragment { // Future<String> mainJS; // ProgressDialog syncDialog; // // public static SyncDialogFragment newInstance() { // SyncDialogFragment f = new SyncDialogFragment(); // return f; // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // } // // @Override // public Dialog onCreateDialog(Bundle savedInstanceState) { // ProgressDialog dialog = new ProgressDialog(getActivity()); // // dialog.setTitle(R.string.sync_title); // dialog.setIndeterminate(false); // dialog.setCancelable(true); // dialog.setMax(100); // dialog.setOnShowListener(new DialogInterface.OnShowListener() { // @Override // public void onShow(DialogInterface dialogInterface) { // ProgressDialog d = (ProgressDialog) getDialog(); // mainJS = Ion.with(getActivity()) // .load(TropesArticle.MAIN_JS_URL) // .progressDialog(d) // .asString() // .setCallback(new FutureCallback<String>() { // @Override // public void onCompleted(Exception e, String s) { // if(e != null) { // e.printStackTrace(); // Toast.makeText(getActivity(), R.string.sync_failed, Toast.LENGTH_LONG).show(); // } // else { // try { // FileOutputStream fos = getActivity().openFileOutput(TropesApplication.MAIN_JS_FILE, Context.MODE_PRIVATE); // fos.write(s.getBytes()); // fos.close(); // Toast.makeText(getActivity(), R.string.sync_completed,Toast.LENGTH_SHORT).show(); // } // catch (Exception ex) { // ex.printStackTrace(); // Toast.makeText(getActivity(), R.string.sync_failed, Toast.LENGTH_LONG).show(); // } // } // // dismiss(); // } // }); // } // }); // // return dialog; // } // }
import android.app.Activity; import android.os.Bundle; import android.view.View; import eu.prismsw.lampshade.fragments.SyncDialogFragment;
package eu.prismsw.lampshade; public class DebugActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.debug_activity); } public void clickHandler(View v) { if(v.getId() == R.id.btn_sync) sync(); } public void sync() {
// Path: lampshade/src/main/java/eu/prismsw/lampshade/fragments/SyncDialogFragment.java // public class SyncDialogFragment extends DialogFragment { // Future<String> mainJS; // ProgressDialog syncDialog; // // public static SyncDialogFragment newInstance() { // SyncDialogFragment f = new SyncDialogFragment(); // return f; // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // } // // @Override // public Dialog onCreateDialog(Bundle savedInstanceState) { // ProgressDialog dialog = new ProgressDialog(getActivity()); // // dialog.setTitle(R.string.sync_title); // dialog.setIndeterminate(false); // dialog.setCancelable(true); // dialog.setMax(100); // dialog.setOnShowListener(new DialogInterface.OnShowListener() { // @Override // public void onShow(DialogInterface dialogInterface) { // ProgressDialog d = (ProgressDialog) getDialog(); // mainJS = Ion.with(getActivity()) // .load(TropesArticle.MAIN_JS_URL) // .progressDialog(d) // .asString() // .setCallback(new FutureCallback<String>() { // @Override // public void onCompleted(Exception e, String s) { // if(e != null) { // e.printStackTrace(); // Toast.makeText(getActivity(), R.string.sync_failed, Toast.LENGTH_LONG).show(); // } // else { // try { // FileOutputStream fos = getActivity().openFileOutput(TropesApplication.MAIN_JS_FILE, Context.MODE_PRIVATE); // fos.write(s.getBytes()); // fos.close(); // Toast.makeText(getActivity(), R.string.sync_completed,Toast.LENGTH_SHORT).show(); // } // catch (Exception ex) { // ex.printStackTrace(); // Toast.makeText(getActivity(), R.string.sync_failed, Toast.LENGTH_LONG).show(); // } // } // // dismiss(); // } // }); // } // }); // // return dialog; // } // } // Path: lampshade/src/main/java/eu/prismsw/lampshade/DebugActivity.java import android.app.Activity; import android.os.Bundle; import android.view.View; import eu.prismsw.lampshade.fragments.SyncDialogFragment; package eu.prismsw.lampshade; public class DebugActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.debug_activity); } public void clickHandler(View v) { if(v.getId() == R.id.btn_sync) sync(); } public void sync() {
SyncDialogFragment s = SyncDialogFragment.newInstance();
strassl/Lampshade
lampshade/src/main/java/eu/prismsw/lampshade/FavoriteArticlesActivity.java
// Path: lampshade/src/main/java/eu/prismsw/lampshade/fragments/FavoriteArticlesFragment.java // public class FavoriteArticlesFragment extends SavedArticlesFragment { // public static FavoriteArticlesFragment newInstance() { // FavoriteArticlesFragment f = new FavoriteArticlesFragment(); // return f; // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // contentUri = ArticleProvider.FAV_URI; // } // // @Override // public void setUpListView(ListView lv) { // super.setUpListView(lv); // // lv.setOnItemClickListener(new ListView.OnItemClickListener() { // public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // ListView lv = getListView(); // ArticleItem item = new ArticleItem((Cursor) lv.getAdapter().getItem(position)); // interactionListener.onLinkClicked(item.url); // } // }); // } // }
import eu.prismsw.lampshade.fragments.FavoriteArticlesFragment;
package eu.prismsw.lampshade; public class FavoriteArticlesActivity extends SavedArticlesActivity { @Override public void addFragments() {
// Path: lampshade/src/main/java/eu/prismsw/lampshade/fragments/FavoriteArticlesFragment.java // public class FavoriteArticlesFragment extends SavedArticlesFragment { // public static FavoriteArticlesFragment newInstance() { // FavoriteArticlesFragment f = new FavoriteArticlesFragment(); // return f; // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // contentUri = ArticleProvider.FAV_URI; // } // // @Override // public void setUpListView(ListView lv) { // super.setUpListView(lv); // // lv.setOnItemClickListener(new ListView.OnItemClickListener() { // public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // ListView lv = getListView(); // ArticleItem item = new ArticleItem((Cursor) lv.getAdapter().getItem(position)); // interactionListener.onLinkClicked(item.url); // } // }); // } // } // Path: lampshade/src/main/java/eu/prismsw/lampshade/FavoriteArticlesActivity.java import eu.prismsw.lampshade.fragments.FavoriteArticlesFragment; package eu.prismsw.lampshade; public class FavoriteArticlesActivity extends SavedArticlesActivity { @Override public void addFragments() {
listFragment = FavoriteArticlesFragment.newInstance();
strassl/Lampshade
lampshade/src/main/java/eu/prismsw/lampshade/RecentArticlesActivity.java
// Path: lampshade/src/main/java/eu/prismsw/lampshade/fragments/RecentArticlesFragment.java // public class RecentArticlesFragment extends SavedArticlesFragment { // public static RecentArticlesFragment newInstance() { // RecentArticlesFragment f = new RecentArticlesFragment(); // return f; // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // contentUri = ArticleProvider.RECENT_URI; // } // // @Override // public void setUpListView(ListView lv) { // super.setUpListView(lv); // // lv.setOnItemClickListener(new ListView.OnItemClickListener() { // public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // ListView lv = getListView(); // ArticleItem item = new ArticleItem((Cursor) lv.getAdapter().getItem(position)); // interactionListener.onLinkClicked(item.url); // } // }); // } // }
import eu.prismsw.lampshade.fragments.RecentArticlesFragment;
package eu.prismsw.lampshade; public class RecentArticlesActivity extends SavedArticlesActivity { @Override public void addFragments() {
// Path: lampshade/src/main/java/eu/prismsw/lampshade/fragments/RecentArticlesFragment.java // public class RecentArticlesFragment extends SavedArticlesFragment { // public static RecentArticlesFragment newInstance() { // RecentArticlesFragment f = new RecentArticlesFragment(); // return f; // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // contentUri = ArticleProvider.RECENT_URI; // } // // @Override // public void setUpListView(ListView lv) { // super.setUpListView(lv); // // lv.setOnItemClickListener(new ListView.OnItemClickListener() { // public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // ListView lv = getListView(); // ArticleItem item = new ArticleItem((Cursor) lv.getAdapter().getItem(position)); // interactionListener.onLinkClicked(item.url); // } // }); // } // } // Path: lampshade/src/main/java/eu/prismsw/lampshade/RecentArticlesActivity.java import eu.prismsw.lampshade.fragments.RecentArticlesFragment; package eu.prismsw.lampshade; public class RecentArticlesActivity extends SavedArticlesActivity { @Override public void addFragments() {
listFragment = RecentArticlesFragment.newInstance();
strassl/Lampshade
lampshade/src/main/java/eu/prismsw/lampshade/database/ProviderHelper.java
// Path: lampshade/src/main/java/eu/prismsw/tropeswrapper/TropesHelper.java // public class TropesHelper { // public static final String randomUrl = "http://tvtropes.org/pmwiki/randomitem.php?p=1"; // public static final String baseUrl = "http://tvtropes.org/pmwiki/"; // public static final String mainUrl = "http://tvtropes.org/pmwiki/pmwiki.php/Main/"; // public static final String tropesUrl = "http://tvtropes.org/pmwiki/pmwiki.php/Main/Tropes"; // // /** Gets the page's title from the url */ // public static String titleFromUrl(Uri url) { // List<String> segments = url.getPathSegments(); // String title = segments.get(segments.size() - 1); // // if(title.indexOf("?") != -1) { // title = title.substring(0, title.indexOf("?")); // } // // return title; // } // // /** Gets the page's title from the url (in String form) **/ // public static String titleFromUrl(String url) { // return titleFromUrl(Uri.parse(url)); // } // // public static Boolean isTropesLink(Uri url) { // String host = url.getHost(); // Pattern pattern = Pattern.compile("([.*]\\.)?tvtropes\\.org"); // Matcher matcher = pattern.matcher(host); // // return matcher.matches(); // } // // public static Boolean isIndex(String title) { // //Dirty, but it works and the failure rate is pretty low // //If it should fail, the user can still view the page as an article // if(title.matches(".*(Index|index|Tropes|tropes).*")) { // return true; // } // return false; // } // // /** Converts a list of TropesLinks into List of <a> tags **/ // public static List<String> linkListToHtmlList(List<TropesLink> links) { // List<String> tags = new ArrayList<String>(); // // for(TropesLink link : links) { // tags.add(linkToHtml(link)); // } // // return tags; // } // // /** Converts a TropesLink into an <a> tag **/ // public static String linkToHtml(TropesLink link) { // return createHtmlLink(link.title, link.url.toString()); // } // // public static String createHtmlLink(String title, String url) { // String html = "<a href =\"" + url + "\" >" + title + "</a>"; // return html; // } // }
import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import eu.prismsw.tropeswrapper.TropesHelper;
package eu.prismsw.lampshade.database; public class ProviderHelper { public static Uri saveArticle(ContentResolver resolver, Uri contentUri, Uri url) { ContentValues values = new ContentValues();
// Path: lampshade/src/main/java/eu/prismsw/tropeswrapper/TropesHelper.java // public class TropesHelper { // public static final String randomUrl = "http://tvtropes.org/pmwiki/randomitem.php?p=1"; // public static final String baseUrl = "http://tvtropes.org/pmwiki/"; // public static final String mainUrl = "http://tvtropes.org/pmwiki/pmwiki.php/Main/"; // public static final String tropesUrl = "http://tvtropes.org/pmwiki/pmwiki.php/Main/Tropes"; // // /** Gets the page's title from the url */ // public static String titleFromUrl(Uri url) { // List<String> segments = url.getPathSegments(); // String title = segments.get(segments.size() - 1); // // if(title.indexOf("?") != -1) { // title = title.substring(0, title.indexOf("?")); // } // // return title; // } // // /** Gets the page's title from the url (in String form) **/ // public static String titleFromUrl(String url) { // return titleFromUrl(Uri.parse(url)); // } // // public static Boolean isTropesLink(Uri url) { // String host = url.getHost(); // Pattern pattern = Pattern.compile("([.*]\\.)?tvtropes\\.org"); // Matcher matcher = pattern.matcher(host); // // return matcher.matches(); // } // // public static Boolean isIndex(String title) { // //Dirty, but it works and the failure rate is pretty low // //If it should fail, the user can still view the page as an article // if(title.matches(".*(Index|index|Tropes|tropes).*")) { // return true; // } // return false; // } // // /** Converts a list of TropesLinks into List of <a> tags **/ // public static List<String> linkListToHtmlList(List<TropesLink> links) { // List<String> tags = new ArrayList<String>(); // // for(TropesLink link : links) { // tags.add(linkToHtml(link)); // } // // return tags; // } // // /** Converts a TropesLink into an <a> tag **/ // public static String linkToHtml(TropesLink link) { // return createHtmlLink(link.title, link.url.toString()); // } // // public static String createHtmlLink(String title, String url) { // String html = "<a href =\"" + url + "\" >" + title + "</a>"; // return html; // } // } // Path: lampshade/src/main/java/eu/prismsw/lampshade/database/ProviderHelper.java import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import eu.prismsw.tropeswrapper.TropesHelper; package eu.prismsw.lampshade.database; public class ProviderHelper { public static Uri saveArticle(ContentResolver resolver, Uri contentUri, Uri url) { ContentValues values = new ContentValues();
values.put(SavedArticlesHelper.ARTICLES_COLUMN_TITLE, TropesHelper.titleFromUrl(url));
iloveeclipse/filesync4eclipse
FileSync/src/de/loskutov/fs/preferences/PreferencesInitializer.java
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // }
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; import de.loskutov.fs.FileSyncPlugin;
/******************************************************************************* * Copyright (c) 2009 Andrey Loskutov. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * Contributor: Andrey Loskutov - initial API and implementation *******************************************************************************/ package de.loskutov.fs.preferences; /** * @author Andrey */ public class PreferencesInitializer extends AbstractPreferenceInitializer { /* (non-Javadoc) * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences() */ @Override public void initializeDefaultPreferences() {
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // } // Path: FileSync/src/de/loskutov/fs/preferences/PreferencesInitializer.java import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; import de.loskutov.fs.FileSyncPlugin; /******************************************************************************* * Copyright (c) 2009 Andrey Loskutov. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * Contributor: Andrey Loskutov - initial API and implementation *******************************************************************************/ package de.loskutov.fs.preferences; /** * @author Andrey */ public class PreferencesInitializer extends AbstractPreferenceInitializer { /* (non-Javadoc) * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences() */ @Override public void initializeDefaultPreferences() {
IPreferenceStore store = FileSyncPlugin.getDefault().getPreferenceStore();
iloveeclipse/filesync4eclipse
FileSync/src/de/loskutov/fs/properties/SupportPanel.java
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // }
import java.net.MalformedURLException; import java.net.URL; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Listener; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.browser.IWebBrowser; import org.eclipse.ui.browser.IWorkbenchBrowserSupport; import de.loskutov.fs.FileSyncPlugin;
public void handleEvent(Event event) { handleUrlClick("http://marketplace.eclipse.org/content/filesync"); } }); link = new Link(commonPanel, SWT.NONE); link.setFont(font); link.setText(" - <a>make a donation to support plugin development</a>"); link.setToolTipText("You do NOT need a PayPal account!"); link.addListener (SWT.Selection, new Listener () { @Override public void handleEvent(Event event) { handleUrlClick("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=R5SHJLNGUXKHU"); } }); } private static void handleUrlClick(final String urlStr) { try { IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport(); IWebBrowser externalBrowser = support.getExternalBrowser(); if(externalBrowser != null){ externalBrowser.openURL(new URL(urlStr)); } else { IWebBrowser browser = support.createBrowser(urlStr); if(browser != null){ browser.openURL(new URL(urlStr)); } } } catch (PartInitException e) {
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // } // Path: FileSync/src/de/loskutov/fs/properties/SupportPanel.java import java.net.MalformedURLException; import java.net.URL; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Listener; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.browser.IWebBrowser; import org.eclipse.ui.browser.IWorkbenchBrowserSupport; import de.loskutov.fs.FileSyncPlugin; public void handleEvent(Event event) { handleUrlClick("http://marketplace.eclipse.org/content/filesync"); } }); link = new Link(commonPanel, SWT.NONE); link.setFont(font); link.setText(" - <a>make a donation to support plugin development</a>"); link.setToolTipText("You do NOT need a PayPal account!"); link.addListener (SWT.Selection, new Listener () { @Override public void handleEvent(Event event) { handleUrlClick("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=R5SHJLNGUXKHU"); } }); } private static void handleUrlClick(final String urlStr) { try { IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport(); IWebBrowser externalBrowser = support.getExternalBrowser(); if(externalBrowser != null){ externalBrowser.openURL(new URL(urlStr)); } else { IWebBrowser browser = support.createBrowser(urlStr); if(browser != null){ browser.openURL(new URL(urlStr)); } } } catch (PartInitException e) {
FileSyncPlugin.log("Failed to open url " + urlStr, e, IStatus.ERROR);
iloveeclipse/filesync4eclipse
FileSync/src/de/loskutov/fs/command/CopyDelegate.java
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import org.eclipse.core.runtime.IStatus; import de.loskutov.fs.FileSyncPlugin;
package de.loskutov.fs.command; /** * @author Coloma Escribano, Ignacio - initial idea and first implementation * @author Andrey - production ready code :) */ public class CopyDelegate { /** * true to use the current date for destination files, * instead of keeping the same date for source and destination */ protected boolean useCurrentDateForDestinationFiles; /** * map of properties to perform the substitution. * Key is variable name, value is the value */ protected Properties variablesMap; protected String encoding; public CopyDelegate() { super(); // setEncoding("ISO-8859-1"); } /** * Single file copy operation with replacement of variables on the fly. * Implementation reads complete file into the memory * @param source - should be file only * @param destination - should be already created * @return true if source was successfully copied */ public boolean copy(File source, File destination) { if (source == null || destination == null || !source.exists() || !destination.exists() || source.isDirectory() || destination.isDirectory()) { if (FS.enableLogging) {
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // } // Path: FileSync/src/de/loskutov/fs/command/CopyDelegate.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import org.eclipse.core.runtime.IStatus; import de.loskutov.fs.FileSyncPlugin; package de.loskutov.fs.command; /** * @author Coloma Escribano, Ignacio - initial idea and first implementation * @author Andrey - production ready code :) */ public class CopyDelegate { /** * true to use the current date for destination files, * instead of keeping the same date for source and destination */ protected boolean useCurrentDateForDestinationFiles; /** * map of properties to perform the substitution. * Key is variable name, value is the value */ protected Properties variablesMap; protected String encoding; public CopyDelegate() { super(); // setEncoding("ISO-8859-1"); } /** * Single file copy operation with replacement of variables on the fly. * Implementation reads complete file into the memory * @param source - should be file only * @param destination - should be already created * @return true if source was successfully copied */ public boolean copy(File source, File destination) { if (source == null || destination == null || !source.exists() || !destination.exists() || source.isDirectory() || destination.isDirectory()) { if (FS.enableLogging) {
FileSyncPlugin.log("Could not copy file '" + source + "' to '"
iloveeclipse/filesync4eclipse
FileSync/src/de/loskutov/fs/properties/PathListLabelProvider.java
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // }
import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.ide.IDE; import de.loskutov.fs.FileSyncPlugin;
} else { buf.append("(All)"); } } return buf.toString(); } public String getPathListElementText(PathListElement cpentry) { IPath path = cpentry.getPath(); StringBuffer buf = new StringBuffer(path.makeRelative().toString()); IResource resource = cpentry.getResource(); if (resource != null && !resource.exists()) { buf.append(' '); buf.append("new"); } return buf.toString(); } @Override public Image getImage(Object element) { if (element instanceof PathListElement) { PathListElement cpentry = (PathListElement) element; String key = null; if (cpentry.getPath().segmentCount() == 1) { key = IDE.SharedImages.IMG_OBJ_PROJECT; } else { key = ISharedImages.IMG_OBJ_FOLDER; }
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // } // Path: FileSync/src/de/loskutov/fs/properties/PathListLabelProvider.java import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.ide.IDE; import de.loskutov.fs.FileSyncPlugin; } else { buf.append("(All)"); } } return buf.toString(); } public String getPathListElementText(PathListElement cpentry) { IPath path = cpentry.getPath(); StringBuffer buf = new StringBuffer(path.makeRelative().toString()); IResource resource = cpentry.getResource(); if (resource != null && !resource.exists()) { buf.append(' '); buf.append("new"); } return buf.toString(); } @Override public Image getImage(Object element) { if (element instanceof PathListElement) { PathListElement cpentry = (PathListElement) element; String key = null; if (cpentry.getPath().segmentCount() == 1) { key = IDE.SharedImages.IMG_OBJ_PROJECT; } else { key = ISharedImages.IMG_OBJ_FOLDER; }
return FileSyncPlugin.getDefault().getWorkbench().getSharedImages().getImage(key);
iloveeclipse/filesync4eclipse
FileSync/src/de/loskutov/fs/FileSyncPlugin.java
// Path: FileSync/src/de/loskutov/fs/preferences/FileSyncConstants.java // public interface FileSyncConstants { // /** used for tests to not to open dialogs */ // String KEY_ASK_USER = "askUser"; // }
import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.plugin.AbstractUIPlugin; import de.loskutov.fs.preferences.FileSyncConstants;
/******************************************************************************* * Copyright (c) 2009 Andrey Loskutov. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * Contributor: Andrey Loskutov - initial API and implementation *******************************************************************************/ package de.loskutov.fs; /** * The main plugin class to be used in the desktop. */ public class FileSyncPlugin extends AbstractUIPlugin { private static FileSyncPlugin plugin; public static final String PLUGIN_ID = "de.loskutov.FileSync"; /** * The constructor. */ public FileSyncPlugin() { super(); if(plugin != null){ throw new IllegalStateException("FileSync plugin is singleton!"); } plugin = this; } /** * Returns the shared instance. */ public static FileSyncPlugin getDefault() { return plugin; } public static void error(String message, Throwable error) { Shell shell = FileSyncPlugin.getShell(); if(message == null){ message = ""; } if (error != null) { message = message + " " + error.getMessage(); } IPreferenceStore store = getDefault().getPreferenceStore();
// Path: FileSync/src/de/loskutov/fs/preferences/FileSyncConstants.java // public interface FileSyncConstants { // /** used for tests to not to open dialogs */ // String KEY_ASK_USER = "askUser"; // } // Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.plugin.AbstractUIPlugin; import de.loskutov.fs.preferences.FileSyncConstants; /******************************************************************************* * Copyright (c) 2009 Andrey Loskutov. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * Contributor: Andrey Loskutov - initial API and implementation *******************************************************************************/ package de.loskutov.fs; /** * The main plugin class to be used in the desktop. */ public class FileSyncPlugin extends AbstractUIPlugin { private static FileSyncPlugin plugin; public static final String PLUGIN_ID = "de.loskutov.FileSync"; /** * The constructor. */ public FileSyncPlugin() { super(); if(plugin != null){ throw new IllegalStateException("FileSync plugin is singleton!"); } plugin = this; } /** * Returns the shared instance. */ public static FileSyncPlugin getDefault() { return plugin; } public static void error(String message, Throwable error) { Shell shell = FileSyncPlugin.getShell(); if(message == null){ message = ""; } if (error != null) { message = message + " " + error.getMessage(); } IPreferenceStore store = getDefault().getPreferenceStore();
if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) {
iloveeclipse/filesync4eclipse
FileSync/src/de/loskutov/fs/dialogs/StatusInfo.java
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // }
import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IStatus; import de.loskutov.fs.FileSyncPlugin;
/* * @see IStatus#matches(int) */ @Override public boolean matches(int severityMask) { return (fSeverity & severityMask) != 0; } /** * Returns always <code>false</code>. * @see IStatus#isMultiStatus() */ @Override public boolean isMultiStatus() { return false; } /* * @see IStatus#getSeverity() */ @Override public int getSeverity() { return fSeverity; } /* * @see IStatus#getPlugin() */ @Override public String getPlugin() {
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // } // Path: FileSync/src/de/loskutov/fs/dialogs/StatusInfo.java import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IStatus; import de.loskutov.fs.FileSyncPlugin; /* * @see IStatus#matches(int) */ @Override public boolean matches(int severityMask) { return (fSeverity & severityMask) != 0; } /** * Returns always <code>false</code>. * @see IStatus#isMultiStatus() */ @Override public boolean isMultiStatus() { return false; } /* * @see IStatus#getSeverity() */ @Override public int getSeverity() { return fSeverity; } /* * @see IStatus#getPlugin() */ @Override public String getPlugin() {
return FileSyncPlugin.PLUGIN_ID;
iloveeclipse/filesync4eclipse
FileSync/src/de/loskutov/fs/command/CopyDelegate1.java
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Pattern; import org.eclipse.core.runtime.IStatus; import de.loskutov.fs.FileSyncPlugin;
* @param source - should be file only * @param destination - should be already created * @return true if source was successfully copied */ @Override protected boolean copyInternal(File source, File destination) { boolean success = true; LineReader reader = null; LineWriter writer = null; try { // Open the file and then get a channel from the stream reader = new LineReader(new FileInputStream(source), encoding); writer = new LineWriter(new FileOutputStream(destination), encoding); String line = null; while((line = reader.readLineToString()) != null){ for (Iterator<Pattern> i = patternToValue.keySet().iterator(); i.hasNext();) { Pattern pattern = i.next(); if(line.indexOf(patternToKey.get(pattern)) < 0 ){ continue; } String value = patternToValue.get(pattern); line = pattern.matcher(line).replaceAll(value); } writer.writeLine(line); } writer.flush(); } catch (IOException e) { if (FS.enableLogging) {
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // } // Path: FileSync/src/de/loskutov/fs/command/CopyDelegate1.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Pattern; import org.eclipse.core.runtime.IStatus; import de.loskutov.fs.FileSyncPlugin; * @param source - should be file only * @param destination - should be already created * @return true if source was successfully copied */ @Override protected boolean copyInternal(File source, File destination) { boolean success = true; LineReader reader = null; LineWriter writer = null; try { // Open the file and then get a channel from the stream reader = new LineReader(new FileInputStream(source), encoding); writer = new LineWriter(new FileOutputStream(destination), encoding); String line = null; while((line = reader.readLineToString()) != null){ for (Iterator<Pattern> i = patternToValue.keySet().iterator(); i.hasNext();) { Pattern pattern = i.next(); if(line.indexOf(patternToKey.get(pattern)) < 0 ){ continue; } String value = patternToValue.get(pattern); line = pattern.matcher(line).replaceAll(value); } writer.writeLine(line); } writer.flush(); } catch (IOException e) { if (FS.enableLogging) {
FileSyncPlugin.log("Could not copy file '" + source + "' to '"
iloveeclipse/filesync4eclipse
FileSync/src/de/loskutov/fs/command/FS.java
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import org.eclipse.core.runtime.IStatus; import de.loskutov.fs.FileSyncPlugin;
/******************************************************************************* * Copyright (c) 2009 Andrey Loskutov. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * Contributor: Andrey Loskutov - initial API and implementation *******************************************************************************/ package de.loskutov.fs.command; /** * Utility class for file system related operations. * @author Andrey */ public final class FS { private static final String OS_NAME = System.getProperty("os.name").toLowerCase(); // not final for tests only public static boolean enableLogging = true; private FS() { // don't instantiate me } public static boolean isWin32() { return OS_NAME.indexOf("windows") >= 0; } /** * Single file/directory create operation. * @param destination * @param isFile * @return true if source was successfully created or if it was already existing */ public static boolean create(File destination, boolean isFile) { if (destination == null) { return true; } if (isFile && destination.isFile()) { return true; } else if (!isFile && destination.isDirectory()) { return true; } boolean result = false; if (isFile) { File dir = destination.getParentFile(); if (!dir.exists()) { result = dir.mkdirs(); if (!result) { if (enableLogging) {
// Path: FileSync/src/de/loskutov/fs/FileSyncPlugin.java // public class FileSyncPlugin extends AbstractUIPlugin { // // private static FileSyncPlugin plugin; // // public static final String PLUGIN_ID = "de.loskutov.FileSync"; // // /** // * The constructor. // */ // public FileSyncPlugin() { // super(); // if(plugin != null){ // throw new IllegalStateException("FileSync plugin is singleton!"); // } // plugin = this; // } // // /** // * Returns the shared instance. // */ // public static FileSyncPlugin getDefault() { // return plugin; // } // // public static void error(String message, Throwable error) { // Shell shell = FileSyncPlugin.getShell(); // if(message == null){ // message = ""; // } // if (error != null) { // message = message + " " + error.getMessage(); // } // IPreferenceStore store = getDefault().getPreferenceStore(); // if (store.getBoolean(FileSyncConstants.KEY_ASK_USER)) { // MessageDialog.openError(shell, "FileSync error", message); // } // log(message, error, IStatus.ERROR); // } // // /** // * @param statusID // * one of IStatus. constants like IStatus.ERROR etc // * @param error // */ // public static void log(String messageID, Throwable error, int statusID) { // if (messageID == null) { // messageID = error.getMessage(); // if (messageID == null) { // messageID = error.toString(); // } // } // Status status = new Status(statusID, PLUGIN_ID, 0, messageID, error); // getDefault().getLog().log(status); // if(getDefault().isDebugging()){ // System.out.println(status); // } // } // // public static Shell getShell() { // return getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(); // } // // /** // * Returns an image descriptor for the image file at the given plug-in // * relative path. // * // * @param path // * the path // * @return the image descriptor // */ // public static ImageDescriptor getImageDescriptor(String path) { // if (path == null) { // return null; // } // ImageRegistry imageRegistry = getDefault().getImageRegistry(); // ImageDescriptor imageDescriptor = imageRegistry.getDescriptor(path); // if (imageDescriptor == null) { // imageDescriptor = imageDescriptorFromPlugin(PLUGIN_ID, path); // imageRegistry.put(path, imageDescriptor); // } // return imageDescriptor; // } // // public static Image getImage(String path) { // if (path == null) { // return null; // } // // prefetch image, if not jet there // ImageDescriptor imageDescriptor = getImageDescriptor(path); // if (imageDescriptor != null) { // return getDefault().getImageRegistry().get(path); // } // // TODO error message // return null; // } // } // Path: FileSync/src/de/loskutov/fs/command/FS.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import org.eclipse.core.runtime.IStatus; import de.loskutov.fs.FileSyncPlugin; /******************************************************************************* * Copyright (c) 2009 Andrey Loskutov. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * Contributor: Andrey Loskutov - initial API and implementation *******************************************************************************/ package de.loskutov.fs.command; /** * Utility class for file system related operations. * @author Andrey */ public final class FS { private static final String OS_NAME = System.getProperty("os.name").toLowerCase(); // not final for tests only public static boolean enableLogging = true; private FS() { // don't instantiate me } public static boolean isWin32() { return OS_NAME.indexOf("windows") >= 0; } /** * Single file/directory create operation. * @param destination * @param isFile * @return true if source was successfully created or if it was already existing */ public static boolean create(File destination, boolean isFile) { if (destination == null) { return true; } if (isFile && destination.isFile()) { return true; } else if (!isFile && destination.isDirectory()) { return true; } boolean result = false; if (isFile) { File dir = destination.getParentFile(); if (!dir.exists()) { result = dir.mkdirs(); if (!result) { if (enableLogging) {
FileSyncPlugin.log("Could not create directory '" + dir + "'",
TGAC/statsdb
Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/run/parser/AnalysisMetadataParser.java
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/DefaultQCAnalysis.java // public class DefaultQCAnalysis extends AbstractQCAnalysis { // public DefaultQCAnalysis() { // properties = new HashMap<>(); // valueTypes = new HashMap<>(); // valueDescriptions = new HashMap<>(); // generalValues = new HashMap<>(); // partitionValues = new ArrayList<>(); // positionValues = new ArrayList<>(); // } // } // // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/QCAnalysis.java // public interface QCAnalysis { // /** // * Get the QCAnalysis ID // * @return the QCAnalysis object ID // */ // public long getId(); // // /** // * Sets the ID of this QCAnalysis object // * @param id // */ // public void setId(long id); // // /** // * Retrieve an analysis property value associated with a given key // * // * @param key // * @return // * @throws QCAnalysisException // */ // public String getProperty(String key) throws QCAnalysisException; // // /** // * Add an analysis property // * // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addProperty(String key, String value) throws QCAnalysisException; // // /** // * Add a partition value // * // * @param range // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addPartitionValue(String range, String key, String value) throws QCAnalysisException; // // /** // * Add a position value // * // * @param position // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addPositionValue(String position, String key, String value) throws QCAnalysisException; // // /** // * Add a general value // * // * @param valueType // * @param valueScope // * @param descriptor // * @throws QCAnalysisException // */ // public void addGeneralValue(String valueType, String valueScope, String descriptor) throws QCAnalysisException; // // /** // * Add a value type scope // * // * @param valueTypeKey // * @param valueScope // * @throws QCAnalysisException // */ // public void addValueType(String valueTypeKey, String valueScope) throws QCAnalysisException; // // /** // * Add a value type description // * // * @param valueTypeKey // * @param valueDescription // * @throws QCAnalysisException // */ // public void addValueDescription(String valueTypeKey, String valueDescription) throws QCAnalysisException; // // /** // * Retrieve all analysis properties // * // * @return a map of key:value pairs // */ // public Map<String, String> getProperties(); // // /** // * Retrieve all analysis general values // * // * @return a map of key:value pairs // */ // public Map<String,String> getGeneralValues(); // // /** // * Retrieve all analysis partition values // * // * @return a list of PartitionValues // */ // public List<PartitionValue> getPartitionValues(); // // /** // * Retrieve all analysis position values // * // * @return a list of PositionValues // */ // public List<PositionValue> getPositionValues(); // // /** // * Retrieve all analysis value descriptions // * // * @return a map of key:value pairs // */ // public Map<String, String> getValueDescriptions(); // // /** // * Retrieve all analysis value type scopes // * // * @return a map of key:value pairs // */ // public Map<String, String> getValueScopes(); // } // // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // }
import uk.ac.tgac.statsdb.analysis.DefaultQCAnalysis; import uk.ac.tgac.statsdb.analysis.QCAnalysis; import uk.ac.tgac.statsdb.exception.QCAnalysisException; import java.io.*; import java.util.ArrayList; import java.util.List;
* in said QCAnalysis objects * * @param csv to parse as a CSV text file string * @return a List of QCAnalysis objects created from the metadata file * @throws QCAnalysisException */ public List<QCAnalysis> parseMetadataFile(String csv) throws QCAnalysisException { List<QCAnalysis> qcas = new ArrayList<>(); Reader r = new StringReader(csv); processMetadataFile(r, qcas); return qcas; } private void processMetadataFile(Reader r, List<QCAnalysis> qcas) throws QCAnalysisException { BufferedReader br = null; try { br = new BufferedReader(r); String line; boolean first = true; String[] headers = null; while ((line = br.readLine()) != null) { if (first) { headers = line.toLowerCase().split("[\\s|,]+"); first = false; } else { String[] values = line.split("[\\s|,]+"); if (headers == null || headers.length != values.length) { throw new QCAnalysisException("Invalid headers found"); }
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/DefaultQCAnalysis.java // public class DefaultQCAnalysis extends AbstractQCAnalysis { // public DefaultQCAnalysis() { // properties = new HashMap<>(); // valueTypes = new HashMap<>(); // valueDescriptions = new HashMap<>(); // generalValues = new HashMap<>(); // partitionValues = new ArrayList<>(); // positionValues = new ArrayList<>(); // } // } // // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/QCAnalysis.java // public interface QCAnalysis { // /** // * Get the QCAnalysis ID // * @return the QCAnalysis object ID // */ // public long getId(); // // /** // * Sets the ID of this QCAnalysis object // * @param id // */ // public void setId(long id); // // /** // * Retrieve an analysis property value associated with a given key // * // * @param key // * @return // * @throws QCAnalysisException // */ // public String getProperty(String key) throws QCAnalysisException; // // /** // * Add an analysis property // * // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addProperty(String key, String value) throws QCAnalysisException; // // /** // * Add a partition value // * // * @param range // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addPartitionValue(String range, String key, String value) throws QCAnalysisException; // // /** // * Add a position value // * // * @param position // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addPositionValue(String position, String key, String value) throws QCAnalysisException; // // /** // * Add a general value // * // * @param valueType // * @param valueScope // * @param descriptor // * @throws QCAnalysisException // */ // public void addGeneralValue(String valueType, String valueScope, String descriptor) throws QCAnalysisException; // // /** // * Add a value type scope // * // * @param valueTypeKey // * @param valueScope // * @throws QCAnalysisException // */ // public void addValueType(String valueTypeKey, String valueScope) throws QCAnalysisException; // // /** // * Add a value type description // * // * @param valueTypeKey // * @param valueDescription // * @throws QCAnalysisException // */ // public void addValueDescription(String valueTypeKey, String valueDescription) throws QCAnalysisException; // // /** // * Retrieve all analysis properties // * // * @return a map of key:value pairs // */ // public Map<String, String> getProperties(); // // /** // * Retrieve all analysis general values // * // * @return a map of key:value pairs // */ // public Map<String,String> getGeneralValues(); // // /** // * Retrieve all analysis partition values // * // * @return a list of PartitionValues // */ // public List<PartitionValue> getPartitionValues(); // // /** // * Retrieve all analysis position values // * // * @return a list of PositionValues // */ // public List<PositionValue> getPositionValues(); // // /** // * Retrieve all analysis value descriptions // * // * @return a map of key:value pairs // */ // public Map<String, String> getValueDescriptions(); // // /** // * Retrieve all analysis value type scopes // * // * @return a map of key:value pairs // */ // public Map<String, String> getValueScopes(); // } // // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // } // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/run/parser/AnalysisMetadataParser.java import uk.ac.tgac.statsdb.analysis.DefaultQCAnalysis; import uk.ac.tgac.statsdb.analysis.QCAnalysis; import uk.ac.tgac.statsdb.exception.QCAnalysisException; import java.io.*; import java.util.ArrayList; import java.util.List; * in said QCAnalysis objects * * @param csv to parse as a CSV text file string * @return a List of QCAnalysis objects created from the metadata file * @throws QCAnalysisException */ public List<QCAnalysis> parseMetadataFile(String csv) throws QCAnalysisException { List<QCAnalysis> qcas = new ArrayList<>(); Reader r = new StringReader(csv); processMetadataFile(r, qcas); return qcas; } private void processMetadataFile(Reader r, List<QCAnalysis> qcas) throws QCAnalysisException { BufferedReader br = null; try { br = new BufferedReader(r); String line; boolean first = true; String[] headers = null; while ((line = br.readLine()) != null) { if (first) { headers = line.toLowerCase().split("[\\s|,]+"); first = false; } else { String[] values = line.split("[\\s|,]+"); if (headers == null || headers.length != values.length) { throw new QCAnalysisException("Invalid headers found"); }
QCAnalysis qa = new DefaultQCAnalysis();
TGAC/statsdb
Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/PartitionValue.java
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // }
import uk.ac.tgac.statsdb.exception.QCAnalysisException;
package uk.ac.tgac.statsdb.analysis; /** * A value class that represents a partionable number, i.e. a range, alongside a given key:value description of that metric * * @author Rob Davey * @date 02/07/13 * @since 1.0_SNAPSHOT */ public class PartitionValue { private long position; private long size; private String key; private String value;
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // } // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/PartitionValue.java import uk.ac.tgac.statsdb.exception.QCAnalysisException; package uk.ac.tgac.statsdb.analysis; /** * A value class that represents a partionable number, i.e. a range, alongside a given key:value description of that metric * * @author Rob Davey * @date 02/07/13 * @since 1.0_SNAPSHOT */ public class PartitionValue { private long position; private long size; private String key; private String value;
public PartitionValue(long position, long size, String key, String value) throws QCAnalysisException {
TGAC/statsdb
Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/QCAnalysis.java
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // }
import uk.ac.tgac.statsdb.exception.QCAnalysisException; import java.util.List; import java.util.Map;
package uk.ac.tgac.statsdb.analysis; /** * Interface defining the contract of QCAnalysis objects * * @author Rob Davey * @date 02/07/13 * @since 1.0-SNAPSHOT */ public interface QCAnalysis { /** * Get the QCAnalysis ID * @return the QCAnalysis object ID */ public long getId(); /** * Sets the ID of this QCAnalysis object * @param id */ public void setId(long id); /** * Retrieve an analysis property value associated with a given key * * @param key * @return * @throws QCAnalysisException */
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // } // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/QCAnalysis.java import uk.ac.tgac.statsdb.exception.QCAnalysisException; import java.util.List; import java.util.Map; package uk.ac.tgac.statsdb.analysis; /** * Interface defining the contract of QCAnalysis objects * * @author Rob Davey * @date 02/07/13 * @since 1.0-SNAPSHOT */ public interface QCAnalysis { /** * Get the QCAnalysis ID * @return the QCAnalysis object ID */ public long getId(); /** * Sets the ID of this QCAnalysis object * @param id */ public void setId(long id); /** * Retrieve an analysis property value associated with a given key * * @param key * @return * @throws QCAnalysisException */
public String getProperty(String key) throws QCAnalysisException;
TGAC/statsdb
Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/util/StatsDBUtils.java
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // }
import uk.ac.tgac.statsdb.exception.QCAnalysisException; import java.util.AbstractMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
package uk.ac.tgac.statsdb.util; /** * Helper class containing any StatsDB general handy constants and functions * * @author Rob Davey * @date 04/07/13 * @since 1.0-SNAPSHOT */ public class StatsDBUtils { /** * Regular expression representing a valid range string */ private static final Pattern rangeSpan = Pattern.compile("([0-9]+)-([0-9]+)"); /** * Regular expression representing a valid point number */ private static final Pattern rangePoint = Pattern.compile("([0-9]+)"); /** * Convert a string object representing a range of numbers separated by a hyphen into two numbers * * @param range * @return A pair (Map.Entry) representing the min and max bounds of a given range string, e.g. 32-142 * results in min=32, max=142 * * @throws uk.ac.tgac.statsdb.exception.QCAnalysisException when a null range is passed to this method, or when the input string is an invalid range string */
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // } // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/util/StatsDBUtils.java import uk.ac.tgac.statsdb.exception.QCAnalysisException; import java.util.AbstractMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; package uk.ac.tgac.statsdb.util; /** * Helper class containing any StatsDB general handy constants and functions * * @author Rob Davey * @date 04/07/13 * @since 1.0-SNAPSHOT */ public class StatsDBUtils { /** * Regular expression representing a valid range string */ private static final Pattern rangeSpan = Pattern.compile("([0-9]+)-([0-9]+)"); /** * Regular expression representing a valid point number */ private static final Pattern rangePoint = Pattern.compile("([0-9]+)"); /** * Convert a string object representing a range of numbers separated by a hyphen into two numbers * * @param range * @return A pair (Map.Entry) representing the min and max bounds of a given range string, e.g. 32-142 * results in min=32, max=142 * * @throws uk.ac.tgac.statsdb.exception.QCAnalysisException when a null range is passed to this method, or when the input string is an invalid range string */
public static Map.Entry<Long, Long> parseRange(String range) throws QCAnalysisException {
TGAC/statsdb
Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/run/parser/QcReportParser.java
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/QCAnalysis.java // public interface QCAnalysis { // /** // * Get the QCAnalysis ID // * @return the QCAnalysis object ID // */ // public long getId(); // // /** // * Sets the ID of this QCAnalysis object // * @param id // */ // public void setId(long id); // // /** // * Retrieve an analysis property value associated with a given key // * // * @param key // * @return // * @throws QCAnalysisException // */ // public String getProperty(String key) throws QCAnalysisException; // // /** // * Add an analysis property // * // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addProperty(String key, String value) throws QCAnalysisException; // // /** // * Add a partition value // * // * @param range // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addPartitionValue(String range, String key, String value) throws QCAnalysisException; // // /** // * Add a position value // * // * @param position // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addPositionValue(String position, String key, String value) throws QCAnalysisException; // // /** // * Add a general value // * // * @param valueType // * @param valueScope // * @param descriptor // * @throws QCAnalysisException // */ // public void addGeneralValue(String valueType, String valueScope, String descriptor) throws QCAnalysisException; // // /** // * Add a value type scope // * // * @param valueTypeKey // * @param valueScope // * @throws QCAnalysisException // */ // public void addValueType(String valueTypeKey, String valueScope) throws QCAnalysisException; // // /** // * Add a value type description // * // * @param valueTypeKey // * @param valueDescription // * @throws QCAnalysisException // */ // public void addValueDescription(String valueTypeKey, String valueDescription) throws QCAnalysisException; // // /** // * Retrieve all analysis properties // * // * @return a map of key:value pairs // */ // public Map<String, String> getProperties(); // // /** // * Retrieve all analysis general values // * // * @return a map of key:value pairs // */ // public Map<String,String> getGeneralValues(); // // /** // * Retrieve all analysis partition values // * // * @return a list of PartitionValues // */ // public List<PartitionValue> getPartitionValues(); // // /** // * Retrieve all analysis position values // * // * @return a list of PositionValues // */ // public List<PositionValue> getPositionValues(); // // /** // * Retrieve all analysis value descriptions // * // * @return a map of key:value pairs // */ // public Map<String, String> getValueDescriptions(); // // /** // * Retrieve all analysis value type scopes // * // * @return a map of key:value pairs // */ // public Map<String, String> getValueScopes(); // } // // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // }
import net.sourceforge.fluxion.spi.Spi; import uk.ac.tgac.statsdb.analysis.QCAnalysis; import uk.ac.tgac.statsdb.exception.QCAnalysisException;
package uk.ac.tgac.statsdb.run.parser; /** * Interface defining contract to parse the output of a QC application into the StatsDB QCAnalysis data type. * * This interface is marked with the @Spi annotation, meaning it can be resolved at runtime by the ServiceLoader * architecture. * * @author Rob Davey * @date 01/07/13 * @since 1.0-SNAPSHOT */ @Spi public interface QcReportParser<T> { /** * Parse a report of type T, populating a given QCAnalysis object properties and values * @param in object of type T * @param qcAnalysis to populate with report contents * @throws QCAnalysisException when the report could not be parsed */
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/QCAnalysis.java // public interface QCAnalysis { // /** // * Get the QCAnalysis ID // * @return the QCAnalysis object ID // */ // public long getId(); // // /** // * Sets the ID of this QCAnalysis object // * @param id // */ // public void setId(long id); // // /** // * Retrieve an analysis property value associated with a given key // * // * @param key // * @return // * @throws QCAnalysisException // */ // public String getProperty(String key) throws QCAnalysisException; // // /** // * Add an analysis property // * // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addProperty(String key, String value) throws QCAnalysisException; // // /** // * Add a partition value // * // * @param range // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addPartitionValue(String range, String key, String value) throws QCAnalysisException; // // /** // * Add a position value // * // * @param position // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addPositionValue(String position, String key, String value) throws QCAnalysisException; // // /** // * Add a general value // * // * @param valueType // * @param valueScope // * @param descriptor // * @throws QCAnalysisException // */ // public void addGeneralValue(String valueType, String valueScope, String descriptor) throws QCAnalysisException; // // /** // * Add a value type scope // * // * @param valueTypeKey // * @param valueScope // * @throws QCAnalysisException // */ // public void addValueType(String valueTypeKey, String valueScope) throws QCAnalysisException; // // /** // * Add a value type description // * // * @param valueTypeKey // * @param valueDescription // * @throws QCAnalysisException // */ // public void addValueDescription(String valueTypeKey, String valueDescription) throws QCAnalysisException; // // /** // * Retrieve all analysis properties // * // * @return a map of key:value pairs // */ // public Map<String, String> getProperties(); // // /** // * Retrieve all analysis general values // * // * @return a map of key:value pairs // */ // public Map<String,String> getGeneralValues(); // // /** // * Retrieve all analysis partition values // * // * @return a list of PartitionValues // */ // public List<PartitionValue> getPartitionValues(); // // /** // * Retrieve all analysis position values // * // * @return a list of PositionValues // */ // public List<PositionValue> getPositionValues(); // // /** // * Retrieve all analysis value descriptions // * // * @return a map of key:value pairs // */ // public Map<String, String> getValueDescriptions(); // // /** // * Retrieve all analysis value type scopes // * // * @return a map of key:value pairs // */ // public Map<String, String> getValueScopes(); // } // // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // } // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/run/parser/QcReportParser.java import net.sourceforge.fluxion.spi.Spi; import uk.ac.tgac.statsdb.analysis.QCAnalysis; import uk.ac.tgac.statsdb.exception.QCAnalysisException; package uk.ac.tgac.statsdb.run.parser; /** * Interface defining contract to parse the output of a QC application into the StatsDB QCAnalysis data type. * * This interface is marked with the @Spi annotation, meaning it can be resolved at runtime by the ServiceLoader * architecture. * * @author Rob Davey * @date 01/07/13 * @since 1.0-SNAPSHOT */ @Spi public interface QcReportParser<T> { /** * Parse a report of type T, populating a given QCAnalysis object properties and values * @param in object of type T * @param qcAnalysis to populate with report contents * @throws QCAnalysisException when the report could not be parsed */
void parseReport(T in, QCAnalysis qcAnalysis) throws QCAnalysisException;
TGAC/statsdb
Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/run/parser/QcReportParser.java
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/QCAnalysis.java // public interface QCAnalysis { // /** // * Get the QCAnalysis ID // * @return the QCAnalysis object ID // */ // public long getId(); // // /** // * Sets the ID of this QCAnalysis object // * @param id // */ // public void setId(long id); // // /** // * Retrieve an analysis property value associated with a given key // * // * @param key // * @return // * @throws QCAnalysisException // */ // public String getProperty(String key) throws QCAnalysisException; // // /** // * Add an analysis property // * // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addProperty(String key, String value) throws QCAnalysisException; // // /** // * Add a partition value // * // * @param range // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addPartitionValue(String range, String key, String value) throws QCAnalysisException; // // /** // * Add a position value // * // * @param position // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addPositionValue(String position, String key, String value) throws QCAnalysisException; // // /** // * Add a general value // * // * @param valueType // * @param valueScope // * @param descriptor // * @throws QCAnalysisException // */ // public void addGeneralValue(String valueType, String valueScope, String descriptor) throws QCAnalysisException; // // /** // * Add a value type scope // * // * @param valueTypeKey // * @param valueScope // * @throws QCAnalysisException // */ // public void addValueType(String valueTypeKey, String valueScope) throws QCAnalysisException; // // /** // * Add a value type description // * // * @param valueTypeKey // * @param valueDescription // * @throws QCAnalysisException // */ // public void addValueDescription(String valueTypeKey, String valueDescription) throws QCAnalysisException; // // /** // * Retrieve all analysis properties // * // * @return a map of key:value pairs // */ // public Map<String, String> getProperties(); // // /** // * Retrieve all analysis general values // * // * @return a map of key:value pairs // */ // public Map<String,String> getGeneralValues(); // // /** // * Retrieve all analysis partition values // * // * @return a list of PartitionValues // */ // public List<PartitionValue> getPartitionValues(); // // /** // * Retrieve all analysis position values // * // * @return a list of PositionValues // */ // public List<PositionValue> getPositionValues(); // // /** // * Retrieve all analysis value descriptions // * // * @return a map of key:value pairs // */ // public Map<String, String> getValueDescriptions(); // // /** // * Retrieve all analysis value type scopes // * // * @return a map of key:value pairs // */ // public Map<String, String> getValueScopes(); // } // // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // }
import net.sourceforge.fluxion.spi.Spi; import uk.ac.tgac.statsdb.analysis.QCAnalysis; import uk.ac.tgac.statsdb.exception.QCAnalysisException;
package uk.ac.tgac.statsdb.run.parser; /** * Interface defining contract to parse the output of a QC application into the StatsDB QCAnalysis data type. * * This interface is marked with the @Spi annotation, meaning it can be resolved at runtime by the ServiceLoader * architecture. * * @author Rob Davey * @date 01/07/13 * @since 1.0-SNAPSHOT */ @Spi public interface QcReportParser<T> { /** * Parse a report of type T, populating a given QCAnalysis object properties and values * @param in object of type T * @param qcAnalysis to populate with report contents * @throws QCAnalysisException when the report could not be parsed */
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/QCAnalysis.java // public interface QCAnalysis { // /** // * Get the QCAnalysis ID // * @return the QCAnalysis object ID // */ // public long getId(); // // /** // * Sets the ID of this QCAnalysis object // * @param id // */ // public void setId(long id); // // /** // * Retrieve an analysis property value associated with a given key // * // * @param key // * @return // * @throws QCAnalysisException // */ // public String getProperty(String key) throws QCAnalysisException; // // /** // * Add an analysis property // * // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addProperty(String key, String value) throws QCAnalysisException; // // /** // * Add a partition value // * // * @param range // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addPartitionValue(String range, String key, String value) throws QCAnalysisException; // // /** // * Add a position value // * // * @param position // * @param key // * @param value // * @throws QCAnalysisException // */ // public void addPositionValue(String position, String key, String value) throws QCAnalysisException; // // /** // * Add a general value // * // * @param valueType // * @param valueScope // * @param descriptor // * @throws QCAnalysisException // */ // public void addGeneralValue(String valueType, String valueScope, String descriptor) throws QCAnalysisException; // // /** // * Add a value type scope // * // * @param valueTypeKey // * @param valueScope // * @throws QCAnalysisException // */ // public void addValueType(String valueTypeKey, String valueScope) throws QCAnalysisException; // // /** // * Add a value type description // * // * @param valueTypeKey // * @param valueDescription // * @throws QCAnalysisException // */ // public void addValueDescription(String valueTypeKey, String valueDescription) throws QCAnalysisException; // // /** // * Retrieve all analysis properties // * // * @return a map of key:value pairs // */ // public Map<String, String> getProperties(); // // /** // * Retrieve all analysis general values // * // * @return a map of key:value pairs // */ // public Map<String,String> getGeneralValues(); // // /** // * Retrieve all analysis partition values // * // * @return a list of PartitionValues // */ // public List<PartitionValue> getPartitionValues(); // // /** // * Retrieve all analysis position values // * // * @return a list of PositionValues // */ // public List<PositionValue> getPositionValues(); // // /** // * Retrieve all analysis value descriptions // * // * @return a map of key:value pairs // */ // public Map<String, String> getValueDescriptions(); // // /** // * Retrieve all analysis value type scopes // * // * @return a map of key:value pairs // */ // public Map<String, String> getValueScopes(); // } // // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // } // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/run/parser/QcReportParser.java import net.sourceforge.fluxion.spi.Spi; import uk.ac.tgac.statsdb.analysis.QCAnalysis; import uk.ac.tgac.statsdb.exception.QCAnalysisException; package uk.ac.tgac.statsdb.run.parser; /** * Interface defining contract to parse the output of a QC application into the StatsDB QCAnalysis data type. * * This interface is marked with the @Spi annotation, meaning it can be resolved at runtime by the ServiceLoader * architecture. * * @author Rob Davey * @date 01/07/13 * @since 1.0-SNAPSHOT */ @Spi public interface QcReportParser<T> { /** * Parse a report of type T, populating a given QCAnalysis object properties and values * @param in object of type T * @param qcAnalysis to populate with report contents * @throws QCAnalysisException when the report could not be parsed */
void parseReport(T in, QCAnalysis qcAnalysis) throws QCAnalysisException;
TGAC/statsdb
Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/PositionValue.java
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // }
import uk.ac.tgac.statsdb.exception.QCAnalysisException;
package uk.ac.tgac.statsdb.analysis; /** * A value class that represents a position number, i.e. a single number, alongside a given key:value description of that metric * * @author Rob Davey * @date 02/07/13 * @since 1.0_SNAPSHOT */ public class PositionValue { private long position; private String key; private String value;
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // } // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/PositionValue.java import uk.ac.tgac.statsdb.exception.QCAnalysisException; package uk.ac.tgac.statsdb.analysis; /** * A value class that represents a position number, i.e. a single number, alongside a given key:value description of that metric * * @author Rob Davey * @date 02/07/13 * @since 1.0_SNAPSHOT */ public class PositionValue { private long position; private String key; private String value;
public PositionValue(long position, String key, String value) throws QCAnalysisException {
TGAC/statsdb
Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/AbstractQCAnalysis.java
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // } // // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/util/StatsDBUtils.java // public class StatsDBUtils { // /** // * Regular expression representing a valid range string // */ // private static final Pattern rangeSpan = Pattern.compile("([0-9]+)-([0-9]+)"); // // /** // * Regular expression representing a valid point number // */ // private static final Pattern rangePoint = Pattern.compile("([0-9]+)"); // // /** // * Convert a string object representing a range of numbers separated by a hyphen into two numbers // * // * @param range // * @return A pair (Map.Entry) representing the min and max bounds of a given range string, e.g. 32-142 // * results in min=32, max=142 // * // * @throws uk.ac.tgac.statsdb.exception.QCAnalysisException when a null range is passed to this method, or when the input string is an invalid range string // */ // public static Map.Entry<Long, Long> parseRange(String range) throws QCAnalysisException { // if (range != null) { // long min = 0L; // long max = 0L; // Matcher m = rangeSpan.matcher(range); // if (m.matches()) { // min = Long.parseLong(m.group(1)); // max = Long.parseLong(m.group(2)); // } // else if (rangePoint.matcher(range).matches()) { // min = max = Long.parseLong(range); // } // else { // throw new QCAnalysisException("Invalid range string '"+range+"'. Needs to be of the form 'a-b'"); // } // return new AbstractMap.SimpleImmutableEntry<>(min, max); // } // else { // throw new QCAnalysisException("Null range supplied to range parse."); // } // } // // /** // * Parses a given range string to produce the size of the difference between the min and max values // * // * @param range // * @return A pair (Map.Entry) representing the min value and the size of the range // * @throws QCAnalysisException // */ // public static Map.Entry<String, String> rangeToSize(String range) throws QCAnalysisException { // Map.Entry<Long, Long> kv = parseRange(range); // long from = kv.getKey(); // long to = kv.getValue(); // long length = Math.abs(to - from); // // if (to < from) { // from = to; // } // // return new AbstractMap.SimpleImmutableEntry<>(String.valueOf(from), String.valueOf(length+1)); // } // // /** // * Capitalise the first letter of a string // * // * @param s // * @return the capitalised string // */ // public static String capitalise(String s) { // return Character.toUpperCase(s.charAt(0)) + s.substring(1); // } // }
import uk.ac.tgac.statsdb.exception.QCAnalysisException; import uk.ac.tgac.statsdb.util.StatsDBUtils; import java.util.AbstractMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
package uk.ac.tgac.statsdb.analysis; /** * Skeleton implementation of a QCAnalysis object. Contains default methods for storing and retrieving QC report * metrics. * * @author Rob Davey * @date 02/07/13 * @since 1.0-SNAPSHOT */ public abstract class AbstractQCAnalysis implements QCAnalysis { private long id = 0L; public Map<String,String> properties; public Map<String,String> valueTypes; public Map<String,String> valueDescriptions; public Map<String,String> generalValues; public List<PartitionValue> partitionValues; public List<PositionValue> positionValues; @Override public void setId(long id) { this.id = id; } @Override public long getId() { return this.id; } @Override
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // } // // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/util/StatsDBUtils.java // public class StatsDBUtils { // /** // * Regular expression representing a valid range string // */ // private static final Pattern rangeSpan = Pattern.compile("([0-9]+)-([0-9]+)"); // // /** // * Regular expression representing a valid point number // */ // private static final Pattern rangePoint = Pattern.compile("([0-9]+)"); // // /** // * Convert a string object representing a range of numbers separated by a hyphen into two numbers // * // * @param range // * @return A pair (Map.Entry) representing the min and max bounds of a given range string, e.g. 32-142 // * results in min=32, max=142 // * // * @throws uk.ac.tgac.statsdb.exception.QCAnalysisException when a null range is passed to this method, or when the input string is an invalid range string // */ // public static Map.Entry<Long, Long> parseRange(String range) throws QCAnalysisException { // if (range != null) { // long min = 0L; // long max = 0L; // Matcher m = rangeSpan.matcher(range); // if (m.matches()) { // min = Long.parseLong(m.group(1)); // max = Long.parseLong(m.group(2)); // } // else if (rangePoint.matcher(range).matches()) { // min = max = Long.parseLong(range); // } // else { // throw new QCAnalysisException("Invalid range string '"+range+"'. Needs to be of the form 'a-b'"); // } // return new AbstractMap.SimpleImmutableEntry<>(min, max); // } // else { // throw new QCAnalysisException("Null range supplied to range parse."); // } // } // // /** // * Parses a given range string to produce the size of the difference between the min and max values // * // * @param range // * @return A pair (Map.Entry) representing the min value and the size of the range // * @throws QCAnalysisException // */ // public static Map.Entry<String, String> rangeToSize(String range) throws QCAnalysisException { // Map.Entry<Long, Long> kv = parseRange(range); // long from = kv.getKey(); // long to = kv.getValue(); // long length = Math.abs(to - from); // // if (to < from) { // from = to; // } // // return new AbstractMap.SimpleImmutableEntry<>(String.valueOf(from), String.valueOf(length+1)); // } // // /** // * Capitalise the first letter of a string // * // * @param s // * @return the capitalised string // */ // public static String capitalise(String s) { // return Character.toUpperCase(s.charAt(0)) + s.substring(1); // } // } // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/AbstractQCAnalysis.java import uk.ac.tgac.statsdb.exception.QCAnalysisException; import uk.ac.tgac.statsdb.util.StatsDBUtils; import java.util.AbstractMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; package uk.ac.tgac.statsdb.analysis; /** * Skeleton implementation of a QCAnalysis object. Contains default methods for storing and retrieving QC report * metrics. * * @author Rob Davey * @date 02/07/13 * @since 1.0-SNAPSHOT */ public abstract class AbstractQCAnalysis implements QCAnalysis { private long id = 0L; public Map<String,String> properties; public Map<String,String> valueTypes; public Map<String,String> valueDescriptions; public Map<String,String> generalValues; public List<PartitionValue> partitionValues; public List<PositionValue> positionValues; @Override public void setId(long id) { this.id = id; } @Override public long getId() { return this.id; } @Override
public String getProperty(String key) throws QCAnalysisException {
TGAC/statsdb
Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/AbstractQCAnalysis.java
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // } // // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/util/StatsDBUtils.java // public class StatsDBUtils { // /** // * Regular expression representing a valid range string // */ // private static final Pattern rangeSpan = Pattern.compile("([0-9]+)-([0-9]+)"); // // /** // * Regular expression representing a valid point number // */ // private static final Pattern rangePoint = Pattern.compile("([0-9]+)"); // // /** // * Convert a string object representing a range of numbers separated by a hyphen into two numbers // * // * @param range // * @return A pair (Map.Entry) representing the min and max bounds of a given range string, e.g. 32-142 // * results in min=32, max=142 // * // * @throws uk.ac.tgac.statsdb.exception.QCAnalysisException when a null range is passed to this method, or when the input string is an invalid range string // */ // public static Map.Entry<Long, Long> parseRange(String range) throws QCAnalysisException { // if (range != null) { // long min = 0L; // long max = 0L; // Matcher m = rangeSpan.matcher(range); // if (m.matches()) { // min = Long.parseLong(m.group(1)); // max = Long.parseLong(m.group(2)); // } // else if (rangePoint.matcher(range).matches()) { // min = max = Long.parseLong(range); // } // else { // throw new QCAnalysisException("Invalid range string '"+range+"'. Needs to be of the form 'a-b'"); // } // return new AbstractMap.SimpleImmutableEntry<>(min, max); // } // else { // throw new QCAnalysisException("Null range supplied to range parse."); // } // } // // /** // * Parses a given range string to produce the size of the difference between the min and max values // * // * @param range // * @return A pair (Map.Entry) representing the min value and the size of the range // * @throws QCAnalysisException // */ // public static Map.Entry<String, String> rangeToSize(String range) throws QCAnalysisException { // Map.Entry<Long, Long> kv = parseRange(range); // long from = kv.getKey(); // long to = kv.getValue(); // long length = Math.abs(to - from); // // if (to < from) { // from = to; // } // // return new AbstractMap.SimpleImmutableEntry<>(String.valueOf(from), String.valueOf(length+1)); // } // // /** // * Capitalise the first letter of a string // * // * @param s // * @return the capitalised string // */ // public static String capitalise(String s) { // return Character.toUpperCase(s.charAt(0)) + s.substring(1); // } // }
import uk.ac.tgac.statsdb.exception.QCAnalysisException; import uk.ac.tgac.statsdb.util.StatsDBUtils; import java.util.AbstractMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
public List<PartitionValue> partitionValues; public List<PositionValue> positionValues; @Override public void setId(long id) { this.id = id; } @Override public long getId() { return this.id; } @Override public String getProperty(String key) throws QCAnalysisException { if (properties.containsKey(key)) { return properties.get(key); } else { throw new QCAnalysisException("No such property on analysis: " + getId()); } } @Override public void addProperty(String key, String value) throws QCAnalysisException { properties.put(key, value); } @Override public void addPartitionValue(String range, String key, String value) throws QCAnalysisException {
// Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/exception/QCAnalysisException.java // public class QCAnalysisException extends Exception { // public QCAnalysisException(String s) { // super(s); // } // // public QCAnalysisException(String s, Throwable cause) { // super(s); // if (cause != null) { // initCause(cause); // } // } // } // // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/util/StatsDBUtils.java // public class StatsDBUtils { // /** // * Regular expression representing a valid range string // */ // private static final Pattern rangeSpan = Pattern.compile("([0-9]+)-([0-9]+)"); // // /** // * Regular expression representing a valid point number // */ // private static final Pattern rangePoint = Pattern.compile("([0-9]+)"); // // /** // * Convert a string object representing a range of numbers separated by a hyphen into two numbers // * // * @param range // * @return A pair (Map.Entry) representing the min and max bounds of a given range string, e.g. 32-142 // * results in min=32, max=142 // * // * @throws uk.ac.tgac.statsdb.exception.QCAnalysisException when a null range is passed to this method, or when the input string is an invalid range string // */ // public static Map.Entry<Long, Long> parseRange(String range) throws QCAnalysisException { // if (range != null) { // long min = 0L; // long max = 0L; // Matcher m = rangeSpan.matcher(range); // if (m.matches()) { // min = Long.parseLong(m.group(1)); // max = Long.parseLong(m.group(2)); // } // else if (rangePoint.matcher(range).matches()) { // min = max = Long.parseLong(range); // } // else { // throw new QCAnalysisException("Invalid range string '"+range+"'. Needs to be of the form 'a-b'"); // } // return new AbstractMap.SimpleImmutableEntry<>(min, max); // } // else { // throw new QCAnalysisException("Null range supplied to range parse."); // } // } // // /** // * Parses a given range string to produce the size of the difference between the min and max values // * // * @param range // * @return A pair (Map.Entry) representing the min value and the size of the range // * @throws QCAnalysisException // */ // public static Map.Entry<String, String> rangeToSize(String range) throws QCAnalysisException { // Map.Entry<Long, Long> kv = parseRange(range); // long from = kv.getKey(); // long to = kv.getValue(); // long length = Math.abs(to - from); // // if (to < from) { // from = to; // } // // return new AbstractMap.SimpleImmutableEntry<>(String.valueOf(from), String.valueOf(length+1)); // } // // /** // * Capitalise the first letter of a string // * // * @param s // * @return the capitalised string // */ // public static String capitalise(String s) { // return Character.toUpperCase(s.charAt(0)) + s.substring(1); // } // } // Path: Java/statsdb-api/src/main/java/uk/ac/tgac/statsdb/analysis/AbstractQCAnalysis.java import uk.ac.tgac.statsdb.exception.QCAnalysisException; import uk.ac.tgac.statsdb.util.StatsDBUtils; import java.util.AbstractMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public List<PartitionValue> partitionValues; public List<PositionValue> positionValues; @Override public void setId(long id) { this.id = id; } @Override public long getId() { return this.id; } @Override public String getProperty(String key) throws QCAnalysisException { if (properties.containsKey(key)) { return properties.get(key); } else { throw new QCAnalysisException("No such property on analysis: " + getId()); } } @Override public void addProperty(String key, String value) throws QCAnalysisException { properties.put(key, value); } @Override public void addPartitionValue(String range, String key, String value) throws QCAnalysisException {
Map.Entry<String, String> positionAndSize = StatsDBUtils.rangeToSize(range);
snazy/ohc
ohc-core/src/main/java/org/caffinitas/ohc/linked/Timeouts.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/Ticker.java // public interface Ticker // { // Ticker DEFAULT = new DefaultTicker(); // // long nanos(); // // long currentTimeMillis(); // }
import com.google.common.primitives.Ints; import org.caffinitas.ohc.Ticker;
/* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.linked; /** * Manages cache entry time-to-live in off-heap memory. * <p> * TTL entries are organized in {@code slots} slots. The <i>slot</i> is chosen using * the entry's {@code expireAt} absolute timestamp value - rounded by the provided * {@code precision}. * Technically the index of a slot is calculated using the formula: * {@code slotIndex = (expireAt >> precisionShift) & slotBitmask}. * </p> * <p> * Each slot maintains an unsorted list of entries. Each entry consists of the * {@code hashEntryAdr} of the cache's entry and the {@code expireAt} absolute * timestamp. The size of a slot's list is unbounded, it is resized if necessary - * both increasing and decreasing. * </p> */ final class Timeouts { private final long slotBitmask; private final int precisionShift; private final int slotCount; private final Slot[] slots;
// Path: ohc-core/src/main/java/org/caffinitas/ohc/Ticker.java // public interface Ticker // { // Ticker DEFAULT = new DefaultTicker(); // // long nanos(); // // long currentTimeMillis(); // } // Path: ohc-core/src/main/java/org/caffinitas/ohc/linked/Timeouts.java import com.google.common.primitives.Ints; import org.caffinitas.ohc.Ticker; /* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.linked; /** * Manages cache entry time-to-live in off-heap memory. * <p> * TTL entries are organized in {@code slots} slots. The <i>slot</i> is chosen using * the entry's {@code expireAt} absolute timestamp value - rounded by the provided * {@code precision}. * Technically the index of a slot is calculated using the formula: * {@code slotIndex = (expireAt >> precisionShift) & slotBitmask}. * </p> * <p> * Each slot maintains an unsorted list of entries. Each entry consists of the * {@code hashEntryAdr} of the cache's entry and the {@code expireAt} absolute * timestamp. The size of a slot's list is unbounded, it is resized if necessary - * both increasing and decreasing. * </p> */ final class Timeouts { private final long slotBitmask; private final int precisionShift; private final int slotCount; private final Slot[] slots;
private final Ticker ticker;
snazy/ohc
ohc-core/src/test/java/org/caffinitas/ohc/linked/HashEntriesTest.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // }
import org.caffinitas.ohc.HashAlgorithm; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import java.nio.ByteBuffer; import static org.testng.Assert.*;
assertEquals(Uns.getInt(adr, Util.ENTRY_OFF_VALUE_LENGTH), 10L); assertEquals(HashEntries.getHash(adr), 0x98765432abcddeafL); assertEquals(HashEntries.getKeyLen(adr), 5L); assertEquals(HashEntries.getValueLen(adr), 10L); assertTrue(HashEntries.dereference(adr)); ok = true; } finally { if (!ok) Uns.free(adr); } } @Test public void testCompareKey() throws Exception { long adr = Uns.allocate(MIN_ALLOC_LEN); KeyBuffer key = new KeyBuffer(11); try { HashEntries.init(0L, 11, 0, adr, Util.SENTINEL_NOT_PRESENT, 0L); ByteBuffer keyBuffer = key.byteBuffer(); keyBuffer.putInt(0x98765432); keyBuffer.putInt(0xabcdabba); keyBuffer.put((byte)(0x44 & 0xff)); keyBuffer.put((byte)(0x55 & 0xff)); keyBuffer.put((byte)(0x88 & 0xff));
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // } // Path: ohc-core/src/test/java/org/caffinitas/ohc/linked/HashEntriesTest.java import org.caffinitas.ohc.HashAlgorithm; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import java.nio.ByteBuffer; import static org.testng.Assert.*; assertEquals(Uns.getInt(adr, Util.ENTRY_OFF_VALUE_LENGTH), 10L); assertEquals(HashEntries.getHash(adr), 0x98765432abcddeafL); assertEquals(HashEntries.getKeyLen(adr), 5L); assertEquals(HashEntries.getValueLen(adr), 10L); assertTrue(HashEntries.dereference(adr)); ok = true; } finally { if (!ok) Uns.free(adr); } } @Test public void testCompareKey() throws Exception { long adr = Uns.allocate(MIN_ALLOC_LEN); KeyBuffer key = new KeyBuffer(11); try { HashEntries.init(0L, 11, 0, adr, Util.SENTINEL_NOT_PRESENT, 0L); ByteBuffer keyBuffer = key.byteBuffer(); keyBuffer.putInt(0x98765432); keyBuffer.putInt(0xabcdabba); keyBuffer.put((byte)(0x44 & 0xff)); keyBuffer.put((byte)(0x55 & 0xff)); keyBuffer.put((byte)(0x88 & 0xff));
key.finish(Hasher.create(HashAlgorithm.MURMUR3));
snazy/ohc
ohc-core/src/test/java/org/caffinitas/ohc/linked/CheckSegment.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/Eviction.java // public enum Eviction // { // LRU, // W_TINY_LFU, // NONE // }
import org.caffinitas.ohc.Eviction; import java.util.*; import java.util.concurrent.atomic.AtomicLong;
/* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.linked; /** * On-heap test-only counterpart of {@link OffHeapLinkedMap} for {@link CheckOHCacheImpl}. */ final class CheckSegment { private final Map<HeapKeyBuffer, byte[]> map; private final LinkedList<HeapKeyBuffer> lru = new LinkedList<>(); private final AtomicLong freeCapacity;
// Path: ohc-core/src/main/java/org/caffinitas/ohc/Eviction.java // public enum Eviction // { // LRU, // W_TINY_LFU, // NONE // } // Path: ohc-core/src/test/java/org/caffinitas/ohc/linked/CheckSegment.java import org.caffinitas.ohc.Eviction; import java.util.*; import java.util.concurrent.atomic.AtomicLong; /* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.linked; /** * On-heap test-only counterpart of {@link OffHeapLinkedMap} for {@link CheckOHCacheImpl}. */ final class CheckSegment { private final Map<HeapKeyBuffer, byte[]> map; private final LinkedList<HeapKeyBuffer> lru = new LinkedList<>(); private final AtomicLong freeCapacity;
private final Eviction eviction;
snazy/ohc
ohc-core/src/main/java/org/caffinitas/ohc/linked/Hasher.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // }
import org.caffinitas.ohc.HashAlgorithm; import java.lang.reflect.InvocationTargetException;
/* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.linked; abstract class Hasher {
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // } // Path: ohc-core/src/main/java/org/caffinitas/ohc/linked/Hasher.java import org.caffinitas.ohc.HashAlgorithm; import java.lang.reflect.InvocationTargetException; /* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.linked; abstract class Hasher {
static Hasher create(HashAlgorithm hashAlgorithm)
snazy/ohc
ohc-core/src/test/java/org/caffinitas/ohc/linked/HasherTest.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // }
import org.caffinitas.ohc.HashAlgorithm; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Random;
/* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.linked; public class HasherTest { @Test public void testMurmur3() {
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // } // Path: ohc-core/src/test/java/org/caffinitas/ohc/linked/HasherTest.java import org.caffinitas.ohc.HashAlgorithm; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Random; /* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.linked; public class HasherTest { @Test public void testMurmur3() {
test(HashAlgorithm.MURMUR3);
snazy/ohc
ohc-core/src/main/java/org/caffinitas/ohc/chunked/Murmur3Hash.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferPosition(ByteBuffer byteBuffer, int position) { // byteBufferAccess.position(byteBuffer, position); // }
import java.nio.ByteBuffer; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferPosition;
k2 ^= toLong(buffer.get(p + 12)) << 32; // fall through case 12: k2 ^= toLong(buffer.get(p + 11)) << 24; // fall through case 11: k2 ^= toLong(buffer.get(p + 10)) << 16; // fall through case 10: k2 ^= toLong(buffer.get(p + 9)) << 8; // fall through case 9: k2 ^= toLong(buffer.get(p + 8)); // fall through case 8: k1 ^= getLong(buffer); break; case 7: k1 ^= toLong(buffer.get(p + 6)) << 48; // fall through case 6: k1 ^= toLong(buffer.get(p + 5)) << 40; // fall through case 5: k1 ^= toLong(buffer.get(p + 4)) << 32; // fall through case 4: k1 ^= toLong(buffer.get(p + 3)) << 24; // fall through case 3: k1 ^= toLong(buffer.get(p + 2)) << 16; // fall through case 2: k1 ^= toLong(buffer.get(p + 1)) << 8; // fall through case 1: k1 ^= toLong(buffer.get(p)); break; default: throw new AssertionError("Should never get here."); }
// Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferPosition(ByteBuffer byteBuffer, int position) { // byteBufferAccess.position(byteBuffer, position); // } // Path: ohc-core/src/main/java/org/caffinitas/ohc/chunked/Murmur3Hash.java import java.nio.ByteBuffer; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferPosition; k2 ^= toLong(buffer.get(p + 12)) << 32; // fall through case 12: k2 ^= toLong(buffer.get(p + 11)) << 24; // fall through case 11: k2 ^= toLong(buffer.get(p + 10)) << 16; // fall through case 10: k2 ^= toLong(buffer.get(p + 9)) << 8; // fall through case 9: k2 ^= toLong(buffer.get(p + 8)); // fall through case 8: k1 ^= getLong(buffer); break; case 7: k1 ^= toLong(buffer.get(p + 6)) << 48; // fall through case 6: k1 ^= toLong(buffer.get(p + 5)) << 40; // fall through case 5: k1 ^= toLong(buffer.get(p + 4)) << 32; // fall through case 4: k1 ^= toLong(buffer.get(p + 3)) << 24; // fall through case 3: k1 ^= toLong(buffer.get(p + 2)) << 16; // fall through case 2: k1 ^= toLong(buffer.get(p + 1)) << 8; // fall through case 1: k1 ^= toLong(buffer.get(p)); break; default: throw new AssertionError("Should never get here."); }
byteBufferPosition(buffer, p + r);
snazy/ohc
ohc-core/src/test/java/org/caffinitas/ohc/linked/KeyBufferTest.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // }
import com.google.common.hash.HashCode; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import org.caffinitas.ohc.HashAlgorithm; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.nio.ByteBuffer; import static org.testng.Assert.assertEquals;
/* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.linked; public class KeyBufferTest { @AfterMethod(alwaysRun = true) public void deinit() { Uns.clearUnsDebugForTest(); } @DataProvider public Object[][] hashes() { return new Object[][]{
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // } // Path: ohc-core/src/test/java/org/caffinitas/ohc/linked/KeyBufferTest.java import com.google.common.hash.HashCode; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import org.caffinitas.ohc.HashAlgorithm; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.nio.ByteBuffer; import static org.testng.Assert.assertEquals; /* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.linked; public class KeyBufferTest { @AfterMethod(alwaysRun = true) public void deinit() { Uns.clearUnsDebugForTest(); } @DataProvider public Object[][] hashes() { return new Object[][]{
{ HashAlgorithm.MURMUR3 },
snazy/ohc
ohc-jmh/src/main/java/org/caffinitas/ohc/jmh/AllocatorBenchmark.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/IAllocator.java // public interface IAllocator // { // long allocate(long size); // void free(long peer); // long getTotalAllocated(); // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/JNANativeAllocator.java // public final class JNANativeAllocator implements IAllocator // { // public long allocate(long size) // { // try // { // return Native.malloc(size); // } // catch (OutOfMemoryError oom) // { // return 0L; // } // } // // public void free(long peer) // { // Native.free(peer); // } // // public long getTotalAllocated() // { // return -1L; // } // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/UnsafeAllocator.java // public final class UnsafeAllocator implements IAllocator // { // static final Unsafe unsafe; // // static // { // try // { // Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); // field.setAccessible(true); // unsafe = (sun.misc.Unsafe) field.get(null); // } // catch (Exception e) // { // throw new AssertionError(e); // } // } // // public long allocate(long size) // { // try // { // return unsafe.allocateMemory(size); // } // catch (OutOfMemoryError oom) // { // return 0L; // } // } // // public void free(long peer) // { // unsafe.freeMemory(peer); // } // // public long getTotalAllocated() // { // return -1L; // } // }
import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.caffinitas.ohc.alloc.IAllocator; import org.caffinitas.ohc.alloc.JNANativeAllocator; import org.caffinitas.ohc.alloc.UnsafeAllocator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.annotations.Warmup;
/* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.jmh; @BenchmarkMode({ /*Mode.AverageTime, */Mode.Throughput }) @State(Scope.Benchmark) @Warmup(iterations = 2) @Measurement(iterations = 3) @Threads(4) @OutputTimeUnit(TimeUnit.MICROSECONDS) @Fork(value = 1, jvmArgsAppend = "-Xmx512M") public class AllocatorBenchmark { @Param({ "128", /*"256", "512", "1024", "1536", "2048", "4096", */"8192" }) private int size = 128; @Param({ "Unsafe", "JNA" }) private String allocatorType = "JNA";
// Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/IAllocator.java // public interface IAllocator // { // long allocate(long size); // void free(long peer); // long getTotalAllocated(); // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/JNANativeAllocator.java // public final class JNANativeAllocator implements IAllocator // { // public long allocate(long size) // { // try // { // return Native.malloc(size); // } // catch (OutOfMemoryError oom) // { // return 0L; // } // } // // public void free(long peer) // { // Native.free(peer); // } // // public long getTotalAllocated() // { // return -1L; // } // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/UnsafeAllocator.java // public final class UnsafeAllocator implements IAllocator // { // static final Unsafe unsafe; // // static // { // try // { // Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); // field.setAccessible(true); // unsafe = (sun.misc.Unsafe) field.get(null); // } // catch (Exception e) // { // throw new AssertionError(e); // } // } // // public long allocate(long size) // { // try // { // return unsafe.allocateMemory(size); // } // catch (OutOfMemoryError oom) // { // return 0L; // } // } // // public void free(long peer) // { // unsafe.freeMemory(peer); // } // // public long getTotalAllocated() // { // return -1L; // } // } // Path: ohc-jmh/src/main/java/org/caffinitas/ohc/jmh/AllocatorBenchmark.java import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.caffinitas.ohc.alloc.IAllocator; import org.caffinitas.ohc.alloc.JNANativeAllocator; import org.caffinitas.ohc.alloc.UnsafeAllocator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.annotations.Warmup; /* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.jmh; @BenchmarkMode({ /*Mode.AverageTime, */Mode.Throughput }) @State(Scope.Benchmark) @Warmup(iterations = 2) @Measurement(iterations = 3) @Threads(4) @OutputTimeUnit(TimeUnit.MICROSECONDS) @Fork(value = 1, jvmArgsAppend = "-Xmx512M") public class AllocatorBenchmark { @Param({ "128", /*"256", "512", "1024", "1536", "2048", "4096", */"8192" }) private int size = 128; @Param({ "Unsafe", "JNA" }) private String allocatorType = "JNA";
private IAllocator allocator;
snazy/ohc
ohc-jmh/src/main/java/org/caffinitas/ohc/jmh/AllocatorBenchmark.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/IAllocator.java // public interface IAllocator // { // long allocate(long size); // void free(long peer); // long getTotalAllocated(); // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/JNANativeAllocator.java // public final class JNANativeAllocator implements IAllocator // { // public long allocate(long size) // { // try // { // return Native.malloc(size); // } // catch (OutOfMemoryError oom) // { // return 0L; // } // } // // public void free(long peer) // { // Native.free(peer); // } // // public long getTotalAllocated() // { // return -1L; // } // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/UnsafeAllocator.java // public final class UnsafeAllocator implements IAllocator // { // static final Unsafe unsafe; // // static // { // try // { // Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); // field.setAccessible(true); // unsafe = (sun.misc.Unsafe) field.get(null); // } // catch (Exception e) // { // throw new AssertionError(e); // } // } // // public long allocate(long size) // { // try // { // return unsafe.allocateMemory(size); // } // catch (OutOfMemoryError oom) // { // return 0L; // } // } // // public void free(long peer) // { // unsafe.freeMemory(peer); // } // // public long getTotalAllocated() // { // return -1L; // } // }
import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.caffinitas.ohc.alloc.IAllocator; import org.caffinitas.ohc.alloc.JNANativeAllocator; import org.caffinitas.ohc.alloc.UnsafeAllocator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.annotations.Warmup;
if (adr.compareAndSet(a, 0L)) { allocator.free(a); break; } } long a = allocator.allocate(size); if (!adr.compareAndSet(0L, a)) { allocator.free(a); } } void freeAll(IAllocator allocator) { for (AtomicLong al : adrs) { long adr = al.get(); if (adr != 0L) allocator.free(adr); } } } @Setup public void createAllocator() { switch (allocatorType) {
// Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/IAllocator.java // public interface IAllocator // { // long allocate(long size); // void free(long peer); // long getTotalAllocated(); // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/JNANativeAllocator.java // public final class JNANativeAllocator implements IAllocator // { // public long allocate(long size) // { // try // { // return Native.malloc(size); // } // catch (OutOfMemoryError oom) // { // return 0L; // } // } // // public void free(long peer) // { // Native.free(peer); // } // // public long getTotalAllocated() // { // return -1L; // } // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/UnsafeAllocator.java // public final class UnsafeAllocator implements IAllocator // { // static final Unsafe unsafe; // // static // { // try // { // Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); // field.setAccessible(true); // unsafe = (sun.misc.Unsafe) field.get(null); // } // catch (Exception e) // { // throw new AssertionError(e); // } // } // // public long allocate(long size) // { // try // { // return unsafe.allocateMemory(size); // } // catch (OutOfMemoryError oom) // { // return 0L; // } // } // // public void free(long peer) // { // unsafe.freeMemory(peer); // } // // public long getTotalAllocated() // { // return -1L; // } // } // Path: ohc-jmh/src/main/java/org/caffinitas/ohc/jmh/AllocatorBenchmark.java import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.caffinitas.ohc.alloc.IAllocator; import org.caffinitas.ohc.alloc.JNANativeAllocator; import org.caffinitas.ohc.alloc.UnsafeAllocator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.annotations.Warmup; if (adr.compareAndSet(a, 0L)) { allocator.free(a); break; } } long a = allocator.allocate(size); if (!adr.compareAndSet(0L, a)) { allocator.free(a); } } void freeAll(IAllocator allocator) { for (AtomicLong al : adrs) { long adr = al.get(); if (adr != 0L) allocator.free(adr); } } } @Setup public void createAllocator() { switch (allocatorType) {
case "Unsafe": allocator = new UnsafeAllocator(); break;
snazy/ohc
ohc-jmh/src/main/java/org/caffinitas/ohc/jmh/AllocatorBenchmark.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/IAllocator.java // public interface IAllocator // { // long allocate(long size); // void free(long peer); // long getTotalAllocated(); // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/JNANativeAllocator.java // public final class JNANativeAllocator implements IAllocator // { // public long allocate(long size) // { // try // { // return Native.malloc(size); // } // catch (OutOfMemoryError oom) // { // return 0L; // } // } // // public void free(long peer) // { // Native.free(peer); // } // // public long getTotalAllocated() // { // return -1L; // } // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/UnsafeAllocator.java // public final class UnsafeAllocator implements IAllocator // { // static final Unsafe unsafe; // // static // { // try // { // Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); // field.setAccessible(true); // unsafe = (sun.misc.Unsafe) field.get(null); // } // catch (Exception e) // { // throw new AssertionError(e); // } // } // // public long allocate(long size) // { // try // { // return unsafe.allocateMemory(size); // } // catch (OutOfMemoryError oom) // { // return 0L; // } // } // // public void free(long peer) // { // unsafe.freeMemory(peer); // } // // public long getTotalAllocated() // { // return -1L; // } // }
import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.caffinitas.ohc.alloc.IAllocator; import org.caffinitas.ohc.alloc.JNANativeAllocator; import org.caffinitas.ohc.alloc.UnsafeAllocator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.annotations.Warmup;
{ allocator.free(a); break; } } long a = allocator.allocate(size); if (!adr.compareAndSet(0L, a)) { allocator.free(a); } } void freeAll(IAllocator allocator) { for (AtomicLong al : adrs) { long adr = al.get(); if (adr != 0L) allocator.free(adr); } } } @Setup public void createAllocator() { switch (allocatorType) { case "Unsafe": allocator = new UnsafeAllocator(); break;
// Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/IAllocator.java // public interface IAllocator // { // long allocate(long size); // void free(long peer); // long getTotalAllocated(); // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/JNANativeAllocator.java // public final class JNANativeAllocator implements IAllocator // { // public long allocate(long size) // { // try // { // return Native.malloc(size); // } // catch (OutOfMemoryError oom) // { // return 0L; // } // } // // public void free(long peer) // { // Native.free(peer); // } // // public long getTotalAllocated() // { // return -1L; // } // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/alloc/UnsafeAllocator.java // public final class UnsafeAllocator implements IAllocator // { // static final Unsafe unsafe; // // static // { // try // { // Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); // field.setAccessible(true); // unsafe = (sun.misc.Unsafe) field.get(null); // } // catch (Exception e) // { // throw new AssertionError(e); // } // } // // public long allocate(long size) // { // try // { // return unsafe.allocateMemory(size); // } // catch (OutOfMemoryError oom) // { // return 0L; // } // } // // public void free(long peer) // { // unsafe.freeMemory(peer); // } // // public long getTotalAllocated() // { // return -1L; // } // } // Path: ohc-jmh/src/main/java/org/caffinitas/ohc/jmh/AllocatorBenchmark.java import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.caffinitas.ohc.alloc.IAllocator; import org.caffinitas.ohc.alloc.JNANativeAllocator; import org.caffinitas.ohc.alloc.UnsafeAllocator; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.annotations.Warmup; { allocator.free(a); break; } } long a = allocator.allocate(size); if (!adr.compareAndSet(0L, a)) { allocator.free(a); } } void freeAll(IAllocator allocator) { for (AtomicLong al : adrs) { long adr = al.get(); if (adr != 0L) allocator.free(adr); } } } @Setup public void createAllocator() { switch (allocatorType) { case "Unsafe": allocator = new UnsafeAllocator(); break;
case "JNA": allocator = new JNANativeAllocator(); break;
snazy/ohc
ohc-core/src/test/java/org/caffinitas/ohc/linked/UnsTest.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferClear(ByteBuffer byteBuffer) { // byteBufferAccess.clear(byteBuffer); // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferFlip(ByteBuffer byteBuffer) { // byteBufferAccess.flip(byteBuffer); // }
import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import sun.misc.Unsafe; import sun.nio.ch.DirectBuffer; import java.io.IOException; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Random; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferClear; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferFlip; import static org.testng.Assert.*;
/* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.linked; public class UnsTest { @AfterMethod(alwaysRun = true) public void deinit() { Uns.clearUnsDebugForTest(); } private static final Unsafe unsafe; static final int CAPACITY = 65536; static final ByteBuffer directBuffer; static { try { Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); unsafe = (Unsafe) field.get(null); if (unsafe.addressSize() > 8) throw new RuntimeException("Address size " + unsafe.addressSize() + " not supported yet (max 8 bytes)"); directBuffer = ByteBuffer.allocateDirect(CAPACITY); } catch (Exception e) { throw new AssertionError(e); } } private static void fillRandom() { Random r = new Random();
// Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferClear(ByteBuffer byteBuffer) { // byteBufferAccess.clear(byteBuffer); // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferFlip(ByteBuffer byteBuffer) { // byteBufferAccess.flip(byteBuffer); // } // Path: ohc-core/src/test/java/org/caffinitas/ohc/linked/UnsTest.java import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import sun.misc.Unsafe; import sun.nio.ch.DirectBuffer; import java.io.IOException; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Random; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferClear; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferFlip; import static org.testng.Assert.*; /* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.linked; public class UnsTest { @AfterMethod(alwaysRun = true) public void deinit() { Uns.clearUnsDebugForTest(); } private static final Unsafe unsafe; static final int CAPACITY = 65536; static final ByteBuffer directBuffer; static { try { Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); unsafe = (Unsafe) field.get(null); if (unsafe.addressSize() > 8) throw new RuntimeException("Address size " + unsafe.addressSize() + " not supported yet (max 8 bytes)"); directBuffer = ByteBuffer.allocateDirect(CAPACITY); } catch (Exception e) { throw new AssertionError(e); } } private static void fillRandom() { Random r = new Random();
byteBufferClear(directBuffer);
snazy/ohc
ohc-core/src/test/java/org/caffinitas/ohc/linked/UnsTest.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferClear(ByteBuffer byteBuffer) { // byteBufferAccess.clear(byteBuffer); // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferFlip(ByteBuffer byteBuffer) { // byteBufferAccess.flip(byteBuffer); // }
import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import sun.misc.Unsafe; import sun.nio.ch.DirectBuffer; import java.io.IOException; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Random; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferClear; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferFlip; import static org.testng.Assert.*;
try { for (byte b = 0; b < 13; b++) for (int offset = 0; offset < 10; offset += 13) { Uns.setMemory(adr, offset, 7777, b); for (int off = 0; off < 7777; off++) assertEquals(unsafe.getByte(adr + offset), b); } } finally { Uns.free(adr); } } @Test public void testGetLongFromByteArray() throws Exception { byte[] arr = TestUtils.randomBytes(32); ByteOrder order = directBuffer.order(); directBuffer.order(ByteOrder.nativeOrder()); try { for (int i = 0; i < 14; i++) { long u = Uns.getLongFromByteArray(arr, i); byteBufferClear(directBuffer); directBuffer.put(arr);
// Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferClear(ByteBuffer byteBuffer) { // byteBufferAccess.clear(byteBuffer); // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferFlip(ByteBuffer byteBuffer) { // byteBufferAccess.flip(byteBuffer); // } // Path: ohc-core/src/test/java/org/caffinitas/ohc/linked/UnsTest.java import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import sun.misc.Unsafe; import sun.nio.ch.DirectBuffer; import java.io.IOException; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Random; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferClear; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferFlip; import static org.testng.Assert.*; try { for (byte b = 0; b < 13; b++) for (int offset = 0; offset < 10; offset += 13) { Uns.setMemory(adr, offset, 7777, b); for (int off = 0; off < 7777; off++) assertEquals(unsafe.getByte(adr + offset), b); } } finally { Uns.free(adr); } } @Test public void testGetLongFromByteArray() throws Exception { byte[] arr = TestUtils.randomBytes(32); ByteOrder order = directBuffer.order(); directBuffer.order(ByteOrder.nativeOrder()); try { for (int i = 0; i < 14; i++) { long u = Uns.getLongFromByteArray(arr, i); byteBufferClear(directBuffer); directBuffer.put(arr);
byteBufferFlip(directBuffer);
snazy/ohc
ohc-core/src/main/java/org/caffinitas/ohc/chunked/Hasher.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // }
import java.nio.ByteBuffer; import org.caffinitas.ohc.HashAlgorithm;
/* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.chunked; abstract class Hasher {
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // } // Path: ohc-core/src/main/java/org/caffinitas/ohc/chunked/Hasher.java import java.nio.ByteBuffer; import org.caffinitas.ohc.HashAlgorithm; /* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.chunked; abstract class Hasher {
static Hasher create(HashAlgorithm hashAlgorithm)
snazy/ohc
ohc-core/src/test/java/org/caffinitas/ohc/chunked/HasherTest.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferPosition(ByteBuffer byteBuffer, int position) { // byteBufferAccess.position(byteBuffer, position); // }
import java.nio.ByteBuffer; import java.util.Random; import org.caffinitas.ohc.HashAlgorithm; import org.testng.Assert; import org.testng.annotations.Test; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferPosition;
/* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.chunked; public class HasherTest { @Test public void testMurmur3() {
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferPosition(ByteBuffer byteBuffer, int position) { // byteBufferAccess.position(byteBuffer, position); // } // Path: ohc-core/src/test/java/org/caffinitas/ohc/chunked/HasherTest.java import java.nio.ByteBuffer; import java.util.Random; import org.caffinitas.ohc.HashAlgorithm; import org.testng.Assert; import org.testng.annotations.Test; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferPosition; /* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.chunked; public class HasherTest { @Test public void testMurmur3() {
test(HashAlgorithm.MURMUR3);
snazy/ohc
ohc-core/src/test/java/org/caffinitas/ohc/chunked/HasherTest.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferPosition(ByteBuffer byteBuffer, int position) { // byteBufferAccess.position(byteBuffer, position); // }
import java.nio.ByteBuffer; import java.util.Random; import org.caffinitas.ohc.HashAlgorithm; import org.testng.Assert; import org.testng.annotations.Test; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferPosition;
} @Test public void testCRC32C() { test(HashAlgorithm.CRC32C); } @Test public void testXX() { test(HashAlgorithm.XX); } private void test(HashAlgorithm hash) { Random rand = new Random(); byte[] buf = new byte[3211]; rand.nextBytes(buf); Hasher hasher = Hasher.create(hash); long arrayVal = hasher.hash(ByteBuffer.wrap(buf)); ByteBuffer nativeMem = Uns.allocate(buf.length + 99, true); try { for (int i = 0; i < 99; i++) nativeMem.put((byte) 0); nativeMem.put(buf);
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferPosition(ByteBuffer byteBuffer, int position) { // byteBufferAccess.position(byteBuffer, position); // } // Path: ohc-core/src/test/java/org/caffinitas/ohc/chunked/HasherTest.java import java.nio.ByteBuffer; import java.util.Random; import org.caffinitas.ohc.HashAlgorithm; import org.testng.Assert; import org.testng.annotations.Test; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferPosition; } @Test public void testCRC32C() { test(HashAlgorithm.CRC32C); } @Test public void testXX() { test(HashAlgorithm.XX); } private void test(HashAlgorithm hash) { Random rand = new Random(); byte[] buf = new byte[3211]; rand.nextBytes(buf); Hasher hasher = Hasher.create(hash); long arrayVal = hasher.hash(ByteBuffer.wrap(buf)); ByteBuffer nativeMem = Uns.allocate(buf.length + 99, true); try { for (int i = 0; i < 99; i++) nativeMem.put((byte) 0); nativeMem.put(buf);
byteBufferPosition(nativeMem, 99);
snazy/ohc
ohc-core/src/test/java/org/caffinitas/ohc/chunked/KeyBufferTest.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferFlip(ByteBuffer byteBuffer) { // byteBufferAccess.flip(byteBuffer); // }
import java.nio.ByteBuffer; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import org.caffinitas.ohc.HashAlgorithm; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferFlip; import static org.testng.Assert.assertEquals;
/* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.chunked; public class KeyBufferTest { @AfterMethod(alwaysRun = true) public void deinit() { Uns.clearUnsDebugForTest(); } @Test public void testHashFinish() throws Exception { byte[] ref = TestUtils.randomBytes(10); ByteBuffer buf = ByteBuffer.allocate(12); buf.put((byte)(42 & 0xff)); buf.put(ref); buf.put((byte)(0xf0 & 0xff));
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferFlip(ByteBuffer byteBuffer) { // byteBufferAccess.flip(byteBuffer); // } // Path: ohc-core/src/test/java/org/caffinitas/ohc/chunked/KeyBufferTest.java import java.nio.ByteBuffer; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import org.caffinitas.ohc.HashAlgorithm; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferFlip; import static org.testng.Assert.assertEquals; /* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.chunked; public class KeyBufferTest { @AfterMethod(alwaysRun = true) public void deinit() { Uns.clearUnsDebugForTest(); } @Test public void testHashFinish() throws Exception { byte[] ref = TestUtils.randomBytes(10); ByteBuffer buf = ByteBuffer.allocate(12); buf.put((byte)(42 & 0xff)); buf.put(ref); buf.put((byte)(0xf0 & 0xff));
byteBufferFlip(buf);
snazy/ohc
ohc-core/src/test/java/org/caffinitas/ohc/chunked/KeyBufferTest.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferFlip(ByteBuffer byteBuffer) { // byteBufferAccess.flip(byteBuffer); // }
import java.nio.ByteBuffer; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import org.caffinitas.ohc.HashAlgorithm; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferFlip; import static org.testng.Assert.assertEquals;
/* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.chunked; public class KeyBufferTest { @AfterMethod(alwaysRun = true) public void deinit() { Uns.clearUnsDebugForTest(); } @Test public void testHashFinish() throws Exception { byte[] ref = TestUtils.randomBytes(10); ByteBuffer buf = ByteBuffer.allocate(12); buf.put((byte)(42 & 0xff)); buf.put(ref); buf.put((byte)(0xf0 & 0xff)); byteBufferFlip(buf);
// Path: ohc-core/src/main/java/org/caffinitas/ohc/HashAlgorithm.java // public enum HashAlgorithm // { // MURMUR3, // // CRC32, // // CRC32C, // // XX // } // // Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferFlip(ByteBuffer byteBuffer) { // byteBufferAccess.flip(byteBuffer); // } // Path: ohc-core/src/test/java/org/caffinitas/ohc/chunked/KeyBufferTest.java import java.nio.ByteBuffer; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import org.caffinitas.ohc.HashAlgorithm; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferFlip; import static org.testng.Assert.assertEquals; /* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.chunked; public class KeyBufferTest { @AfterMethod(alwaysRun = true) public void deinit() { Uns.clearUnsDebugForTest(); } @Test public void testHashFinish() throws Exception { byte[] ref = TestUtils.randomBytes(10); ByteBuffer buf = ByteBuffer.allocate(12); buf.put((byte)(42 & 0xff)); buf.put(ref); buf.put((byte)(0xf0 & 0xff)); byteBufferFlip(buf);
KeyBuffer out = new KeyBuffer(buf).finish(org.caffinitas.ohc.chunked.Hasher.create(HashAlgorithm.MURMUR3));
snazy/ohc
ohc-core/src/test/java/org/caffinitas/ohc/chunked/UnsTest.java
// Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferClear(ByteBuffer byteBuffer) { // byteBufferAccess.clear(byteBuffer); // }
import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.Random; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import sun.misc.Unsafe; import sun.nio.ch.DirectBuffer; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferClear; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue;
/* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.chunked; public class UnsTest { @AfterMethod(alwaysRun = true) public void deinit() { Uns.clearUnsDebugForTest(); } private static final Unsafe unsafe; static final int CAPACITY = 65536; static final ByteBuffer directBuffer; static { try { Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); unsafe = (Unsafe) field.get(null); if (unsafe.addressSize() > 8) throw new RuntimeException("Address size " + unsafe.addressSize() + " not supported yet (max 8 bytes)"); directBuffer = ByteBuffer.allocateDirect(CAPACITY); } catch (Exception e) { throw new AssertionError(e); } } private static void fillRandom() { Random r = new Random();
// Path: ohc-core/src/main/java/org/caffinitas/ohc/util/ByteBufferCompat.java // public static void byteBufferClear(ByteBuffer byteBuffer) { // byteBufferAccess.clear(byteBuffer); // } // Path: ohc-core/src/test/java/org/caffinitas/ohc/chunked/UnsTest.java import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.Random; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import sun.misc.Unsafe; import sun.nio.ch.DirectBuffer; import static org.caffinitas.ohc.util.ByteBufferCompat.byteBufferClear; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; /* * Copyright (C) 2014 Robert Stupp, Koeln, Germany, robert-stupp.de * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.caffinitas.ohc.chunked; public class UnsTest { @AfterMethod(alwaysRun = true) public void deinit() { Uns.clearUnsDebugForTest(); } private static final Unsafe unsafe; static final int CAPACITY = 65536; static final ByteBuffer directBuffer; static { try { Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); unsafe = (Unsafe) field.get(null); if (unsafe.addressSize() > 8) throw new RuntimeException("Address size " + unsafe.addressSize() + " not supported yet (max 8 bytes)"); directBuffer = ByteBuffer.allocateDirect(CAPACITY); } catch (Exception e) { throw new AssertionError(e); } } private static void fillRandom() { Random r = new Random();
byteBufferClear(directBuffer);
developers-payu-latam/payu-latam-java-payments-sdk
src/main/java/com/payu/sdk/payments/model/MassiveTokenPaymentsResponse.java
// Path: src/main/java/com/payu/sdk/model/response/Response.java // @XmlRootElement(name = "response") // @XmlAccessorType(XmlAccessType.FIELD) // public class Response implements Serializable { // // /** The generated serial version Id */ // private static final long serialVersionUID = -3399914855691352540L; // /** The response code sent by the server */ // @XmlElement // private ResponseCode code; // /** The error message sent by the server */ // @XmlElement(required = false) // private String error; // // /** // * Returns the code // * // * @return the code // */ // public ResponseCode getCode() { // return code; // } // // /** // * Returns the error message // * // * @return the error message // */ // public String getError() { // return error; // } // // /** // * Sets the error message // * // * @param error // * the error message to set // */ // public void setError(String error) { // this.error = error; // } // // /** // * Sets the code // * // * @param code // * the code to set // */ // public void setCode(ResponseCode code) { // this.code = code; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format("Response [code=%s, error=%s]", code, error); // } // // /** // * Converts the response to string response // * // * @return The response in a xml format // * @throws PayUException // */ // public String toXml() throws PayUException { // // try { // return JaxbUtil.convertJavaToXml(this, true); // } catch (Exception e) { // throw new PayUException(ErrorCode.XML_SERIALIZATION_ERROR, e); // } // } // // /** // * Converts a string response to the response // * // * @param xmlData // * The response in a xml format // * @return The response object // * @throws PayUException // */ // protected static Response fromBaseXml(Response response, String xmlData) // throws PayUException { // // try { // // // Response code // ResponseCode responseCode = ResponseCode.SUCCESS; // Response baseResponse = null; // // if (xmlData.contains("<response>")) { // baseResponse = JaxbUtil.convertXmlToJava(Response.class, // xmlData); // responseCode = baseResponse.getCode(); // } else if (xmlData.contains("<paymentResponse>")) { // baseResponse = JaxbUtil.convertXmlToJava(PaymentResponse.class, // xmlData); // responseCode = baseResponse.getCode(); // } else if (xmlData.contains("<reportingResponse>")) { // baseResponse = JaxbUtil.convertXmlToJava( // ReportingResponse.class, xmlData); // responseCode = baseResponse.getCode(); // } else if (xmlData.contains("<transactionTokenBatchResponse>")) { // baseResponse = JaxbUtil.convertXmlToJava(MassiveTokenPaymentsResponse.class, xmlData); // responseCode = baseResponse.getCode(); // } // // if (ResponseCode.SUCCESS.equals(responseCode)) { // return JaxbUtil.convertXmlToJava(response.getClass(), xmlData); // } else { // throw new PayUException(ErrorCode.API_ERROR, // baseResponse.getError()); // } // // } catch (PayUException e) { // throw e; // } catch (Exception e) { // throw new PayUException(ErrorCode.XML_DESERIALIZATION_ERROR, e); // } // } // }
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.payu.sdk.exceptions.PayUException; import com.payu.sdk.model.response.Response;
/** * The MIT License (MIT) * * Copyright (c) 2016 developers-payu-latam * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.payu.sdk.payments.model; /** * Represents a massive token payments response in the PayU SDK. * * @author Alejandro Cadena (alejandro.cadena@payu.com) * @version 1.3.9 * @since 29/09/21 */ @XmlRootElement(name = "transactionTokenBatchResponse") @XmlAccessorType(XmlAccessType.FIELD)
// Path: src/main/java/com/payu/sdk/model/response/Response.java // @XmlRootElement(name = "response") // @XmlAccessorType(XmlAccessType.FIELD) // public class Response implements Serializable { // // /** The generated serial version Id */ // private static final long serialVersionUID = -3399914855691352540L; // /** The response code sent by the server */ // @XmlElement // private ResponseCode code; // /** The error message sent by the server */ // @XmlElement(required = false) // private String error; // // /** // * Returns the code // * // * @return the code // */ // public ResponseCode getCode() { // return code; // } // // /** // * Returns the error message // * // * @return the error message // */ // public String getError() { // return error; // } // // /** // * Sets the error message // * // * @param error // * the error message to set // */ // public void setError(String error) { // this.error = error; // } // // /** // * Sets the code // * // * @param code // * the code to set // */ // public void setCode(ResponseCode code) { // this.code = code; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format("Response [code=%s, error=%s]", code, error); // } // // /** // * Converts the response to string response // * // * @return The response in a xml format // * @throws PayUException // */ // public String toXml() throws PayUException { // // try { // return JaxbUtil.convertJavaToXml(this, true); // } catch (Exception e) { // throw new PayUException(ErrorCode.XML_SERIALIZATION_ERROR, e); // } // } // // /** // * Converts a string response to the response // * // * @param xmlData // * The response in a xml format // * @return The response object // * @throws PayUException // */ // protected static Response fromBaseXml(Response response, String xmlData) // throws PayUException { // // try { // // // Response code // ResponseCode responseCode = ResponseCode.SUCCESS; // Response baseResponse = null; // // if (xmlData.contains("<response>")) { // baseResponse = JaxbUtil.convertXmlToJava(Response.class, // xmlData); // responseCode = baseResponse.getCode(); // } else if (xmlData.contains("<paymentResponse>")) { // baseResponse = JaxbUtil.convertXmlToJava(PaymentResponse.class, // xmlData); // responseCode = baseResponse.getCode(); // } else if (xmlData.contains("<reportingResponse>")) { // baseResponse = JaxbUtil.convertXmlToJava( // ReportingResponse.class, xmlData); // responseCode = baseResponse.getCode(); // } else if (xmlData.contains("<transactionTokenBatchResponse>")) { // baseResponse = JaxbUtil.convertXmlToJava(MassiveTokenPaymentsResponse.class, xmlData); // responseCode = baseResponse.getCode(); // } // // if (ResponseCode.SUCCESS.equals(responseCode)) { // return JaxbUtil.convertXmlToJava(response.getClass(), xmlData); // } else { // throw new PayUException(ErrorCode.API_ERROR, // baseResponse.getError()); // } // // } catch (PayUException e) { // throw e; // } catch (Exception e) { // throw new PayUException(ErrorCode.XML_DESERIALIZATION_ERROR, e); // } // } // } // Path: src/main/java/com/payu/sdk/payments/model/MassiveTokenPaymentsResponse.java import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.payu.sdk.exceptions.PayUException; import com.payu.sdk.model.response.Response; /** * The MIT License (MIT) * * Copyright (c) 2016 developers-payu-latam * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.payu.sdk.payments.model; /** * Represents a massive token payments response in the PayU SDK. * * @author Alejandro Cadena (alejandro.cadena@payu.com) * @version 1.3.9 * @since 29/09/21 */ @XmlRootElement(name = "transactionTokenBatchResponse") @XmlAccessorType(XmlAccessType.FIELD)
public class MassiveTokenPaymentsResponse extends Response {
developers-payu-latam/payu-latam-java-payments-sdk
src/main/java/com/payu/sdk/model/TransactionResponse.java
// Path: src/main/java/com/payu/sdk/utils/xml/MapAdditionalInfoAdapter.java // public class MapAdditionalInfoAdapter extends XmlAdapter<MapAdditionalInfoElement, Map<String, String>> { // // @Override // public MapAdditionalInfoElement marshal(Map<String, String> v) throws Exception { // // if (v == null || v.isEmpty()) { // return null; // } // // MapAdditionalInfoElement map = new MapAdditionalInfoElement(); // map.setCardType(v.get("cardType")); // return map; // } // // @Override // public Map<String, String> unmarshal(MapAdditionalInfoElement v) throws Exception { // // if (v == null) { // return null; // } // // Map<String, String> map = new HashMap<String, String>(1); // map.put("cardType", v.getCardType()); // return map; // } // }
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.payu.sdk.utils.xml.DateAdapter; import com.payu.sdk.utils.xml.MapAdditionalInfoAdapter; import com.payu.sdk.utils.xml.MapExtraParameterAdapter; import java.io.Serializable; import java.util.Date; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement;
/** * The MIT License (MIT) * * Copyright (c) 2016 developers-payu-latam * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.payu.sdk.model; /** * Represents a response for a transaction in the PayU SDK. * * @author PayU Latam * @since 1.0.0 * @version 1.0.0, 21/08/2013 */ @XmlRootElement(name = "transactionResponse") @XmlAccessorType(XmlAccessType.FIELD) public class TransactionResponse implements Serializable { /** The generated serial version Id */ private static final long serialVersionUID = 7073372114746122059L; /** the related order id. */ @XmlElement(required = false) private Long orderId; /** the order's reference code */ @XmlElement(required = false) private String orderReferenceCode; /** the related transaction id. */ @XmlElement(required = false) private String transactionId; /** The transaction state */ @XmlElement(required = false) private TransactionState state; /** The payment network response code. */ @XmlElement(required = false) private String paymentNetworkResponseCode; /** The error message related to the payment network response. */ @XmlElement(required = false) private String paymentNetworkResponseErrorMessage; /** The trazability code related with the response. */ @XmlElement(required = false) private String trazabilityCode; /** The authorization code. */ @XmlElement(required = false) private String authorizationCode; /** The transaction pending reason */ @XmlElement(required = false) private TransactionPendingReason pendingReason; /** The transaction response code */ @XmlElement(required = false) private TransactionResponseCode responseCode; /** The error code. */ @XmlElement(required = false) private TransactionErrorCode errorCode; /** The message related to the response code. */ @XmlElement(required = false) private String responseMessage; /** The payment date. */ @XmlElement(required = false) private String transactionDate; /** The payment time. */ @XmlElement(required = false) private String transactionTime; /** The operation date. */ @XmlElement(required = false) @XmlJavaTypeAdapter(DateAdapter.class) private Date operationDate; /** The extra parameters. */ @XmlJavaTypeAdapter(MapExtraParameterAdapter.class) private Map<String, Object> extraParameters; /** The addicional info fields */
// Path: src/main/java/com/payu/sdk/utils/xml/MapAdditionalInfoAdapter.java // public class MapAdditionalInfoAdapter extends XmlAdapter<MapAdditionalInfoElement, Map<String, String>> { // // @Override // public MapAdditionalInfoElement marshal(Map<String, String> v) throws Exception { // // if (v == null || v.isEmpty()) { // return null; // } // // MapAdditionalInfoElement map = new MapAdditionalInfoElement(); // map.setCardType(v.get("cardType")); // return map; // } // // @Override // public Map<String, String> unmarshal(MapAdditionalInfoElement v) throws Exception { // // if (v == null) { // return null; // } // // Map<String, String> map = new HashMap<String, String>(1); // map.put("cardType", v.getCardType()); // return map; // } // } // Path: src/main/java/com/payu/sdk/model/TransactionResponse.java import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.payu.sdk.utils.xml.DateAdapter; import com.payu.sdk.utils.xml.MapAdditionalInfoAdapter; import com.payu.sdk.utils.xml.MapExtraParameterAdapter; import java.io.Serializable; import java.util.Date; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; /** * The MIT License (MIT) * * Copyright (c) 2016 developers-payu-latam * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.payu.sdk.model; /** * Represents a response for a transaction in the PayU SDK. * * @author PayU Latam * @since 1.0.0 * @version 1.0.0, 21/08/2013 */ @XmlRootElement(name = "transactionResponse") @XmlAccessorType(XmlAccessType.FIELD) public class TransactionResponse implements Serializable { /** The generated serial version Id */ private static final long serialVersionUID = 7073372114746122059L; /** the related order id. */ @XmlElement(required = false) private Long orderId; /** the order's reference code */ @XmlElement(required = false) private String orderReferenceCode; /** the related transaction id. */ @XmlElement(required = false) private String transactionId; /** The transaction state */ @XmlElement(required = false) private TransactionState state; /** The payment network response code. */ @XmlElement(required = false) private String paymentNetworkResponseCode; /** The error message related to the payment network response. */ @XmlElement(required = false) private String paymentNetworkResponseErrorMessage; /** The trazability code related with the response. */ @XmlElement(required = false) private String trazabilityCode; /** The authorization code. */ @XmlElement(required = false) private String authorizationCode; /** The transaction pending reason */ @XmlElement(required = false) private TransactionPendingReason pendingReason; /** The transaction response code */ @XmlElement(required = false) private TransactionResponseCode responseCode; /** The error code. */ @XmlElement(required = false) private TransactionErrorCode errorCode; /** The message related to the response code. */ @XmlElement(required = false) private String responseMessage; /** The payment date. */ @XmlElement(required = false) private String transactionDate; /** The payment time. */ @XmlElement(required = false) private String transactionTime; /** The operation date. */ @XmlElement(required = false) @XmlJavaTypeAdapter(DateAdapter.class) private Date operationDate; /** The extra parameters. */ @XmlJavaTypeAdapter(MapExtraParameterAdapter.class) private Map<String, Object> extraParameters; /** The addicional info fields */
@XmlJavaTypeAdapter(MapAdditionalInfoAdapter.class)
developers-payu-latam/payu-latam-java-payments-sdk
src/main/java/com/payu/sdk/utils/CommonRequestUtil.java
// Path: src/main/java/com/payu/sdk/model/PaymentMethod.java // @Deprecated // public enum PaymentMethod { // // VISA(PaymentMethodType.CREDIT_CARD), // // AMEX(PaymentMethodType.CREDIT_CARD), // // HIPERCARD(PaymentMethodType.CREDIT_CARD), // // DINERS(PaymentMethodType.CREDIT_CARD), // // MASTERCARD(PaymentMethodType.CREDIT_CARD), // // DISCOVER(PaymentMethodType.CREDIT_CARD), // // ELO(PaymentMethodType.CREDIT_CARD), // // SHOPPING(PaymentMethodType.CREDIT_CARD), // // NARANJA(PaymentMethodType.CREDIT_CARD), // // CABAL(PaymentMethodType.CREDIT_CARD), // // ARGENCARD(PaymentMethodType.CREDIT_CARD), // // PRESTO(PaymentMethodType.CREDIT_CARD), // // RIPLEY(PaymentMethodType.CREDIT_CARD), // // CODENSA(PaymentMethodType.CREDIT_CARD), // // PSE(PaymentMethodType.PSE), // // BALOTO(PaymentMethodType.CASH), // // EFECTY(PaymentMethodType.CASH), // // BCP(PaymentMethodType.REFERENCED), // // SEVEN_ELEVEN(PaymentMethodType.CASH), // // OXXO(PaymentMethodType.CASH), // // BOLETO_BANCARIO(PaymentMethodType.CASH), // // RAPIPAGO(PaymentMethodType.CASH), // // PAGOFACIL(PaymentMethodType.CASH), // // BAPRO(PaymentMethodType.CASH), // // COBRO_EXPRESS(PaymentMethodType.CASH), // // SERVIPAG(PaymentMethodType.CASH), // // SENCILLITO(PaymentMethodType.CASH), // // BAJIO(PaymentMethodType.REFERENCED), // // BANAMEX(PaymentMethodType.REFERENCED), // // BANCOMER(PaymentMethodType.REFERENCED), // // HSBC(PaymentMethodType.REFERENCED), // // IXE(PaymentMethodType.REFERENCED), // // SANTANDER(PaymentMethodType.REFERENCED), // // SCOTIABANK(PaymentMethodType.REFERENCED), // // BANK_REFERENCED(PaymentMethodType.BANK_REFERENCED); // // /** // * Default constructor // * // * @param type // * the payment method type // */ // private PaymentMethod(PaymentMethodType type) { // this.type = type; // } // // /** // * The type of the payment method. // */ // private PaymentMethodType type; // // /** // * <p> // * Return a PaymentMethodMain Object from the String.<br> // * Ex. PaymentMethodMain.fromString("visa") return PaymentMethodMain.VISA // * Ex. PaymentMethodMain.fromString("VISA") return PaymentMethodMain.VISA // * Ex. PaymentMethodMain.fromString("XX") return null // * </p> // * // * @param paymentMethodMain // * @return // */ // public static PaymentMethod fromString(String paymentMethod) { // if (paymentMethod != null) { // for (PaymentMethod pmm : PaymentMethod.values()) { // if (paymentMethod.equalsIgnoreCase(pmm.toString())) { // return pmm; // } // } // } // return null; // } // // /** // * Filters the payments methods list by type. // * // * @param type // * , the filter type. // * @return the list of the payments method given type. // */ // public static List<PaymentMethod> getPaymentMethods(PaymentMethodType type) { // List<PaymentMethod> paymentsMethod = new ArrayList<PaymentMethod>(); // PaymentMethod[] values = PaymentMethod.values(); // for (int i = 0; i < values.length; i++) { // if (values[i].getType() == type) { // paymentsMethod.add(values[i]); // } // } // return paymentsMethod; // } // // /** // * Returns the type of the payment method. // * // * @return the type of the payment method. // */ // public PaymentMethodType getType() { // return type; // } // // }
import java.util.Set; import com.payu.sdk.constants.Constants; import com.payu.sdk.exceptions.InvalidParametersException; import com.payu.sdk.model.AdditionalValue; import com.payu.sdk.model.Currency; import com.payu.sdk.model.PaymentMethod; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map;
* * @param enumClass The enum class * @param parameters * The parameters to be sent to the server * @param paramName * the parameter to get * @return The Enum value parameter it got * @throws InvalidParametersException */ public static <E extends Enum<E>> E getEnumValueParameter( Class<E> enumClass, Map<String, String> parameters, String paramName) throws InvalidParametersException { String parameter = getParameter(parameters, paramName); E enumValueParameter = (parameter != null ? getEnumValue(enumClass, parameter) : null); return enumValueParameter; } /** * Gets the PaymentMethod value parameter from the parameters map. * If the parameter is null or does not belong to the enumeration returns null * @param parameters The parameters to be sent to the server * @param paramName the parameter to get * @return the PaymentMethod value or null * @deprecated Not for public use in the future because the class PaymentMethod is deprecated * @see #com.payu.sdk.PayUPayments.getPaymentMethodParameter(Map<String, String> parameters, String paramName) */ @Deprecated
// Path: src/main/java/com/payu/sdk/model/PaymentMethod.java // @Deprecated // public enum PaymentMethod { // // VISA(PaymentMethodType.CREDIT_CARD), // // AMEX(PaymentMethodType.CREDIT_CARD), // // HIPERCARD(PaymentMethodType.CREDIT_CARD), // // DINERS(PaymentMethodType.CREDIT_CARD), // // MASTERCARD(PaymentMethodType.CREDIT_CARD), // // DISCOVER(PaymentMethodType.CREDIT_CARD), // // ELO(PaymentMethodType.CREDIT_CARD), // // SHOPPING(PaymentMethodType.CREDIT_CARD), // // NARANJA(PaymentMethodType.CREDIT_CARD), // // CABAL(PaymentMethodType.CREDIT_CARD), // // ARGENCARD(PaymentMethodType.CREDIT_CARD), // // PRESTO(PaymentMethodType.CREDIT_CARD), // // RIPLEY(PaymentMethodType.CREDIT_CARD), // // CODENSA(PaymentMethodType.CREDIT_CARD), // // PSE(PaymentMethodType.PSE), // // BALOTO(PaymentMethodType.CASH), // // EFECTY(PaymentMethodType.CASH), // // BCP(PaymentMethodType.REFERENCED), // // SEVEN_ELEVEN(PaymentMethodType.CASH), // // OXXO(PaymentMethodType.CASH), // // BOLETO_BANCARIO(PaymentMethodType.CASH), // // RAPIPAGO(PaymentMethodType.CASH), // // PAGOFACIL(PaymentMethodType.CASH), // // BAPRO(PaymentMethodType.CASH), // // COBRO_EXPRESS(PaymentMethodType.CASH), // // SERVIPAG(PaymentMethodType.CASH), // // SENCILLITO(PaymentMethodType.CASH), // // BAJIO(PaymentMethodType.REFERENCED), // // BANAMEX(PaymentMethodType.REFERENCED), // // BANCOMER(PaymentMethodType.REFERENCED), // // HSBC(PaymentMethodType.REFERENCED), // // IXE(PaymentMethodType.REFERENCED), // // SANTANDER(PaymentMethodType.REFERENCED), // // SCOTIABANK(PaymentMethodType.REFERENCED), // // BANK_REFERENCED(PaymentMethodType.BANK_REFERENCED); // // /** // * Default constructor // * // * @param type // * the payment method type // */ // private PaymentMethod(PaymentMethodType type) { // this.type = type; // } // // /** // * The type of the payment method. // */ // private PaymentMethodType type; // // /** // * <p> // * Return a PaymentMethodMain Object from the String.<br> // * Ex. PaymentMethodMain.fromString("visa") return PaymentMethodMain.VISA // * Ex. PaymentMethodMain.fromString("VISA") return PaymentMethodMain.VISA // * Ex. PaymentMethodMain.fromString("XX") return null // * </p> // * // * @param paymentMethodMain // * @return // */ // public static PaymentMethod fromString(String paymentMethod) { // if (paymentMethod != null) { // for (PaymentMethod pmm : PaymentMethod.values()) { // if (paymentMethod.equalsIgnoreCase(pmm.toString())) { // return pmm; // } // } // } // return null; // } // // /** // * Filters the payments methods list by type. // * // * @param type // * , the filter type. // * @return the list of the payments method given type. // */ // public static List<PaymentMethod> getPaymentMethods(PaymentMethodType type) { // List<PaymentMethod> paymentsMethod = new ArrayList<PaymentMethod>(); // PaymentMethod[] values = PaymentMethod.values(); // for (int i = 0; i < values.length; i++) { // if (values[i].getType() == type) { // paymentsMethod.add(values[i]); // } // } // return paymentsMethod; // } // // /** // * Returns the type of the payment method. // * // * @return the type of the payment method. // */ // public PaymentMethodType getType() { // return type; // } // // } // Path: src/main/java/com/payu/sdk/utils/CommonRequestUtil.java import java.util.Set; import com.payu.sdk.constants.Constants; import com.payu.sdk.exceptions.InvalidParametersException; import com.payu.sdk.model.AdditionalValue; import com.payu.sdk.model.Currency; import com.payu.sdk.model.PaymentMethod; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; * * @param enumClass The enum class * @param parameters * The parameters to be sent to the server * @param paramName * the parameter to get * @return The Enum value parameter it got * @throws InvalidParametersException */ public static <E extends Enum<E>> E getEnumValueParameter( Class<E> enumClass, Map<String, String> parameters, String paramName) throws InvalidParametersException { String parameter = getParameter(parameters, paramName); E enumValueParameter = (parameter != null ? getEnumValue(enumClass, parameter) : null); return enumValueParameter; } /** * Gets the PaymentMethod value parameter from the parameters map. * If the parameter is null or does not belong to the enumeration returns null * @param parameters The parameters to be sent to the server * @param paramName the parameter to get * @return the PaymentMethod value or null * @deprecated Not for public use in the future because the class PaymentMethod is deprecated * @see #com.payu.sdk.PayUPayments.getPaymentMethodParameter(Map<String, String> parameters, String paramName) */ @Deprecated
public static PaymentMethod getPaymentMethodParameter(Map<String, String> parameters, String paramName){
developers-payu-latam/payu-latam-java-payments-sdk
src/main/java/com/payu/sdk/payments/model/ConfirmationPageRequest.java
// Path: src/main/java/com/payu/sdk/constants/Resources.java // public interface Resources { // // /** // * The API request methods // */ // enum RequestMethod { // /** The get request method. */ // GET, // /** The post request method. */ // POST, // /** The delete request method. */ // DELETE, // /** The put request method. */ // PUT // } // // // --------------------------------------------- // // URL (Named) Parameters identifiers // // --------------------------------------------- // // /** // * API Version 4.3 // */ // String V4_3 = "v4.3"; // // /** // * API Version 4.0 // */ // String V4_0 = "4.0"; // // /** // * API Version 4.9 // */ // String V4_9 = "v4.9"; // // /** // * Payment Plan Current Version // */ // String PAYMENT_PLAN_VERSION = V4_9; // // /** // * Default API Current Version // */ // String CURRENT_API_VERSION = V4_0; // // // --------------------------------------------- // // URL (Named) Parameters identifiers // // --------------------------------------------- // // /** // * Default API URI // */ // String DEFAULT_API_URL = CURRENT_API_VERSION + "/service.cgi"; // // /** // * Default entity API URI pattern // */ // String ENTITY_API_URL_PATTERN = "%srest/%s/%s"; // // /** // * Default parameterized entity API URI pattern // */ // String PARAM_ENTITY_API_URL_PATTERN = "%srest/%s/%s/%s"; // // /** // * Dependent entity API URI pattern // */ // String DEPENDENT_ENTITY_API_URL_PATTERN = "%srest/%s/%s/%s/%s"; // // /** // * Dependent parameterized entity API URI pattern // */ // String DEPENDENT_PARAM_ENTITY_API_URL_PATTERN = "%srest/%s/%s/%s/%s/%s"; // // /** // * Plans Operations URI // */ // String URI_PLANS = "plans"; // // /** // * Subscription URI // */ // String URI_SUBSCRIPTIONS = "subscriptions"; // // /** // * Recurring bill items URI // */ // String URI_RECURRING_BILL_ITEMS = "recurringBillItems"; // // /** // * Recurring bill item URI // */ // String URI_RECURRING_BILL = "recurringBill"; // // /** // * send Confirmation page URI // */ // String URI_SEND_CONFIRMATION_PAGE = "sendConfirmationPage"; // // /** // * Customers item URI // */ // String URI_CUSTOMERS = "customers"; // // /** // * Credit Card's item URI // */ // String URI_CREDIT_CARDS = "creditCards"; // // /** // * Bank accounts item URI // */ // String URI_BANK_ACCOUNTS = "bankAccounts"; // // /** // * Recurring bill payment retry // */ // String URI_RECURRING_BILL_PAYMENT_RETRY = "paymentRetry"; // // /** // * Payment request URI. // */ // String URI_PAYMENT_REQUEST = "paymentRequest"; // // }
import com.payu.sdk.constants.Resources; import com.payu.sdk.model.request.CommandRequest; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement;
/** * The MIT License (MIT) * <p> * Copyright (c) 2016 developers-payu-latam * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.payu.sdk.payments.model; /** * Represents a notification request in the PayU SDK. * * @author PayU Latam * @version 1.2.3, 28/03/2017 * @since 1.2.3 */ @XmlRootElement(name = "request") @XmlAccessorType(XmlAccessType.FIELD) public class ConfirmationPageRequest extends CommandRequest { /** * The generated serial version Id */ private static final long serialVersionUID = 1; /** * The transaction id */ @XmlElement(required = true) private String transactionId; /** * Returns the transaction id * * @return the transaction id */ public String getTransactionId() { return transactionId; } /** * Sets the transaction id * * @param transactionId the transaction id to set */ public void setTransactionId(String transactionId) { this.transactionId = transactionId; } /* * (non-Javadoc) * @see com.payu.sdk.model.request.Request#getBaseRequestUrl( * java.lang.String, com.payu.sdk.constants.Resources.RequestMethod) */ @Override protected String getBaseRequestUrl(String baseUrl,
// Path: src/main/java/com/payu/sdk/constants/Resources.java // public interface Resources { // // /** // * The API request methods // */ // enum RequestMethod { // /** The get request method. */ // GET, // /** The post request method. */ // POST, // /** The delete request method. */ // DELETE, // /** The put request method. */ // PUT // } // // // --------------------------------------------- // // URL (Named) Parameters identifiers // // --------------------------------------------- // // /** // * API Version 4.3 // */ // String V4_3 = "v4.3"; // // /** // * API Version 4.0 // */ // String V4_0 = "4.0"; // // /** // * API Version 4.9 // */ // String V4_9 = "v4.9"; // // /** // * Payment Plan Current Version // */ // String PAYMENT_PLAN_VERSION = V4_9; // // /** // * Default API Current Version // */ // String CURRENT_API_VERSION = V4_0; // // // --------------------------------------------- // // URL (Named) Parameters identifiers // // --------------------------------------------- // // /** // * Default API URI // */ // String DEFAULT_API_URL = CURRENT_API_VERSION + "/service.cgi"; // // /** // * Default entity API URI pattern // */ // String ENTITY_API_URL_PATTERN = "%srest/%s/%s"; // // /** // * Default parameterized entity API URI pattern // */ // String PARAM_ENTITY_API_URL_PATTERN = "%srest/%s/%s/%s"; // // /** // * Dependent entity API URI pattern // */ // String DEPENDENT_ENTITY_API_URL_PATTERN = "%srest/%s/%s/%s/%s"; // // /** // * Dependent parameterized entity API URI pattern // */ // String DEPENDENT_PARAM_ENTITY_API_URL_PATTERN = "%srest/%s/%s/%s/%s/%s"; // // /** // * Plans Operations URI // */ // String URI_PLANS = "plans"; // // /** // * Subscription URI // */ // String URI_SUBSCRIPTIONS = "subscriptions"; // // /** // * Recurring bill items URI // */ // String URI_RECURRING_BILL_ITEMS = "recurringBillItems"; // // /** // * Recurring bill item URI // */ // String URI_RECURRING_BILL = "recurringBill"; // // /** // * send Confirmation page URI // */ // String URI_SEND_CONFIRMATION_PAGE = "sendConfirmationPage"; // // /** // * Customers item URI // */ // String URI_CUSTOMERS = "customers"; // // /** // * Credit Card's item URI // */ // String URI_CREDIT_CARDS = "creditCards"; // // /** // * Bank accounts item URI // */ // String URI_BANK_ACCOUNTS = "bankAccounts"; // // /** // * Recurring bill payment retry // */ // String URI_RECURRING_BILL_PAYMENT_RETRY = "paymentRetry"; // // /** // * Payment request URI. // */ // String URI_PAYMENT_REQUEST = "paymentRequest"; // // } // Path: src/main/java/com/payu/sdk/payments/model/ConfirmationPageRequest.java import com.payu.sdk.constants.Resources; import com.payu.sdk.model.request.CommandRequest; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * The MIT License (MIT) * <p> * Copyright (c) 2016 developers-payu-latam * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.payu.sdk.payments.model; /** * Represents a notification request in the PayU SDK. * * @author PayU Latam * @version 1.2.3, 28/03/2017 * @since 1.2.3 */ @XmlRootElement(name = "request") @XmlAccessorType(XmlAccessType.FIELD) public class ConfirmationPageRequest extends CommandRequest { /** * The generated serial version Id */ private static final long serialVersionUID = 1; /** * The transaction id */ @XmlElement(required = true) private String transactionId; /** * Returns the transaction id * * @return the transaction id */ public String getTransactionId() { return transactionId; } /** * Sets the transaction id * * @param transactionId the transaction id to set */ public void setTransactionId(String transactionId) { this.transactionId = transactionId; } /* * (non-Javadoc) * @see com.payu.sdk.model.request.Request#getBaseRequestUrl( * java.lang.String, com.payu.sdk.constants.Resources.RequestMethod) */ @Override protected String getBaseRequestUrl(String baseUrl,
Resources.RequestMethod requestMethod) {
developers-payu-latam/payu-latam-java-payments-sdk
src/main/java/com/payu/sdk/model/response/Response.java
// Path: src/main/java/com/payu/sdk/payments/model/MassiveTokenPaymentsResponse.java // @XmlRootElement(name = "transactionTokenBatchResponse") // @XmlAccessorType(XmlAccessType.FIELD) // public class MassiveTokenPaymentsResponse extends Response { // // /** The generated serial version Id */ // private static final long serialVersionUID = 1157400679436549655L; // // /** The transaction response sent by the server */ // @XmlElement(required = false) // private String id; // // /** // * Returns the transaction batch token id // * // * @return the transaction batch token id // */ // public String getId() { // // return id; // } // // /** // * Sets the transaction batch token id // * // * @param id the transaction batch token id to set // */ // public void setId(String id) { // // this.id = id; // } // // /** // * Converts a xml string into a payment response object // * // * @param xml // * The object in a xml format // * @return The payment response object // * @throws PayUException // */ // public static MassiveTokenPaymentsResponse fromXml(String xml) throws PayUException { // // return (MassiveTokenPaymentsResponse) fromBaseXml(new MassiveTokenPaymentsResponse(), xml); // } // // }
import com.payu.sdk.exceptions.PayUException; import com.payu.sdk.exceptions.SDKException.ErrorCode; import com.payu.sdk.payments.model.MassiveTokenPaymentsResponse; import com.payu.sdk.payments.model.PaymentResponse; import com.payu.sdk.reporting.model.ReportingResponse; import com.payu.sdk.utils.JaxbUtil; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement;
/** * Converts a string response to the response * * @param xmlData * The response in a xml format * @return The response object * @throws PayUException */ protected static Response fromBaseXml(Response response, String xmlData) throws PayUException { try { // Response code ResponseCode responseCode = ResponseCode.SUCCESS; Response baseResponse = null; if (xmlData.contains("<response>")) { baseResponse = JaxbUtil.convertXmlToJava(Response.class, xmlData); responseCode = baseResponse.getCode(); } else if (xmlData.contains("<paymentResponse>")) { baseResponse = JaxbUtil.convertXmlToJava(PaymentResponse.class, xmlData); responseCode = baseResponse.getCode(); } else if (xmlData.contains("<reportingResponse>")) { baseResponse = JaxbUtil.convertXmlToJava( ReportingResponse.class, xmlData); responseCode = baseResponse.getCode(); } else if (xmlData.contains("<transactionTokenBatchResponse>")) {
// Path: src/main/java/com/payu/sdk/payments/model/MassiveTokenPaymentsResponse.java // @XmlRootElement(name = "transactionTokenBatchResponse") // @XmlAccessorType(XmlAccessType.FIELD) // public class MassiveTokenPaymentsResponse extends Response { // // /** The generated serial version Id */ // private static final long serialVersionUID = 1157400679436549655L; // // /** The transaction response sent by the server */ // @XmlElement(required = false) // private String id; // // /** // * Returns the transaction batch token id // * // * @return the transaction batch token id // */ // public String getId() { // // return id; // } // // /** // * Sets the transaction batch token id // * // * @param id the transaction batch token id to set // */ // public void setId(String id) { // // this.id = id; // } // // /** // * Converts a xml string into a payment response object // * // * @param xml // * The object in a xml format // * @return The payment response object // * @throws PayUException // */ // public static MassiveTokenPaymentsResponse fromXml(String xml) throws PayUException { // // return (MassiveTokenPaymentsResponse) fromBaseXml(new MassiveTokenPaymentsResponse(), xml); // } // // } // Path: src/main/java/com/payu/sdk/model/response/Response.java import com.payu.sdk.exceptions.PayUException; import com.payu.sdk.exceptions.SDKException.ErrorCode; import com.payu.sdk.payments.model.MassiveTokenPaymentsResponse; import com.payu.sdk.payments.model.PaymentResponse; import com.payu.sdk.reporting.model.ReportingResponse; import com.payu.sdk.utils.JaxbUtil; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * Converts a string response to the response * * @param xmlData * The response in a xml format * @return The response object * @throws PayUException */ protected static Response fromBaseXml(Response response, String xmlData) throws PayUException { try { // Response code ResponseCode responseCode = ResponseCode.SUCCESS; Response baseResponse = null; if (xmlData.contains("<response>")) { baseResponse = JaxbUtil.convertXmlToJava(Response.class, xmlData); responseCode = baseResponse.getCode(); } else if (xmlData.contains("<paymentResponse>")) { baseResponse = JaxbUtil.convertXmlToJava(PaymentResponse.class, xmlData); responseCode = baseResponse.getCode(); } else if (xmlData.contains("<reportingResponse>")) { baseResponse = JaxbUtil.convertXmlToJava( ReportingResponse.class, xmlData); responseCode = baseResponse.getCode(); } else if (xmlData.contains("<transactionTokenBatchResponse>")) {
baseResponse = JaxbUtil.convertXmlToJava(MassiveTokenPaymentsResponse.class, xmlData);
dubasdey/MQQueueMonitor
src/main/java/org/erc/qmm/mq/agent/Agent.java
// Path: src/main/java/org/erc/qmm/mq/MQUtils.java // public abstract class MQUtils { // // /** // * Builds the manager. // * // * @param config the config // * @return the MQ queue manager // * @throws MQException the MQ exception // */ // public static MQQueueManager buildManager(QueueConfig config) throws MQException{ // return buildManager(config.getHost(),config.getPort(),config.getChannel(), config.getManager()); // } // // /** // * Builds the manager. // * // * @param host the host // * @param port the port // * @param channel the channel // * @param manager the manager // * @return the MQ queue manager // * @throws MQException the MQ exception // */ // public static MQQueueManager buildManager(String host,int port,String channel,String manager) throws MQException{ // Hashtable<String,Object> mqProps = new Hashtable<String,Object>(); // // if(host != null){ // mqProps.put("hostname", host); // } // if(port >0 ){ // mqProps.put("port",port); // } // if(channel != null){ // mqProps.put("channel", channel); // } // return new MQQueueManager(manager,mqProps); // } // }
import java.io.IOException; import java.util.List; import java.util.Vector; import org.erc.qmm.mq.MQUtils; import com.ibm.mq.MQException; import com.ibm.mq.MQGetMessageOptions; import com.ibm.mq.MQMessage; import com.ibm.mq.MQPutMessageOptions; import com.ibm.mq.MQQueue; import com.ibm.mq.MQQueueManager;
package org.erc.qmm.mq.agent; /** * The Class Agent. */ public class Agent { /** The pmo. */ private final MQPutMessageOptions pmo = new MQPutMessageOptions(); /** The gmo. */ private final MQGetMessageOptions gmo = new MQGetMessageOptions(); /** The Constant modelQueueName. */ private static final String modelQueueName = "SYSTEM.DEFAULT.MODEL.QUEUE"; /** The Constant expiryTime. */ private static final int expiryTime = 300; /** The Constant encoding. */ private static final int encoding = 273; /** The qmanager. */ private MQQueueManager qmanager; /** The admin queue. */ private MQQueue adminQueue; /** The reply queue. */ private MQQueue replyQueue; /** The qmanager_level. */ private int qmanager_level; /** The qmanager_platform. */ private int qmanager_platform; /** * Instantiates a new agent. * * @param host the host * @param port the port * @param channel the channel * @param manager the manager * @throws MQException the MQ exception */ public Agent(String host, int port, String channel,String manager) throws MQException { pmo.options = 128; gmo.options = 24577; gmo.waitInterval = 30000;
// Path: src/main/java/org/erc/qmm/mq/MQUtils.java // public abstract class MQUtils { // // /** // * Builds the manager. // * // * @param config the config // * @return the MQ queue manager // * @throws MQException the MQ exception // */ // public static MQQueueManager buildManager(QueueConfig config) throws MQException{ // return buildManager(config.getHost(),config.getPort(),config.getChannel(), config.getManager()); // } // // /** // * Builds the manager. // * // * @param host the host // * @param port the port // * @param channel the channel // * @param manager the manager // * @return the MQ queue manager // * @throws MQException the MQ exception // */ // public static MQQueueManager buildManager(String host,int port,String channel,String manager) throws MQException{ // Hashtable<String,Object> mqProps = new Hashtable<String,Object>(); // // if(host != null){ // mqProps.put("hostname", host); // } // if(port >0 ){ // mqProps.put("port",port); // } // if(channel != null){ // mqProps.put("channel", channel); // } // return new MQQueueManager(manager,mqProps); // } // } // Path: src/main/java/org/erc/qmm/mq/agent/Agent.java import java.io.IOException; import java.util.List; import java.util.Vector; import org.erc.qmm.mq.MQUtils; import com.ibm.mq.MQException; import com.ibm.mq.MQGetMessageOptions; import com.ibm.mq.MQMessage; import com.ibm.mq.MQPutMessageOptions; import com.ibm.mq.MQQueue; import com.ibm.mq.MQQueueManager; package org.erc.qmm.mq.agent; /** * The Class Agent. */ public class Agent { /** The pmo. */ private final MQPutMessageOptions pmo = new MQPutMessageOptions(); /** The gmo. */ private final MQGetMessageOptions gmo = new MQGetMessageOptions(); /** The Constant modelQueueName. */ private static final String modelQueueName = "SYSTEM.DEFAULT.MODEL.QUEUE"; /** The Constant expiryTime. */ private static final int expiryTime = 300; /** The Constant encoding. */ private static final int encoding = 273; /** The qmanager. */ private MQQueueManager qmanager; /** The admin queue. */ private MQQueue adminQueue; /** The reply queue. */ private MQQueue replyQueue; /** The qmanager_level. */ private int qmanager_level; /** The qmanager_platform. */ private int qmanager_platform; /** * Instantiates a new agent. * * @param host the host * @param port the port * @param channel the channel * @param manager the manager * @throws MQException the MQ exception */ public Agent(String host, int port, String channel,String manager) throws MQException { pmo.options = 128; gmo.options = 24577; gmo.waitInterval = 30000;
qmanager = MQUtils.buildManager(host,port,channel,manager);
dubasdey/MQQueueMonitor
src/main/java/org/erc/qmm/config/ConfigManager.java
// Path: src/main/java/org/erc/qmm/util/FileUtils.java // public abstract class FileUtils { // // /** // * Copy. // * // * @param source the source // * @param dest the dest // * @throws IOException Signals that an I/O exception has occurred. // */ // public static void copy(File source, File dest) throws IOException { // InputStream is = null; // OutputStream os = null; // try { // is = new FileInputStream(source); // os = new FileOutputStream(dest); // byte[] buffer = new byte[1024]; // int length; // while ((length = is.read(buffer)) > 0) { // os.write(buffer, 0, length); // } // } finally { // is.close(); // os.close(); // } // } // // /** // * Store. // * // * @param file the file // * @param content the content // * @throws IOException Signals that an I/O exception has occurred. // */ // public static void store(File file,String content) throws IOException{ // BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile())); // bw.write(content); // bw.close(); // } // // }
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.erc.qmm.util.FileUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException;
Node node = queuesList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) node; QueueConfig queue = new QueueConfig(); queue.setDesc(eElement.getAttribute("desc")); queue.setHost(getText(eElement,"host")); queue.setPort(getInt(eElement,"port")); queue.setPollTime(getInt(eElement,"poll")); queue.setManager(getText(eElement,"manager")); queue.setChannel(getText(eElement,"channel")); queue.setName(getText(eElement,"name")); queue.setActive(getBool(eElement,"active",true)); items.add(queue); } } } return items; } /** * Save queues. * * @param queues the queues * @throws IOException Signals that an I/O exception has occurred. */ public void saveQueues(List<QueueConfig> queues) throws IOException{ File xmlFile = new File("config/config.xml"); File configFilder = new File("config"); if(xmlFile.exists()){
// Path: src/main/java/org/erc/qmm/util/FileUtils.java // public abstract class FileUtils { // // /** // * Copy. // * // * @param source the source // * @param dest the dest // * @throws IOException Signals that an I/O exception has occurred. // */ // public static void copy(File source, File dest) throws IOException { // InputStream is = null; // OutputStream os = null; // try { // is = new FileInputStream(source); // os = new FileOutputStream(dest); // byte[] buffer = new byte[1024]; // int length; // while ((length = is.read(buffer)) > 0) { // os.write(buffer, 0, length); // } // } finally { // is.close(); // os.close(); // } // } // // /** // * Store. // * // * @param file the file // * @param content the content // * @throws IOException Signals that an I/O exception has occurred. // */ // public static void store(File file,String content) throws IOException{ // BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile())); // bw.write(content); // bw.close(); // } // // } // Path: src/main/java/org/erc/qmm/config/ConfigManager.java import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.erc.qmm.util.FileUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; Node node = queuesList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) node; QueueConfig queue = new QueueConfig(); queue.setDesc(eElement.getAttribute("desc")); queue.setHost(getText(eElement,"host")); queue.setPort(getInt(eElement,"port")); queue.setPollTime(getInt(eElement,"poll")); queue.setManager(getText(eElement,"manager")); queue.setChannel(getText(eElement,"channel")); queue.setName(getText(eElement,"name")); queue.setActive(getBool(eElement,"active",true)); items.add(queue); } } } return items; } /** * Save queues. * * @param queues the queues * @throws IOException Signals that an I/O exception has occurred. */ public void saveQueues(List<QueueConfig> queues) throws IOException{ File xmlFile = new File("config/config.xml"); File configFilder = new File("config"); if(xmlFile.exists()){
FileUtils.copy(xmlFile, new File("config/config.xml.bak"));
jochen777/jFormchecker
src/main/java/de/jformchecker/criteria/Range.java
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // }
import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement;
package de.jformchecker.criteria; /** * Checks that value is within the given range. * * Based on work of armandino (at) gmail.com */ public final class Range implements Criterion { private int min; private int max; Range(int min, int max) { this.min = min; this.max = max; } @Override
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // Path: src/main/java/de/jformchecker/criteria/Range.java import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement; package de.jformchecker.criteria; /** * Checks that value is within the given range. * * Based on work of armandino (at) gmail.com */ public final class Range implements Criterion { private int min; private int max; Range(int min, int max) { this.min = min; this.max = max; } @Override
public ValidationResult validate(FormCheckerElement value) {
jochen777/jFormchecker
src/main/java/de/jformchecker/FormCheckerElement.java
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/message/MessageSource.java // @FunctionalInterface // public interface MessageSource { // // public String getMessage(String key); // // public default String getSafeMessage(String key) { // try { // String msg = this.getMessage(key); // return msg; // } catch (Exception e) { // return "??" + key + "??"; // } // } // // // public default String getMessage(ValidationResult vr) { // // give translated messages higher prio than message-keys // if (vr.getTranslatedMessage() != null) { // return vr.getTranslatedMessage(); // } else // if (vr.getMessage() != null) { // return(String.format(this.getSafeMessage( // vr.getMessage() // ), vr.getErrorVals())); // // } else { // throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text"); // } // } // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // }
import java.util.List; import java.util.Map; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.message.MessageSource; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator;
package de.jformchecker; /** * Interface for Input-Elements handled by formchecker * * @author jochen * */ public interface FormCheckerElement { // RFE: check, if some methods can be protected // get internal name of this input-element public String getName(); // set internal name public void setName(String name); // get the value that the user entered public String getValue(); // get the value that the user entered, but html-encoded @Deprecated public String getValueHtmlEncoded(); public void setValue(String value); public String getPreSetValue(); // set an initial value to the element, before the user edited it. public <T extends FormCheckerElement> T setPreSetValue(String value); public <T extends FormCheckerElement> T setTabIndex(int tabIndex); public int getTabIndex(); public int getLastTabIndex(); // set the test in the label (builder pattern) public <T extends FormCheckerElement> T setDescription(String desc); // as "setDescription" but does not return anything (no builder pattern) public void changeDescription(String desc); public String getDescription(); // returns true if element is valid public boolean isValid(); public void setInvalid(); // inits the value with the current http-request
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/message/MessageSource.java // @FunctionalInterface // public interface MessageSource { // // public String getMessage(String key); // // public default String getSafeMessage(String key) { // try { // String msg = this.getMessage(key); // return msg; // } catch (Exception e) { // return "??" + key + "??"; // } // } // // // public default String getMessage(ValidationResult vr) { // // give translated messages higher prio than message-keys // if (vr.getTranslatedMessage() != null) { // return vr.getTranslatedMessage(); // } else // if (vr.getMessage() != null) { // return(String.format(this.getSafeMessage( // vr.getMessage() // ), vr.getErrorVals())); // // } else { // throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text"); // } // } // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // } // Path: src/main/java/de/jformchecker/FormCheckerElement.java import java.util.List; import java.util.Map; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.message.MessageSource; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator; package de.jformchecker; /** * Interface for Input-Elements handled by formchecker * * @author jochen * */ public interface FormCheckerElement { // RFE: check, if some methods can be protected // get internal name of this input-element public String getName(); // set internal name public void setName(String name); // get the value that the user entered public String getValue(); // get the value that the user entered, but html-encoded @Deprecated public String getValueHtmlEncoded(); public void setValue(String value); public String getPreSetValue(); // set an initial value to the element, before the user edited it. public <T extends FormCheckerElement> T setPreSetValue(String value); public <T extends FormCheckerElement> T setTabIndex(int tabIndex); public int getTabIndex(); public int getLastTabIndex(); // set the test in the label (builder pattern) public <T extends FormCheckerElement> T setDescription(String desc); // as "setDescription" but does not return anything (no builder pattern) public void changeDescription(String desc); public String getDescription(); // returns true if element is valid public boolean isValid(); public void setInvalid(); // inits the value with the current http-request
public void init(Request req, boolean firstrun, Validator validator);
jochen777/jFormchecker
src/main/java/de/jformchecker/FormCheckerElement.java
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/message/MessageSource.java // @FunctionalInterface // public interface MessageSource { // // public String getMessage(String key); // // public default String getSafeMessage(String key) { // try { // String msg = this.getMessage(key); // return msg; // } catch (Exception e) { // return "??" + key + "??"; // } // } // // // public default String getMessage(ValidationResult vr) { // // give translated messages higher prio than message-keys // if (vr.getTranslatedMessage() != null) { // return vr.getTranslatedMessage(); // } else // if (vr.getMessage() != null) { // return(String.format(this.getSafeMessage( // vr.getMessage() // ), vr.getErrorVals())); // // } else { // throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text"); // } // } // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // }
import java.util.List; import java.util.Map; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.message.MessageSource; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator;
package de.jformchecker; /** * Interface for Input-Elements handled by formchecker * * @author jochen * */ public interface FormCheckerElement { // RFE: check, if some methods can be protected // get internal name of this input-element public String getName(); // set internal name public void setName(String name); // get the value that the user entered public String getValue(); // get the value that the user entered, but html-encoded @Deprecated public String getValueHtmlEncoded(); public void setValue(String value); public String getPreSetValue(); // set an initial value to the element, before the user edited it. public <T extends FormCheckerElement> T setPreSetValue(String value); public <T extends FormCheckerElement> T setTabIndex(int tabIndex); public int getTabIndex(); public int getLastTabIndex(); // set the test in the label (builder pattern) public <T extends FormCheckerElement> T setDescription(String desc); // as "setDescription" but does not return anything (no builder pattern) public void changeDescription(String desc); public String getDescription(); // returns true if element is valid public boolean isValid(); public void setInvalid(); // inits the value with the current http-request
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/message/MessageSource.java // @FunctionalInterface // public interface MessageSource { // // public String getMessage(String key); // // public default String getSafeMessage(String key) { // try { // String msg = this.getMessage(key); // return msg; // } catch (Exception e) { // return "??" + key + "??"; // } // } // // // public default String getMessage(ValidationResult vr) { // // give translated messages higher prio than message-keys // if (vr.getTranslatedMessage() != null) { // return vr.getTranslatedMessage(); // } else // if (vr.getMessage() != null) { // return(String.format(this.getSafeMessage( // vr.getMessage() // ), vr.getErrorVals())); // // } else { // throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text"); // } // } // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // } // Path: src/main/java/de/jformchecker/FormCheckerElement.java import java.util.List; import java.util.Map; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.message.MessageSource; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator; package de.jformchecker; /** * Interface for Input-Elements handled by formchecker * * @author jochen * */ public interface FormCheckerElement { // RFE: check, if some methods can be protected // get internal name of this input-element public String getName(); // set internal name public void setName(String name); // get the value that the user entered public String getValue(); // get the value that the user entered, but html-encoded @Deprecated public String getValueHtmlEncoded(); public void setValue(String value); public String getPreSetValue(); // set an initial value to the element, before the user edited it. public <T extends FormCheckerElement> T setPreSetValue(String value); public <T extends FormCheckerElement> T setTabIndex(int tabIndex); public int getTabIndex(); public int getLastTabIndex(); // set the test in the label (builder pattern) public <T extends FormCheckerElement> T setDescription(String desc); // as "setDescription" but does not return anything (no builder pattern) public void changeDescription(String desc); public String getDescription(); // returns true if element is valid public boolean isValid(); public void setInvalid(); // inits the value with the current http-request
public void init(Request req, boolean firstrun, Validator validator);
jochen777/jFormchecker
src/main/java/de/jformchecker/FormCheckerElement.java
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/message/MessageSource.java // @FunctionalInterface // public interface MessageSource { // // public String getMessage(String key); // // public default String getSafeMessage(String key) { // try { // String msg = this.getMessage(key); // return msg; // } catch (Exception e) { // return "??" + key + "??"; // } // } // // // public default String getMessage(ValidationResult vr) { // // give translated messages higher prio than message-keys // if (vr.getTranslatedMessage() != null) { // return vr.getTranslatedMessage(); // } else // if (vr.getMessage() != null) { // return(String.format(this.getSafeMessage( // vr.getMessage() // ), vr.getErrorVals())); // // } else { // throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text"); // } // } // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // }
import java.util.List; import java.util.Map; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.message.MessageSource; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator;
package de.jformchecker; /** * Interface for Input-Elements handled by formchecker * * @author jochen * */ public interface FormCheckerElement { // RFE: check, if some methods can be protected // get internal name of this input-element public String getName(); // set internal name public void setName(String name); // get the value that the user entered public String getValue(); // get the value that the user entered, but html-encoded @Deprecated public String getValueHtmlEncoded(); public void setValue(String value); public String getPreSetValue(); // set an initial value to the element, before the user edited it. public <T extends FormCheckerElement> T setPreSetValue(String value); public <T extends FormCheckerElement> T setTabIndex(int tabIndex); public int getTabIndex(); public int getLastTabIndex(); // set the test in the label (builder pattern) public <T extends FormCheckerElement> T setDescription(String desc); // as "setDescription" but does not return anything (no builder pattern) public void changeDescription(String desc); public String getDescription(); // returns true if element is valid public boolean isValid(); public void setInvalid(); // inits the value with the current http-request public void init(Request req, boolean firstrun, Validator validator);
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/message/MessageSource.java // @FunctionalInterface // public interface MessageSource { // // public String getMessage(String key); // // public default String getSafeMessage(String key) { // try { // String msg = this.getMessage(key); // return msg; // } catch (Exception e) { // return "??" + key + "??"; // } // } // // // public default String getMessage(ValidationResult vr) { // // give translated messages higher prio than message-keys // if (vr.getTranslatedMessage() != null) { // return vr.getTranslatedMessage(); // } else // if (vr.getMessage() != null) { // return(String.format(this.getSafeMessage( // vr.getMessage() // ), vr.getErrorVals())); // // } else { // throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text"); // } // } // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // } // Path: src/main/java/de/jformchecker/FormCheckerElement.java import java.util.List; import java.util.Map; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.message.MessageSource; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator; package de.jformchecker; /** * Interface for Input-Elements handled by formchecker * * @author jochen * */ public interface FormCheckerElement { // RFE: check, if some methods can be protected // get internal name of this input-element public String getName(); // set internal name public void setName(String name); // get the value that the user entered public String getValue(); // get the value that the user entered, but html-encoded @Deprecated public String getValueHtmlEncoded(); public void setValue(String value); public String getPreSetValue(); // set an initial value to the element, before the user edited it. public <T extends FormCheckerElement> T setPreSetValue(String value); public <T extends FormCheckerElement> T setTabIndex(int tabIndex); public int getTabIndex(); public int getLastTabIndex(); // set the test in the label (builder pattern) public <T extends FormCheckerElement> T setDescription(String desc); // as "setDescription" but does not return anything (no builder pattern) public void changeDescription(String desc); public String getDescription(); // returns true if element is valid public boolean isValid(); public void setInvalid(); // inits the value with the current http-request public void init(Request req, boolean firstrun, Validator validator);
public ValidationResult getValidationResult();
jochen777/jFormchecker
src/main/java/de/jformchecker/FormCheckerElement.java
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/message/MessageSource.java // @FunctionalInterface // public interface MessageSource { // // public String getMessage(String key); // // public default String getSafeMessage(String key) { // try { // String msg = this.getMessage(key); // return msg; // } catch (Exception e) { // return "??" + key + "??"; // } // } // // // public default String getMessage(ValidationResult vr) { // // give translated messages higher prio than message-keys // if (vr.getTranslatedMessage() != null) { // return vr.getTranslatedMessage(); // } else // if (vr.getMessage() != null) { // return(String.format(this.getSafeMessage( // vr.getMessage() // ), vr.getErrorVals())); // // } else { // throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text"); // } // } // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // }
import java.util.List; import java.util.Map; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.message.MessageSource; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator;
package de.jformchecker; /** * Interface for Input-Elements handled by formchecker * * @author jochen * */ public interface FormCheckerElement { // RFE: check, if some methods can be protected // get internal name of this input-element public String getName(); // set internal name public void setName(String name); // get the value that the user entered public String getValue(); // get the value that the user entered, but html-encoded @Deprecated public String getValueHtmlEncoded(); public void setValue(String value); public String getPreSetValue(); // set an initial value to the element, before the user edited it. public <T extends FormCheckerElement> T setPreSetValue(String value); public <T extends FormCheckerElement> T setTabIndex(int tabIndex); public int getTabIndex(); public int getLastTabIndex(); // set the test in the label (builder pattern) public <T extends FormCheckerElement> T setDescription(String desc); // as "setDescription" but does not return anything (no builder pattern) public void changeDescription(String desc); public String getDescription(); // returns true if element is valid public boolean isValid(); public void setInvalid(); // inits the value with the current http-request public void init(Request req, boolean firstrun, Validator validator); public ValidationResult getValidationResult(); public void setValidationResult(ValidationResult validationResult); public String getInputTag();
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/message/MessageSource.java // @FunctionalInterface // public interface MessageSource { // // public String getMessage(String key); // // public default String getSafeMessage(String key) { // try { // String msg = this.getMessage(key); // return msg; // } catch (Exception e) { // return "??" + key + "??"; // } // } // // // public default String getMessage(ValidationResult vr) { // // give translated messages higher prio than message-keys // if (vr.getTranslatedMessage() != null) { // return vr.getTranslatedMessage(); // } else // if (vr.getMessage() != null) { // return(String.format(this.getSafeMessage( // vr.getMessage() // ), vr.getErrorVals())); // // } else { // throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text"); // } // } // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // } // Path: src/main/java/de/jformchecker/FormCheckerElement.java import java.util.List; import java.util.Map; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.message.MessageSource; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator; package de.jformchecker; /** * Interface for Input-Elements handled by formchecker * * @author jochen * */ public interface FormCheckerElement { // RFE: check, if some methods can be protected // get internal name of this input-element public String getName(); // set internal name public void setName(String name); // get the value that the user entered public String getValue(); // get the value that the user entered, but html-encoded @Deprecated public String getValueHtmlEncoded(); public void setValue(String value); public String getPreSetValue(); // set an initial value to the element, before the user edited it. public <T extends FormCheckerElement> T setPreSetValue(String value); public <T extends FormCheckerElement> T setTabIndex(int tabIndex); public int getTabIndex(); public int getLastTabIndex(); // set the test in the label (builder pattern) public <T extends FormCheckerElement> T setDescription(String desc); // as "setDescription" but does not return anything (no builder pattern) public void changeDescription(String desc); public String getDescription(); // returns true if element is valid public boolean isValid(); public void setInvalid(); // inits the value with the current http-request public void init(Request req, boolean firstrun, Validator validator); public ValidationResult getValidationResult(); public void setValidationResult(ValidationResult validationResult); public String getInputTag();
public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation);
jochen777/jFormchecker
src/main/java/de/jformchecker/elements/SimpleLabel.java
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // }
import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator;
package de.jformchecker.elements; public class SimpleLabel extends AbstractInput<SimpleLabel> implements FormCheckerElement { public static SimpleLabel build(String name) { SimpleLabel i = new SimpleLabel(); i.name = name; return i; } @Override public String getValue() { return this.getDescription(); } @Override public String getInputTag(Map<String, String> attributes) { return ""; // output nothing, because headline will be outputted as // label } @Override
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // } // Path: src/main/java/de/jformchecker/elements/SimpleLabel.java import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator; package de.jformchecker.elements; public class SimpleLabel extends AbstractInput<SimpleLabel> implements FormCheckerElement { public static SimpleLabel build(String name) { SimpleLabel i = new SimpleLabel(); i.name = name; return i; } @Override public String getValue() { return this.getDescription(); } @Override public String getInputTag(Map<String, String> attributes) { return ""; // output nothing, because headline will be outputted as // label } @Override
public void init(Request request, boolean firstRun, Validator validator) {
jochen777/jFormchecker
src/main/java/de/jformchecker/elements/SimpleLabel.java
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // }
import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator;
package de.jformchecker.elements; public class SimpleLabel extends AbstractInput<SimpleLabel> implements FormCheckerElement { public static SimpleLabel build(String name) { SimpleLabel i = new SimpleLabel(); i.name = name; return i; } @Override public String getValue() { return this.getDescription(); } @Override public String getInputTag(Map<String, String> attributes) { return ""; // output nothing, because headline will be outputted as // label } @Override
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // } // Path: src/main/java/de/jformchecker/elements/SimpleLabel.java import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator; package de.jformchecker.elements; public class SimpleLabel extends AbstractInput<SimpleLabel> implements FormCheckerElement { public static SimpleLabel build(String name) { SimpleLabel i = new SimpleLabel(); i.name = name; return i; } @Override public String getValue() { return this.getDescription(); } @Override public String getInputTag(Map<String, String> attributes) { return ""; // output nothing, because headline will be outputted as // label } @Override
public void init(Request request, boolean firstRun, Validator validator) {
jochen777/jFormchecker
src/main/java/de/jformchecker/criteria/MinLength.java
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // }
import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement;
package de.jformchecker.criteria; /** * Checks that value is not less than the specified minimum. * * Based on work of armandino (at) gmail.com */ public final class MinLength implements Criterion { private int minLength; MinLength(int minLength) { this.minLength = minLength; } @Override
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // Path: src/main/java/de/jformchecker/criteria/MinLength.java import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement; package de.jformchecker.criteria; /** * Checks that value is not less than the specified minimum. * * Based on work of armandino (at) gmail.com */ public final class MinLength implements Criterion { private int minLength; MinLength(int minLength) { this.minLength = minLength; } @Override
public ValidationResult validate(FormCheckerElement value) {
jochen777/jFormchecker
src/main/java/de/jformchecker/validator/DefaultValidator.java
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // }
import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement; import de.jformchecker.criteria.ValidationResult;
package de.jformchecker.validator; /** * Validator, that checks a complete form * * @author jochen * */ public class DefaultValidator implements Validator { /* * (non-Javadoc) * * @see de.jformchecker.validator.Validator#validate(de.jformchecker. * FormCheckerElement) */ @Override
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // Path: src/main/java/de/jformchecker/validator/DefaultValidator.java import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement; import de.jformchecker.criteria.ValidationResult; package de.jformchecker.validator; /** * Validator, that checks a complete form * * @author jochen * */ public class DefaultValidator implements Validator { /* * (non-Javadoc) * * @see de.jformchecker.validator.Validator#validate(de.jformchecker. * FormCheckerElement) */ @Override
public ValidationResult validate(FormCheckerElement elem) {
jochen777/jFormchecker
src/main/java/de/jformchecker/validator/DefaultValidator.java
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // }
import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement; import de.jformchecker.criteria.ValidationResult;
package de.jformchecker.validator; /** * Validator, that checks a complete form * * @author jochen * */ public class DefaultValidator implements Validator { /* * (non-Javadoc) * * @see de.jformchecker.validator.Validator#validate(de.jformchecker. * FormCheckerElement) */ @Override
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // Path: src/main/java/de/jformchecker/validator/DefaultValidator.java import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement; import de.jformchecker.criteria.ValidationResult; package de.jformchecker.validator; /** * Validator, that checks a complete form * * @author jochen * */ public class DefaultValidator implements Validator { /* * (non-Javadoc) * * @see de.jformchecker.validator.Validator#validate(de.jformchecker. * FormCheckerElement) */ @Override
public ValidationResult validate(FormCheckerElement elem) {
jochen777/jFormchecker
src/main/java/de/jformchecker/validator/DefaultValidator.java
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // }
import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement; import de.jformchecker.criteria.ValidationResult;
package de.jformchecker.validator; /** * Validator, that checks a complete form * * @author jochen * */ public class DefaultValidator implements Validator { /* * (non-Javadoc) * * @see de.jformchecker.validator.Validator#validate(de.jformchecker. * FormCheckerElement) */ @Override public ValidationResult validate(FormCheckerElement elem) { String value = elem.getValue(); ValidationResult vr = ValidationResult.ok(); if (value != null && !"".equals(value)) { vr = allCriteriaSatisfied(elem); } else { // blank input is valid if it's not required if (elem.isRequired()) { vr = ValidationResult.fail("jformchecker.required", ""); } } return vr; } // RFE: Maybe return here an array? So we can have more than one error-message per field. private ValidationResult allCriteriaSatisfied(FormCheckerElement elem) {
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // Path: src/main/java/de/jformchecker/validator/DefaultValidator.java import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement; import de.jformchecker.criteria.ValidationResult; package de.jformchecker.validator; /** * Validator, that checks a complete form * * @author jochen * */ public class DefaultValidator implements Validator { /* * (non-Javadoc) * * @see de.jformchecker.validator.Validator#validate(de.jformchecker. * FormCheckerElement) */ @Override public ValidationResult validate(FormCheckerElement elem) { String value = elem.getValue(); ValidationResult vr = ValidationResult.ok(); if (value != null && !"".equals(value)) { vr = allCriteriaSatisfied(elem); } else { // blank input is valid if it's not required if (elem.isRequired()) { vr = ValidationResult.fail("jformchecker.required", ""); } } return vr; } // RFE: Maybe return here an array? So we can have more than one error-message per field. private ValidationResult allCriteriaSatisfied(FormCheckerElement elem) {
for (Criterion criterion : elem.getCriteria()) {
jochen777/jFormchecker
src/test/java/de/jformchecker/test/ValidationErrorTest.java
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/elements/TextInput.java // public class TextInput extends AbstractInput<TextInput> implements FormCheckerElement { // // private String placeholderText = ""; // // public static TextInput build(String name) { // TextInput i = new TextInput(); // i.name = name; // return i; // } // // public TextInput setPlaceholerText(String placeholderText) { // this.placeholderText = placeholderText; // return this; // } // // @Override // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) { // TagAttributes tagAttributes = new TagAttributes(attributes); // tagAttributes.add(this.inputAttributes); // return String.format("<input " + buildAllAttributes(tagAttributes, messageSource, html5Validation) + buildMaxLen() // + "type=\"text\" name=\"%s\" value=\"%s\"" + getPlaceholder() + ">", name, // (value == null ? "" : getValueHtmlEncoded())); // } // // // protected String getPlaceholder() { // return StringUtils.isEmpty(placeholderText) ? "" // : " placeholder=\"" + Escape.htmlText(placeholderText) + "\""; // } // // @Override // public String getType() { // return "text"; // } // // // } // // Path: src/main/java/de/jformchecker/validator/DefaultValidator.java // public class DefaultValidator implements Validator { // // /* // * (non-Javadoc) // * // * @see de.jformchecker.validator.Validator#validate(de.jformchecker. // * FormCheckerElement) // */ // @Override // public ValidationResult validate(FormCheckerElement elem) { // String value = elem.getValue(); // ValidationResult vr = ValidationResult.ok(); // if (value != null && !"".equals(value)) { // vr = allCriteriaSatisfied(elem); // } else { // // blank input is valid if it's not required // if (elem.isRequired()) { // vr = ValidationResult.fail("jformchecker.required", ""); // } // } // return vr; // } // // // RFE: Maybe return here an array? So we can have more than one error-message per field. // private ValidationResult allCriteriaSatisfied(FormCheckerElement elem) { // for (Criterion criterion : elem.getCriteria()) { // ValidationResult vr = criterion.validate(elem); // if (!vr.isValid()) { // return vr; // } // } // // return ValidationResult.ok(); // } // // // }
import org.junit.Assert; import org.junit.Test; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.elements.TextInput; import de.jformchecker.validator.DefaultValidator;
package de.jformchecker.test; /** * Tests the behaviour of validation errors * * @author jochen * */ public class ValidationErrorTest { // Tests if a not translated comes @Test public void testMessageKeyError() { String errorMsg = "ErrorMsg"; boolean translateMsg = false;
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/elements/TextInput.java // public class TextInput extends AbstractInput<TextInput> implements FormCheckerElement { // // private String placeholderText = ""; // // public static TextInput build(String name) { // TextInput i = new TextInput(); // i.name = name; // return i; // } // // public TextInput setPlaceholerText(String placeholderText) { // this.placeholderText = placeholderText; // return this; // } // // @Override // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) { // TagAttributes tagAttributes = new TagAttributes(attributes); // tagAttributes.add(this.inputAttributes); // return String.format("<input " + buildAllAttributes(tagAttributes, messageSource, html5Validation) + buildMaxLen() // + "type=\"text\" name=\"%s\" value=\"%s\"" + getPlaceholder() + ">", name, // (value == null ? "" : getValueHtmlEncoded())); // } // // // protected String getPlaceholder() { // return StringUtils.isEmpty(placeholderText) ? "" // : " placeholder=\"" + Escape.htmlText(placeholderText) + "\""; // } // // @Override // public String getType() { // return "text"; // } // // // } // // Path: src/main/java/de/jformchecker/validator/DefaultValidator.java // public class DefaultValidator implements Validator { // // /* // * (non-Javadoc) // * // * @see de.jformchecker.validator.Validator#validate(de.jformchecker. // * FormCheckerElement) // */ // @Override // public ValidationResult validate(FormCheckerElement elem) { // String value = elem.getValue(); // ValidationResult vr = ValidationResult.ok(); // if (value != null && !"".equals(value)) { // vr = allCriteriaSatisfied(elem); // } else { // // blank input is valid if it's not required // if (elem.isRequired()) { // vr = ValidationResult.fail("jformchecker.required", ""); // } // } // return vr; // } // // // RFE: Maybe return here an array? So we can have more than one error-message per field. // private ValidationResult allCriteriaSatisfied(FormCheckerElement elem) { // for (Criterion criterion : elem.getCriteria()) { // ValidationResult vr = criterion.validate(elem); // if (!vr.isValid()) { // return vr; // } // } // // return ValidationResult.ok(); // } // // // } // Path: src/test/java/de/jformchecker/test/ValidationErrorTest.java import org.junit.Assert; import org.junit.Test; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.elements.TextInput; import de.jformchecker.validator.DefaultValidator; package de.jformchecker.test; /** * Tests the behaviour of validation errors * * @author jochen * */ public class ValidationErrorTest { // Tests if a not translated comes @Test public void testMessageKeyError() { String errorMsg = "ErrorMsg"; boolean translateMsg = false;
TextInput ti = getFormElement(translateMsg, errorMsg);
jochen777/jFormchecker
src/test/java/de/jformchecker/test/ValidationErrorTest.java
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/elements/TextInput.java // public class TextInput extends AbstractInput<TextInput> implements FormCheckerElement { // // private String placeholderText = ""; // // public static TextInput build(String name) { // TextInput i = new TextInput(); // i.name = name; // return i; // } // // public TextInput setPlaceholerText(String placeholderText) { // this.placeholderText = placeholderText; // return this; // } // // @Override // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) { // TagAttributes tagAttributes = new TagAttributes(attributes); // tagAttributes.add(this.inputAttributes); // return String.format("<input " + buildAllAttributes(tagAttributes, messageSource, html5Validation) + buildMaxLen() // + "type=\"text\" name=\"%s\" value=\"%s\"" + getPlaceholder() + ">", name, // (value == null ? "" : getValueHtmlEncoded())); // } // // // protected String getPlaceholder() { // return StringUtils.isEmpty(placeholderText) ? "" // : " placeholder=\"" + Escape.htmlText(placeholderText) + "\""; // } // // @Override // public String getType() { // return "text"; // } // // // } // // Path: src/main/java/de/jformchecker/validator/DefaultValidator.java // public class DefaultValidator implements Validator { // // /* // * (non-Javadoc) // * // * @see de.jformchecker.validator.Validator#validate(de.jformchecker. // * FormCheckerElement) // */ // @Override // public ValidationResult validate(FormCheckerElement elem) { // String value = elem.getValue(); // ValidationResult vr = ValidationResult.ok(); // if (value != null && !"".equals(value)) { // vr = allCriteriaSatisfied(elem); // } else { // // blank input is valid if it's not required // if (elem.isRequired()) { // vr = ValidationResult.fail("jformchecker.required", ""); // } // } // return vr; // } // // // RFE: Maybe return here an array? So we can have more than one error-message per field. // private ValidationResult allCriteriaSatisfied(FormCheckerElement elem) { // for (Criterion criterion : elem.getCriteria()) { // ValidationResult vr = criterion.validate(elem); // if (!vr.isValid()) { // return vr; // } // } // // return ValidationResult.ok(); // } // // // }
import org.junit.Assert; import org.junit.Test; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.elements.TextInput; import de.jformchecker.validator.DefaultValidator;
package de.jformchecker.test; /** * Tests the behaviour of validation errors * * @author jochen * */ public class ValidationErrorTest { // Tests if a not translated comes @Test public void testMessageKeyError() { String errorMsg = "ErrorMsg"; boolean translateMsg = false; TextInput ti = getFormElement(translateMsg, errorMsg); boolean firstRun = false;
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/elements/TextInput.java // public class TextInput extends AbstractInput<TextInput> implements FormCheckerElement { // // private String placeholderText = ""; // // public static TextInput build(String name) { // TextInput i = new TextInput(); // i.name = name; // return i; // } // // public TextInput setPlaceholerText(String placeholderText) { // this.placeholderText = placeholderText; // return this; // } // // @Override // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) { // TagAttributes tagAttributes = new TagAttributes(attributes); // tagAttributes.add(this.inputAttributes); // return String.format("<input " + buildAllAttributes(tagAttributes, messageSource, html5Validation) + buildMaxLen() // + "type=\"text\" name=\"%s\" value=\"%s\"" + getPlaceholder() + ">", name, // (value == null ? "" : getValueHtmlEncoded())); // } // // // protected String getPlaceholder() { // return StringUtils.isEmpty(placeholderText) ? "" // : " placeholder=\"" + Escape.htmlText(placeholderText) + "\""; // } // // @Override // public String getType() { // return "text"; // } // // // } // // Path: src/main/java/de/jformchecker/validator/DefaultValidator.java // public class DefaultValidator implements Validator { // // /* // * (non-Javadoc) // * // * @see de.jformchecker.validator.Validator#validate(de.jformchecker. // * FormCheckerElement) // */ // @Override // public ValidationResult validate(FormCheckerElement elem) { // String value = elem.getValue(); // ValidationResult vr = ValidationResult.ok(); // if (value != null && !"".equals(value)) { // vr = allCriteriaSatisfied(elem); // } else { // // blank input is valid if it's not required // if (elem.isRequired()) { // vr = ValidationResult.fail("jformchecker.required", ""); // } // } // return vr; // } // // // RFE: Maybe return here an array? So we can have more than one error-message per field. // private ValidationResult allCriteriaSatisfied(FormCheckerElement elem) { // for (Criterion criterion : elem.getCriteria()) { // ValidationResult vr = criterion.validate(elem); // if (!vr.isValid()) { // return vr; // } // } // // return ValidationResult.ok(); // } // // // } // Path: src/test/java/de/jformchecker/test/ValidationErrorTest.java import org.junit.Assert; import org.junit.Test; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.elements.TextInput; import de.jformchecker.validator.DefaultValidator; package de.jformchecker.test; /** * Tests the behaviour of validation errors * * @author jochen * */ public class ValidationErrorTest { // Tests if a not translated comes @Test public void testMessageKeyError() { String errorMsg = "ErrorMsg"; boolean translateMsg = false; TextInput ti = getFormElement(translateMsg, errorMsg); boolean firstRun = false;
ti.init(key -> "NotCorrect", firstRun, new DefaultValidator());
jochen777/jFormchecker
src/test/java/de/jformchecker/test/ValidationErrorTest.java
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/elements/TextInput.java // public class TextInput extends AbstractInput<TextInput> implements FormCheckerElement { // // private String placeholderText = ""; // // public static TextInput build(String name) { // TextInput i = new TextInput(); // i.name = name; // return i; // } // // public TextInput setPlaceholerText(String placeholderText) { // this.placeholderText = placeholderText; // return this; // } // // @Override // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) { // TagAttributes tagAttributes = new TagAttributes(attributes); // tagAttributes.add(this.inputAttributes); // return String.format("<input " + buildAllAttributes(tagAttributes, messageSource, html5Validation) + buildMaxLen() // + "type=\"text\" name=\"%s\" value=\"%s\"" + getPlaceholder() + ">", name, // (value == null ? "" : getValueHtmlEncoded())); // } // // // protected String getPlaceholder() { // return StringUtils.isEmpty(placeholderText) ? "" // : " placeholder=\"" + Escape.htmlText(placeholderText) + "\""; // } // // @Override // public String getType() { // return "text"; // } // // // } // // Path: src/main/java/de/jformchecker/validator/DefaultValidator.java // public class DefaultValidator implements Validator { // // /* // * (non-Javadoc) // * // * @see de.jformchecker.validator.Validator#validate(de.jformchecker. // * FormCheckerElement) // */ // @Override // public ValidationResult validate(FormCheckerElement elem) { // String value = elem.getValue(); // ValidationResult vr = ValidationResult.ok(); // if (value != null && !"".equals(value)) { // vr = allCriteriaSatisfied(elem); // } else { // // blank input is valid if it's not required // if (elem.isRequired()) { // vr = ValidationResult.fail("jformchecker.required", ""); // } // } // return vr; // } // // // RFE: Maybe return here an array? So we can have more than one error-message per field. // private ValidationResult allCriteriaSatisfied(FormCheckerElement elem) { // for (Criterion criterion : elem.getCriteria()) { // ValidationResult vr = criterion.validate(elem); // if (!vr.isValid()) { // return vr; // } // } // // return ValidationResult.ok(); // } // // // }
import org.junit.Assert; import org.junit.Test; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.elements.TextInput; import de.jformchecker.validator.DefaultValidator;
package de.jformchecker.test; /** * Tests the behaviour of validation errors * * @author jochen * */ public class ValidationErrorTest { // Tests if a not translated comes @Test public void testMessageKeyError() { String errorMsg = "ErrorMsg"; boolean translateMsg = false; TextInput ti = getFormElement(translateMsg, errorMsg); boolean firstRun = false; ti.init(key -> "NotCorrect", firstRun, new DefaultValidator()); Assert.assertEquals(errorMsg, ti.getValidationResult().getMessage()); } // Test if a translated message is coming @Test public void testTranslatedError() { String errorMsg = "ErrorMsg"; boolean translateMsg = true; TextInput ti = getFormElement(translateMsg, errorMsg); boolean firstRun = false; ti.init(key -> "NotCorrect", firstRun, new DefaultValidator()); Assert.assertEquals(errorMsg, ti.getValidationResult().getTranslatedMessage()); } private TextInput getFormElement(boolean translatedMessage, String errorMsg) { String content = "Jochen"; TextInput ti = (TextInput) TextInput.build("firstname").setPreSetValue(content); ti.addCriteria(el -> { return (!el.getValue().equals(content) ? (
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // // Path: src/main/java/de/jformchecker/elements/TextInput.java // public class TextInput extends AbstractInput<TextInput> implements FormCheckerElement { // // private String placeholderText = ""; // // public static TextInput build(String name) { // TextInput i = new TextInput(); // i.name = name; // return i; // } // // public TextInput setPlaceholerText(String placeholderText) { // this.placeholderText = placeholderText; // return this; // } // // @Override // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) { // TagAttributes tagAttributes = new TagAttributes(attributes); // tagAttributes.add(this.inputAttributes); // return String.format("<input " + buildAllAttributes(tagAttributes, messageSource, html5Validation) + buildMaxLen() // + "type=\"text\" name=\"%s\" value=\"%s\"" + getPlaceholder() + ">", name, // (value == null ? "" : getValueHtmlEncoded())); // } // // // protected String getPlaceholder() { // return StringUtils.isEmpty(placeholderText) ? "" // : " placeholder=\"" + Escape.htmlText(placeholderText) + "\""; // } // // @Override // public String getType() { // return "text"; // } // // // } // // Path: src/main/java/de/jformchecker/validator/DefaultValidator.java // public class DefaultValidator implements Validator { // // /* // * (non-Javadoc) // * // * @see de.jformchecker.validator.Validator#validate(de.jformchecker. // * FormCheckerElement) // */ // @Override // public ValidationResult validate(FormCheckerElement elem) { // String value = elem.getValue(); // ValidationResult vr = ValidationResult.ok(); // if (value != null && !"".equals(value)) { // vr = allCriteriaSatisfied(elem); // } else { // // blank input is valid if it's not required // if (elem.isRequired()) { // vr = ValidationResult.fail("jformchecker.required", ""); // } // } // return vr; // } // // // RFE: Maybe return here an array? So we can have more than one error-message per field. // private ValidationResult allCriteriaSatisfied(FormCheckerElement elem) { // for (Criterion criterion : elem.getCriteria()) { // ValidationResult vr = criterion.validate(elem); // if (!vr.isValid()) { // return vr; // } // } // // return ValidationResult.ok(); // } // // // } // Path: src/test/java/de/jformchecker/test/ValidationErrorTest.java import org.junit.Assert; import org.junit.Test; import de.jformchecker.criteria.ValidationResult; import de.jformchecker.elements.TextInput; import de.jformchecker.validator.DefaultValidator; package de.jformchecker.test; /** * Tests the behaviour of validation errors * * @author jochen * */ public class ValidationErrorTest { // Tests if a not translated comes @Test public void testMessageKeyError() { String errorMsg = "ErrorMsg"; boolean translateMsg = false; TextInput ti = getFormElement(translateMsg, errorMsg); boolean firstRun = false; ti.init(key -> "NotCorrect", firstRun, new DefaultValidator()); Assert.assertEquals(errorMsg, ti.getValidationResult().getMessage()); } // Test if a translated message is coming @Test public void testTranslatedError() { String errorMsg = "ErrorMsg"; boolean translateMsg = true; TextInput ti = getFormElement(translateMsg, errorMsg); boolean firstRun = false; ti.init(key -> "NotCorrect", firstRun, new DefaultValidator()); Assert.assertEquals(errorMsg, ti.getValidationResult().getTranslatedMessage()); } private TextInput getFormElement(boolean translatedMessage, String errorMsg) { String content = "Jochen"; TextInput ti = (TextInput) TextInput.build("firstname").setPreSetValue(content); ti.addCriteria(el -> { return (!el.getValue().equals(content) ? (
translatedMessage ? ValidationResult.failWithTranslated(errorMsg) :
jochen777/jFormchecker
src/main/java/de/jformchecker/message/MessageSource.java
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // }
import de.jformchecker.criteria.ValidationResult;
package de.jformchecker.message; /** * Source for mssages that should be displayed typically coming from a property * file holding localized messages * * @author jpier * */ @FunctionalInterface public interface MessageSource { public String getMessage(String key); public default String getSafeMessage(String key) { try { String msg = this.getMessage(key); return msg; } catch (Exception e) { return "??" + key + "??"; } }
// Path: src/main/java/de/jformchecker/criteria/ValidationResult.java // public class ValidationResult { // // boolean isValid = false; // // // caching: // private static ValidationResult okResult = new ValidationResult(true, "", null, null); // // public boolean isValid() { // return isValid; // } // // public String getMessage() { // return message; // } // // public Object[] getErrorVals() { // return errorVals; // } // // String message; // String translatedMessage; // Object[] errorVals; // // public ValidationResult(boolean isValid, String message, Object[] errorVals, String translatedMessage) { // this.isValid = isValid; // this.message = message; // this.errorVals = errorVals; // this.translatedMessage = translatedMessage; // } // // // factory methods // public static ValidationResult of_(boolean isValid, String message, Object... errorVals) { // return new ValidationResult(isValid, message, errorVals, null); // } // // public static ValidationResult fail(String message, Object... errorVals) { // return new ValidationResult(false, message, errorVals, null); // } // // public static ValidationResult failWithTranslated(String message, Object... errorVals) { // return new ValidationResult(false, null, errorVals, message); // } // // public static ValidationResult failWithTranslated(String message) { // return new ValidationResult(false, null, new Object[0], message); // } // // public static ValidationResult ok() { // // RFE: Could return always the same object! will reduce memory // // footprint! // return okResult; // } // // public String getTranslatedMessage() { // return translatedMessage; // } // // } // Path: src/main/java/de/jformchecker/message/MessageSource.java import de.jformchecker.criteria.ValidationResult; package de.jformchecker.message; /** * Source for mssages that should be displayed typically coming from a property * file holding localized messages * * @author jpier * */ @FunctionalInterface public interface MessageSource { public String getMessage(String key); public default String getSafeMessage(String key) { try { String msg = this.getMessage(key); return msg; } catch (Exception e) { return "??" + key + "??"; } }
public default String getMessage(ValidationResult vr) {
jochen777/jFormchecker
src/main/java/de/jformchecker/criteria/CaseInsensitiveRegex.java
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // }
import java.util.regex.Pattern; import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement;
package de.jformchecker.criteria; /** * Checks if a string matches a regular expression in a case insensitive way. * RFE: Avoid doublication with Regex.java * * Based on work of armandino (at) gmail.com */ public class CaseInsensitiveRegex implements Criterion { private Pattern pattern; private String errorMsg = "jformchecker.regexp"; public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } CaseInsensitiveRegex(String pattern) { this.pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); } @Override
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // Path: src/main/java/de/jformchecker/criteria/CaseInsensitiveRegex.java import java.util.regex.Pattern; import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement; package de.jformchecker.criteria; /** * Checks if a string matches a regular expression in a case insensitive way. * RFE: Avoid doublication with Regex.java * * Based on work of armandino (at) gmail.com */ public class CaseInsensitiveRegex implements Criterion { private Pattern pattern; private String errorMsg = "jformchecker.regexp"; public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } CaseInsensitiveRegex(String pattern) { this.pattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); } @Override
public ValidationResult validate(FormCheckerElement value) {
jochen777/jFormchecker
src/main/java/de/jformchecker/elements/HTMLSnippet.java
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // }
import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator;
package de.jformchecker.elements; public class HTMLSnippet extends AbstractInput<HTMLSnippet> implements FormCheckerElement { String html; public static HTMLSnippet build(String name) { HTMLSnippet i = new HTMLSnippet(); i.name = name; return i; } public HTMLSnippet setHTML(String html) { this.html = html; return this; } @Override public String getValue() { return ""; } @Override public String getInputTag(Map<String, String> attributes) { return html; } @Override
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // } // Path: src/main/java/de/jformchecker/elements/HTMLSnippet.java import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator; package de.jformchecker.elements; public class HTMLSnippet extends AbstractInput<HTMLSnippet> implements FormCheckerElement { String html; public static HTMLSnippet build(String name) { HTMLSnippet i = new HTMLSnippet(); i.name = name; return i; } public HTMLSnippet setHTML(String html) { this.html = html; return this; } @Override public String getValue() { return ""; } @Override public String getInputTag(Map<String, String> attributes) { return html; } @Override
public void init(Request request, boolean firstRun, Validator validator) {
jochen777/jFormchecker
src/main/java/de/jformchecker/elements/HTMLSnippet.java
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // }
import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator;
package de.jformchecker.elements; public class HTMLSnippet extends AbstractInput<HTMLSnippet> implements FormCheckerElement { String html; public static HTMLSnippet build(String name) { HTMLSnippet i = new HTMLSnippet(); i.name = name; return i; } public HTMLSnippet setHTML(String html) { this.html = html; return this; } @Override public String getValue() { return ""; } @Override public String getInputTag(Map<String, String> attributes) { return html; } @Override
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/validator/Validator.java // public interface Validator { // // ValidationResult validate(FormCheckerElement elem); // // } // Path: src/main/java/de/jformchecker/elements/HTMLSnippet.java import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.request.Request; import de.jformchecker.validator.Validator; package de.jformchecker.elements; public class HTMLSnippet extends AbstractInput<HTMLSnippet> implements FormCheckerElement { String html; public static HTMLSnippet build(String name) { HTMLSnippet i = new HTMLSnippet(); i.name = name; return i; } public HTMLSnippet setHTML(String html) { this.html = html; return this; } @Override public String getValue() { return ""; } @Override public String getInputTag(Map<String, String> attributes) { return html; } @Override
public void init(Request request, boolean firstRun, Validator validator) {
jochen777/jFormchecker
src/main/java/de/jformchecker/elements/SelectInput.java
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // }
import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes;
@Deprecated public static SelectInput build(String name, LinkedHashMap<String, String> possibleNames) { SelectInput si = SelectInput.build(name); si.setPossibleValues(possibleNames); return si; } // convenience method public static SelectInput build(String name, String keys[], String values[]) { SelectInput si = SelectInput.build(name); if (keys.length != values.length) { throw new IllegalArgumentException("Key / Values with unequal length"); } List<SelectInputEntry> entries = new ArrayList<>(); for (int i = 0; i < keys.length; i++) { entries.add(si.generateEntry(keys[i], values[i])); } si.setEntries(entries); return si; } // build a select-box with groups (This may be impossible to build) public static SelectInput build(String name, List<SelectInputEntryGroup> inputGroups) { SelectInput si = SelectInput.build(name); si.setGroups(inputGroups); return si; } public String getInputTag(Map<String, String> attributes) {
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // Path: src/main/java/de/jformchecker/elements/SelectInput.java import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; @Deprecated public static SelectInput build(String name, LinkedHashMap<String, String> possibleNames) { SelectInput si = SelectInput.build(name); si.setPossibleValues(possibleNames); return si; } // convenience method public static SelectInput build(String name, String keys[], String values[]) { SelectInput si = SelectInput.build(name); if (keys.length != values.length) { throw new IllegalArgumentException("Key / Values with unequal length"); } List<SelectInputEntry> entries = new ArrayList<>(); for (int i = 0; i < keys.length; i++) { entries.add(si.generateEntry(keys[i], values[i])); } si.setEntries(entries); return si; } // build a select-box with groups (This may be impossible to build) public static SelectInput build(String name, List<SelectInputEntryGroup> inputGroups) { SelectInput si = SelectInput.build(name); si.setGroups(inputGroups); return si; } public String getInputTag(Map<String, String> attributes) {
TagAttributes tagAttributes = new TagAttributes(attributes);
jochen777/jFormchecker
src/main/java/de/jformchecker/criteria/AbstractNumberComparingCriterion.java
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // }
import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement;
package de.jformchecker.criteria; /** * provides some utils for criterias, that compare numbers (currentyl: min/max) * * @author jpier * */ public abstract class AbstractNumberComparingCriterion implements Criterion { @Override
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // Path: src/main/java/de/jformchecker/criteria/AbstractNumberComparingCriterion.java import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement; package de.jformchecker.criteria; /** * provides some utils for criterias, that compare numbers (currentyl: min/max) * * @author jpier * */ public abstract class AbstractNumberComparingCriterion implements Criterion { @Override
public ValidationResult validate(FormCheckerElement value) {
jochen777/jFormchecker
src/main/java/de/jformchecker/criteria/ExactLength.java
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // }
import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement;
package de.jformchecker.criteria; /** * Checks that the length of the value is equal to the given length. * * Based on work of armandino (at) gmail.com */ public final class ExactLength implements Criterion { private int length; ExactLength(int length) { this.length = length; } @Override
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // Path: src/main/java/de/jformchecker/criteria/ExactLength.java import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement; package de.jformchecker.criteria; /** * Checks that the length of the value is equal to the given length. * * Based on work of armandino (at) gmail.com */ public final class ExactLength implements Criterion { private int length; ExactLength(int length) { this.length = length; } @Override
public ValidationResult validate(FormCheckerElement value) {
jochen777/jFormchecker
src/main/java/de/jformchecker/criteria/Number.java
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // }
import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement;
package de.jformchecker.criteria; /** * Checks that value is a number. * * Based on work of armandino (at) gmail.com */ public final class Number implements Criterion { Number() { } @Override
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // Path: src/main/java/de/jformchecker/criteria/Number.java import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement; package de.jformchecker.criteria; /** * Checks that value is a number. * * Based on work of armandino (at) gmail.com */ public final class Number implements Criterion { Number() { } @Override
public ValidationResult validate(FormCheckerElement value) {
jochen777/jFormchecker
src/main/java/de/jformchecker/criteria/Length.java
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // }
import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement;
package de.jformchecker.criteria; /** * Checks that the length of the value is within the given range. * * Based on work of armandino (at) gmail.com */ public final class Length implements Criterion { private int min; private int max; Length(int min, int max) { this.min = min; this.max = max; } @Override
// Path: src/main/java/de/jformchecker/Criterion.java // @FunctionalInterface // public interface Criterion { // /** // * Tests whether the specified value satisfies this criterion. // * // * @param value // * to be tested against this criterion. // * @return a ValidationResult which holds true or false for validaton result // * and a potential errormsg // */ // public ValidationResult validate(FormCheckerElement value); // // } // // Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // Path: src/main/java/de/jformchecker/criteria/Length.java import de.jformchecker.Criterion; import de.jformchecker.FormCheckerElement; package de.jformchecker.criteria; /** * Checks that the length of the value is within the given range. * * Based on work of armandino (at) gmail.com */ public final class Length implements Criterion { private int min; private int max; Length(int min, int max) { this.min = min; this.max = max; } @Override
public ValidationResult validate(FormCheckerElement value) {
jochen777/jFormchecker
src/main/java/de/jformchecker/elements/PasswordInput.java
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/message/MessageSource.java // @FunctionalInterface // public interface MessageSource { // // public String getMessage(String key); // // public default String getSafeMessage(String key) { // try { // String msg = this.getMessage(key); // return msg; // } catch (Exception e) { // return "??" + key + "??"; // } // } // // // public default String getMessage(ValidationResult vr) { // // give translated messages higher prio than message-keys // if (vr.getTranslatedMessage() != null) { // return vr.getTranslatedMessage(); // } else // if (vr.getMessage() != null) { // return(String.format(this.getSafeMessage( // vr.getMessage() // ), vr.getErrorVals())); // // } else { // throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text"); // } // } // // }
import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.message.MessageSource;
package de.jformchecker.elements; public class PasswordInput extends TextInput implements FormCheckerElement { public static PasswordInput build(String name) { PasswordInput i = new PasswordInput(); i.name = name; return i; } @Override
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/message/MessageSource.java // @FunctionalInterface // public interface MessageSource { // // public String getMessage(String key); // // public default String getSafeMessage(String key) { // try { // String msg = this.getMessage(key); // return msg; // } catch (Exception e) { // return "??" + key + "??"; // } // } // // // public default String getMessage(ValidationResult vr) { // // give translated messages higher prio than message-keys // if (vr.getTranslatedMessage() != null) { // return vr.getTranslatedMessage(); // } else // if (vr.getMessage() != null) { // return(String.format(this.getSafeMessage( // vr.getMessage() // ), vr.getErrorVals())); // // } else { // throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text"); // } // } // // } // Path: src/main/java/de/jformchecker/elements/PasswordInput.java import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.message.MessageSource; package de.jformchecker.elements; public class PasswordInput extends TextInput implements FormCheckerElement { public static PasswordInput build(String name) { PasswordInput i = new PasswordInput(); i.name = name; return i; } @Override
public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) {
jochen777/jFormchecker
src/main/java/de/jformchecker/elements/PasswordInput.java
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/message/MessageSource.java // @FunctionalInterface // public interface MessageSource { // // public String getMessage(String key); // // public default String getSafeMessage(String key) { // try { // String msg = this.getMessage(key); // return msg; // } catch (Exception e) { // return "??" + key + "??"; // } // } // // // public default String getMessage(ValidationResult vr) { // // give translated messages higher prio than message-keys // if (vr.getTranslatedMessage() != null) { // return vr.getTranslatedMessage(); // } else // if (vr.getMessage() != null) { // return(String.format(this.getSafeMessage( // vr.getMessage() // ), vr.getErrorVals())); // // } else { // throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text"); // } // } // // }
import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.message.MessageSource;
package de.jformchecker.elements; public class PasswordInput extends TextInput implements FormCheckerElement { public static PasswordInput build(String name) { PasswordInput i = new PasswordInput(); i.name = name; return i; } @Override public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) {
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/message/MessageSource.java // @FunctionalInterface // public interface MessageSource { // // public String getMessage(String key); // // public default String getSafeMessage(String key) { // try { // String msg = this.getMessage(key); // return msg; // } catch (Exception e) { // return "??" + key + "??"; // } // } // // // public default String getMessage(ValidationResult vr) { // // give translated messages higher prio than message-keys // if (vr.getTranslatedMessage() != null) { // return vr.getTranslatedMessage(); // } else // if (vr.getMessage() != null) { // return(String.format(this.getSafeMessage( // vr.getMessage() // ), vr.getErrorVals())); // // } else { // throw new IllegalArgumentException("ValidationResult has neither message-key nor translated text"); // } // } // // } // Path: src/main/java/de/jformchecker/elements/PasswordInput.java import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.message.MessageSource; package de.jformchecker.elements; public class PasswordInput extends TextInput implements FormCheckerElement { public static PasswordInput build(String name) { PasswordInput i = new PasswordInput(); i.name = name; return i; } @Override public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation) {
TagAttributes tagAttributes = new TagAttributes(attributes);
jochen777/jFormchecker
src/main/java/de/jformchecker/themes/BasicBootstrapFormBuilder.java
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/Wrapper.java // public class Wrapper { // public final String start; // public final String end; // // public static Wrapper of(String start, String end) { // return new Wrapper(start, end); // } // // public Wrapper(String start, String end) { // this.start = start; // this.end = end; // } // // public String getStart() { // return start; // } // // public String getEnd() { // return end; // } // // public String wrap(String content) { // return new StringBuffer(start).append(content).append(end).toString(); // } // // public static Wrapper empty() { // return Wrapper.of("", ""); // } // // public static Wrapper ofTag(String tagName) { // return Wrapper.of("<" + tagName + ">", "</" + tagName + ">"); // } // // }
import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.Wrapper;
package de.jformchecker.themes; public class BasicBootstrapFormBuilder extends BasicFormBuilder { @Override
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/Wrapper.java // public class Wrapper { // public final String start; // public final String end; // // public static Wrapper of(String start, String end) { // return new Wrapper(start, end); // } // // public Wrapper(String start, String end) { // this.start = start; // this.end = end; // } // // public String getStart() { // return start; // } // // public String getEnd() { // return end; // } // // public String wrap(String content) { // return new StringBuffer(start).append(content).append(end).toString(); // } // // public static Wrapper empty() { // return Wrapper.of("", ""); // } // // public static Wrapper ofTag(String tagName) { // return Wrapper.of("<" + tagName + ">", "</" + tagName + ">"); // } // // } // Path: src/main/java/de/jformchecker/themes/BasicBootstrapFormBuilder.java import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.Wrapper; package de.jformchecker.themes; public class BasicBootstrapFormBuilder extends BasicFormBuilder { @Override
public TagAttributes getFormAttributes() {
jochen777/jFormchecker
src/main/java/de/jformchecker/themes/BasicBootstrapFormBuilder.java
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/Wrapper.java // public class Wrapper { // public final String start; // public final String end; // // public static Wrapper of(String start, String end) { // return new Wrapper(start, end); // } // // public Wrapper(String start, String end) { // this.start = start; // this.end = end; // } // // public String getStart() { // return start; // } // // public String getEnd() { // return end; // } // // public String wrap(String content) { // return new StringBuffer(start).append(content).append(end).toString(); // } // // public static Wrapper empty() { // return Wrapper.of("", ""); // } // // public static Wrapper ofTag(String tagName) { // return Wrapper.of("<" + tagName + ">", "</" + tagName + ">"); // } // // }
import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.Wrapper;
package de.jformchecker.themes; public class BasicBootstrapFormBuilder extends BasicFormBuilder { @Override public TagAttributes getFormAttributes() { TagAttributes attributes = new TagAttributes(); return attributes; } @Override
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/Wrapper.java // public class Wrapper { // public final String start; // public final String end; // // public static Wrapper of(String start, String end) { // return new Wrapper(start, end); // } // // public Wrapper(String start, String end) { // this.start = start; // this.end = end; // } // // public String getStart() { // return start; // } // // public String getEnd() { // return end; // } // // public String wrap(String content) { // return new StringBuffer(start).append(content).append(end).toString(); // } // // public static Wrapper empty() { // return Wrapper.of("", ""); // } // // public static Wrapper ofTag(String tagName) { // return Wrapper.of("<" + tagName + ">", "</" + tagName + ">"); // } // // } // Path: src/main/java/de/jformchecker/themes/BasicBootstrapFormBuilder.java import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.Wrapper; package de.jformchecker.themes; public class BasicBootstrapFormBuilder extends BasicFormBuilder { @Override public TagAttributes getFormAttributes() { TagAttributes attributes = new TagAttributes(); return attributes; } @Override
public Wrapper getWrapperForInput(FormCheckerElement elem) {
jochen777/jFormchecker
src/main/java/de/jformchecker/themes/BasicBootstrapFormBuilder.java
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/Wrapper.java // public class Wrapper { // public final String start; // public final String end; // // public static Wrapper of(String start, String end) { // return new Wrapper(start, end); // } // // public Wrapper(String start, String end) { // this.start = start; // this.end = end; // } // // public String getStart() { // return start; // } // // public String getEnd() { // return end; // } // // public String wrap(String content) { // return new StringBuffer(start).append(content).append(end).toString(); // } // // public static Wrapper empty() { // return Wrapper.of("", ""); // } // // public static Wrapper ofTag(String tagName) { // return Wrapper.of("<" + tagName + ">", "</" + tagName + ">"); // } // // }
import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.Wrapper;
package de.jformchecker.themes; public class BasicBootstrapFormBuilder extends BasicFormBuilder { @Override public TagAttributes getFormAttributes() { TagAttributes attributes = new TagAttributes(); return attributes; } @Override
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/Wrapper.java // public class Wrapper { // public final String start; // public final String end; // // public static Wrapper of(String start, String end) { // return new Wrapper(start, end); // } // // public Wrapper(String start, String end) { // this.start = start; // this.end = end; // } // // public String getStart() { // return start; // } // // public String getEnd() { // return end; // } // // public String wrap(String content) { // return new StringBuffer(start).append(content).append(end).toString(); // } // // public static Wrapper empty() { // return Wrapper.of("", ""); // } // // public static Wrapper ofTag(String tagName) { // return Wrapper.of("<" + tagName + ">", "</" + tagName + ">"); // } // // } // Path: src/main/java/de/jformchecker/themes/BasicBootstrapFormBuilder.java import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.Wrapper; package de.jformchecker.themes; public class BasicBootstrapFormBuilder extends BasicFormBuilder { @Override public TagAttributes getFormAttributes() { TagAttributes attributes = new TagAttributes(); return attributes; } @Override
public Wrapper getWrapperForInput(FormCheckerElement elem) {
jochen777/jFormchecker
src/main/java/de/jformchecker/security/XSRFBuilder.java
// Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/request/SessionGet.java // @FunctionalInterface // public interface SessionGet { // public Object getAttribute(String name); // } // // Path: src/main/java/de/jformchecker/request/SessionSet.java // @FunctionalInterface // public interface SessionSet { // public void setAttribute(String name, Object o); // }
import java.security.SecureRandom; import java.util.Base64; import com.coverity.security.Escape; import de.jformchecker.request.Request; import de.jformchecker.request.SessionGet; import de.jformchecker.request.SessionSet;
package de.jformchecker.security; public class XSRFBuilder { private final SecureRandom random = new SecureRandom();
// Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/request/SessionGet.java // @FunctionalInterface // public interface SessionGet { // public Object getAttribute(String name); // } // // Path: src/main/java/de/jformchecker/request/SessionSet.java // @FunctionalInterface // public interface SessionSet { // public void setAttribute(String name, Object o); // } // Path: src/main/java/de/jformchecker/security/XSRFBuilder.java import java.security.SecureRandom; import java.util.Base64; import com.coverity.security.Escape; import de.jformchecker.request.Request; import de.jformchecker.request.SessionGet; import de.jformchecker.request.SessionSet; package de.jformchecker.security; public class XSRFBuilder { private final SecureRandom random = new SecureRandom();
public String buildCSRFTokens(Request req, boolean firstRun, SessionGet sessionGet, SessionSet sessionSet) {
jochen777/jFormchecker
src/main/java/de/jformchecker/security/XSRFBuilder.java
// Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/request/SessionGet.java // @FunctionalInterface // public interface SessionGet { // public Object getAttribute(String name); // } // // Path: src/main/java/de/jformchecker/request/SessionSet.java // @FunctionalInterface // public interface SessionSet { // public void setAttribute(String name, Object o); // }
import java.security.SecureRandom; import java.util.Base64; import com.coverity.security.Escape; import de.jformchecker.request.Request; import de.jformchecker.request.SessionGet; import de.jformchecker.request.SessionSet;
package de.jformchecker.security; public class XSRFBuilder { private final SecureRandom random = new SecureRandom();
// Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/request/SessionGet.java // @FunctionalInterface // public interface SessionGet { // public Object getAttribute(String name); // } // // Path: src/main/java/de/jformchecker/request/SessionSet.java // @FunctionalInterface // public interface SessionSet { // public void setAttribute(String name, Object o); // } // Path: src/main/java/de/jformchecker/security/XSRFBuilder.java import java.security.SecureRandom; import java.util.Base64; import com.coverity.security.Escape; import de.jformchecker.request.Request; import de.jformchecker.request.SessionGet; import de.jformchecker.request.SessionSet; package de.jformchecker.security; public class XSRFBuilder { private final SecureRandom random = new SecureRandom();
public String buildCSRFTokens(Request req, boolean firstRun, SessionGet sessionGet, SessionSet sessionSet) {
jochen777/jFormchecker
src/main/java/de/jformchecker/security/XSRFBuilder.java
// Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/request/SessionGet.java // @FunctionalInterface // public interface SessionGet { // public Object getAttribute(String name); // } // // Path: src/main/java/de/jformchecker/request/SessionSet.java // @FunctionalInterface // public interface SessionSet { // public void setAttribute(String name, Object o); // }
import java.security.SecureRandom; import java.util.Base64; import com.coverity.security.Escape; import de.jformchecker.request.Request; import de.jformchecker.request.SessionGet; import de.jformchecker.request.SessionSet;
package de.jformchecker.security; public class XSRFBuilder { private final SecureRandom random = new SecureRandom();
// Path: src/main/java/de/jformchecker/request/Request.java // @FunctionalInterface // public interface Request { // public String getParameter(String name); // } // // Path: src/main/java/de/jformchecker/request/SessionGet.java // @FunctionalInterface // public interface SessionGet { // public Object getAttribute(String name); // } // // Path: src/main/java/de/jformchecker/request/SessionSet.java // @FunctionalInterface // public interface SessionSet { // public void setAttribute(String name, Object o); // } // Path: src/main/java/de/jformchecker/security/XSRFBuilder.java import java.security.SecureRandom; import java.util.Base64; import com.coverity.security.Escape; import de.jformchecker.request.Request; import de.jformchecker.request.SessionGet; import de.jformchecker.request.SessionSet; package de.jformchecker.security; public class XSRFBuilder { private final SecureRandom random = new SecureRandom();
public String buildCSRFTokens(Request req, boolean firstRun, SessionGet sessionGet, SessionSet sessionSet) {
jochen777/jFormchecker
src/main/java/de/jformchecker/themes/BasicMaterialLightFormBuilder.java
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/Wrapper.java // public class Wrapper { // public final String start; // public final String end; // // public static Wrapper of(String start, String end) { // return new Wrapper(start, end); // } // // public Wrapper(String start, String end) { // this.start = start; // this.end = end; // } // // public String getStart() { // return start; // } // // public String getEnd() { // return end; // } // // public String wrap(String content) { // return new StringBuffer(start).append(content).append(end).toString(); // } // // public static Wrapper empty() { // return Wrapper.of("", ""); // } // // public static Wrapper ofTag(String tagName) { // return Wrapper.of("<" + tagName + ">", "</" + tagName + ">"); // } // // }
import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.Wrapper;
package de.jformchecker.themes; public class BasicMaterialLightFormBuilder extends BasicFormBuilder { @Override
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/Wrapper.java // public class Wrapper { // public final String start; // public final String end; // // public static Wrapper of(String start, String end) { // return new Wrapper(start, end); // } // // public Wrapper(String start, String end) { // this.start = start; // this.end = end; // } // // public String getStart() { // return start; // } // // public String getEnd() { // return end; // } // // public String wrap(String content) { // return new StringBuffer(start).append(content).append(end).toString(); // } // // public static Wrapper empty() { // return Wrapper.of("", ""); // } // // public static Wrapper ofTag(String tagName) { // return Wrapper.of("<" + tagName + ">", "</" + tagName + ">"); // } // // } // Path: src/main/java/de/jformchecker/themes/BasicMaterialLightFormBuilder.java import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.Wrapper; package de.jformchecker.themes; public class BasicMaterialLightFormBuilder extends BasicFormBuilder { @Override
public TagAttributes getFormAttributes() {
jochen777/jFormchecker
src/main/java/de/jformchecker/themes/BasicMaterialLightFormBuilder.java
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/Wrapper.java // public class Wrapper { // public final String start; // public final String end; // // public static Wrapper of(String start, String end) { // return new Wrapper(start, end); // } // // public Wrapper(String start, String end) { // this.start = start; // this.end = end; // } // // public String getStart() { // return start; // } // // public String getEnd() { // return end; // } // // public String wrap(String content) { // return new StringBuffer(start).append(content).append(end).toString(); // } // // public static Wrapper empty() { // return Wrapper.of("", ""); // } // // public static Wrapper ofTag(String tagName) { // return Wrapper.of("<" + tagName + ">", "</" + tagName + ">"); // } // // }
import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.Wrapper;
package de.jformchecker.themes; public class BasicMaterialLightFormBuilder extends BasicFormBuilder { @Override public TagAttributes getFormAttributes() { TagAttributes attributes = new TagAttributes(); return attributes; } @Override
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/Wrapper.java // public class Wrapper { // public final String start; // public final String end; // // public static Wrapper of(String start, String end) { // return new Wrapper(start, end); // } // // public Wrapper(String start, String end) { // this.start = start; // this.end = end; // } // // public String getStart() { // return start; // } // // public String getEnd() { // return end; // } // // public String wrap(String content) { // return new StringBuffer(start).append(content).append(end).toString(); // } // // public static Wrapper empty() { // return Wrapper.of("", ""); // } // // public static Wrapper ofTag(String tagName) { // return Wrapper.of("<" + tagName + ">", "</" + tagName + ">"); // } // // } // Path: src/main/java/de/jformchecker/themes/BasicMaterialLightFormBuilder.java import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.Wrapper; package de.jformchecker.themes; public class BasicMaterialLightFormBuilder extends BasicFormBuilder { @Override public TagAttributes getFormAttributes() { TagAttributes attributes = new TagAttributes(); return attributes; } @Override
public Wrapper getWrapperForInput(FormCheckerElement elem) {
jochen777/jFormchecker
src/main/java/de/jformchecker/themes/BasicMaterialLightFormBuilder.java
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/Wrapper.java // public class Wrapper { // public final String start; // public final String end; // // public static Wrapper of(String start, String end) { // return new Wrapper(start, end); // } // // public Wrapper(String start, String end) { // this.start = start; // this.end = end; // } // // public String getStart() { // return start; // } // // public String getEnd() { // return end; // } // // public String wrap(String content) { // return new StringBuffer(start).append(content).append(end).toString(); // } // // public static Wrapper empty() { // return Wrapper.of("", ""); // } // // public static Wrapper ofTag(String tagName) { // return Wrapper.of("<" + tagName + ">", "</" + tagName + ">"); // } // // }
import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.Wrapper;
package de.jformchecker.themes; public class BasicMaterialLightFormBuilder extends BasicFormBuilder { @Override public TagAttributes getFormAttributes() { TagAttributes attributes = new TagAttributes(); return attributes; } @Override
// Path: src/main/java/de/jformchecker/FormCheckerElement.java // public interface FormCheckerElement { // // // RFE: check, if some methods can be protected // // // get internal name of this input-element // public String getName(); // // // set internal name // public void setName(String name); // // // // get the value that the user entered // public String getValue(); // // // get the value that the user entered, but html-encoded // @Deprecated // public String getValueHtmlEncoded(); // // public void setValue(String value); // // public String getPreSetValue(); // // // set an initial value to the element, before the user edited it. // public <T extends FormCheckerElement> T setPreSetValue(String value); // // public <T extends FormCheckerElement> T setTabIndex(int tabIndex); // // public int getTabIndex(); // // public int getLastTabIndex(); // // // set the test in the label (builder pattern) // // public <T extends FormCheckerElement> T setDescription(String desc); // // // as "setDescription" but does not return anything (no builder pattern) // public void changeDescription(String desc); // // public String getDescription(); // // // returns true if element is valid // public boolean isValid(); // // public void setInvalid(); // // // inits the value with the current http-request // public void init(Request req, boolean firstrun, Validator validator); // // public ValidationResult getValidationResult(); // // public void setValidationResult(ValidationResult validationResult); // // public String getInputTag(); // // public String getInputTag(Map<String, String> attributes, MessageSource messageSource, boolean html5Validation); // // @Deprecated // public String getInputTag(Map<String, String> attributes); // // public boolean isRequired(); // // public <T extends FormCheckerElement> T setRequired(); // // public List<Criterion> getCriteria(); // // public void setFormChecker(FormChecker fc); // // // returns the complete label-html tag // public String getLabel(); // // // returns the label-html and the input-html // public String getCompleteInput(); // RFE: Perhaps toString makes this even // // more convenient?! // // public String getHelpText(); // // // sets the size attribute // public <T extends FormCheckerElement> T setSize(int size); // // public String getType(); // // } // // Path: src/main/java/de/jformchecker/TagAttributes.java // public class TagAttributes { // // // conveniance methods // public static TagAttributes of(String key, String value) { // return new TagAttributes(key, value); // } // // public static TagAttributes of(Map<String, String> attribs) { // return new TagAttributes(attribs); // } // // LinkedHashMap<String, String> attributes; // // public TagAttributes(Map<String, String> attribs) { // attributes = new LinkedHashMap<>(attribs); // } // // public TagAttributes(LinkedHashMap<String, String> attribs) { // attributes = attribs; // } // // public TagAttributes() { // this(new LinkedHashMap<>()); // } // // public TagAttributes(String key, String value) { // this(); // this.put(key, value); // } // // public TagAttributes put(String key, String value) { // attributes.put(key, value); // return this; // } // // public String get(String key) { // return attributes.get(key); // } // // public void addToAttribute(String key, String value) { // if (!attributes.containsKey(key)) { // attributes.put(key, value); // } else { // attributes.put(key, attributes.get(key) + value); // } // } // // public Set<String> keySet() { // return attributes.keySet(); // } // // public Map<String, String> getAttributes() { // return attributes; // } // // public void add(TagAttributes formAttributes) { // if (formAttributes != null) { // formAttributes.attributes.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // public void add(LinkedHashMap<String, String> attribs) { // if (attribs != null) { // attribs.forEach((key, value) -> this.addToAttribute(key, value)); // } // } // // } // // Path: src/main/java/de/jformchecker/Wrapper.java // public class Wrapper { // public final String start; // public final String end; // // public static Wrapper of(String start, String end) { // return new Wrapper(start, end); // } // // public Wrapper(String start, String end) { // this.start = start; // this.end = end; // } // // public String getStart() { // return start; // } // // public String getEnd() { // return end; // } // // public String wrap(String content) { // return new StringBuffer(start).append(content).append(end).toString(); // } // // public static Wrapper empty() { // return Wrapper.of("", ""); // } // // public static Wrapper ofTag(String tagName) { // return Wrapper.of("<" + tagName + ">", "</" + tagName + ">"); // } // // } // Path: src/main/java/de/jformchecker/themes/BasicMaterialLightFormBuilder.java import java.util.Map; import de.jformchecker.FormCheckerElement; import de.jformchecker.TagAttributes; import de.jformchecker.Wrapper; package de.jformchecker.themes; public class BasicMaterialLightFormBuilder extends BasicFormBuilder { @Override public TagAttributes getFormAttributes() { TagAttributes attributes = new TagAttributes(); return attributes; } @Override
public Wrapper getWrapperForInput(FormCheckerElement elem) {