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
tensorchen/rrs
src/main/java/cn/com/chenyixiao/rrs/dao/impl/UserDAOImpl.java
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/UserDAO.java // public interface UserDAO { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // }
import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import cn.com.chenyixiao.rrs.dao.UserDAO; import cn.com.chenyixiao.rrs.entity.User;
package cn.com.chenyixiao.rrs.dao.impl; @Repository public class UserDAOImpl implements UserDAO { @Autowired private SessionFactory sessionFactory; private Session getCurrentSession() { return sessionFactory.getCurrentSession(); }
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/UserDAO.java // public interface UserDAO { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // } // Path: src/main/java/cn/com/chenyixiao/rrs/dao/impl/UserDAOImpl.java import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import cn.com.chenyixiao.rrs.dao.UserDAO; import cn.com.chenyixiao.rrs.entity.User; package cn.com.chenyixiao.rrs.dao.impl; @Repository public class UserDAOImpl implements UserDAO { @Autowired private SessionFactory sessionFactory; private Session getCurrentSession() { return sessionFactory.getCurrentSession(); }
public void addUser(User user) {
tensorchen/rrs
src/main/java/cn/com/chenyixiao/rrs/service/impl/RestaurantServiceImpl.java
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/RestaurantDAO.java // public interface RestaurantDAO { // // public void addRestaurant(Restaurant restaurant); // public void updateRestaurant(Restaurant restaurant); // public Restaurant getRestaurant(Long id); // public List<Restaurant> getAllRestaurants(); // public void deleteRestaurant(Long id); // public void deleteAllRestaurants(); // // public Long count(); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/Restaurant.java // @Entity // @Table(name = "restaurant", catalog = "rrs") // public class Restaurant implements java.io.Serializable { // // private long id; // private String name; // private String category; // private String region; // // public Restaurant() { // } // // public Restaurant(long id) { // this.id = id; // } // // public Restaurant(long id, String name, String category, String region) { // this.id = id; // this.name = name; // this.category = category; // this.region = region; // } // // @Id // // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // @Column(name = "category", length = 45) // public String getCategory() { // return this.category; // } // // public void setCategory(String category) { // this.category = category; // } // // @Column(name = "region", length = 45) // public String getRegion() { // return this.region; // } // // public void setRegion(String region) { // this.region = region; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/RestaurantService.java // public interface RestaurantService { // // public void addRestaurant(Restaurant restaurant); // public void updateRestaurant(Restaurant restaurant); // public Restaurant getRestaurant(Long id); // public List<Restaurant> getAllRestaurants(); // public void deleteRestaurant(Long id); // public void deleteAllRestaurants(); // // public Long count(); // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.RestaurantDAO; import cn.com.chenyixiao.rrs.entity.Restaurant; import cn.com.chenyixiao.rrs.service.RestaurantService;
package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/RestaurantDAO.java // public interface RestaurantDAO { // // public void addRestaurant(Restaurant restaurant); // public void updateRestaurant(Restaurant restaurant); // public Restaurant getRestaurant(Long id); // public List<Restaurant> getAllRestaurants(); // public void deleteRestaurant(Long id); // public void deleteAllRestaurants(); // // public Long count(); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/Restaurant.java // @Entity // @Table(name = "restaurant", catalog = "rrs") // public class Restaurant implements java.io.Serializable { // // private long id; // private String name; // private String category; // private String region; // // public Restaurant() { // } // // public Restaurant(long id) { // this.id = id; // } // // public Restaurant(long id, String name, String category, String region) { // this.id = id; // this.name = name; // this.category = category; // this.region = region; // } // // @Id // // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // @Column(name = "category", length = 45) // public String getCategory() { // return this.category; // } // // public void setCategory(String category) { // this.category = category; // } // // @Column(name = "region", length = 45) // public String getRegion() { // return this.region; // } // // public void setRegion(String region) { // this.region = region; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/RestaurantService.java // public interface RestaurantService { // // public void addRestaurant(Restaurant restaurant); // public void updateRestaurant(Restaurant restaurant); // public Restaurant getRestaurant(Long id); // public List<Restaurant> getAllRestaurants(); // public void deleteRestaurant(Long id); // public void deleteAllRestaurants(); // // public Long count(); // } // Path: src/main/java/cn/com/chenyixiao/rrs/service/impl/RestaurantServiceImpl.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.RestaurantDAO; import cn.com.chenyixiao.rrs.entity.Restaurant; import cn.com.chenyixiao.rrs.service.RestaurantService; package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional
public class RestaurantServiceImpl implements RestaurantService {
tensorchen/rrs
src/main/java/cn/com/chenyixiao/rrs/service/impl/RestaurantServiceImpl.java
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/RestaurantDAO.java // public interface RestaurantDAO { // // public void addRestaurant(Restaurant restaurant); // public void updateRestaurant(Restaurant restaurant); // public Restaurant getRestaurant(Long id); // public List<Restaurant> getAllRestaurants(); // public void deleteRestaurant(Long id); // public void deleteAllRestaurants(); // // public Long count(); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/Restaurant.java // @Entity // @Table(name = "restaurant", catalog = "rrs") // public class Restaurant implements java.io.Serializable { // // private long id; // private String name; // private String category; // private String region; // // public Restaurant() { // } // // public Restaurant(long id) { // this.id = id; // } // // public Restaurant(long id, String name, String category, String region) { // this.id = id; // this.name = name; // this.category = category; // this.region = region; // } // // @Id // // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // @Column(name = "category", length = 45) // public String getCategory() { // return this.category; // } // // public void setCategory(String category) { // this.category = category; // } // // @Column(name = "region", length = 45) // public String getRegion() { // return this.region; // } // // public void setRegion(String region) { // this.region = region; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/RestaurantService.java // public interface RestaurantService { // // public void addRestaurant(Restaurant restaurant); // public void updateRestaurant(Restaurant restaurant); // public Restaurant getRestaurant(Long id); // public List<Restaurant> getAllRestaurants(); // public void deleteRestaurant(Long id); // public void deleteAllRestaurants(); // // public Long count(); // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.RestaurantDAO; import cn.com.chenyixiao.rrs.entity.Restaurant; import cn.com.chenyixiao.rrs.service.RestaurantService;
package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional public class RestaurantServiceImpl implements RestaurantService { @Autowired
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/RestaurantDAO.java // public interface RestaurantDAO { // // public void addRestaurant(Restaurant restaurant); // public void updateRestaurant(Restaurant restaurant); // public Restaurant getRestaurant(Long id); // public List<Restaurant> getAllRestaurants(); // public void deleteRestaurant(Long id); // public void deleteAllRestaurants(); // // public Long count(); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/Restaurant.java // @Entity // @Table(name = "restaurant", catalog = "rrs") // public class Restaurant implements java.io.Serializable { // // private long id; // private String name; // private String category; // private String region; // // public Restaurant() { // } // // public Restaurant(long id) { // this.id = id; // } // // public Restaurant(long id, String name, String category, String region) { // this.id = id; // this.name = name; // this.category = category; // this.region = region; // } // // @Id // // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // @Column(name = "category", length = 45) // public String getCategory() { // return this.category; // } // // public void setCategory(String category) { // this.category = category; // } // // @Column(name = "region", length = 45) // public String getRegion() { // return this.region; // } // // public void setRegion(String region) { // this.region = region; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/RestaurantService.java // public interface RestaurantService { // // public void addRestaurant(Restaurant restaurant); // public void updateRestaurant(Restaurant restaurant); // public Restaurant getRestaurant(Long id); // public List<Restaurant> getAllRestaurants(); // public void deleteRestaurant(Long id); // public void deleteAllRestaurants(); // // public Long count(); // } // Path: src/main/java/cn/com/chenyixiao/rrs/service/impl/RestaurantServiceImpl.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.RestaurantDAO; import cn.com.chenyixiao.rrs.entity.Restaurant; import cn.com.chenyixiao.rrs.service.RestaurantService; package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional public class RestaurantServiceImpl implements RestaurantService { @Autowired
private RestaurantDAO restaurantDAO;
tensorchen/rrs
src/main/java/cn/com/chenyixiao/rrs/service/impl/RestaurantServiceImpl.java
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/RestaurantDAO.java // public interface RestaurantDAO { // // public void addRestaurant(Restaurant restaurant); // public void updateRestaurant(Restaurant restaurant); // public Restaurant getRestaurant(Long id); // public List<Restaurant> getAllRestaurants(); // public void deleteRestaurant(Long id); // public void deleteAllRestaurants(); // // public Long count(); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/Restaurant.java // @Entity // @Table(name = "restaurant", catalog = "rrs") // public class Restaurant implements java.io.Serializable { // // private long id; // private String name; // private String category; // private String region; // // public Restaurant() { // } // // public Restaurant(long id) { // this.id = id; // } // // public Restaurant(long id, String name, String category, String region) { // this.id = id; // this.name = name; // this.category = category; // this.region = region; // } // // @Id // // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // @Column(name = "category", length = 45) // public String getCategory() { // return this.category; // } // // public void setCategory(String category) { // this.category = category; // } // // @Column(name = "region", length = 45) // public String getRegion() { // return this.region; // } // // public void setRegion(String region) { // this.region = region; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/RestaurantService.java // public interface RestaurantService { // // public void addRestaurant(Restaurant restaurant); // public void updateRestaurant(Restaurant restaurant); // public Restaurant getRestaurant(Long id); // public List<Restaurant> getAllRestaurants(); // public void deleteRestaurant(Long id); // public void deleteAllRestaurants(); // // public Long count(); // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.RestaurantDAO; import cn.com.chenyixiao.rrs.entity.Restaurant; import cn.com.chenyixiao.rrs.service.RestaurantService;
package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional public class RestaurantServiceImpl implements RestaurantService { @Autowired private RestaurantDAO restaurantDAO;
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/RestaurantDAO.java // public interface RestaurantDAO { // // public void addRestaurant(Restaurant restaurant); // public void updateRestaurant(Restaurant restaurant); // public Restaurant getRestaurant(Long id); // public List<Restaurant> getAllRestaurants(); // public void deleteRestaurant(Long id); // public void deleteAllRestaurants(); // // public Long count(); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/Restaurant.java // @Entity // @Table(name = "restaurant", catalog = "rrs") // public class Restaurant implements java.io.Serializable { // // private long id; // private String name; // private String category; // private String region; // // public Restaurant() { // } // // public Restaurant(long id) { // this.id = id; // } // // public Restaurant(long id, String name, String category, String region) { // this.id = id; // this.name = name; // this.category = category; // this.region = region; // } // // @Id // // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // @Column(name = "category", length = 45) // public String getCategory() { // return this.category; // } // // public void setCategory(String category) { // this.category = category; // } // // @Column(name = "region", length = 45) // public String getRegion() { // return this.region; // } // // public void setRegion(String region) { // this.region = region; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/RestaurantService.java // public interface RestaurantService { // // public void addRestaurant(Restaurant restaurant); // public void updateRestaurant(Restaurant restaurant); // public Restaurant getRestaurant(Long id); // public List<Restaurant> getAllRestaurants(); // public void deleteRestaurant(Long id); // public void deleteAllRestaurants(); // // public Long count(); // } // Path: src/main/java/cn/com/chenyixiao/rrs/service/impl/RestaurantServiceImpl.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.RestaurantDAO; import cn.com.chenyixiao.rrs.entity.Restaurant; import cn.com.chenyixiao.rrs.service.RestaurantService; package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional public class RestaurantServiceImpl implements RestaurantService { @Autowired private RestaurantDAO restaurantDAO;
public void addRestaurant(Restaurant restaurant) {
tensorchen/rrs
src/main/java/cn/com/chenyixiao/rrs/service/impl/UserServiceImpl.java
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/UserDAO.java // public interface UserDAO { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/UserService.java // public interface UserService { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.UserDAO; import cn.com.chenyixiao.rrs.entity.User; import cn.com.chenyixiao.rrs.service.UserService;
package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/UserDAO.java // public interface UserDAO { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/UserService.java // public interface UserService { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // Path: src/main/java/cn/com/chenyixiao/rrs/service/impl/UserServiceImpl.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.UserDAO; import cn.com.chenyixiao.rrs.entity.User; import cn.com.chenyixiao.rrs.service.UserService; package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional
public class UserServiceImpl implements UserService {
tensorchen/rrs
src/main/java/cn/com/chenyixiao/rrs/service/impl/UserServiceImpl.java
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/UserDAO.java // public interface UserDAO { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/UserService.java // public interface UserService { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.UserDAO; import cn.com.chenyixiao.rrs.entity.User; import cn.com.chenyixiao.rrs.service.UserService;
package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/UserDAO.java // public interface UserDAO { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/UserService.java // public interface UserService { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // Path: src/main/java/cn/com/chenyixiao/rrs/service/impl/UserServiceImpl.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.UserDAO; import cn.com.chenyixiao.rrs.entity.User; import cn.com.chenyixiao.rrs.service.UserService; package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired
private UserDAO userDAO;
tensorchen/rrs
src/main/java/cn/com/chenyixiao/rrs/service/impl/UserServiceImpl.java
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/UserDAO.java // public interface UserDAO { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/UserService.java // public interface UserService { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.UserDAO; import cn.com.chenyixiao.rrs.entity.User; import cn.com.chenyixiao.rrs.service.UserService;
package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserDAO userDAO;
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/UserDAO.java // public interface UserDAO { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/UserService.java // public interface UserService { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // Path: src/main/java/cn/com/chenyixiao/rrs/service/impl/UserServiceImpl.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.UserDAO; import cn.com.chenyixiao.rrs.entity.User; import cn.com.chenyixiao.rrs.service.UserService; package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserDAO userDAO;
public void addUser(User user) {
tensorchen/rrs
src/main/java/cn/com/chenyixiao/rrs/controller/UserController.java
// Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/UserService.java // public interface UserService { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.Gson; import cn.com.chenyixiao.rrs.entity.User; import cn.com.chenyixiao.rrs.service.UserService;
package cn.com.chenyixiao.rrs.controller; @Controller @RequestMapping(produces="application/json;charset=UTF-8", consumes="application/json;charset=UTF-8") public class UserController { @Autowired
// Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/UserService.java // public interface UserService { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // Path: src/main/java/cn/com/chenyixiao/rrs/controller/UserController.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.Gson; import cn.com.chenyixiao.rrs.entity.User; import cn.com.chenyixiao.rrs.service.UserService; package cn.com.chenyixiao.rrs.controller; @Controller @RequestMapping(produces="application/json;charset=UTF-8", consumes="application/json;charset=UTF-8") public class UserController { @Autowired
private UserService userService;
tensorchen/rrs
src/main/java/cn/com/chenyixiao/rrs/controller/UserController.java
// Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/UserService.java // public interface UserService { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.Gson; import cn.com.chenyixiao.rrs.entity.User; import cn.com.chenyixiao.rrs.service.UserService;
package cn.com.chenyixiao.rrs.controller; @Controller @RequestMapping(produces="application/json;charset=UTF-8", consumes="application/json;charset=UTF-8") public class UserController { @Autowired private UserService userService; @ResponseBody @RequestMapping(value="/user", method = RequestMethod.POST)
// Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/UserService.java // public interface UserService { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // Path: src/main/java/cn/com/chenyixiao/rrs/controller/UserController.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.Gson; import cn.com.chenyixiao.rrs.entity.User; import cn.com.chenyixiao.rrs.service.UserService; package cn.com.chenyixiao.rrs.controller; @Controller @RequestMapping(produces="application/json;charset=UTF-8", consumes="application/json;charset=UTF-8") public class UserController { @Autowired private UserService userService; @ResponseBody @RequestMapping(value="/user", method = RequestMethod.POST)
public String addUser(@RequestBody User user) {
tensorchen/rrs
src/main/java/cn/com/chenyixiao/rrs/util/DataLoader.java
// Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/UserService.java // public interface UserService { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/vo/PreferenceVO.java // public class PreferenceVO { // // private Long userId; // private String userName; // private List<Double> scores; // private List<String> recommendFoods; // // public PreferenceVO() { // } // // public PreferenceVO(Long userId, String userName, List<Double> scores, List<String> recommendFoods) { // this.userId = userId; // this.userName = userName; // this.scores = scores; // this.recommendFoods = recommendFoods; // } // // // // public Long getUserId() { // return userId; // } // public void setUserId(Long userId) { // this.userId = userId; // } // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public List<Double> getScores() { // return scores; // } // public void setScores(List<Double> scores) { // this.scores = scores; // } // public List<String> getRecommendFoods() { // return recommendFoods; // } // public void setRecommendFoods(List<String> recommendFoods) { // this.recommendFoods = recommendFoods; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/vo/Rrs.java // public class Rrs { // private Long restaurantId; // private String restaurantName; // private String restaurantRegion; // private String restaurantCategory; // // private List<FoodVO> foods; // private List<PreferenceVO> preferences; // // // public Rrs() { // } // // public Rrs(Long restaurantId, String restaurantName, String restaurantRegion, String restaurantCategory, // List<FoodVO> foods, List<PreferenceVO> preferences) { // this.restaurantId = restaurantId; // this.restaurantName = restaurantName; // this.restaurantRegion = restaurantRegion; // this.restaurantCategory = restaurantCategory; // this.foods = foods; // this.preferences = preferences; // } // // public Long getRestaurantId() { // return restaurantId; // } // public void setRestaurantId(Long restaurantId) { // this.restaurantId = restaurantId; // } // public String getRestaurantName() { // return restaurantName; // } // public void setRestaurantName(String restaurantName) { // this.restaurantName = restaurantName; // } // public String getRestaurantRegion() { // return restaurantRegion; // } // public void setRestaurantRegion(String restaurantRegion) { // this.restaurantRegion = restaurantRegion; // } // public String getRestaurantCategory() { // return restaurantCategory; // } // public void setRestaurantCategory(String restaurantCategory) { // this.restaurantCategory = restaurantCategory; // } // public List<FoodVO> getFoods() { // return foods; // } // public void setFoods(List<FoodVO> foods) { // this.foods = foods; // } // public List<PreferenceVO> getPreferences() { // return preferences; // } // public void setPreferences(List<PreferenceVO> preferences) { // this.preferences = preferences; // } // // // }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import com.google.gson.Gson; import cn.com.chenyixiao.rrs.entity.User; import cn.com.chenyixiao.rrs.service.UserService; import cn.com.chenyixiao.rrs.vo.PreferenceVO; import cn.com.chenyixiao.rrs.vo.Rrs;
package cn.com.chenyixiao.rrs.util; public class DataLoader { private static final String dataFile = "D://data/dianping.json"; @Autowired
// Path: src/main/java/cn/com/chenyixiao/rrs/entity/User.java // @Entity // @Table(name = "user", catalog = "rrs") // public class User implements java.io.Serializable { // // private long id; // private String name; // // public User() { // } // // public User(long id) { // this.id = id; // } // // public User(long id, String name) { // this.id = id; // this.name = name; // } // // @Id // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "name") // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/UserService.java // public interface UserService { // // public void addUser(User user); // public void updateUser(User user); // public User getUser(Long id); // public List<User> getAllUsers(); // public void deleteUser(Long id); // public void deleteAllUsers(); // // public Long count(); // // public User getUserByName(String name); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/vo/PreferenceVO.java // public class PreferenceVO { // // private Long userId; // private String userName; // private List<Double> scores; // private List<String> recommendFoods; // // public PreferenceVO() { // } // // public PreferenceVO(Long userId, String userName, List<Double> scores, List<String> recommendFoods) { // this.userId = userId; // this.userName = userName; // this.scores = scores; // this.recommendFoods = recommendFoods; // } // // // // public Long getUserId() { // return userId; // } // public void setUserId(Long userId) { // this.userId = userId; // } // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public List<Double> getScores() { // return scores; // } // public void setScores(List<Double> scores) { // this.scores = scores; // } // public List<String> getRecommendFoods() { // return recommendFoods; // } // public void setRecommendFoods(List<String> recommendFoods) { // this.recommendFoods = recommendFoods; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/vo/Rrs.java // public class Rrs { // private Long restaurantId; // private String restaurantName; // private String restaurantRegion; // private String restaurantCategory; // // private List<FoodVO> foods; // private List<PreferenceVO> preferences; // // // public Rrs() { // } // // public Rrs(Long restaurantId, String restaurantName, String restaurantRegion, String restaurantCategory, // List<FoodVO> foods, List<PreferenceVO> preferences) { // this.restaurantId = restaurantId; // this.restaurantName = restaurantName; // this.restaurantRegion = restaurantRegion; // this.restaurantCategory = restaurantCategory; // this.foods = foods; // this.preferences = preferences; // } // // public Long getRestaurantId() { // return restaurantId; // } // public void setRestaurantId(Long restaurantId) { // this.restaurantId = restaurantId; // } // public String getRestaurantName() { // return restaurantName; // } // public void setRestaurantName(String restaurantName) { // this.restaurantName = restaurantName; // } // public String getRestaurantRegion() { // return restaurantRegion; // } // public void setRestaurantRegion(String restaurantRegion) { // this.restaurantRegion = restaurantRegion; // } // public String getRestaurantCategory() { // return restaurantCategory; // } // public void setRestaurantCategory(String restaurantCategory) { // this.restaurantCategory = restaurantCategory; // } // public List<FoodVO> getFoods() { // return foods; // } // public void setFoods(List<FoodVO> foods) { // this.foods = foods; // } // public List<PreferenceVO> getPreferences() { // return preferences; // } // public void setPreferences(List<PreferenceVO> preferences) { // this.preferences = preferences; // } // // // } // Path: src/main/java/cn/com/chenyixiao/rrs/util/DataLoader.java import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import com.google.gson.Gson; import cn.com.chenyixiao.rrs.entity.User; import cn.com.chenyixiao.rrs.service.UserService; import cn.com.chenyixiao.rrs.vo.PreferenceVO; import cn.com.chenyixiao.rrs.vo.Rrs; package cn.com.chenyixiao.rrs.util; public class DataLoader { private static final String dataFile = "D://data/dianping.json"; @Autowired
private static UserService userService;
tensorchen/rrs
src/main/java/cn/com/chenyixiao/rrs/service/impl/Preference2dServiceImpl.java
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/Preference2dDAO.java // public interface Preference2dDAO { // // public void addPreference2d(Preference2d preference2d); // public void updatePreference2d(Preference2d preference2d); // public Preference2d getPreference2d(Long id); // public List<Preference2d> getAllPreference2ds(); // public void deletePreference2d(Long id); // public void deleteAllPreference2d(); // // public Long count(); // // public List<Preference2d> getPreferencesByUserId(Long userId); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/Preference2d.java // @Entity // @Table(name = "preference2d", catalog = "rrs") // public class Preference2d implements java.io.Serializable { // // private long id; // private Long restaurantId; // private Long userId; // private Double score; // // public Preference2d() { // } // // public Preference2d(long id) { // this.id = id; // } // // public Preference2d(long id, Long restaurantId, Long userId, Double score) { // this.id = id; // this.restaurantId = restaurantId; // this.userId = userId; // this.score = score; // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "restaurant_id") // public Long getRestaurantId() { // return this.restaurantId; // } // // public void setRestaurantId(Long restaurantId) { // this.restaurantId = restaurantId; // } // // @Column(name = "user_id") // public Long getUserId() { // return this.userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // @Column(name = "score", precision = 22, scale = 0) // public Double getScore() { // return this.score; // } // // public void setScore(Double score) { // this.score = score; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/Preference2dService.java // public interface Preference2dService { // // public void addPreference2d(Preference2d preference2d); // public void updatePreference2d(Preference2d preference2d); // public Preference2d getPreference2d(Long id); // public List<Preference2d> getAllPreference2ds(); // public void deletePreference2d(Long id); // public void deleteAllPreference2d(); // // public Long count(); // // public List<Preference2d> getPreferencesByUserId(Long userId); // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.Preference2dDAO; import cn.com.chenyixiao.rrs.entity.Preference2d; import cn.com.chenyixiao.rrs.service.Preference2dService;
package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/Preference2dDAO.java // public interface Preference2dDAO { // // public void addPreference2d(Preference2d preference2d); // public void updatePreference2d(Preference2d preference2d); // public Preference2d getPreference2d(Long id); // public List<Preference2d> getAllPreference2ds(); // public void deletePreference2d(Long id); // public void deleteAllPreference2d(); // // public Long count(); // // public List<Preference2d> getPreferencesByUserId(Long userId); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/Preference2d.java // @Entity // @Table(name = "preference2d", catalog = "rrs") // public class Preference2d implements java.io.Serializable { // // private long id; // private Long restaurantId; // private Long userId; // private Double score; // // public Preference2d() { // } // // public Preference2d(long id) { // this.id = id; // } // // public Preference2d(long id, Long restaurantId, Long userId, Double score) { // this.id = id; // this.restaurantId = restaurantId; // this.userId = userId; // this.score = score; // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "restaurant_id") // public Long getRestaurantId() { // return this.restaurantId; // } // // public void setRestaurantId(Long restaurantId) { // this.restaurantId = restaurantId; // } // // @Column(name = "user_id") // public Long getUserId() { // return this.userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // @Column(name = "score", precision = 22, scale = 0) // public Double getScore() { // return this.score; // } // // public void setScore(Double score) { // this.score = score; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/Preference2dService.java // public interface Preference2dService { // // public void addPreference2d(Preference2d preference2d); // public void updatePreference2d(Preference2d preference2d); // public Preference2d getPreference2d(Long id); // public List<Preference2d> getAllPreference2ds(); // public void deletePreference2d(Long id); // public void deleteAllPreference2d(); // // public Long count(); // // public List<Preference2d> getPreferencesByUserId(Long userId); // } // Path: src/main/java/cn/com/chenyixiao/rrs/service/impl/Preference2dServiceImpl.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.Preference2dDAO; import cn.com.chenyixiao.rrs.entity.Preference2d; import cn.com.chenyixiao.rrs.service.Preference2dService; package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional
public class Preference2dServiceImpl implements Preference2dService {
tensorchen/rrs
src/main/java/cn/com/chenyixiao/rrs/service/impl/Preference2dServiceImpl.java
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/Preference2dDAO.java // public interface Preference2dDAO { // // public void addPreference2d(Preference2d preference2d); // public void updatePreference2d(Preference2d preference2d); // public Preference2d getPreference2d(Long id); // public List<Preference2d> getAllPreference2ds(); // public void deletePreference2d(Long id); // public void deleteAllPreference2d(); // // public Long count(); // // public List<Preference2d> getPreferencesByUserId(Long userId); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/Preference2d.java // @Entity // @Table(name = "preference2d", catalog = "rrs") // public class Preference2d implements java.io.Serializable { // // private long id; // private Long restaurantId; // private Long userId; // private Double score; // // public Preference2d() { // } // // public Preference2d(long id) { // this.id = id; // } // // public Preference2d(long id, Long restaurantId, Long userId, Double score) { // this.id = id; // this.restaurantId = restaurantId; // this.userId = userId; // this.score = score; // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "restaurant_id") // public Long getRestaurantId() { // return this.restaurantId; // } // // public void setRestaurantId(Long restaurantId) { // this.restaurantId = restaurantId; // } // // @Column(name = "user_id") // public Long getUserId() { // return this.userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // @Column(name = "score", precision = 22, scale = 0) // public Double getScore() { // return this.score; // } // // public void setScore(Double score) { // this.score = score; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/Preference2dService.java // public interface Preference2dService { // // public void addPreference2d(Preference2d preference2d); // public void updatePreference2d(Preference2d preference2d); // public Preference2d getPreference2d(Long id); // public List<Preference2d> getAllPreference2ds(); // public void deletePreference2d(Long id); // public void deleteAllPreference2d(); // // public Long count(); // // public List<Preference2d> getPreferencesByUserId(Long userId); // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.Preference2dDAO; import cn.com.chenyixiao.rrs.entity.Preference2d; import cn.com.chenyixiao.rrs.service.Preference2dService;
package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional public class Preference2dServiceImpl implements Preference2dService { @Autowired
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/Preference2dDAO.java // public interface Preference2dDAO { // // public void addPreference2d(Preference2d preference2d); // public void updatePreference2d(Preference2d preference2d); // public Preference2d getPreference2d(Long id); // public List<Preference2d> getAllPreference2ds(); // public void deletePreference2d(Long id); // public void deleteAllPreference2d(); // // public Long count(); // // public List<Preference2d> getPreferencesByUserId(Long userId); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/Preference2d.java // @Entity // @Table(name = "preference2d", catalog = "rrs") // public class Preference2d implements java.io.Serializable { // // private long id; // private Long restaurantId; // private Long userId; // private Double score; // // public Preference2d() { // } // // public Preference2d(long id) { // this.id = id; // } // // public Preference2d(long id, Long restaurantId, Long userId, Double score) { // this.id = id; // this.restaurantId = restaurantId; // this.userId = userId; // this.score = score; // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "restaurant_id") // public Long getRestaurantId() { // return this.restaurantId; // } // // public void setRestaurantId(Long restaurantId) { // this.restaurantId = restaurantId; // } // // @Column(name = "user_id") // public Long getUserId() { // return this.userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // @Column(name = "score", precision = 22, scale = 0) // public Double getScore() { // return this.score; // } // // public void setScore(Double score) { // this.score = score; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/Preference2dService.java // public interface Preference2dService { // // public void addPreference2d(Preference2d preference2d); // public void updatePreference2d(Preference2d preference2d); // public Preference2d getPreference2d(Long id); // public List<Preference2d> getAllPreference2ds(); // public void deletePreference2d(Long id); // public void deleteAllPreference2d(); // // public Long count(); // // public List<Preference2d> getPreferencesByUserId(Long userId); // } // Path: src/main/java/cn/com/chenyixiao/rrs/service/impl/Preference2dServiceImpl.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.Preference2dDAO; import cn.com.chenyixiao.rrs.entity.Preference2d; import cn.com.chenyixiao.rrs.service.Preference2dService; package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional public class Preference2dServiceImpl implements Preference2dService { @Autowired
private Preference2dDAO preference2dDAO;
tensorchen/rrs
src/main/java/cn/com/chenyixiao/rrs/service/impl/Preference2dServiceImpl.java
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/Preference2dDAO.java // public interface Preference2dDAO { // // public void addPreference2d(Preference2d preference2d); // public void updatePreference2d(Preference2d preference2d); // public Preference2d getPreference2d(Long id); // public List<Preference2d> getAllPreference2ds(); // public void deletePreference2d(Long id); // public void deleteAllPreference2d(); // // public Long count(); // // public List<Preference2d> getPreferencesByUserId(Long userId); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/Preference2d.java // @Entity // @Table(name = "preference2d", catalog = "rrs") // public class Preference2d implements java.io.Serializable { // // private long id; // private Long restaurantId; // private Long userId; // private Double score; // // public Preference2d() { // } // // public Preference2d(long id) { // this.id = id; // } // // public Preference2d(long id, Long restaurantId, Long userId, Double score) { // this.id = id; // this.restaurantId = restaurantId; // this.userId = userId; // this.score = score; // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "restaurant_id") // public Long getRestaurantId() { // return this.restaurantId; // } // // public void setRestaurantId(Long restaurantId) { // this.restaurantId = restaurantId; // } // // @Column(name = "user_id") // public Long getUserId() { // return this.userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // @Column(name = "score", precision = 22, scale = 0) // public Double getScore() { // return this.score; // } // // public void setScore(Double score) { // this.score = score; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/Preference2dService.java // public interface Preference2dService { // // public void addPreference2d(Preference2d preference2d); // public void updatePreference2d(Preference2d preference2d); // public Preference2d getPreference2d(Long id); // public List<Preference2d> getAllPreference2ds(); // public void deletePreference2d(Long id); // public void deleteAllPreference2d(); // // public Long count(); // // public List<Preference2d> getPreferencesByUserId(Long userId); // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.Preference2dDAO; import cn.com.chenyixiao.rrs.entity.Preference2d; import cn.com.chenyixiao.rrs.service.Preference2dService;
package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional public class Preference2dServiceImpl implements Preference2dService { @Autowired private Preference2dDAO preference2dDAO;
// Path: src/main/java/cn/com/chenyixiao/rrs/dao/Preference2dDAO.java // public interface Preference2dDAO { // // public void addPreference2d(Preference2d preference2d); // public void updatePreference2d(Preference2d preference2d); // public Preference2d getPreference2d(Long id); // public List<Preference2d> getAllPreference2ds(); // public void deletePreference2d(Long id); // public void deleteAllPreference2d(); // // public Long count(); // // public List<Preference2d> getPreferencesByUserId(Long userId); // } // // Path: src/main/java/cn/com/chenyixiao/rrs/entity/Preference2d.java // @Entity // @Table(name = "preference2d", catalog = "rrs") // public class Preference2d implements java.io.Serializable { // // private long id; // private Long restaurantId; // private Long userId; // private Double score; // // public Preference2d() { // } // // public Preference2d(long id) { // this.id = id; // } // // public Preference2d(long id, Long restaurantId, Long userId, Double score) { // this.id = id; // this.restaurantId = restaurantId; // this.userId = userId; // this.score = score; // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id", unique = true, nullable = false) // public long getId() { // return this.id; // } // // public void setId(long id) { // this.id = id; // } // // @Column(name = "restaurant_id") // public Long getRestaurantId() { // return this.restaurantId; // } // // public void setRestaurantId(Long restaurantId) { // this.restaurantId = restaurantId; // } // // @Column(name = "user_id") // public Long getUserId() { // return this.userId; // } // // public void setUserId(Long userId) { // this.userId = userId; // } // // @Column(name = "score", precision = 22, scale = 0) // public Double getScore() { // return this.score; // } // // public void setScore(Double score) { // this.score = score; // } // // } // // Path: src/main/java/cn/com/chenyixiao/rrs/service/Preference2dService.java // public interface Preference2dService { // // public void addPreference2d(Preference2d preference2d); // public void updatePreference2d(Preference2d preference2d); // public Preference2d getPreference2d(Long id); // public List<Preference2d> getAllPreference2ds(); // public void deletePreference2d(Long id); // public void deleteAllPreference2d(); // // public Long count(); // // public List<Preference2d> getPreferencesByUserId(Long userId); // } // Path: src/main/java/cn/com/chenyixiao/rrs/service/impl/Preference2dServiceImpl.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.com.chenyixiao.rrs.dao.Preference2dDAO; import cn.com.chenyixiao.rrs.entity.Preference2d; import cn.com.chenyixiao.rrs.service.Preference2dService; package cn.com.chenyixiao.rrs.service.impl; @Service @Transactional public class Preference2dServiceImpl implements Preference2dService { @Autowired private Preference2dDAO preference2dDAO;
public void addPreference2d(Preference2d preference2d) {
timtiemens/secretshare
src/main/java/com/tiemens/secretshare/md5sum/Md5ChecksummerFactory.java
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // }
import com.tiemens.secretshare.exceptions.SecretShareException;
/******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.md5sum; public final class Md5ChecksummerFactory { // ================================================== // class static data // ================================================== private static final String KEY = "ssmd5class"; // ================================================== // class static methods // ================================================== // ================================================== // instance data // ================================================== // ================================================== // factories // ================================================== public static Md5Checksummer create() { String cname = System.getProperty(KEY); if (cname != null) { return createFromClassName(cname); } else { try { return new Md5ChecksummerImpl(); }
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5ChecksummerFactory.java import com.tiemens.secretshare.exceptions.SecretShareException; /******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.md5sum; public final class Md5ChecksummerFactory { // ================================================== // class static data // ================================================== private static final String KEY = "ssmd5class"; // ================================================== // class static methods // ================================================== // ================================================== // instance data // ================================================== // ================================================== // factories // ================================================== public static Md5Checksummer create() { String cname = System.getProperty(KEY); if (cname != null) { return createFromClassName(cname); } else { try { return new Md5ChecksummerImpl(); }
catch (SecretShareException e)
timtiemens/secretshare
src/main/java/com/tiemens/secretshare/md5sum/Md5ChecksummerImpl.java
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // }
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import com.tiemens.secretshare.exceptions.SecretShareException;
/******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.md5sum; public class Md5ChecksummerImpl implements Md5Checksummer { // ================================================== // class static data // ================================================== // ================================================== // class static methods // ================================================== // ================================================== // instance data // ================================================== private final MessageDigest digest; // ================================================== // factories // ================================================== // ================================================== // constructors // ================================================== /** * @throws SecretShareException if something goes wrong on construction */ public Md5ChecksummerImpl() { try { digest = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) {
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5ChecksummerImpl.java import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import com.tiemens.secretshare.exceptions.SecretShareException; /******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.md5sum; public class Md5ChecksummerImpl implements Md5Checksummer { // ================================================== // class static data // ================================================== // ================================================== // class static methods // ================================================== // ================================================== // instance data // ================================================== private final MessageDigest digest; // ================================================== // factories // ================================================== // ================================================== // constructors // ================================================== /** * @throws SecretShareException if something goes wrong on construction */ public Md5ChecksummerImpl() { try { digest = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) {
throw new SecretShareException("failed to create md5 digest", e);
timtiemens/secretshare
src/test/java/com/tiemens/secretshare/math/type/BigIntStringChecksumTest.java
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // }
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Random; import org.junit.Assert; import org.junit.Test; import com.tiemens.secretshare.exceptions.SecretShareException;
// true = generates 'reallyBad'[odd] string false = run tests boolean runAsGenerate = false; String[] reallyBad = new String[] { "AB##", "461C44", "8f4...", "1750A6", "$", "7DE9C3", "00abcO", "E5D568", // that is abc-letter-O not abc-zero }; for (int i = 0, n = reallyBad.length; i < n; i += 2) { if (runAsGenerate) { // This path generates the strings above String s = reallyBad[i]; System.out.println("\"" + s + "\", \"" + BigIntStringChecksum.computeMd5ChecksumLimit6(s) + "\","); } else { // This path checks the strings above BigIntStringChecksum bisc = new BigIntStringChecksum(reallyBad[i], reallyBad[i + 1]); try { bisc.asBigInteger(); // should throw exception Assert.fail("Really bad input '" + reallyBad[i] + "' failed to fail"); }
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // Path: src/test/java/com/tiemens/secretshare/math/type/BigIntStringChecksumTest.java import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Random; import org.junit.Assert; import org.junit.Test; import com.tiemens.secretshare.exceptions.SecretShareException; // true = generates 'reallyBad'[odd] string false = run tests boolean runAsGenerate = false; String[] reallyBad = new String[] { "AB##", "461C44", "8f4...", "1750A6", "$", "7DE9C3", "00abcO", "E5D568", // that is abc-letter-O not abc-zero }; for (int i = 0, n = reallyBad.length; i < n; i += 2) { if (runAsGenerate) { // This path generates the strings above String s = reallyBad[i]; System.out.println("\"" + s + "\", \"" + BigIntStringChecksum.computeMd5ChecksumLimit6(s) + "\","); } else { // This path checks the strings above BigIntStringChecksum bisc = new BigIntStringChecksum(reallyBad[i], reallyBad[i + 1]); try { bisc.asBigInteger(); // should throw exception Assert.fail("Really bad input '" + reallyBad[i] + "' failed to fail"); }
catch (SecretShareException e)
timtiemens/secretshare
src/test/java/com/tiemens/secretshare/math/equation/EasyLinearEquationTest.java
// Path: src/main/java/com/tiemens/secretshare/math/equation/EasyLinearEquation.java // public static class EasySolve // { // private final BigInteger[] answers; // public EasySolve(BigInteger[] inAnswers) // { // answers = new BigInteger[inAnswers.length]; // System.arraycopy(inAnswers, 0, answers, 0, answers.length); // } // // public BigInteger getAnswer(int i) // { // if (i < 0) // { // throw new SecretShareException("Answer index cannot be negative: " + i); // } // if (i == 0) // { // throw new SecretShareException("Answer index 0 is the constant, not an answer." + // " Use range 1-n [not 0-n-1]"); // } // return answers[i]; // } // // }
import org.junit.Test; import com.tiemens.secretshare.math.equation.EasyLinearEquation.EasySolve; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.math.BigInteger; import java.util.logging.ConsoleHandler; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import org.junit.Assert;
/******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.math.equation; public class EasyLinearEquationTest { // ================================================== // class static data // ================================================== // ================================================== // class static methods // ================================================== // ================================================== // instance data // ================================================== // ================================================== // factories // ================================================== // ================================================== // constructors // ================================================== // ================================================== // public methods // ================================================== @Test public void testFirst() { EasyLinearEquation ele = null; ele = EasyLinearEquation .create(new int[][] { { 33, 1, 2, 3}, { 81, 4, 5, 6}, { 52, 3, 2, 4} });
// Path: src/main/java/com/tiemens/secretshare/math/equation/EasyLinearEquation.java // public static class EasySolve // { // private final BigInteger[] answers; // public EasySolve(BigInteger[] inAnswers) // { // answers = new BigInteger[inAnswers.length]; // System.arraycopy(inAnswers, 0, answers, 0, answers.length); // } // // public BigInteger getAnswer(int i) // { // if (i < 0) // { // throw new SecretShareException("Answer index cannot be negative: " + i); // } // if (i == 0) // { // throw new SecretShareException("Answer index 0 is the constant, not an answer." + // " Use range 1-n [not 0-n-1]"); // } // return answers[i]; // } // // } // Path: src/test/java/com/tiemens/secretshare/math/equation/EasyLinearEquationTest.java import org.junit.Test; import com.tiemens.secretshare.math.equation.EasyLinearEquation.EasySolve; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.math.BigInteger; import java.util.logging.ConsoleHandler; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import org.junit.Assert; /******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.math.equation; public class EasyLinearEquationTest { // ================================================== // class static data // ================================================== // ================================================== // class static methods // ================================================== // ================================================== // instance data // ================================================== // ================================================== // factories // ================================================== // ================================================== // constructors // ================================================== // ================================================== // public methods // ================================================== @Test public void testFirst() { EasyLinearEquation ele = null; ele = EasyLinearEquation .create(new int[][] { { 33, 1, 2, 3}, { 81, 4, 5, 6}, { 52, 3, 2, 4} });
EasySolve solve = ele.solve();
timtiemens/secretshare
src/main/java/com/tiemens/secretshare/math/matrix/NumberMatrix.java
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // }
import java.io.PrintStream; import com.tiemens.secretshare.exceptions.SecretShareException;
protected NumberMatrix(E[][] in) { matrix = in; } public NumberMatrix(int height, int width) { matrix = create(height, width); } public int getHeight() { return matrix.length; } public int getWidth() { return matrix[0].length; } public final boolean isValueOne(E other) { return one().equals(other); } public void fill(int j, int... rowsandcols) { if ((rowsandcols.length % j) != 0) {
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // Path: src/main/java/com/tiemens/secretshare/math/matrix/NumberMatrix.java import java.io.PrintStream; import com.tiemens.secretshare.exceptions.SecretShareException; protected NumberMatrix(E[][] in) { matrix = in; } public NumberMatrix(int height, int width) { matrix = create(height, width); } public int getHeight() { return matrix.length; } public int getWidth() { return matrix[0].length; } public final boolean isValueOne(E other) { return one().equals(other); } public void fill(int j, int... rowsandcols) { if ((rowsandcols.length % j) != 0) {
throw new SecretShareException("array size must be evenly divisible by j(" + j + ")");
timtiemens/secretshare
src/test/java/com/tiemens/secretshare/engine/SecretShareParanoidInputTest.java
// Path: src/main/java/com/tiemens/secretshare/engine/SecretShare.java // public static final class ParanoidInput // { // // maximum combine operations to perform - negative means "all", null means "all" // private BigInteger maximumCombinationsAllowedToTest = null; // // for output/debug purposes, output a line every "this percentage" // private int percentEvery = 30; // or 10 for every 10% // // stop processing when any answer hits this count (should be greater than 1) // private Integer stopCombiningWhenAnyCount = null; // // limit the number of "combine.N" lines printed // private Integer limitPrint = null; // // @Override // public String toString() // { // return "ParanoidInput [" + // "maximumCombinationsAllowedToTest=" + maximumCombinationsAllowedToTest + // ", percentEvery=" + percentEvery + // ", stopCombiningWhenAnyCount=" + stopCombiningWhenAnyCount + // ", limitPrint=" + limitPrint + // "]"; // } // // // // split only allows <number> or the string "all" // public static ParanoidInput parseForSplit(String argumentName, String arg) // { // ParanoidInput ret = new ParanoidInput(); // if ("all".equals(arg)) // { // ret.maximumCombinationsAllowedToTest = null; // } // else // { // ret.maximumCombinationsAllowedToTest = new BigInteger(arg); // } // return ret; // } // // // combine allows <number>|"all" followed by other options // public static ParanoidInput parseForCombine(String argumentName, String arg) // { // ParanoidInput ret = new ParanoidInput(); // String[] pieces = arg.split(","); // for (String piece : pieces) // { // Integer v; // v = parse(piece, "limitPrint="); // if (v != null) // { // ret.limitPrint = v; // } // else // { // v = parse(piece, "stopCombiningWhenAnyCount="); // if (v != null) // { // ret.stopCombiningWhenAnyCount = v; // } // else // { // v = parse(piece, ""); // if (v == null) // { // v = parse(piece, "maxCombinationsAllowedToTest="); // } // if (v != null) // { // ret.maximumCombinationsAllowedToTest = BigInteger.valueOf(v); // } // else // { // throw new SecretShareException("Failed to parse piece '" + piece + // "' as part of argument '" + arg + "'"); // } // } // } // } // // return ret; // } // // private static Integer parse(String arg, String lookfor) // { // arg = arg.toLowerCase(); // lookfor = lookfor.toLowerCase(); // // Integer ret = null; // if (arg.startsWith(lookfor)) // { // String rest = arg.substring(lookfor.length()); // try // { // ret = Integer.parseInt(rest); // } // catch (NumberFormatException e) // { // // } // } // return ret; // } // // public static ParanoidInput createAll() // { // // null == "All" // return create(null); // } // // public static ParanoidInput create(BigInteger max) // { // ParanoidInput ret = new ParanoidInput(); // ret.maximumCombinationsAllowedToTest = max; // return ret; // } // // private ParanoidInput() // { // // } // // public BigInteger getMaximumCombinationsToTest() // { // return maximumCombinationsAllowedToTest; // } // // public void setOutputEvery(int percentage0to100) // { // percentEvery = percentage0to100; // } // // public BigInteger getMaximumCombinationsAllowedToTest() // { // return maximumCombinationsAllowedToTest; // } // // public int getPercentEvery() // { // return percentEvery; // } // // public Integer getStopCombiningWhenAnyCount() // { // return stopCombiningWhenAnyCount; // } // // public Integer getLimitPrint() // { // return limitPrint; // } // }
import java.math.BigInteger; import org.junit.Assert; import org.junit.Test; import com.tiemens.secretshare.engine.SecretShare.ParanoidInput;
/******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.engine; public class SecretShareParanoidInputTest { // ================================================== // class static data // ================================================== // ================================================== // class static methods // ================================================== // ================================================== // instance data // ================================================== // ================================================== // factories // ================================================== // ================================================== // constructors // ================================================== // @Before // ================================================== // public methods // ================================================== @Test public void testJustMax() { validate("5", 5, null, null); validate("50,stopCombiningWhenAnyCount=4,limitPrint=22", 50, 4, 22); validate("50,limitPrint=22", 50, null, 22); validate("limitPrint=22,50", 50, null, 22); validate("maxCombinationsAllowedToTest=50,limitPrint=22", 50, null, 22); validate("maxCombinationsAllowedToTest=50,stopCombiningWhenAnyCount=3,limitPrint=22", 50, 3, 22); } // ================================================== // non public methods // ================================================== private void validate(String arg, Integer expectMaxInt, Integer expectStopWhenCount, Integer expectLimitPrint) {
// Path: src/main/java/com/tiemens/secretshare/engine/SecretShare.java // public static final class ParanoidInput // { // // maximum combine operations to perform - negative means "all", null means "all" // private BigInteger maximumCombinationsAllowedToTest = null; // // for output/debug purposes, output a line every "this percentage" // private int percentEvery = 30; // or 10 for every 10% // // stop processing when any answer hits this count (should be greater than 1) // private Integer stopCombiningWhenAnyCount = null; // // limit the number of "combine.N" lines printed // private Integer limitPrint = null; // // @Override // public String toString() // { // return "ParanoidInput [" + // "maximumCombinationsAllowedToTest=" + maximumCombinationsAllowedToTest + // ", percentEvery=" + percentEvery + // ", stopCombiningWhenAnyCount=" + stopCombiningWhenAnyCount + // ", limitPrint=" + limitPrint + // "]"; // } // // // // split only allows <number> or the string "all" // public static ParanoidInput parseForSplit(String argumentName, String arg) // { // ParanoidInput ret = new ParanoidInput(); // if ("all".equals(arg)) // { // ret.maximumCombinationsAllowedToTest = null; // } // else // { // ret.maximumCombinationsAllowedToTest = new BigInteger(arg); // } // return ret; // } // // // combine allows <number>|"all" followed by other options // public static ParanoidInput parseForCombine(String argumentName, String arg) // { // ParanoidInput ret = new ParanoidInput(); // String[] pieces = arg.split(","); // for (String piece : pieces) // { // Integer v; // v = parse(piece, "limitPrint="); // if (v != null) // { // ret.limitPrint = v; // } // else // { // v = parse(piece, "stopCombiningWhenAnyCount="); // if (v != null) // { // ret.stopCombiningWhenAnyCount = v; // } // else // { // v = parse(piece, ""); // if (v == null) // { // v = parse(piece, "maxCombinationsAllowedToTest="); // } // if (v != null) // { // ret.maximumCombinationsAllowedToTest = BigInteger.valueOf(v); // } // else // { // throw new SecretShareException("Failed to parse piece '" + piece + // "' as part of argument '" + arg + "'"); // } // } // } // } // // return ret; // } // // private static Integer parse(String arg, String lookfor) // { // arg = arg.toLowerCase(); // lookfor = lookfor.toLowerCase(); // // Integer ret = null; // if (arg.startsWith(lookfor)) // { // String rest = arg.substring(lookfor.length()); // try // { // ret = Integer.parseInt(rest); // } // catch (NumberFormatException e) // { // // } // } // return ret; // } // // public static ParanoidInput createAll() // { // // null == "All" // return create(null); // } // // public static ParanoidInput create(BigInteger max) // { // ParanoidInput ret = new ParanoidInput(); // ret.maximumCombinationsAllowedToTest = max; // return ret; // } // // private ParanoidInput() // { // // } // // public BigInteger getMaximumCombinationsToTest() // { // return maximumCombinationsAllowedToTest; // } // // public void setOutputEvery(int percentage0to100) // { // percentEvery = percentage0to100; // } // // public BigInteger getMaximumCombinationsAllowedToTest() // { // return maximumCombinationsAllowedToTest; // } // // public int getPercentEvery() // { // return percentEvery; // } // // public Integer getStopCombiningWhenAnyCount() // { // return stopCombiningWhenAnyCount; // } // // public Integer getLimitPrint() // { // return limitPrint; // } // } // Path: src/test/java/com/tiemens/secretshare/engine/SecretShareParanoidInputTest.java import java.math.BigInteger; import org.junit.Assert; import org.junit.Test; import com.tiemens.secretshare.engine.SecretShare.ParanoidInput; /******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.engine; public class SecretShareParanoidInputTest { // ================================================== // class static data // ================================================== // ================================================== // class static methods // ================================================== // ================================================== // instance data // ================================================== // ================================================== // factories // ================================================== // ================================================== // constructors // ================================================== // @Before // ================================================== // public methods // ================================================== @Test public void testJustMax() { validate("5", 5, null, null); validate("50,stopCombiningWhenAnyCount=4,limitPrint=22", 50, 4, 22); validate("50,limitPrint=22", 50, null, 22); validate("limitPrint=22,50", 50, null, 22); validate("maxCombinationsAllowedToTest=50,limitPrint=22", 50, null, 22); validate("maxCombinationsAllowedToTest=50,stopCombiningWhenAnyCount=3,limitPrint=22", 50, 3, 22); } // ================================================== // non public methods // ================================================== private void validate(String arg, Integer expectMaxInt, Integer expectStopWhenCount, Integer expectLimitPrint) {
ParanoidInput actual = ParanoidInput.parseForCombine("paranoid", arg);
timtiemens/secretshare
src/main/java/com/tiemens/secretshare/math/equation/EasyLinearEquation.java
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // }
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import com.tiemens.secretshare.exceptions.SecretShareException;
/******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.math.equation; /** * "Easy" implementation of linear equation solver. * * * Example: given 3 equations like: * 1491 = 83a + 32b + 22c * 329 = 5a + 13b + 22c * 122 = 3a + 2b + 19c * The goal is to solve for a, b, and c [3 unknowns, 3 equations]. * * The problem above is encoded into a matrix of numbers like: * 1491 83 32 22 * 329 5 13 22 * 122 3 2 19 * and stored in this class as a List[Row] objects. * * Then, this class can "solve" it into the 'diagonal 1', giving: * 11 1 0 0 * 16 0 1 0 * 3 0 0 1 * Which in turn means that a=11, b=16 and c=3 * * * This implementation is called "easy" because it is really straight-forward, * but also really inefficient. * Values are "canceled" by multiplying the two together. * e.g. "8" and "4" just needs the "4" to be multiplied by 2, then subtracted. * This implementation takes 8*4 and subtracts 4*8 because that just works, and you don't * need to compute the least common multiple. * * This implementation is also "easy" since it doesn't use any lin-eq library. * There are a lot of those libraries available: it turns out it was easier * to write this class than to figure out how to use the horrible APIs they presented. * [The ones with good APIs didn't support BigInteger] * * @author tiemens * */ public final class EasyLinearEquation { // ================================================== // class static data // ================================================== // want to turn on debug? See EasyLinearEquationTest.enableLogging() private static Logger logger = Logger.getLogger(EasyLinearEquation.class.getName()); private static boolean debugPrinting = false; // ================================================== // class static methods // ================================================== public static Logger getLogger() { return logger; } public static BigInteger[][] convertIntToBigInteger(int[][] inMatrix) { BigInteger[][] cvt = new BigInteger[inMatrix.length][]; for (int i = 0, n = inMatrix.length; i < n; i++) { cvt[i] = new BigInteger[inMatrix[i].length]; for (int c = 0, rn = inMatrix[i].length; c < rn; c++) { cvt[i][c] = BigInteger.valueOf(inMatrix[i][c]); } } return cvt; } // ================================================== // instance data // ================================================== private final List<Row> rows; // 'modulus' can be null, which means do not perform mod() on values private final BigInteger modulus; // ================================================== // factories // ================================================== /** * Create solver for polynomial equations. * * Polynomial linear equations are a special case, because the C,x,x^2,x^3 coefficients * can be turned into the rows we need by being given: * a) which "x" values were used * b) what "constant" values were computed * This information happens to be exactly what the holder of a "Secret" in * "Secret Sharing" has been given. * So this constructor can be used to recover the secret if * given enough of the secrets. * * @param xarray the "X" values * @param fofxarray the "f(x)" values * @return instance for solving this special case */ public static EasyLinearEquation createForPolynomial(final BigInteger[] xarray, final BigInteger[] fofxarray) { if (xarray.length != fofxarray.length) {
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // Path: src/main/java/com/tiemens/secretshare/math/equation/EasyLinearEquation.java import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import com.tiemens.secretshare.exceptions.SecretShareException; /******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.math.equation; /** * "Easy" implementation of linear equation solver. * * * Example: given 3 equations like: * 1491 = 83a + 32b + 22c * 329 = 5a + 13b + 22c * 122 = 3a + 2b + 19c * The goal is to solve for a, b, and c [3 unknowns, 3 equations]. * * The problem above is encoded into a matrix of numbers like: * 1491 83 32 22 * 329 5 13 22 * 122 3 2 19 * and stored in this class as a List[Row] objects. * * Then, this class can "solve" it into the 'diagonal 1', giving: * 11 1 0 0 * 16 0 1 0 * 3 0 0 1 * Which in turn means that a=11, b=16 and c=3 * * * This implementation is called "easy" because it is really straight-forward, * but also really inefficient. * Values are "canceled" by multiplying the two together. * e.g. "8" and "4" just needs the "4" to be multiplied by 2, then subtracted. * This implementation takes 8*4 and subtracts 4*8 because that just works, and you don't * need to compute the least common multiple. * * This implementation is also "easy" since it doesn't use any lin-eq library. * There are a lot of those libraries available: it turns out it was easier * to write this class than to figure out how to use the horrible APIs they presented. * [The ones with good APIs didn't support BigInteger] * * @author tiemens * */ public final class EasyLinearEquation { // ================================================== // class static data // ================================================== // want to turn on debug? See EasyLinearEquationTest.enableLogging() private static Logger logger = Logger.getLogger(EasyLinearEquation.class.getName()); private static boolean debugPrinting = false; // ================================================== // class static methods // ================================================== public static Logger getLogger() { return logger; } public static BigInteger[][] convertIntToBigInteger(int[][] inMatrix) { BigInteger[][] cvt = new BigInteger[inMatrix.length][]; for (int i = 0, n = inMatrix.length; i < n; i++) { cvt[i] = new BigInteger[inMatrix[i].length]; for (int c = 0, rn = inMatrix[i].length; c < rn; c++) { cvt[i][c] = BigInteger.valueOf(inMatrix[i][c]); } } return cvt; } // ================================================== // instance data // ================================================== private final List<Row> rows; // 'modulus' can be null, which means do not perform mod() on values private final BigInteger modulus; // ================================================== // factories // ================================================== /** * Create solver for polynomial equations. * * Polynomial linear equations are a special case, because the C,x,x^2,x^3 coefficients * can be turned into the rows we need by being given: * a) which "x" values were used * b) what "constant" values were computed * This information happens to be exactly what the holder of a "Secret" in * "Secret Sharing" has been given. * So this constructor can be used to recover the secret if * given enough of the secrets. * * @param xarray the "X" values * @param fofxarray the "f(x)" values * @return instance for solving this special case */ public static EasyLinearEquation createForPolynomial(final BigInteger[] xarray, final BigInteger[] fofxarray) { if (xarray.length != fofxarray.length) {
throw new SecretShareException("Unequal length arrays are not allowed");
timtiemens/secretshare
src/test/java/com/tiemens/secretshare/jdeps/model/JDepsTest.java
// Path: src/test/java/com/tiemens/secretshare/jdeps/model/JDeps.java // public static class JdepsLineModule2Module extends JdepsLine // { // private final String userModule; // private final String usesModule; // public JdepsLineModule2Module(String userModule, String usesModule) // { // super(); // this.userModule = userModule; // this.usesModule = usesModule; // } // public String getUserModule() // { // return userModule; // } // public String getUsesModule() // { // return usesModule; // } // } // // Path: src/test/java/com/tiemens/secretshare/jdeps/model/JDeps.java // public static class JdepsLinePackage2PackageModule extends JdepsLine // { // private final String userPackage; // private final String usesPackage; // private final String usesModule; // public JdepsLinePackage2PackageModule(String userPackage, // String usesPackage, String usesModule) // { // super(); // this.userPackage = userPackage; // this.usesPackage = usesPackage; // this.usesModule = usesModule; // } // public String getUserPackage() // { // return userPackage; // } // public String getUsesPackage() // { // return usesPackage; // } // public String getUsesModule() // { // return usesModule; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Test; import com.tiemens.secretshare.jdeps.model.JDeps.JdepsLineModule2Module; import com.tiemens.secretshare.jdeps.model.JDeps.JdepsLinePackage2PackageModule;
/******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.jdeps.model; public class JDepsTest { @Test public void testm2m() { subtestm2m("classes -> java.base", "classes", "java.base"); subtestm2m("classes -> not found", "classes", "not found"); subtestm2m(" classes -> java.base", null, null); } private void subtestm2m(String input, String expectedUser, String expectedUsed) { JDeps.ParseJdepsLine parser = new JDeps.ParseJdepsLineModule2Module();
// Path: src/test/java/com/tiemens/secretshare/jdeps/model/JDeps.java // public static class JdepsLineModule2Module extends JdepsLine // { // private final String userModule; // private final String usesModule; // public JdepsLineModule2Module(String userModule, String usesModule) // { // super(); // this.userModule = userModule; // this.usesModule = usesModule; // } // public String getUserModule() // { // return userModule; // } // public String getUsesModule() // { // return usesModule; // } // } // // Path: src/test/java/com/tiemens/secretshare/jdeps/model/JDeps.java // public static class JdepsLinePackage2PackageModule extends JdepsLine // { // private final String userPackage; // private final String usesPackage; // private final String usesModule; // public JdepsLinePackage2PackageModule(String userPackage, // String usesPackage, String usesModule) // { // super(); // this.userPackage = userPackage; // this.usesPackage = usesPackage; // this.usesModule = usesModule; // } // public String getUserPackage() // { // return userPackage; // } // public String getUsesPackage() // { // return usesPackage; // } // public String getUsesModule() // { // return usesModule; // } // } // Path: src/test/java/com/tiemens/secretshare/jdeps/model/JDepsTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Test; import com.tiemens.secretshare.jdeps.model.JDeps.JdepsLineModule2Module; import com.tiemens.secretshare.jdeps.model.JDeps.JdepsLinePackage2PackageModule; /******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.jdeps.model; public class JDepsTest { @Test public void testm2m() { subtestm2m("classes -> java.base", "classes", "java.base"); subtestm2m("classes -> not found", "classes", "not found"); subtestm2m(" classes -> java.base", null, null); } private void subtestm2m(String input, String expectedUser, String expectedUsed) { JDeps.ParseJdepsLine parser = new JDeps.ParseJdepsLineModule2Module();
JdepsLineModule2Module ret = (JdepsLineModule2Module) parser.parseLine(input);
timtiemens/secretshare
src/test/java/com/tiemens/secretshare/jdeps/model/JDepsTest.java
// Path: src/test/java/com/tiemens/secretshare/jdeps/model/JDeps.java // public static class JdepsLineModule2Module extends JdepsLine // { // private final String userModule; // private final String usesModule; // public JdepsLineModule2Module(String userModule, String usesModule) // { // super(); // this.userModule = userModule; // this.usesModule = usesModule; // } // public String getUserModule() // { // return userModule; // } // public String getUsesModule() // { // return usesModule; // } // } // // Path: src/test/java/com/tiemens/secretshare/jdeps/model/JDeps.java // public static class JdepsLinePackage2PackageModule extends JdepsLine // { // private final String userPackage; // private final String usesPackage; // private final String usesModule; // public JdepsLinePackage2PackageModule(String userPackage, // String usesPackage, String usesModule) // { // super(); // this.userPackage = userPackage; // this.usesPackage = usesPackage; // this.usesModule = usesModule; // } // public String getUserPackage() // { // return userPackage; // } // public String getUsesPackage() // { // return usesPackage; // } // public String getUsesModule() // { // return usesModule; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Test; import com.tiemens.secretshare.jdeps.model.JDeps.JdepsLineModule2Module; import com.tiemens.secretshare.jdeps.model.JDeps.JdepsLinePackage2PackageModule;
} private void subtestm2m(String input, String expectedUser, String expectedUsed) { JDeps.ParseJdepsLine parser = new JDeps.ParseJdepsLineModule2Module(); JdepsLineModule2Module ret = (JdepsLineModule2Module) parser.parseLine(input); if (expectedUser != null) { assertNotNull(ret); assertEquals(expectedUser, ret.getUserModule()); assertEquals(expectedUsed, ret.getUsesModule()); } else { assertNull(ret); } } @Test public void testp2pm() { subtestp2pm(" com.tiemens.secretshare -> java.io java.base", "com.tiemens.secretshare", "java.io", "java.base"); } private void subtestp2pm(String input, String expectedPackage, String expectedUsesPackage, String expectedUsesModule) { JDeps.ParseJdepsLine parser = new JDeps.ParseJdepsLinePackage2PackageModule();
// Path: src/test/java/com/tiemens/secretshare/jdeps/model/JDeps.java // public static class JdepsLineModule2Module extends JdepsLine // { // private final String userModule; // private final String usesModule; // public JdepsLineModule2Module(String userModule, String usesModule) // { // super(); // this.userModule = userModule; // this.usesModule = usesModule; // } // public String getUserModule() // { // return userModule; // } // public String getUsesModule() // { // return usesModule; // } // } // // Path: src/test/java/com/tiemens/secretshare/jdeps/model/JDeps.java // public static class JdepsLinePackage2PackageModule extends JdepsLine // { // private final String userPackage; // private final String usesPackage; // private final String usesModule; // public JdepsLinePackage2PackageModule(String userPackage, // String usesPackage, String usesModule) // { // super(); // this.userPackage = userPackage; // this.usesPackage = usesPackage; // this.usesModule = usesModule; // } // public String getUserPackage() // { // return userPackage; // } // public String getUsesPackage() // { // return usesPackage; // } // public String getUsesModule() // { // return usesModule; // } // } // Path: src/test/java/com/tiemens/secretshare/jdeps/model/JDepsTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Test; import com.tiemens.secretshare.jdeps.model.JDeps.JdepsLineModule2Module; import com.tiemens.secretshare.jdeps.model.JDeps.JdepsLinePackage2PackageModule; } private void subtestm2m(String input, String expectedUser, String expectedUsed) { JDeps.ParseJdepsLine parser = new JDeps.ParseJdepsLineModule2Module(); JdepsLineModule2Module ret = (JdepsLineModule2Module) parser.parseLine(input); if (expectedUser != null) { assertNotNull(ret); assertEquals(expectedUser, ret.getUserModule()); assertEquals(expectedUsed, ret.getUsesModule()); } else { assertNull(ret); } } @Test public void testp2pm() { subtestp2pm(" com.tiemens.secretshare -> java.io java.base", "com.tiemens.secretshare", "java.io", "java.base"); } private void subtestp2pm(String input, String expectedPackage, String expectedUsesPackage, String expectedUsesModule) { JDeps.ParseJdepsLine parser = new JDeps.ParseJdepsLinePackage2PackageModule();
JdepsLinePackage2PackageModule ret = (JdepsLinePackage2PackageModule) parser.parseLine(input);
timtiemens/secretshare
src/main/java/com/tiemens/secretshare/math/matrix/NumberSimplex.java
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // }
import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.tiemens.secretshare.exceptions.SecretShareException;
/******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.math.matrix; public class NumberSimplex<E extends Number> { // ================================================== // class static data // ================================================== // ================================================== // class static methods // ================================================== // ================================================== // instance data // ================================================== /** Abstract method to create a matrix */ private final NumberMatrix<E> matrix; /** index of the "B" column - i.e. the index of the constants */ private final int constantsInThisColumnIndex; // 0-based index // computed values private NumberOrVariable<E>[] mTop; private NumberOrVariable<E>[] mSide; private E[][] mArrayhide; private Map<NumberOrVariable<E>, E> mAnswers; // ================================================== // factories // ================================================== // ================================================== // constructors // ================================================== public NumberSimplex(NumberMatrix<E> inMatrix, int inConstantsIndex) { matrix = inMatrix; constantsInThisColumnIndex = inConstantsIndex; //System.out.println("SIMPLEX cons matrix.h=" + matrix.getHeight() + " matrix.w=" + matrix.getWidth() + // " m.array.length=" + // matrix.getArray().length + " m.array[0].length=" + matrix.getArray()[0].length); } // ================================================== // public methods // ================================================== // .initForSolve(), then .solve(), then .getAnswer() public void initForSolve(PrintStream out) { final int width = matrix.getWidth(); final int height = matrix.getHeight(); mTop = fillInTopVariables(width - 1); mSide = fillInConstants(height); //System.out.println("INIT-SOLVE matrix.h=" + matrix.getHeight() + // " matrix.w=" + matrix.getWidth() + " m.array.length=" + // matrix.getArray().length + " m.array[0].length=" + matrix.getArray()[0].length); mArrayhide = fillInArray(matrix.getArray(), constantsInThisColumnIndex); nullPrintln(out, "INIT-SOLVE, TOP.length = " + mTop.length + " matrix.height=" + height + " matrix.w=" + width); printTopArraySide(out); } public void solve(PrintStream out) { final int height = mArrayhide.length; final int width = mArrayhide[0].length; if (height != width) {
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // Path: src/main/java/com/tiemens/secretshare/math/matrix/NumberSimplex.java import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.tiemens.secretshare.exceptions.SecretShareException; /******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.math.matrix; public class NumberSimplex<E extends Number> { // ================================================== // class static data // ================================================== // ================================================== // class static methods // ================================================== // ================================================== // instance data // ================================================== /** Abstract method to create a matrix */ private final NumberMatrix<E> matrix; /** index of the "B" column - i.e. the index of the constants */ private final int constantsInThisColumnIndex; // 0-based index // computed values private NumberOrVariable<E>[] mTop; private NumberOrVariable<E>[] mSide; private E[][] mArrayhide; private Map<NumberOrVariable<E>, E> mAnswers; // ================================================== // factories // ================================================== // ================================================== // constructors // ================================================== public NumberSimplex(NumberMatrix<E> inMatrix, int inConstantsIndex) { matrix = inMatrix; constantsInThisColumnIndex = inConstantsIndex; //System.out.println("SIMPLEX cons matrix.h=" + matrix.getHeight() + " matrix.w=" + matrix.getWidth() + // " m.array.length=" + // matrix.getArray().length + " m.array[0].length=" + matrix.getArray()[0].length); } // ================================================== // public methods // ================================================== // .initForSolve(), then .solve(), then .getAnswer() public void initForSolve(PrintStream out) { final int width = matrix.getWidth(); final int height = matrix.getHeight(); mTop = fillInTopVariables(width - 1); mSide = fillInConstants(height); //System.out.println("INIT-SOLVE matrix.h=" + matrix.getHeight() + // " matrix.w=" + matrix.getWidth() + " m.array.length=" + // matrix.getArray().length + " m.array[0].length=" + matrix.getArray()[0].length); mArrayhide = fillInArray(matrix.getArray(), constantsInThisColumnIndex); nullPrintln(out, "INIT-SOLVE, TOP.length = " + mTop.length + " matrix.height=" + height + " matrix.w=" + width); printTopArraySide(out); } public void solve(PrintStream out) { final int height = mArrayhide.length; final int width = mArrayhide[0].length; if (height != width) {
throw new SecretShareException("h=" + height + " w=" + width + " must match");
timtiemens/secretshare
src/main/java/com/tiemens/secretshare/math/equation/PolyEquationImpl.java
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // }
import java.io.PrintStream; import java.math.BigInteger; import com.tiemens.secretshare.exceptions.SecretShareException;
/******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.math.equation; /** * Polynomial equation implementation. * 8*x^3 + 5*x^2 + 13*x + 432 * [term3] [term2] [term1] [term0] * * Arguments to the constructor are in this order: * 432 + 13*x + 5*x^2 + 8*x^3 * [term0] [term1] [term2] [term3] * * * Provides support ONLY for integer exponent values. * Provides support ONLY for BigInteger values of "x". * Provides support ONLY for BigInteger values of "coefficients" * * It may be a "short distance" between BigInteger and BigDecimal, * but that distance is still too big to justify making * this implementation more complex. * * @author tiemens * */ public class PolyEquationImpl { // ================================================== // class static data // ================================================== // ================================================== // class static methods // ================================================== // ================================================== // instance data // ================================================== // [0] is x^0, i.e. "*1" the "constant term" // [1] is x^1, i.e. "*x" the "x term" // [2] is x^2, i.e. the "*x^2 term" private BigInteger[] coefficients; // ================================================== // factories // ================================================== /** * Helper factory to create instances. * Accepts 'int', converts them to BigInteger, and calls the constructor. * * @param args as int values * @return instance */ public static PolyEquationImpl create(final int... args) { BigInteger[] bigints = new BigInteger[args.length]; for (int i = 0, n = args.length; i < n; i++) { bigints[i] = BigInteger.valueOf(args[i]); } return new PolyEquationImpl(bigints); } // ================================================== // constructors // ================================================== public PolyEquationImpl(final BigInteger[] inCoeffs) { if (inCoeffs.length <= 0) {
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // Path: src/main/java/com/tiemens/secretshare/math/equation/PolyEquationImpl.java import java.io.PrintStream; import java.math.BigInteger; import com.tiemens.secretshare.exceptions.SecretShareException; /******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.math.equation; /** * Polynomial equation implementation. * 8*x^3 + 5*x^2 + 13*x + 432 * [term3] [term2] [term1] [term0] * * Arguments to the constructor are in this order: * 432 + 13*x + 5*x^2 + 8*x^3 * [term0] [term1] [term2] [term3] * * * Provides support ONLY for integer exponent values. * Provides support ONLY for BigInteger values of "x". * Provides support ONLY for BigInteger values of "coefficients" * * It may be a "short distance" between BigInteger and BigDecimal, * but that distance is still too big to justify making * this implementation more complex. * * @author tiemens * */ public class PolyEquationImpl { // ================================================== // class static data // ================================================== // ================================================== // class static methods // ================================================== // ================================================== // instance data // ================================================== // [0] is x^0, i.e. "*1" the "constant term" // [1] is x^1, i.e. "*x" the "x term" // [2] is x^2, i.e. the "*x^2 term" private BigInteger[] coefficients; // ================================================== // factories // ================================================== /** * Helper factory to create instances. * Accepts 'int', converts them to BigInteger, and calls the constructor. * * @param args as int values * @return instance */ public static PolyEquationImpl create(final int... args) { BigInteger[] bigints = new BigInteger[args.length]; for (int i = 0, n = args.length; i < n; i++) { bigints[i] = BigInteger.valueOf(args[i]); } return new PolyEquationImpl(bigints); } // ================================================== // constructors // ================================================== public PolyEquationImpl(final BigInteger[] inCoeffs) { if (inCoeffs.length <= 0) {
throw new SecretShareException("Must have at least 1 coefficient");
timtiemens/secretshare
src/test/java/com/tiemens/secretshare/math/type/BigIntUtilitiesTest.java
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // }
import java.math.BigInteger; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.junit.Assert; import org.junit.Test; import com.tiemens.secretshare.exceptions.SecretShareException;
subTestCaseSensitivity(origPart1, origPart2, origPart3, origPart4); subTestCaseSensitivity(origPart1.toUpperCase(), origPart2, origPart3, origPart4); subTestCaseSensitivity(origPart1, origPart2.toUpperCase(), origPart3, origPart4); subTestCaseSensitivity(origPart1, origPart2, origPart3.toUpperCase(), origPart4); subTestCaseSensitivity(origPart1, origPart2, origPart3, origPart4.toUpperCase()); subTestCaseSensitivity(origPart1.toUpperCase(), origPart2.toUpperCase(), origPart3.toUpperCase(), origPart4.toUpperCase()); subTestCaseSensitivity(origPart1.toLowerCase(), origPart2, origPart3, origPart4); subTestCaseSensitivity(origPart1, origPart2.toLowerCase(), origPart3, origPart4); subTestCaseSensitivity(origPart1, origPart2, origPart3.toLowerCase(), origPart4); subTestCaseSensitivity(origPart1.toLowerCase(), origPart2.toLowerCase(), origPart3.toLowerCase(), origPart4.toLowerCase()); } // ================================================== // non public methods // ================================================== private void subTestCaseSensitivity(String part1, String part2, String part3, String part4) { final String input = part1 + part2 + part3 + part4; try { BigInteger ret = BigIntUtilities.Checksum.createBigInteger(input); Assert.assertNotNull(ret); }
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // Path: src/test/java/com/tiemens/secretshare/math/type/BigIntUtilitiesTest.java import java.math.BigInteger; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.junit.Assert; import org.junit.Test; import com.tiemens.secretshare.exceptions.SecretShareException; subTestCaseSensitivity(origPart1, origPart2, origPart3, origPart4); subTestCaseSensitivity(origPart1.toUpperCase(), origPart2, origPart3, origPart4); subTestCaseSensitivity(origPart1, origPart2.toUpperCase(), origPart3, origPart4); subTestCaseSensitivity(origPart1, origPart2, origPart3.toUpperCase(), origPart4); subTestCaseSensitivity(origPart1, origPart2, origPart3, origPart4.toUpperCase()); subTestCaseSensitivity(origPart1.toUpperCase(), origPart2.toUpperCase(), origPart3.toUpperCase(), origPart4.toUpperCase()); subTestCaseSensitivity(origPart1.toLowerCase(), origPart2, origPart3, origPart4); subTestCaseSensitivity(origPart1, origPart2.toLowerCase(), origPart3, origPart4); subTestCaseSensitivity(origPart1, origPart2, origPart3.toLowerCase(), origPart4); subTestCaseSensitivity(origPart1.toLowerCase(), origPart2.toLowerCase(), origPart3.toLowerCase(), origPart4.toLowerCase()); } // ================================================== // non public methods // ================================================== private void subTestCaseSensitivity(String part1, String part2, String part3, String part4) { final String input = part1 + part2 + part3 + part4; try { BigInteger ret = BigIntUtilities.Checksum.createBigInteger(input); Assert.assertNotNull(ret); }
catch (SecretShareException e)
timtiemens/secretshare
src/test/java/com/tiemens/secretshare/main/cli/MainBigIntCsTest.java
// Path: src/main/java/com/tiemens/secretshare/main/cli/MainBigIntCs.java // public static enum Type // { // bics, bi, s; // // /** // * @param in type to find // * @param argName to display if an error happens // * @return Type or throw exception // * @throws SecretShareException if 'in' is not found // */ // public static Type findByString(String in, String argName) // { // Type ret = valueOf(in); // if (ret != null) // { // return ret; // } // else // { // throw new SecretShareException("Type value '" + in + "' not found." + // ((argName != null) ? " Argname=" + argName : "")); // } // } // }
import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; import com.tiemens.secretshare.main.cli.MainBigIntCs.Type;
/******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.main.cli; public class MainBigIntCsTest { @Test public void testConvert() {
// Path: src/main/java/com/tiemens/secretshare/main/cli/MainBigIntCs.java // public static enum Type // { // bics, bi, s; // // /** // * @param in type to find // * @param argName to display if an error happens // * @return Type or throw exception // * @throws SecretShareException if 'in' is not found // */ // public static Type findByString(String in, String argName) // { // Type ret = valueOf(in); // if (ret != null) // { // return ret; // } // else // { // throw new SecretShareException("Type value '" + in + "' not found." + // ((argName != null) ? " Argname=" + argName : "")); // } // } // } // Path: src/test/java/com/tiemens/secretshare/main/cli/MainBigIntCsTest.java import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; import com.tiemens.secretshare.main.cli.MainBigIntCs.Type; /******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.main.cli; public class MainBigIntCsTest { @Test public void testConvert() {
subTestConvert("Cat", Type.s, Type.s, "Cat");
timtiemens/secretshare
src/main/java/com/tiemens/secretshare/math/combination/CombinationGenerator.java
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // }
import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import com.tiemens.secretshare.exceptions.SecretShareException;
/******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.math.combination; public class CombinationGenerator<E> implements Iterator<List<E>>, Iterable<List<E>> { // ================================================== // class static data // ================================================== // ================================================== // class static methods // ================================================== public static void main(String[] args) { System.out.println("fact(5)=" + factorial(5)); System.out.println("fact(3)=" + factorial(3)); List<String> list = Arrays.asList("1", "2", "3", "4", "5"); CombinationGenerator<String> combos = new CombinationGenerator<String>(list, 3); int count = 1; System.out.println("Total number=" + combos.getTotalNumberOfCombinations()); for (List<String> combination : combos) { System.out.println(count + ": " + combination + " {" + combos.indexesAsString + "}"); count++; } } // ================================================== // instance data // ================================================== private final List<E> list; // currentIndexes contains the indexes to use for the NEXT iteration private int[] currentIndexes; // indexesAsString contains either null or the CURRENT iteration's indexes private String indexesAsString; // private final BigInteger totalNumberOfCombinations; // ranges 0 to totalNumber, where "0" means "you haven't called next() yet" private BigInteger combinationNumber; // ================================================== // factories // ================================================== // ================================================== // constructors // ================================================== public CombinationGenerator(final List<E> inList, final int inChoiceSize) { if (inChoiceSize < 1) {
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // Path: src/main/java/com/tiemens/secretshare/math/combination/CombinationGenerator.java import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import com.tiemens.secretshare.exceptions.SecretShareException; /******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.math.combination; public class CombinationGenerator<E> implements Iterator<List<E>>, Iterable<List<E>> { // ================================================== // class static data // ================================================== // ================================================== // class static methods // ================================================== public static void main(String[] args) { System.out.println("fact(5)=" + factorial(5)); System.out.println("fact(3)=" + factorial(3)); List<String> list = Arrays.asList("1", "2", "3", "4", "5"); CombinationGenerator<String> combos = new CombinationGenerator<String>(list, 3); int count = 1; System.out.println("Total number=" + combos.getTotalNumberOfCombinations()); for (List<String> combination : combos) { System.out.println(count + ": " + combination + " {" + combos.indexesAsString + "}"); count++; } } // ================================================== // instance data // ================================================== private final List<E> list; // currentIndexes contains the indexes to use for the NEXT iteration private int[] currentIndexes; // indexesAsString contains either null or the CURRENT iteration's indexes private String indexesAsString; // private final BigInteger totalNumberOfCombinations; // ranges 0 to totalNumber, where "0" means "you haven't called next() yet" private BigInteger combinationNumber; // ================================================== // factories // ================================================== // ================================================== // constructors // ================================================== public CombinationGenerator(final List<E> inList, final int inChoiceSize) { if (inChoiceSize < 1) {
throw new SecretShareException("choice size cannot be less than 1:" + inChoiceSize);
timtiemens/secretshare
src/main/java/com/tiemens/secretshare/math/type/BigIntStringChecksum.java
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5Checksummer.java // public interface Md5Checksummer // { // /** // * @param in the byte array to compute a checksum // * @return the complete md5 checksum // */ // public byte[] createMd5Checksum(final byte[] in); // } // // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5ChecksummerFactory.java // public final class Md5ChecksummerFactory // { // // // ================================================== // // class static data // // ================================================== // // private static final String KEY = "ssmd5class"; // // // ================================================== // // class static methods // // ================================================== // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // public static Md5Checksummer create() // { // String cname = System.getProperty(KEY); // if (cname != null) // { // return createFromClassName(cname); // } // else // { // try // { // return new Md5ChecksummerImpl(); // } // catch (SecretShareException e) // { // throw new SecretShareException("Failed to create built-in MD5 digest. " + // "Use -D" + KEY + "=a.b.c.YourMd5Checksummer" + // " where your class must implement the interface " + // Md5Checksummer.class.getName(), e); // } // // } // } // // /** // * @param cname the name of the class that implements Md5Checksummer interface // * @return instance // * @throws SecretShareException on error // */ // public static Md5Checksummer createFromClassName(String cname) // { // final String msg = "create md5, name='" + cname + "' "; // try // { // Class<?> c = Class.forName(cname); // if (Md5Checksummer.class.isAssignableFrom(c)) // { // return (Md5Checksummer) c.newInstance(); // } // else // { // throw new SecretShareException(msg + " does not implement interface " + // Md5Checksummer.class.getName()); // } // } // catch (InstantiationException e) // { // throw new SecretShareException(msg + "instantiation", e); // } // catch (IllegalAccessException e) // { // throw new SecretShareException(msg + "access", e); // } // catch (ClassNotFoundException e) // { // throw new SecretShareException(msg + "class not found", e); // } // } // // // ================================================== // // constructors // // ================================================== // // private Md5ChecksummerFactory() // { // // no instances // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // }
import java.math.BigInteger; import com.tiemens.secretshare.exceptions.SecretShareException; import com.tiemens.secretshare.md5sum.Md5Checksummer; import com.tiemens.secretshare.md5sum.Md5ChecksummerFactory;
/** * Take string as input, and either return an instance or return null. * * @param bics string in "bigintcs:hhhhhh-hhhhhh-CCCCCC" format * @return big integer string checksum object * OR null if incorrect format, error parsing, etc. */ public static BigIntStringChecksum fromStringOrNull(String bics) { BigIntStringChecksum ret; if (bics == null) { ret = null; } else if (! startsWithPrefix(bics)) { ret = null; } else { try { ret = fromString(bics); // completely test the input: make sure // asBigInteger will throw a SecretShareException on error if (ret.asBigInteger() == null) { // asBigInteger() is not allowed to return null. // but just in case it does:
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5Checksummer.java // public interface Md5Checksummer // { // /** // * @param in the byte array to compute a checksum // * @return the complete md5 checksum // */ // public byte[] createMd5Checksum(final byte[] in); // } // // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5ChecksummerFactory.java // public final class Md5ChecksummerFactory // { // // // ================================================== // // class static data // // ================================================== // // private static final String KEY = "ssmd5class"; // // // ================================================== // // class static methods // // ================================================== // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // public static Md5Checksummer create() // { // String cname = System.getProperty(KEY); // if (cname != null) // { // return createFromClassName(cname); // } // else // { // try // { // return new Md5ChecksummerImpl(); // } // catch (SecretShareException e) // { // throw new SecretShareException("Failed to create built-in MD5 digest. " + // "Use -D" + KEY + "=a.b.c.YourMd5Checksummer" + // " where your class must implement the interface " + // Md5Checksummer.class.getName(), e); // } // // } // } // // /** // * @param cname the name of the class that implements Md5Checksummer interface // * @return instance // * @throws SecretShareException on error // */ // public static Md5Checksummer createFromClassName(String cname) // { // final String msg = "create md5, name='" + cname + "' "; // try // { // Class<?> c = Class.forName(cname); // if (Md5Checksummer.class.isAssignableFrom(c)) // { // return (Md5Checksummer) c.newInstance(); // } // else // { // throw new SecretShareException(msg + " does not implement interface " + // Md5Checksummer.class.getName()); // } // } // catch (InstantiationException e) // { // throw new SecretShareException(msg + "instantiation", e); // } // catch (IllegalAccessException e) // { // throw new SecretShareException(msg + "access", e); // } // catch (ClassNotFoundException e) // { // throw new SecretShareException(msg + "class not found", e); // } // } // // // ================================================== // // constructors // // ================================================== // // private Md5ChecksummerFactory() // { // // no instances // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // Path: src/main/java/com/tiemens/secretshare/math/type/BigIntStringChecksum.java import java.math.BigInteger; import com.tiemens.secretshare.exceptions.SecretShareException; import com.tiemens.secretshare.md5sum.Md5Checksummer; import com.tiemens.secretshare.md5sum.Md5ChecksummerFactory; /** * Take string as input, and either return an instance or return null. * * @param bics string in "bigintcs:hhhhhh-hhhhhh-CCCCCC" format * @return big integer string checksum object * OR null if incorrect format, error parsing, etc. */ public static BigIntStringChecksum fromStringOrNull(String bics) { BigIntStringChecksum ret; if (bics == null) { ret = null; } else if (! startsWithPrefix(bics)) { ret = null; } else { try { ret = fromString(bics); // completely test the input: make sure // asBigInteger will throw a SecretShareException on error if (ret.asBigInteger() == null) { // asBigInteger() is not allowed to return null. // but just in case it does:
throw new SecretShareException("Programmer error converting '" +
timtiemens/secretshare
src/main/java/com/tiemens/secretshare/math/type/BigIntStringChecksum.java
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5Checksummer.java // public interface Md5Checksummer // { // /** // * @param in the byte array to compute a checksum // * @return the complete md5 checksum // */ // public byte[] createMd5Checksum(final byte[] in); // } // // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5ChecksummerFactory.java // public final class Md5ChecksummerFactory // { // // // ================================================== // // class static data // // ================================================== // // private static final String KEY = "ssmd5class"; // // // ================================================== // // class static methods // // ================================================== // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // public static Md5Checksummer create() // { // String cname = System.getProperty(KEY); // if (cname != null) // { // return createFromClassName(cname); // } // else // { // try // { // return new Md5ChecksummerImpl(); // } // catch (SecretShareException e) // { // throw new SecretShareException("Failed to create built-in MD5 digest. " + // "Use -D" + KEY + "=a.b.c.YourMd5Checksummer" + // " where your class must implement the interface " + // Md5Checksummer.class.getName(), e); // } // // } // } // // /** // * @param cname the name of the class that implements Md5Checksummer interface // * @return instance // * @throws SecretShareException on error // */ // public static Md5Checksummer createFromClassName(String cname) // { // final String msg = "create md5, name='" + cname + "' "; // try // { // Class<?> c = Class.forName(cname); // if (Md5Checksummer.class.isAssignableFrom(c)) // { // return (Md5Checksummer) c.newInstance(); // } // else // { // throw new SecretShareException(msg + " does not implement interface " + // Md5Checksummer.class.getName()); // } // } // catch (InstantiationException e) // { // throw new SecretShareException(msg + "instantiation", e); // } // catch (IllegalAccessException e) // { // throw new SecretShareException(msg + "access", e); // } // catch (ClassNotFoundException e) // { // throw new SecretShareException(msg + "class not found", e); // } // } // // // ================================================== // // constructors // // ================================================== // // private Md5ChecksummerFactory() // { // // no instances // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // }
import java.math.BigInteger; import com.tiemens.secretshare.exceptions.SecretShareException; import com.tiemens.secretshare.md5sum.Md5Checksummer; import com.tiemens.secretshare.md5sum.Md5ChecksummerFactory;
boolean returnIsNegative = false; if (input.startsWith("-")) { returnIsNegative = true; input = input.substring(1); } while ((input.length() % lengthPerGroup) != 0) { input = "0" + input; } String sep = ""; for (int i = 0, n = input.length() / lengthPerGroup; i < n; i++) { ret += sep; sep = "-"; ret += input.substring((i + 0) * lengthPerGroup, (i + 1) * lengthPerGroup); } if (returnIsNegative) { ret = "-" + ret; } return ret; } private static boolean testonlyUseInternalMd5Impl = false; private static byte[] computeMd5ChecksumFull(String inAsHex2) {
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5Checksummer.java // public interface Md5Checksummer // { // /** // * @param in the byte array to compute a checksum // * @return the complete md5 checksum // */ // public byte[] createMd5Checksum(final byte[] in); // } // // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5ChecksummerFactory.java // public final class Md5ChecksummerFactory // { // // // ================================================== // // class static data // // ================================================== // // private static final String KEY = "ssmd5class"; // // // ================================================== // // class static methods // // ================================================== // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // public static Md5Checksummer create() // { // String cname = System.getProperty(KEY); // if (cname != null) // { // return createFromClassName(cname); // } // else // { // try // { // return new Md5ChecksummerImpl(); // } // catch (SecretShareException e) // { // throw new SecretShareException("Failed to create built-in MD5 digest. " + // "Use -D" + KEY + "=a.b.c.YourMd5Checksummer" + // " where your class must implement the interface " + // Md5Checksummer.class.getName(), e); // } // // } // } // // /** // * @param cname the name of the class that implements Md5Checksummer interface // * @return instance // * @throws SecretShareException on error // */ // public static Md5Checksummer createFromClassName(String cname) // { // final String msg = "create md5, name='" + cname + "' "; // try // { // Class<?> c = Class.forName(cname); // if (Md5Checksummer.class.isAssignableFrom(c)) // { // return (Md5Checksummer) c.newInstance(); // } // else // { // throw new SecretShareException(msg + " does not implement interface " + // Md5Checksummer.class.getName()); // } // } // catch (InstantiationException e) // { // throw new SecretShareException(msg + "instantiation", e); // } // catch (IllegalAccessException e) // { // throw new SecretShareException(msg + "access", e); // } // catch (ClassNotFoundException e) // { // throw new SecretShareException(msg + "class not found", e); // } // } // // // ================================================== // // constructors // // ================================================== // // private Md5ChecksummerFactory() // { // // no instances // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // Path: src/main/java/com/tiemens/secretshare/math/type/BigIntStringChecksum.java import java.math.BigInteger; import com.tiemens.secretshare.exceptions.SecretShareException; import com.tiemens.secretshare.md5sum.Md5Checksummer; import com.tiemens.secretshare.md5sum.Md5ChecksummerFactory; boolean returnIsNegative = false; if (input.startsWith("-")) { returnIsNegative = true; input = input.substring(1); } while ((input.length() % lengthPerGroup) != 0) { input = "0" + input; } String sep = ""; for (int i = 0, n = input.length() / lengthPerGroup; i < n; i++) { ret += sep; sep = "-"; ret += input.substring((i + 0) * lengthPerGroup, (i + 1) * lengthPerGroup); } if (returnIsNegative) { ret = "-" + ret; } return ret; } private static boolean testonlyUseInternalMd5Impl = false; private static byte[] computeMd5ChecksumFull(String inAsHex2) {
Md5Checksummer md5summer = null;
timtiemens/secretshare
src/main/java/com/tiemens/secretshare/math/type/BigIntStringChecksum.java
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5Checksummer.java // public interface Md5Checksummer // { // /** // * @param in the byte array to compute a checksum // * @return the complete md5 checksum // */ // public byte[] createMd5Checksum(final byte[] in); // } // // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5ChecksummerFactory.java // public final class Md5ChecksummerFactory // { // // // ================================================== // // class static data // // ================================================== // // private static final String KEY = "ssmd5class"; // // // ================================================== // // class static methods // // ================================================== // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // public static Md5Checksummer create() // { // String cname = System.getProperty(KEY); // if (cname != null) // { // return createFromClassName(cname); // } // else // { // try // { // return new Md5ChecksummerImpl(); // } // catch (SecretShareException e) // { // throw new SecretShareException("Failed to create built-in MD5 digest. " + // "Use -D" + KEY + "=a.b.c.YourMd5Checksummer" + // " where your class must implement the interface " + // Md5Checksummer.class.getName(), e); // } // // } // } // // /** // * @param cname the name of the class that implements Md5Checksummer interface // * @return instance // * @throws SecretShareException on error // */ // public static Md5Checksummer createFromClassName(String cname) // { // final String msg = "create md5, name='" + cname + "' "; // try // { // Class<?> c = Class.forName(cname); // if (Md5Checksummer.class.isAssignableFrom(c)) // { // return (Md5Checksummer) c.newInstance(); // } // else // { // throw new SecretShareException(msg + " does not implement interface " + // Md5Checksummer.class.getName()); // } // } // catch (InstantiationException e) // { // throw new SecretShareException(msg + "instantiation", e); // } // catch (IllegalAccessException e) // { // throw new SecretShareException(msg + "access", e); // } // catch (ClassNotFoundException e) // { // throw new SecretShareException(msg + "class not found", e); // } // } // // // ================================================== // // constructors // // ================================================== // // private Md5ChecksummerFactory() // { // // no instances // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // }
import java.math.BigInteger; import com.tiemens.secretshare.exceptions.SecretShareException; import com.tiemens.secretshare.md5sum.Md5Checksummer; import com.tiemens.secretshare.md5sum.Md5ChecksummerFactory;
{ returnIsNegative = true; input = input.substring(1); } while ((input.length() % lengthPerGroup) != 0) { input = "0" + input; } String sep = ""; for (int i = 0, n = input.length() / lengthPerGroup; i < n; i++) { ret += sep; sep = "-"; ret += input.substring((i + 0) * lengthPerGroup, (i + 1) * lengthPerGroup); } if (returnIsNegative) { ret = "-" + ret; } return ret; } private static boolean testonlyUseInternalMd5Impl = false; private static byte[] computeMd5ChecksumFull(String inAsHex2) { Md5Checksummer md5summer = null;
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5Checksummer.java // public interface Md5Checksummer // { // /** // * @param in the byte array to compute a checksum // * @return the complete md5 checksum // */ // public byte[] createMd5Checksum(final byte[] in); // } // // Path: src/main/java/com/tiemens/secretshare/md5sum/Md5ChecksummerFactory.java // public final class Md5ChecksummerFactory // { // // // ================================================== // // class static data // // ================================================== // // private static final String KEY = "ssmd5class"; // // // ================================================== // // class static methods // // ================================================== // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // public static Md5Checksummer create() // { // String cname = System.getProperty(KEY); // if (cname != null) // { // return createFromClassName(cname); // } // else // { // try // { // return new Md5ChecksummerImpl(); // } // catch (SecretShareException e) // { // throw new SecretShareException("Failed to create built-in MD5 digest. " + // "Use -D" + KEY + "=a.b.c.YourMd5Checksummer" + // " where your class must implement the interface " + // Md5Checksummer.class.getName(), e); // } // // } // } // // /** // * @param cname the name of the class that implements Md5Checksummer interface // * @return instance // * @throws SecretShareException on error // */ // public static Md5Checksummer createFromClassName(String cname) // { // final String msg = "create md5, name='" + cname + "' "; // try // { // Class<?> c = Class.forName(cname); // if (Md5Checksummer.class.isAssignableFrom(c)) // { // return (Md5Checksummer) c.newInstance(); // } // else // { // throw new SecretShareException(msg + " does not implement interface " + // Md5Checksummer.class.getName()); // } // } // catch (InstantiationException e) // { // throw new SecretShareException(msg + "instantiation", e); // } // catch (IllegalAccessException e) // { // throw new SecretShareException(msg + "access", e); // } // catch (ClassNotFoundException e) // { // throw new SecretShareException(msg + "class not found", e); // } // } // // // ================================================== // // constructors // // ================================================== // // private Md5ChecksummerFactory() // { // // no instances // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // Path: src/main/java/com/tiemens/secretshare/math/type/BigIntStringChecksum.java import java.math.BigInteger; import com.tiemens.secretshare.exceptions.SecretShareException; import com.tiemens.secretshare.md5sum.Md5Checksummer; import com.tiemens.secretshare.md5sum.Md5ChecksummerFactory; { returnIsNegative = true; input = input.substring(1); } while ((input.length() % lengthPerGroup) != 0) { input = "0" + input; } String sep = ""; for (int i = 0, n = input.length() / lengthPerGroup; i < n; i++) { ret += sep; sep = "-"; ret += input.substring((i + 0) * lengthPerGroup, (i + 1) * lengthPerGroup); } if (returnIsNegative) { ret = "-" + ret; } return ret; } private static boolean testonlyUseInternalMd5Impl = false; private static byte[] computeMd5ChecksumFull(String inAsHex2) { Md5Checksummer md5summer = null;
md5summer = Md5ChecksummerFactory.create();
timtiemens/secretshare
src/main/java/com/tiemens/secretshare/math/type/BigIntUtilities.java
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // }
import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.security.SecureRandom; import java.util.Random; import com.tiemens.secretshare.exceptions.SecretShareException;
/******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.math.type; public final class BigIntUtilities { // ================================================== // class static data // ================================================== private static final String UTF8 = "UTF-8"; // ================================================== // class static methods // ================================================== /** * Converter class : "Human" * Input format : Any (human readable) string * Example input : "This is my cat" * gives BigInteger : 1711994770713785234966317640147316 */ public static class Human { /** * Convert a "human string" into a BigInteger by using the string's * byte[] array. * This is NOT EVEN CLOSE to the same as new BigInteger("string"). * * @param in a string like "This is my cat" or "123FooBar" * @return BigInteger * @throws SecretShareException on error */ public static BigInteger createBigInteger(final String in) { BigInteger ret = null; try { byte[] b = in.getBytes(UTF8); ret = new BigInteger(b); return ret; } catch (UnsupportedEncodingException e) { // just can't happen, but if it does:
// Path: src/main/java/com/tiemens/secretshare/exceptions/SecretShareException.java // public class SecretShareException // extends RuntimeException // { // // ================================================== // // class static data // // ================================================== // // private static final long serialVersionUID = 2193317873773384997L; // // // ================================================== // // class static methods // // ================================================== // // // // // ================================================== // // instance data // // ================================================== // // // ================================================== // // factories // // ================================================== // // // ================================================== // // constructors // // ================================================== // // // /** Constructs a new runtime exception with the specified detail message. // * The cause is not initialized, and may subsequently be initialized by a // * call to {@link #initCause}. // * // * @param message the detail message. The detail message is saved for // * later retrieval by the {@link #getMessage()} method. // */ // public SecretShareException(final String message) // { // super(message); // } // // /** // * Constructs a new runtime exception with the specified detail message and // * cause. <p>Note that the detail message associated with // * <code>cause</code> is <i>not</i> automatically incorporated in // * this runtime exception's detail message. // * // * @param message the detail message (which is saved for later retrieval // * by the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <code>null</code> value is // * permitted, and indicates that the cause is nonexistent or // * unknown.) // */ // public SecretShareException(final String message, // final Throwable cause) // { // super(message, cause); // } // // // ================================================== // // public methods // // ================================================== // // // ================================================== // // non public methods // // ================================================== // } // Path: src/main/java/com/tiemens/secretshare/math/type/BigIntUtilities.java import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.security.SecureRandom; import java.util.Random; import com.tiemens.secretshare.exceptions.SecretShareException; /******************************************************************************* * Copyright (c) 2009, 2014 Tim Tiemens. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * * Contributors: * Tim Tiemens - initial API and implementation *******************************************************************************/ package com.tiemens.secretshare.math.type; public final class BigIntUtilities { // ================================================== // class static data // ================================================== private static final String UTF8 = "UTF-8"; // ================================================== // class static methods // ================================================== /** * Converter class : "Human" * Input format : Any (human readable) string * Example input : "This is my cat" * gives BigInteger : 1711994770713785234966317640147316 */ public static class Human { /** * Convert a "human string" into a BigInteger by using the string's * byte[] array. * This is NOT EVEN CLOSE to the same as new BigInteger("string"). * * @param in a string like "This is my cat" or "123FooBar" * @return BigInteger * @throws SecretShareException on error */ public static BigInteger createBigInteger(final String in) { BigInteger ret = null; try { byte[] b = in.getBytes(UTF8); ret = new BigInteger(b); return ret; } catch (UnsupportedEncodingException e) { // just can't happen, but if it does:
throw new SecretShareException("UTF8 not found", e);
danburkert/kudu-ts
core/src/main/java/org/kududb/ts/core/Metrics.java
// Path: core/src/main/java/org/kududb/client/AbstractionBulldozer.java // public final class AbstractionBulldozer { // // private AbstractionBulldozer() {} // // /** // * Set {@link AbstractKuduScannerBuilder#sortResultsByPrimaryKey} on a scanner builder. // * // * @param builder to set primary key sorting on // * @return the builder // */ // public static <S extends AbstractKuduScannerBuilder<S, T>, T> AbstractKuduScannerBuilder<S, T> // sortResultsByPrimaryKey(AbstractKuduScannerBuilder<S, T> builder) { // builder.sortResultsByPrimaryKey(); // return builder; // } // }
import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import java.util.List; import javax.annotation.concurrent.ThreadSafe; import org.apache.kudu.annotations.InterfaceAudience; import org.apache.kudu.client.AbstractionBulldozer; import org.apache.kudu.client.AsyncKuduClient; import org.apache.kudu.client.AsyncKuduScanner; import org.apache.kudu.client.Insert; import org.apache.kudu.client.Upsert; import org.apache.kudu.client.KuduPredicate; import org.apache.kudu.client.KuduTable; import org.apache.kudu.client.RowResult; import org.apache.kudu.client.RowResultIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
Upsert insert = table.newUpsert(); insert.getRow().addString(Tables.METRICS_METRIC_INDEX, metric); insert.getRow().addInt(Tables.METRICS_TAGSET_ID_INDEX, tagsetID); insert.getRow().addLong(Tables.METRICS_TIME_INDEX, time); insert.getRow().addDouble(Tables.METRICS_VALUE_INDEX, value); return insert; } public Deferred<Datapoints> scanSeries(final String metric, final int tagsetID, final long startTime, final long endTime, final Aggregator downsampler, final long downsampleInterval) { KuduPredicate metricPred = KuduPredicate.newComparisonPredicate(Tables.METRICS_METRIC_COLUMN, KuduPredicate.ComparisonOp.EQUAL, metric); KuduPredicate tagsetIdPred = KuduPredicate.newComparisonPredicate(Tables.METRICS_TAGSET_ID_COLUMN, KuduPredicate.ComparisonOp.EQUAL, tagsetID); KuduPredicate startTimestampPred = KuduPredicate.newComparisonPredicate(Tables.METRICS_TIME_COLUMN, KuduPredicate.ComparisonOp.GREATER_EQUAL, startTime); KuduPredicate endTimestampPred = KuduPredicate.newComparisonPredicate(Tables.METRICS_TIME_COLUMN, KuduPredicate.ComparisonOp.LESS, endTime);
// Path: core/src/main/java/org/kududb/client/AbstractionBulldozer.java // public final class AbstractionBulldozer { // // private AbstractionBulldozer() {} // // /** // * Set {@link AbstractKuduScannerBuilder#sortResultsByPrimaryKey} on a scanner builder. // * // * @param builder to set primary key sorting on // * @return the builder // */ // public static <S extends AbstractKuduScannerBuilder<S, T>, T> AbstractKuduScannerBuilder<S, T> // sortResultsByPrimaryKey(AbstractKuduScannerBuilder<S, T> builder) { // builder.sortResultsByPrimaryKey(); // return builder; // } // } // Path: core/src/main/java/org/kududb/ts/core/Metrics.java import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import java.util.List; import javax.annotation.concurrent.ThreadSafe; import org.apache.kudu.annotations.InterfaceAudience; import org.apache.kudu.client.AbstractionBulldozer; import org.apache.kudu.client.AsyncKuduClient; import org.apache.kudu.client.AsyncKuduScanner; import org.apache.kudu.client.Insert; import org.apache.kudu.client.Upsert; import org.apache.kudu.client.KuduPredicate; import org.apache.kudu.client.KuduTable; import org.apache.kudu.client.RowResult; import org.apache.kudu.client.RowResultIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; Upsert insert = table.newUpsert(); insert.getRow().addString(Tables.METRICS_METRIC_INDEX, metric); insert.getRow().addInt(Tables.METRICS_TAGSET_ID_INDEX, tagsetID); insert.getRow().addLong(Tables.METRICS_TIME_INDEX, time); insert.getRow().addDouble(Tables.METRICS_VALUE_INDEX, value); return insert; } public Deferred<Datapoints> scanSeries(final String metric, final int tagsetID, final long startTime, final long endTime, final Aggregator downsampler, final long downsampleInterval) { KuduPredicate metricPred = KuduPredicate.newComparisonPredicate(Tables.METRICS_METRIC_COLUMN, KuduPredicate.ComparisonOp.EQUAL, metric); KuduPredicate tagsetIdPred = KuduPredicate.newComparisonPredicate(Tables.METRICS_TAGSET_ID_COLUMN, KuduPredicate.ComparisonOp.EQUAL, tagsetID); KuduPredicate startTimestampPred = KuduPredicate.newComparisonPredicate(Tables.METRICS_TIME_COLUMN, KuduPredicate.ComparisonOp.GREATER_EQUAL, startTime); KuduPredicate endTimestampPred = KuduPredicate.newComparisonPredicate(Tables.METRICS_TIME_COLUMN, KuduPredicate.ComparisonOp.LESS, endTime);
final AsyncKuduScanner scanner = AbstractionBulldozer.sortResultsByPrimaryKey(
danburkert/kudu-ts
ktsd/src/main/java/org/kududb/ts/ktsd/PutSeries.java
// Path: core/src/main/java/org/kududb/ts/core/Datapoint.java // @InterfaceAudience.Public // @InterfaceStability.Unstable // @NotThreadSafe // public final class Datapoint { // private long time; // private double value; // // private Datapoint(long time, double value) { // this.time = time; // this.value = value; // } // // /** // * Creates a new {@code Datapoint} with the provided time and value. // * @param microseconds the {@code Datapoint}'s time in microseconds // * @param value the {@code Datapoint}'s value // * @return a new {@code Datapoint} // */ // public static Datapoint create(long microseconds, double value) { // return new Datapoint(microseconds, value); // } // // /** // * Returns the {@code Datapoint}'s time in microseconds. // * @return the {@code Datapoint}'s time in microseconds // */ // public long getTime() { // return time; // } // // /** // * Returns the {@code Datapoint}'s value. // * @return the {@code Datapoint}'s value // */ // public double getValue() { // return value; // } // // /** // * Sets the time of the {@code Datapoint}. // * @param microseconds the new time in microseconds // */ // public void setTime(long microseconds) { // time = microseconds; // } // // /** // * Sets the value of the {@code Datapoint}. // * @param value the new value // */ // public void setValue(double value) { // this.value = value; // } // // /** {@inheritDoc} */ // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("time", time) // .add("value", value) // .toString(); // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import java.net.URI; import java.util.SortedMap; import java.util.concurrent.CountDownLatch; import org.LatencyUtils.LatencyStats; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.kududb.ts.core.Datapoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
private final String metric; private final SortedMap<String, String> tags; private final DatapointGenerator datapoints; private final LatencyStats stats; private final CloseableHttpClient client; private final ObjectMapper mapper; private final CountDownLatch latch; public PutSeries(URI url, String metric, SortedMap<String, String> tags, DatapointGenerator datapoints, LatencyStats stats, CloseableHttpClient client, ObjectMapper mapper, CountDownLatch latch) { this.url = url; this.metric = metric; this.tags = tags; this.datapoints = datapoints; this.stats = stats; this.client = client; this.mapper = mapper; this.latch = latch; } @Override public void run() { try { while (datapoints.hasNext()) {
// Path: core/src/main/java/org/kududb/ts/core/Datapoint.java // @InterfaceAudience.Public // @InterfaceStability.Unstable // @NotThreadSafe // public final class Datapoint { // private long time; // private double value; // // private Datapoint(long time, double value) { // this.time = time; // this.value = value; // } // // /** // * Creates a new {@code Datapoint} with the provided time and value. // * @param microseconds the {@code Datapoint}'s time in microseconds // * @param value the {@code Datapoint}'s value // * @return a new {@code Datapoint} // */ // public static Datapoint create(long microseconds, double value) { // return new Datapoint(microseconds, value); // } // // /** // * Returns the {@code Datapoint}'s time in microseconds. // * @return the {@code Datapoint}'s time in microseconds // */ // public long getTime() { // return time; // } // // /** // * Returns the {@code Datapoint}'s value. // * @return the {@code Datapoint}'s value // */ // public double getValue() { // return value; // } // // /** // * Sets the time of the {@code Datapoint}. // * @param microseconds the new time in microseconds // */ // public void setTime(long microseconds) { // time = microseconds; // } // // /** // * Sets the value of the {@code Datapoint}. // * @param value the new value // */ // public void setValue(double value) { // this.value = value; // } // // /** {@inheritDoc} */ // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("time", time) // .add("value", value) // .toString(); // } // } // Path: ktsd/src/main/java/org/kududb/ts/ktsd/PutSeries.java import com.fasterxml.jackson.databind.ObjectMapper; import java.net.URI; import java.util.SortedMap; import java.util.concurrent.CountDownLatch; import org.LatencyUtils.LatencyStats; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.kududb.ts.core.Datapoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; private final String metric; private final SortedMap<String, String> tags; private final DatapointGenerator datapoints; private final LatencyStats stats; private final CloseableHttpClient client; private final ObjectMapper mapper; private final CountDownLatch latch; public PutSeries(URI url, String metric, SortedMap<String, String> tags, DatapointGenerator datapoints, LatencyStats stats, CloseableHttpClient client, ObjectMapper mapper, CountDownLatch latch) { this.url = url; this.metric = metric; this.tags = tags; this.datapoints = datapoints; this.stats = stats; this.client = client; this.mapper = mapper; this.latch = latch; } @Override public void run() { try { while (datapoints.hasNext()) {
Datapoint dp = datapoints.next();
danburkert/kudu-ts
core/src/main/java/org/kududb/ts/core/Tagsets.java
// Path: core/src/main/java/org/kududb/client/AbstractionBulldozer.java // public final class AbstractionBulldozer { // // private AbstractionBulldozer() {} // // /** // * Set {@link AbstractKuduScannerBuilder#sortResultsByPrimaryKey} on a scanner builder. // * // * @param builder to set primary key sorting on // * @return the builder // */ // public static <S extends AbstractKuduScannerBuilder<S, T>, T> AbstractKuduScannerBuilder<S, T> // sortResultsByPrimaryKey(AbstractKuduScannerBuilder<S, T> builder) { // builder.sortResultsByPrimaryKey(); // return builder; // } // }
import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import com.google.common.hash.Hashing; import com.google.common.primitives.Ints; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.annotation.concurrent.ThreadSafe; import org.apache.kudu.annotations.InterfaceAudience; import org.apache.kudu.client.AbstractionBulldozer; import org.apache.kudu.client.AsyncKuduClient; import org.apache.kudu.client.AsyncKuduScanner; import org.apache.kudu.client.AsyncKuduSession; import org.apache.kudu.client.Insert; import org.apache.kudu.client.KuduException; import org.apache.kudu.client.KuduPredicate; import org.apache.kudu.client.KuduPredicate.ComparisonOp; import org.apache.kudu.client.KuduTable; import org.apache.kudu.client.OperationResponse; import org.apache.kudu.client.RowResult; import org.apache.kudu.client.RowResultIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
return lookupTagset(tagset, id).addCallbackDeferring(new LookupCB()) .addErrback(new LookupErrback()); } private Deferred<TagsetLookupResult> lookupTagset(SerializedTagset tagset, int id) { LOG.debug("Looking up tagset; id: {}, tags: {}", id, tagset); AsyncKuduScanner tagsetScanner = tagsetScanner(id); return tagsetScanner.nextRows().addCallbackDeferring( new TagsetScanCB(tagset, id, tagsetScanner)); } /** * Creates an {@link AsyncKuduScanner} over the tagset table beginning with * the specified ID. * * @param id the ID to begin scanning from * @return the scanner */ private AsyncKuduScanner tagsetScanner(int id) { AsyncKuduScanner.AsyncKuduScannerBuilder scanBuilder = client.newScannerBuilder(tagsetsTable); scanBuilder.addPredicate(KuduPredicate.newComparisonPredicate(Tables.TAGSETS_ID_COLUMN, ComparisonOp.GREATER_EQUAL, id)); if (id < Integer.MAX_VALUE - TAGSETS_PER_SCAN) { scanBuilder.addPredicate(KuduPredicate.newComparisonPredicate(Tables.TAGSETS_ID_COLUMN, ComparisonOp.LESS, id + TAGSETS_PER_SCAN)); } scanBuilder.setProjectedColumnIndexes(columnIndexes);
// Path: core/src/main/java/org/kududb/client/AbstractionBulldozer.java // public final class AbstractionBulldozer { // // private AbstractionBulldozer() {} // // /** // * Set {@link AbstractKuduScannerBuilder#sortResultsByPrimaryKey} on a scanner builder. // * // * @param builder to set primary key sorting on // * @return the builder // */ // public static <S extends AbstractKuduScannerBuilder<S, T>, T> AbstractKuduScannerBuilder<S, T> // sortResultsByPrimaryKey(AbstractKuduScannerBuilder<S, T> builder) { // builder.sortResultsByPrimaryKey(); // return builder; // } // } // Path: core/src/main/java/org/kududb/ts/core/Tagsets.java import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import com.google.common.hash.Hashing; import com.google.common.primitives.Ints; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.annotation.concurrent.ThreadSafe; import org.apache.kudu.annotations.InterfaceAudience; import org.apache.kudu.client.AbstractionBulldozer; import org.apache.kudu.client.AsyncKuduClient; import org.apache.kudu.client.AsyncKuduScanner; import org.apache.kudu.client.AsyncKuduSession; import org.apache.kudu.client.Insert; import org.apache.kudu.client.KuduException; import org.apache.kudu.client.KuduPredicate; import org.apache.kudu.client.KuduPredicate.ComparisonOp; import org.apache.kudu.client.KuduTable; import org.apache.kudu.client.OperationResponse; import org.apache.kudu.client.RowResult; import org.apache.kudu.client.RowResultIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; return lookupTagset(tagset, id).addCallbackDeferring(new LookupCB()) .addErrback(new LookupErrback()); } private Deferred<TagsetLookupResult> lookupTagset(SerializedTagset tagset, int id) { LOG.debug("Looking up tagset; id: {}, tags: {}", id, tagset); AsyncKuduScanner tagsetScanner = tagsetScanner(id); return tagsetScanner.nextRows().addCallbackDeferring( new TagsetScanCB(tagset, id, tagsetScanner)); } /** * Creates an {@link AsyncKuduScanner} over the tagset table beginning with * the specified ID. * * @param id the ID to begin scanning from * @return the scanner */ private AsyncKuduScanner tagsetScanner(int id) { AsyncKuduScanner.AsyncKuduScannerBuilder scanBuilder = client.newScannerBuilder(tagsetsTable); scanBuilder.addPredicate(KuduPredicate.newComparisonPredicate(Tables.TAGSETS_ID_COLUMN, ComparisonOp.GREATER_EQUAL, id)); if (id < Integer.MAX_VALUE - TAGSETS_PER_SCAN) { scanBuilder.addPredicate(KuduPredicate.newComparisonPredicate(Tables.TAGSETS_ID_COLUMN, ComparisonOp.LESS, id + TAGSETS_PER_SCAN)); } scanBuilder.setProjectedColumnIndexes(columnIndexes);
AbstractionBulldozer.sortResultsByPrimaryKey(scanBuilder);
danburkert/kudu-ts
core/src/main/java/org/kududb/ts/core/Query.java
// Path: core/src/main/java/org/kududb/ts/core/Interpolators.java // @InterfaceAudience.Public // @InterfaceStability.Unstable // @ThreadSafe // public interface Interpolator { // // /** // * Create an interpolation over a set of datapoints. // * @param datapoints to interpolate // * @return the interpolation // */ // Interpolation interpolate(Datapoints datapoints); // }
import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import java.util.Map; import javax.annotation.concurrent.NotThreadSafe; import org.apache.kudu.annotations.InterfaceAudience; import org.apache.kudu.annotations.InterfaceStability; import org.kududb.ts.core.Interpolators.Interpolator;
package org.kududb.ts.core; @InterfaceAudience.Public @InterfaceStability.Evolving @NotThreadSafe public class Query { private final String metric; private final Map<String, String> tags; private final Aggregator aggregator; private long start = Long.MIN_VALUE; private long end = Long.MAX_VALUE; private Aggregator downsampler = null; private long downsampleInterval = 0;
// Path: core/src/main/java/org/kududb/ts/core/Interpolators.java // @InterfaceAudience.Public // @InterfaceStability.Unstable // @ThreadSafe // public interface Interpolator { // // /** // * Create an interpolation over a set of datapoints. // * @param datapoints to interpolate // * @return the interpolation // */ // Interpolation interpolate(Datapoints datapoints); // } // Path: core/src/main/java/org/kududb/ts/core/Query.java import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import java.util.Map; import javax.annotation.concurrent.NotThreadSafe; import org.apache.kudu.annotations.InterfaceAudience; import org.apache.kudu.annotations.InterfaceStability; import org.kududb.ts.core.Interpolators.Interpolator; package org.kududb.ts.core; @InterfaceAudience.Public @InterfaceStability.Evolving @NotThreadSafe public class Query { private final String metric; private final Map<String, String> tags; private final Aggregator aggregator; private long start = Long.MIN_VALUE; private long end = Long.MAX_VALUE; private Aggregator downsampler = null; private long downsampleInterval = 0;
private Interpolator interpolator = null;
gin-fizz/pollistics
src/test/java/com/pollistics/models/validators/PollValidatorTest.java
// Path: src/main/java/com/pollistics/models/Poll.java // @Document(collection="polls") // public class Poll { // @Id // private ObjectId id; // // @Length(min=1, max=500, message="Poll title must be be between 1 and 500 characters") // private String title; // private HashMap<String,Integer> options; // private User user; // // @Indexed(unique = true, sparse = true) // private String slug; // // // todo: orden these constructors with `this(...arg)` // // public Poll(String title, HashMap<String,Integer> options) { // this.title = title; // this.options = options; // this.slug = createSlug(); // } // // public Poll(ObjectId id, String title, HashMap<String, Integer> options) { // this.id = id; // this.title = title; // this.options = options; // this.slug = createSlug(); // } // // public Poll(String title, HashMap<String,Integer> options, String slug) { // this.title = title; // this.options = options; // this.slug = slug; // } // // public Poll(String title, HashMap<String,Integer> options, String slug, User user) { // this.title = title; // this.options = options; // this.user = user; // this.slug = slug; // } // // public Poll(String title, HashMap<String,Integer> options, User user) { // this.title = title; // this.options = options; // this.user = user; // this.slug = createSlug(); // } // // public Poll() { // } // // public String getId() { // return id.toHexString(); // } // // public String getTitle() { // return title; // } // // public void setTitle(String name) { // this.title = name; // } // // public HashMap<String, Integer> getOptions() { // return options; // } // // public void setOptions(HashMap<String, Integer> options) { // this.options = options; // } // // private String createSlug() { // return MemeSlugs.getCombo(); // } // // @JsonIgnore // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public void setSlug(String slug) { // this.slug = slug; // } // // public String getSlug() { // return slug; // } // // public boolean vote(String option) { // if(!options.containsKey(option)) { // return false; // } else { // int val = options.get(option); // val++; // options.put(option,val); // return true; // } // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // Poll poll = (Poll) obj; // return this.getId().equals(poll.getId()); // } // }
import com.pollistics.models.Poll; import org.junit.Test; import org.springframework.validation.DirectFieldBindingResult; import java.util.HashMap; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
package com.pollistics.models.validators; public class PollValidatorTest { @Test public void validateOptionsTest() {
// Path: src/main/java/com/pollistics/models/Poll.java // @Document(collection="polls") // public class Poll { // @Id // private ObjectId id; // // @Length(min=1, max=500, message="Poll title must be be between 1 and 500 characters") // private String title; // private HashMap<String,Integer> options; // private User user; // // @Indexed(unique = true, sparse = true) // private String slug; // // // todo: orden these constructors with `this(...arg)` // // public Poll(String title, HashMap<String,Integer> options) { // this.title = title; // this.options = options; // this.slug = createSlug(); // } // // public Poll(ObjectId id, String title, HashMap<String, Integer> options) { // this.id = id; // this.title = title; // this.options = options; // this.slug = createSlug(); // } // // public Poll(String title, HashMap<String,Integer> options, String slug) { // this.title = title; // this.options = options; // this.slug = slug; // } // // public Poll(String title, HashMap<String,Integer> options, String slug, User user) { // this.title = title; // this.options = options; // this.user = user; // this.slug = slug; // } // // public Poll(String title, HashMap<String,Integer> options, User user) { // this.title = title; // this.options = options; // this.user = user; // this.slug = createSlug(); // } // // public Poll() { // } // // public String getId() { // return id.toHexString(); // } // // public String getTitle() { // return title; // } // // public void setTitle(String name) { // this.title = name; // } // // public HashMap<String, Integer> getOptions() { // return options; // } // // public void setOptions(HashMap<String, Integer> options) { // this.options = options; // } // // private String createSlug() { // return MemeSlugs.getCombo(); // } // // @JsonIgnore // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public void setSlug(String slug) { // this.slug = slug; // } // // public String getSlug() { // return slug; // } // // public boolean vote(String option) { // if(!options.containsKey(option)) { // return false; // } else { // int val = options.get(option); // val++; // options.put(option,val); // return true; // } // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // Poll poll = (Poll) obj; // return this.getId().equals(poll.getId()); // } // } // Path: src/test/java/com/pollistics/models/validators/PollValidatorTest.java import com.pollistics.models.Poll; import org.junit.Test; import org.springframework.validation.DirectFieldBindingResult; import java.util.HashMap; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; package com.pollistics.models.validators; public class PollValidatorTest { @Test public void validateOptionsTest() {
Poll poll = new Poll();
gin-fizz/pollistics
src/main/java/com/pollistics/config/WebSecurityConfig.java
// Path: src/main/java/com/pollistics/services/UserService.java // @Service // public class UserService implements UserDetailsService { // // @Autowired // private UserRepository userRepository; // // public boolean userExists(String username) { // return userRepository.findByUsername(username) != null; // } // // public void createUser(User user) { // BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // String hashedPassword = passwordEncoder.encode(user.getPassword()); // user.setPassword(hashedPassword); // userRepository.insert(user); // } // // @Override // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userRepository.findByUsername(username); // if(user == null){ // throw new UsernameNotFoundException(username); // } else{ // return user; // } // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository; import com.pollistics.services.UserService; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
package com.pollistics.config; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
// Path: src/main/java/com/pollistics/services/UserService.java // @Service // public class UserService implements UserDetailsService { // // @Autowired // private UserRepository userRepository; // // public boolean userExists(String username) { // return userRepository.findByUsername(username) != null; // } // // public void createUser(User user) { // BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // String hashedPassword = passwordEncoder.encode(user.getPassword()); // user.setPassword(hashedPassword); // userRepository.insert(user); // } // // @Override // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userRepository.findByUsername(username); // if(user == null){ // throw new UsernameNotFoundException(username); // } else{ // return user; // } // } // } // Path: src/main/java/com/pollistics/config/WebSecurityConfig.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository; import com.pollistics.services.UserService; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; package com.pollistics.config; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
private UserService userService;
gin-fizz/pollistics
src/test/java/com/pollistics/controllers/AccountControllerTests.java
// Path: src/main/java/com/pollistics/services/UserService.java // @Service // public class UserService implements UserDetailsService { // // @Autowired // private UserRepository userRepository; // // public boolean userExists(String username) { // return userRepository.findByUsername(username) != null; // } // // public void createUser(User user) { // BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // String hashedPassword = passwordEncoder.encode(user.getPassword()); // user.setPassword(hashedPassword); // userRepository.insert(user); // } // // @Override // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userRepository.findByUsername(username); // if(user == null){ // throw new UsernameNotFoundException(username); // } else{ // return user; // } // } // }
import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import com.pollistics.services.UserService;
package com.pollistics.controllers; //import com.pollistics.services.PollService; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc @ContextConfiguration public class AccountControllerTests { @MockBean
// Path: src/main/java/com/pollistics/services/UserService.java // @Service // public class UserService implements UserDetailsService { // // @Autowired // private UserRepository userRepository; // // public boolean userExists(String username) { // return userRepository.findByUsername(username) != null; // } // // public void createUser(User user) { // BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // String hashedPassword = passwordEncoder.encode(user.getPassword()); // user.setPassword(hashedPassword); // userRepository.insert(user); // } // // @Override // public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // User user = userRepository.findByUsername(username); // if(user == null){ // throw new UsernameNotFoundException(username); // } else{ // return user; // } // } // } // Path: src/test/java/com/pollistics/controllers/AccountControllerTests.java import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import com.pollistics.services.UserService; package com.pollistics.controllers; //import com.pollistics.services.PollService; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc @ContextConfiguration public class AccountControllerTests { @MockBean
private UserService userService;
gin-fizz/pollistics
src/test/java/com/pollistics/services/UserServiceTests.java
// Path: src/main/java/com/pollistics/PollisticsApplication.java // @SpringBootApplication // public class PollisticsApplication { // public static void main(String[] args) { // SpringApplication.run(PollisticsApplication.class, args); // } // } // // Path: src/main/java/com/pollistics/models/User.java // @Document(collection="users") // public class User implements UserDetails { // @Id // private ObjectId id; // // @Length(max=100, message="Name can't be more than 100 characters long") // private String name; // private String username; // @Email(message="Email is invalid") // private String email; // private String password; // // public User(String username, String email, String password) { // this.username = username; // this.email = email; // this.password = password; // id = ObjectId.get(); // } // // public User(String username, String password) { // this.username = username; // this.password = password; // id = ObjectId.get(); // } // // public User() { // } // // public String getId() { // return id.toHexString(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setUsername(String username) { // this.username = username; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // User user = (User) obj; // return this.getId().equals(user.getId()); // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return null; // } // // @Override // public String getPassword() { // return password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // } // // Path: src/main/java/com/pollistics/repositories/UserRepository.java // @Repository // public interface UserRepository extends MongoRepository<User,String> { // User findByUsername(String username); // }
import com.pollistics.PollisticsApplication; import com.pollistics.models.User; import com.pollistics.repositories.UserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when;
package com.pollistics.services; @RunWith(SpringRunner.class) @SpringBootTest(classes = PollisticsApplication.class) public class UserServiceTests { @MockBean
// Path: src/main/java/com/pollistics/PollisticsApplication.java // @SpringBootApplication // public class PollisticsApplication { // public static void main(String[] args) { // SpringApplication.run(PollisticsApplication.class, args); // } // } // // Path: src/main/java/com/pollistics/models/User.java // @Document(collection="users") // public class User implements UserDetails { // @Id // private ObjectId id; // // @Length(max=100, message="Name can't be more than 100 characters long") // private String name; // private String username; // @Email(message="Email is invalid") // private String email; // private String password; // // public User(String username, String email, String password) { // this.username = username; // this.email = email; // this.password = password; // id = ObjectId.get(); // } // // public User(String username, String password) { // this.username = username; // this.password = password; // id = ObjectId.get(); // } // // public User() { // } // // public String getId() { // return id.toHexString(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setUsername(String username) { // this.username = username; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // User user = (User) obj; // return this.getId().equals(user.getId()); // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return null; // } // // @Override // public String getPassword() { // return password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // } // // Path: src/main/java/com/pollistics/repositories/UserRepository.java // @Repository // public interface UserRepository extends MongoRepository<User,String> { // User findByUsername(String username); // } // Path: src/test/java/com/pollistics/services/UserServiceTests.java import com.pollistics.PollisticsApplication; import com.pollistics.models.User; import com.pollistics.repositories.UserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; package com.pollistics.services; @RunWith(SpringRunner.class) @SpringBootTest(classes = PollisticsApplication.class) public class UserServiceTests { @MockBean
private UserRepository userRepo;
gin-fizz/pollistics
src/test/java/com/pollistics/services/UserServiceTests.java
// Path: src/main/java/com/pollistics/PollisticsApplication.java // @SpringBootApplication // public class PollisticsApplication { // public static void main(String[] args) { // SpringApplication.run(PollisticsApplication.class, args); // } // } // // Path: src/main/java/com/pollistics/models/User.java // @Document(collection="users") // public class User implements UserDetails { // @Id // private ObjectId id; // // @Length(max=100, message="Name can't be more than 100 characters long") // private String name; // private String username; // @Email(message="Email is invalid") // private String email; // private String password; // // public User(String username, String email, String password) { // this.username = username; // this.email = email; // this.password = password; // id = ObjectId.get(); // } // // public User(String username, String password) { // this.username = username; // this.password = password; // id = ObjectId.get(); // } // // public User() { // } // // public String getId() { // return id.toHexString(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setUsername(String username) { // this.username = username; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // User user = (User) obj; // return this.getId().equals(user.getId()); // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return null; // } // // @Override // public String getPassword() { // return password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // } // // Path: src/main/java/com/pollistics/repositories/UserRepository.java // @Repository // public interface UserRepository extends MongoRepository<User,String> { // User findByUsername(String username); // }
import com.pollistics.PollisticsApplication; import com.pollistics.models.User; import com.pollistics.repositories.UserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when;
package com.pollistics.services; @RunWith(SpringRunner.class) @SpringBootTest(classes = PollisticsApplication.class) public class UserServiceTests { @MockBean private UserRepository userRepo; @Autowired private UserService userService; @Test public void createUserTest() { try {
// Path: src/main/java/com/pollistics/PollisticsApplication.java // @SpringBootApplication // public class PollisticsApplication { // public static void main(String[] args) { // SpringApplication.run(PollisticsApplication.class, args); // } // } // // Path: src/main/java/com/pollistics/models/User.java // @Document(collection="users") // public class User implements UserDetails { // @Id // private ObjectId id; // // @Length(max=100, message="Name can't be more than 100 characters long") // private String name; // private String username; // @Email(message="Email is invalid") // private String email; // private String password; // // public User(String username, String email, String password) { // this.username = username; // this.email = email; // this.password = password; // id = ObjectId.get(); // } // // public User(String username, String password) { // this.username = username; // this.password = password; // id = ObjectId.get(); // } // // public User() { // } // // public String getId() { // return id.toHexString(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setUsername(String username) { // this.username = username; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // User user = (User) obj; // return this.getId().equals(user.getId()); // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return null; // } // // @Override // public String getPassword() { // return password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // } // // Path: src/main/java/com/pollistics/repositories/UserRepository.java // @Repository // public interface UserRepository extends MongoRepository<User,String> { // User findByUsername(String username); // } // Path: src/test/java/com/pollistics/services/UserServiceTests.java import com.pollistics.PollisticsApplication; import com.pollistics.models.User; import com.pollistics.repositories.UserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; package com.pollistics.services; @RunWith(SpringRunner.class) @SpringBootTest(classes = PollisticsApplication.class) public class UserServiceTests { @MockBean private UserRepository userRepo; @Autowired private UserService userService; @Test public void createUserTest() { try {
User u = new User("gebruikersnaam", "Azerty123");
gin-fizz/pollistics
src/main/java/com/pollistics/services/UserService.java
// Path: src/main/java/com/pollistics/models/User.java // @Document(collection="users") // public class User implements UserDetails { // @Id // private ObjectId id; // // @Length(max=100, message="Name can't be more than 100 characters long") // private String name; // private String username; // @Email(message="Email is invalid") // private String email; // private String password; // // public User(String username, String email, String password) { // this.username = username; // this.email = email; // this.password = password; // id = ObjectId.get(); // } // // public User(String username, String password) { // this.username = username; // this.password = password; // id = ObjectId.get(); // } // // public User() { // } // // public String getId() { // return id.toHexString(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setUsername(String username) { // this.username = username; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // User user = (User) obj; // return this.getId().equals(user.getId()); // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return null; // } // // @Override // public String getPassword() { // return password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // } // // Path: src/main/java/com/pollistics/repositories/UserRepository.java // @Repository // public interface UserRepository extends MongoRepository<User,String> { // User findByUsername(String username); // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import com.pollistics.models.User; import com.pollistics.repositories.UserRepository;
package com.pollistics.services; @Service public class UserService implements UserDetailsService { @Autowired
// Path: src/main/java/com/pollistics/models/User.java // @Document(collection="users") // public class User implements UserDetails { // @Id // private ObjectId id; // // @Length(max=100, message="Name can't be more than 100 characters long") // private String name; // private String username; // @Email(message="Email is invalid") // private String email; // private String password; // // public User(String username, String email, String password) { // this.username = username; // this.email = email; // this.password = password; // id = ObjectId.get(); // } // // public User(String username, String password) { // this.username = username; // this.password = password; // id = ObjectId.get(); // } // // public User() { // } // // public String getId() { // return id.toHexString(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setUsername(String username) { // this.username = username; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // User user = (User) obj; // return this.getId().equals(user.getId()); // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return null; // } // // @Override // public String getPassword() { // return password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // } // // Path: src/main/java/com/pollistics/repositories/UserRepository.java // @Repository // public interface UserRepository extends MongoRepository<User,String> { // User findByUsername(String username); // } // Path: src/main/java/com/pollistics/services/UserService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import com.pollistics.models.User; import com.pollistics.repositories.UserRepository; package com.pollistics.services; @Service public class UserService implements UserDetailsService { @Autowired
private UserRepository userRepository;
gin-fizz/pollistics
src/main/java/com/pollistics/services/UserService.java
// Path: src/main/java/com/pollistics/models/User.java // @Document(collection="users") // public class User implements UserDetails { // @Id // private ObjectId id; // // @Length(max=100, message="Name can't be more than 100 characters long") // private String name; // private String username; // @Email(message="Email is invalid") // private String email; // private String password; // // public User(String username, String email, String password) { // this.username = username; // this.email = email; // this.password = password; // id = ObjectId.get(); // } // // public User(String username, String password) { // this.username = username; // this.password = password; // id = ObjectId.get(); // } // // public User() { // } // // public String getId() { // return id.toHexString(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setUsername(String username) { // this.username = username; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // User user = (User) obj; // return this.getId().equals(user.getId()); // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return null; // } // // @Override // public String getPassword() { // return password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // } // // Path: src/main/java/com/pollistics/repositories/UserRepository.java // @Repository // public interface UserRepository extends MongoRepository<User,String> { // User findByUsername(String username); // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import com.pollistics.models.User; import com.pollistics.repositories.UserRepository;
package com.pollistics.services; @Service public class UserService implements UserDetailsService { @Autowired private UserRepository userRepository; public boolean userExists(String username) { return userRepository.findByUsername(username) != null; }
// Path: src/main/java/com/pollistics/models/User.java // @Document(collection="users") // public class User implements UserDetails { // @Id // private ObjectId id; // // @Length(max=100, message="Name can't be more than 100 characters long") // private String name; // private String username; // @Email(message="Email is invalid") // private String email; // private String password; // // public User(String username, String email, String password) { // this.username = username; // this.email = email; // this.password = password; // id = ObjectId.get(); // } // // public User(String username, String password) { // this.username = username; // this.password = password; // id = ObjectId.get(); // } // // public User() { // } // // public String getId() { // return id.toHexString(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setUsername(String username) { // this.username = username; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // User user = (User) obj; // return this.getId().equals(user.getId()); // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return null; // } // // @Override // public String getPassword() { // return password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // } // // Path: src/main/java/com/pollistics/repositories/UserRepository.java // @Repository // public interface UserRepository extends MongoRepository<User,String> { // User findByUsername(String username); // } // Path: src/main/java/com/pollistics/services/UserService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import com.pollistics.models.User; import com.pollistics.repositories.UserRepository; package com.pollistics.services; @Service public class UserService implements UserDetailsService { @Autowired private UserRepository userRepository; public boolean userExists(String username) { return userRepository.findByUsername(username) != null; }
public void createUser(User user) {
gin-fizz/pollistics
src/test/java/com/pollistics/models/validators/UserValidatorTest.java
// Path: src/main/java/com/pollistics/models/User.java // @Document(collection="users") // public class User implements UserDetails { // @Id // private ObjectId id; // // @Length(max=100, message="Name can't be more than 100 characters long") // private String name; // private String username; // @Email(message="Email is invalid") // private String email; // private String password; // // public User(String username, String email, String password) { // this.username = username; // this.email = email; // this.password = password; // id = ObjectId.get(); // } // // public User(String username, String password) { // this.username = username; // this.password = password; // id = ObjectId.get(); // } // // public User() { // } // // public String getId() { // return id.toHexString(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setUsername(String username) { // this.username = username; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // User user = (User) obj; // return this.getId().equals(user.getId()); // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return null; // } // // @Override // public String getPassword() { // return password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // }
import org.springframework.validation.DirectFieldBindingResult; import static org.junit.Assert.*; import org.junit.Test; import com.pollistics.models.User;
package com.pollistics.models.validators; public class UserValidatorTest { @Test public void validateUsernameTest() {
// Path: src/main/java/com/pollistics/models/User.java // @Document(collection="users") // public class User implements UserDetails { // @Id // private ObjectId id; // // @Length(max=100, message="Name can't be more than 100 characters long") // private String name; // private String username; // @Email(message="Email is invalid") // private String email; // private String password; // // public User(String username, String email, String password) { // this.username = username; // this.email = email; // this.password = password; // id = ObjectId.get(); // } // // public User(String username, String password) { // this.username = username; // this.password = password; // id = ObjectId.get(); // } // // public User() { // } // // public String getId() { // return id.toHexString(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setUsername(String username) { // this.username = username; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // User user = (User) obj; // return this.getId().equals(user.getId()); // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return null; // } // // @Override // public String getPassword() { // return password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // } // Path: src/test/java/com/pollistics/models/validators/UserValidatorTest.java import org.springframework.validation.DirectFieldBindingResult; import static org.junit.Assert.*; import org.junit.Test; import com.pollistics.models.User; package com.pollistics.models.validators; public class UserValidatorTest { @Test public void validateUsernameTest() {
User user = new User();
gin-fizz/pollistics
src/main/java/com/pollistics/config/WebConfig.java
// Path: src/main/java/com/pollistics/utils/AuthHandlerInterceptor.java // public class AuthHandlerInterceptor extends HandlerInterceptorAdapter { // @Override // public void postHandle(final HttpServletRequest request, // final HttpServletResponse response, final Object handler, // final ModelAndView modelAndView) throws Exception { // // Authentication auth = SecurityContextHolder.getContext().getAuthentication(); // if(auth != null) { // Object user = auth.getPrincipal(); // if (modelAndView != null && user instanceof User) { // modelAndView.getModelMap().addAttribute("user", (User) user); // } // } // } // }
import org.jtwig.environment.EnvironmentConfigurationBuilder; import org.jtwig.hot.reloading.HotReloadingExtension; import org.jtwig.spring.JtwigViewResolver; import org.jtwig.spring.asset.SpringAssetExtension; import org.jtwig.spring.asset.resolver.AssetResolver; import org.jtwig.spring.asset.resolver.BaseAssetResolver; import org.jtwig.spring.boot.config.JtwigViewResolverConfigurer; import org.jtwig.web.servlet.JtwigRenderer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.pollistics.utils.AuthHandlerInterceptor;
package com.pollistics.config; @EnableWebMvc @Configuration public class WebConfig extends WebMvcConfigurerAdapter implements JtwigViewResolverConfigurer { @Override public void configure(JtwigViewResolver viewResolver) { viewResolver.setRenderer(new JtwigRenderer( EnvironmentConfigurationBuilder.configuration() .extensions() .add(new HotReloadingExtension()) .add(new SpringAssetExtension()) .and() .build() )); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authInterceptor()); } @Bean public AssetResolver assetResolver () { BaseAssetResolver assetResolver = new BaseAssetResolver(); assetResolver.setPrefix(""); return assetResolver; } @Bean
// Path: src/main/java/com/pollistics/utils/AuthHandlerInterceptor.java // public class AuthHandlerInterceptor extends HandlerInterceptorAdapter { // @Override // public void postHandle(final HttpServletRequest request, // final HttpServletResponse response, final Object handler, // final ModelAndView modelAndView) throws Exception { // // Authentication auth = SecurityContextHolder.getContext().getAuthentication(); // if(auth != null) { // Object user = auth.getPrincipal(); // if (modelAndView != null && user instanceof User) { // modelAndView.getModelMap().addAttribute("user", (User) user); // } // } // } // } // Path: src/main/java/com/pollistics/config/WebConfig.java import org.jtwig.environment.EnvironmentConfigurationBuilder; import org.jtwig.hot.reloading.HotReloadingExtension; import org.jtwig.spring.JtwigViewResolver; import org.jtwig.spring.asset.SpringAssetExtension; import org.jtwig.spring.asset.resolver.AssetResolver; import org.jtwig.spring.asset.resolver.BaseAssetResolver; import org.jtwig.spring.boot.config.JtwigViewResolverConfigurer; import org.jtwig.web.servlet.JtwigRenderer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.pollistics.utils.AuthHandlerInterceptor; package com.pollistics.config; @EnableWebMvc @Configuration public class WebConfig extends WebMvcConfigurerAdapter implements JtwigViewResolverConfigurer { @Override public void configure(JtwigViewResolver viewResolver) { viewResolver.setRenderer(new JtwigRenderer( EnvironmentConfigurationBuilder.configuration() .extensions() .add(new HotReloadingExtension()) .add(new SpringAssetExtension()) .and() .build() )); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authInterceptor()); } @Bean public AssetResolver assetResolver () { BaseAssetResolver assetResolver = new BaseAssetResolver(); assetResolver.setPrefix(""); return assetResolver; } @Bean
public AuthHandlerInterceptor authInterceptor() {
gin-fizz/pollistics
src/main/java/com/pollistics/controllers/APIController.java
// Path: src/main/java/com/pollistics/models/Poll.java // @Document(collection="polls") // public class Poll { // @Id // private ObjectId id; // // @Length(min=1, max=500, message="Poll title must be be between 1 and 500 characters") // private String title; // private HashMap<String,Integer> options; // private User user; // // @Indexed(unique = true, sparse = true) // private String slug; // // // todo: orden these constructors with `this(...arg)` // // public Poll(String title, HashMap<String,Integer> options) { // this.title = title; // this.options = options; // this.slug = createSlug(); // } // // public Poll(ObjectId id, String title, HashMap<String, Integer> options) { // this.id = id; // this.title = title; // this.options = options; // this.slug = createSlug(); // } // // public Poll(String title, HashMap<String,Integer> options, String slug) { // this.title = title; // this.options = options; // this.slug = slug; // } // // public Poll(String title, HashMap<String,Integer> options, String slug, User user) { // this.title = title; // this.options = options; // this.user = user; // this.slug = slug; // } // // public Poll(String title, HashMap<String,Integer> options, User user) { // this.title = title; // this.options = options; // this.user = user; // this.slug = createSlug(); // } // // public Poll() { // } // // public String getId() { // return id.toHexString(); // } // // public String getTitle() { // return title; // } // // public void setTitle(String name) { // this.title = name; // } // // public HashMap<String, Integer> getOptions() { // return options; // } // // public void setOptions(HashMap<String, Integer> options) { // this.options = options; // } // // private String createSlug() { // return MemeSlugs.getCombo(); // } // // @JsonIgnore // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public void setSlug(String slug) { // this.slug = slug; // } // // public String getSlug() { // return slug; // } // // public boolean vote(String option) { // if(!options.containsKey(option)) { // return false; // } else { // int val = options.get(option); // val++; // options.put(option,val); // return true; // } // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // Poll poll = (Poll) obj; // return this.getId().equals(poll.getId()); // } // } // // Path: src/main/java/com/pollistics/services/PollService.java // @Service // public class PollService { // @Autowired // private PollRepository pollRepo; // // public Poll getPoll(String query) { // Poll poll = pollRepo.findBySlug(query); // if(poll == null) { // return pollRepo.findOne(query); // } // return poll; // } // // public List<Poll> getAllPolls() { // return pollRepo.findAll(); // } // // public String createPoll(String title, HashMap<String, Integer> options) { // Poll poll = pollRepo.insert(new Poll(title, options)); // return poll.getSlug(); // } // // public String createPoll(String title, HashMap<String, Integer> options, String slug) { // Poll poll = pollRepo.insert(new Poll(title, options, slug)); // return poll.getSlug(); // } // // public String createPoll(String title, HashMap<String, Integer> options, User user) { // Poll poll = pollRepo.insert(new Poll(title, options, user)); // return poll.getSlug(); // } // // public String createPoll(String title, HashMap<String, Integer> options, String slug, User user) { // Poll poll = pollRepo.insert(new Poll(title, options, slug, user)); // return poll.getSlug(); // } // // public boolean deletePoll(String slug) { // try { // pollRepo.deleteBySlug(slug); // return true; // } catch (Exception e) { // return false; // } // } // // public boolean voteOption(Poll p, String option) { // boolean result = p.vote(option); // if (!result) { // return false; // } // pollRepo.save(p); // todo false when not works // return true; // } // // public List<Poll> getPolls(User user) { // return pollRepo.findByUser(user); // } // }
import com.pollistics.models.Poll; import com.pollistics.services.PollService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.HashMap; import java.util.List;
package com.pollistics.controllers; @RestController @RequestMapping("/api/1/polls") // todo: this should have a subclass or something for all poll-things public class APIController { @Autowired
// Path: src/main/java/com/pollistics/models/Poll.java // @Document(collection="polls") // public class Poll { // @Id // private ObjectId id; // // @Length(min=1, max=500, message="Poll title must be be between 1 and 500 characters") // private String title; // private HashMap<String,Integer> options; // private User user; // // @Indexed(unique = true, sparse = true) // private String slug; // // // todo: orden these constructors with `this(...arg)` // // public Poll(String title, HashMap<String,Integer> options) { // this.title = title; // this.options = options; // this.slug = createSlug(); // } // // public Poll(ObjectId id, String title, HashMap<String, Integer> options) { // this.id = id; // this.title = title; // this.options = options; // this.slug = createSlug(); // } // // public Poll(String title, HashMap<String,Integer> options, String slug) { // this.title = title; // this.options = options; // this.slug = slug; // } // // public Poll(String title, HashMap<String,Integer> options, String slug, User user) { // this.title = title; // this.options = options; // this.user = user; // this.slug = slug; // } // // public Poll(String title, HashMap<String,Integer> options, User user) { // this.title = title; // this.options = options; // this.user = user; // this.slug = createSlug(); // } // // public Poll() { // } // // public String getId() { // return id.toHexString(); // } // // public String getTitle() { // return title; // } // // public void setTitle(String name) { // this.title = name; // } // // public HashMap<String, Integer> getOptions() { // return options; // } // // public void setOptions(HashMap<String, Integer> options) { // this.options = options; // } // // private String createSlug() { // return MemeSlugs.getCombo(); // } // // @JsonIgnore // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public void setSlug(String slug) { // this.slug = slug; // } // // public String getSlug() { // return slug; // } // // public boolean vote(String option) { // if(!options.containsKey(option)) { // return false; // } else { // int val = options.get(option); // val++; // options.put(option,val); // return true; // } // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // Poll poll = (Poll) obj; // return this.getId().equals(poll.getId()); // } // } // // Path: src/main/java/com/pollistics/services/PollService.java // @Service // public class PollService { // @Autowired // private PollRepository pollRepo; // // public Poll getPoll(String query) { // Poll poll = pollRepo.findBySlug(query); // if(poll == null) { // return pollRepo.findOne(query); // } // return poll; // } // // public List<Poll> getAllPolls() { // return pollRepo.findAll(); // } // // public String createPoll(String title, HashMap<String, Integer> options) { // Poll poll = pollRepo.insert(new Poll(title, options)); // return poll.getSlug(); // } // // public String createPoll(String title, HashMap<String, Integer> options, String slug) { // Poll poll = pollRepo.insert(new Poll(title, options, slug)); // return poll.getSlug(); // } // // public String createPoll(String title, HashMap<String, Integer> options, User user) { // Poll poll = pollRepo.insert(new Poll(title, options, user)); // return poll.getSlug(); // } // // public String createPoll(String title, HashMap<String, Integer> options, String slug, User user) { // Poll poll = pollRepo.insert(new Poll(title, options, slug, user)); // return poll.getSlug(); // } // // public boolean deletePoll(String slug) { // try { // pollRepo.deleteBySlug(slug); // return true; // } catch (Exception e) { // return false; // } // } // // public boolean voteOption(Poll p, String option) { // boolean result = p.vote(option); // if (!result) { // return false; // } // pollRepo.save(p); // todo false when not works // return true; // } // // public List<Poll> getPolls(User user) { // return pollRepo.findByUser(user); // } // } // Path: src/main/java/com/pollistics/controllers/APIController.java import com.pollistics.models.Poll; import com.pollistics.services.PollService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.HashMap; import java.util.List; package com.pollistics.controllers; @RestController @RequestMapping("/api/1/polls") // todo: this should have a subclass or something for all poll-things public class APIController { @Autowired
private PollService pollService;
gin-fizz/pollistics
src/main/java/com/pollistics/models/Poll.java
// Path: src/main/java/com/pollistics/utils/MemeSlugs.java // public class MemeSlugs { // private final static String[] words = new String[]{ // "meme", // "bullgit", // "yolo", // "swag", // "memer", // "coolio", // "fun", // "quark", // "odisee", // "lel", // "xddd", // "giga", // "wauw", // "poll", // "paul", // "maliek", // "hanne", // "elias", // "ruben", // "haroen", // "peter", // "katja", // "kevin", // "ok", // "leuk" // }; // // public static String getCombo() { // return MessageFormat.format("{0}-{1}-{2}", getWord(), getWord(), getWord()); // } // // public static String getWord() { // return words[(int) Math.floor(Math.random() * words.length)]; // } // }
import com.fasterxml.jackson.annotation.JsonIgnore; import com.pollistics.utils.MemeSlugs; import org.bson.types.ObjectId; import org.hibernate.validator.constraints.Length; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; import java.util.HashMap; import java.util.Objects;
this.title = title; this.options = options; this.user = user; this.slug = createSlug(); } public Poll() { } public String getId() { return id.toHexString(); } public String getTitle() { return title; } public void setTitle(String name) { this.title = name; } public HashMap<String, Integer> getOptions() { return options; } public void setOptions(HashMap<String, Integer> options) { this.options = options; } private String createSlug() {
// Path: src/main/java/com/pollistics/utils/MemeSlugs.java // public class MemeSlugs { // private final static String[] words = new String[]{ // "meme", // "bullgit", // "yolo", // "swag", // "memer", // "coolio", // "fun", // "quark", // "odisee", // "lel", // "xddd", // "giga", // "wauw", // "poll", // "paul", // "maliek", // "hanne", // "elias", // "ruben", // "haroen", // "peter", // "katja", // "kevin", // "ok", // "leuk" // }; // // public static String getCombo() { // return MessageFormat.format("{0}-{1}-{2}", getWord(), getWord(), getWord()); // } // // public static String getWord() { // return words[(int) Math.floor(Math.random() * words.length)]; // } // } // Path: src/main/java/com/pollistics/models/Poll.java import com.fasterxml.jackson.annotation.JsonIgnore; import com.pollistics.utils.MemeSlugs; import org.bson.types.ObjectId; import org.hibernate.validator.constraints.Length; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; import java.util.HashMap; import java.util.Objects; this.title = title; this.options = options; this.user = user; this.slug = createSlug(); } public Poll() { } public String getId() { return id.toHexString(); } public String getTitle() { return title; } public void setTitle(String name) { this.title = name; } public HashMap<String, Integer> getOptions() { return options; } public void setOptions(HashMap<String, Integer> options) { this.options = options; } private String createSlug() {
return MemeSlugs.getCombo();
gin-fizz/pollistics
src/main/java/com/pollistics/utils/AuthHandlerInterceptor.java
// Path: src/main/java/com/pollistics/models/User.java // @Document(collection="users") // public class User implements UserDetails { // @Id // private ObjectId id; // // @Length(max=100, message="Name can't be more than 100 characters long") // private String name; // private String username; // @Email(message="Email is invalid") // private String email; // private String password; // // public User(String username, String email, String password) { // this.username = username; // this.email = email; // this.password = password; // id = ObjectId.get(); // } // // public User(String username, String password) { // this.username = username; // this.password = password; // id = ObjectId.get(); // } // // public User() { // } // // public String getId() { // return id.toHexString(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setUsername(String username) { // this.username = username; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // User user = (User) obj; // return this.getId().equals(user.getId()); // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return null; // } // // @Override // public String getPassword() { // return password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // }
import com.pollistics.models.User; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
package com.pollistics.utils; public class AuthHandlerInterceptor extends HandlerInterceptorAdapter { @Override public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if(auth != null) { Object user = auth.getPrincipal();
// Path: src/main/java/com/pollistics/models/User.java // @Document(collection="users") // public class User implements UserDetails { // @Id // private ObjectId id; // // @Length(max=100, message="Name can't be more than 100 characters long") // private String name; // private String username; // @Email(message="Email is invalid") // private String email; // private String password; // // public User(String username, String email, String password) { // this.username = username; // this.email = email; // this.password = password; // id = ObjectId.get(); // } // // public User(String username, String password) { // this.username = username; // this.password = password; // id = ObjectId.get(); // } // // public User() { // } // // public String getId() { // return id.toHexString(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public void setUsername(String username) { // this.username = username; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public int hashCode() { // return Objects.hash(id); // } // // @Override // public boolean equals(Object obj) { // if(this == obj) { // return true; // } // if((obj == null) || (obj.getClass() != this.getClass())) { // return false; // } // // User user = (User) obj; // return this.getId().equals(user.getId()); // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return null; // } // // @Override // public String getPassword() { // return password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // } // Path: src/main/java/com/pollistics/utils/AuthHandlerInterceptor.java import com.pollistics.models.User; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; package com.pollistics.utils; public class AuthHandlerInterceptor extends HandlerInterceptorAdapter { @Override public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if(auth != null) { Object user = auth.getPrincipal();
if (modelAndView != null && user instanceof User) {
bpow/varitas
src/main/java/org/drpowell/vcf/VCFVariant.java
// Path: src/main/java/org/drpowell/util/CustomPercentEncoder.java // public class CustomPercentEncoder { // private final BitSet leaveAlone; // private final boolean plusSpaces; // // public static final char [] HEX_DIGITS = "0123456789ABCDEF".toCharArray(); // // protected CustomPercentEncoder(BitSet charsToLeaveAlone, boolean convertSpacesToPlus) { // leaveAlone = charsToLeaveAlone; // plusSpaces = convertSpacesToPlus; // // // sanity checks // if (plusSpaces) { // leaveAlone.set(' '); // space characters will be handled differently... // leaveAlone.clear('+'); // must encode plus characters if replacing spaces with plus // } // // leaveAlone.clear('%'); // have to encode the escape character! // } // // public static CustomPercentEncoder xFormURLEncoder() { // return allowAlphanumeric().recodeAdditionalCharacters("-_.!~*'()".toCharArray()); // } // // public static CustomPercentEncoder allowAsciiPrintable(boolean convertSpacesToPlus) { // BitSet leaveAlone = new BitSet(256); // leaveAlone.set(32, 126); // return new CustomPercentEncoder(leaveAlone, convertSpacesToPlus); // } // // public static CustomPercentEncoder allowAlphanumeric() { // BitSet leaveAlone = new BitSet(256); // // alpha // leaveAlone.set('a', 'z'); // leaveAlone.set('A', 'Z'); // // numeric // leaveAlone.set('0', '9'); // // return new CustomPercentEncoder(leaveAlone, true); // } // // public static CustomPercentEncoder recodeAFewChars(char [] charsToRecode, boolean convertSpaceToPlus) { // BitSet leaveAlone = new BitSet(256); // for (char c: charsToRecode) { // leaveAlone.set(c); // } // return new CustomPercentEncoder(leaveAlone, convertSpaceToPlus); // } // // public CustomPercentEncoder passThroughAdditionalCharacters(char [] charsToPass) { // BitSet newLeaveAlone = (BitSet) leaveAlone.clone(); // for (char c : charsToPass) { // newLeaveAlone.clear(c); // } // return new CustomPercentEncoder(newLeaveAlone, plusSpaces); // // } // // public CustomPercentEncoder recodeAdditionalCharacters(char [] charsToRecode) { // BitSet newLeaveAlone = (BitSet) leaveAlone.clone(); // for (char c : charsToRecode) { // newLeaveAlone.clear(c); // } // return new CustomPercentEncoder(newLeaveAlone, plusSpaces); // } // // private static final StringBuilder appendEncodedChar(StringBuilder sb, char c) { // if (c <= 0x007f) { // sb.append('%').append(HEX_DIGITS[(c>>4)&0xf]).append(HEX_DIGITS[c&0xf]); // } else { // throw new UnsupportedOperationException("Tried to URLEncode a non-ASCII character: " + c); // } // return sb; // } // // public String encode(String in) { // StringBuilder sb = null; // int i = 0; // while (i < in.length()) { // char c = in.charAt(i); // if ((c == ' ' && plusSpaces) || !leaveAlone.get(c)) { // sb = new StringBuilder(in.length()*2); // sb.append(in.substring(0, i)); // break; // } // i++; // } // if (null == sb) return in; // we did not reach anything that needed to be changed // while (i < in.length()) { // char c = in.charAt(i); // if (c == ' ' && plusSpaces) { // sb.append('+'); // } else if (!leaveAlone.get(c)) { // appendEncodedChar(sb, c); // } else { // sb.append(c); // } // i++; // } // return sb.toString(); // } // // public String decode(String encoded) { // StringBuilder sb = null; // int i = 0; // while (i < encoded.length()) { // char c = encoded.charAt(i); // if (c == '+' && plusSpaces || c == '%') { // sb = new StringBuilder(encoded.length()); // sb.append(encoded.substring(0, i)); // break; // } // i++; // } // if (null == sb) return encoded; // nothing to change // while (i < encoded.length()) { // char c = encoded.charAt(i); // if (c == '+' && plusSpaces) { // sb.append(' '); // i++; // } else if (c == '%') { // sb.append((char) Integer.parseInt(encoded.substring(i+1,i+3),16)); // i += 3; // } else { // sb.append(c); // i++; // } // } // return sb.toString(); // } // // }
import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.logging.Level; import java.util.logging.Logger; import org.drpowell.util.CustomPercentEncoder;
package org.drpowell.vcf; /** * Representation of a single row of a VCF file * * INFO flag fields will be set to the special value 'FLAG_INFO' if set * * @author bpow */ public class VCFVariant { private Map<String, String[]> info; private String qual; private String [] row; private int start; // fixme should this be final? private int end; private boolean urlEncode = true; private volatile double [][] logLikelihoods; private static final String [] FLAG_INFO = new String[0];
// Path: src/main/java/org/drpowell/util/CustomPercentEncoder.java // public class CustomPercentEncoder { // private final BitSet leaveAlone; // private final boolean plusSpaces; // // public static final char [] HEX_DIGITS = "0123456789ABCDEF".toCharArray(); // // protected CustomPercentEncoder(BitSet charsToLeaveAlone, boolean convertSpacesToPlus) { // leaveAlone = charsToLeaveAlone; // plusSpaces = convertSpacesToPlus; // // // sanity checks // if (plusSpaces) { // leaveAlone.set(' '); // space characters will be handled differently... // leaveAlone.clear('+'); // must encode plus characters if replacing spaces with plus // } // // leaveAlone.clear('%'); // have to encode the escape character! // } // // public static CustomPercentEncoder xFormURLEncoder() { // return allowAlphanumeric().recodeAdditionalCharacters("-_.!~*'()".toCharArray()); // } // // public static CustomPercentEncoder allowAsciiPrintable(boolean convertSpacesToPlus) { // BitSet leaveAlone = new BitSet(256); // leaveAlone.set(32, 126); // return new CustomPercentEncoder(leaveAlone, convertSpacesToPlus); // } // // public static CustomPercentEncoder allowAlphanumeric() { // BitSet leaveAlone = new BitSet(256); // // alpha // leaveAlone.set('a', 'z'); // leaveAlone.set('A', 'Z'); // // numeric // leaveAlone.set('0', '9'); // // return new CustomPercentEncoder(leaveAlone, true); // } // // public static CustomPercentEncoder recodeAFewChars(char [] charsToRecode, boolean convertSpaceToPlus) { // BitSet leaveAlone = new BitSet(256); // for (char c: charsToRecode) { // leaveAlone.set(c); // } // return new CustomPercentEncoder(leaveAlone, convertSpaceToPlus); // } // // public CustomPercentEncoder passThroughAdditionalCharacters(char [] charsToPass) { // BitSet newLeaveAlone = (BitSet) leaveAlone.clone(); // for (char c : charsToPass) { // newLeaveAlone.clear(c); // } // return new CustomPercentEncoder(newLeaveAlone, plusSpaces); // // } // // public CustomPercentEncoder recodeAdditionalCharacters(char [] charsToRecode) { // BitSet newLeaveAlone = (BitSet) leaveAlone.clone(); // for (char c : charsToRecode) { // newLeaveAlone.clear(c); // } // return new CustomPercentEncoder(newLeaveAlone, plusSpaces); // } // // private static final StringBuilder appendEncodedChar(StringBuilder sb, char c) { // if (c <= 0x007f) { // sb.append('%').append(HEX_DIGITS[(c>>4)&0xf]).append(HEX_DIGITS[c&0xf]); // } else { // throw new UnsupportedOperationException("Tried to URLEncode a non-ASCII character: " + c); // } // return sb; // } // // public String encode(String in) { // StringBuilder sb = null; // int i = 0; // while (i < in.length()) { // char c = in.charAt(i); // if ((c == ' ' && plusSpaces) || !leaveAlone.get(c)) { // sb = new StringBuilder(in.length()*2); // sb.append(in.substring(0, i)); // break; // } // i++; // } // if (null == sb) return in; // we did not reach anything that needed to be changed // while (i < in.length()) { // char c = in.charAt(i); // if (c == ' ' && plusSpaces) { // sb.append('+'); // } else if (!leaveAlone.get(c)) { // appendEncodedChar(sb, c); // } else { // sb.append(c); // } // i++; // } // return sb.toString(); // } // // public String decode(String encoded) { // StringBuilder sb = null; // int i = 0; // while (i < encoded.length()) { // char c = encoded.charAt(i); // if (c == '+' && plusSpaces || c == '%') { // sb = new StringBuilder(encoded.length()); // sb.append(encoded.substring(0, i)); // break; // } // i++; // } // if (null == sb) return encoded; // nothing to change // while (i < encoded.length()) { // char c = encoded.charAt(i); // if (c == '+' && plusSpaces) { // sb.append(' '); // i++; // } else if (c == '%') { // sb.append((char) Integer.parseInt(encoded.substring(i+1,i+3),16)); // i += 3; // } else { // sb.append(c); // i++; // } // } // return sb.toString(); // } // // } // Path: src/main/java/org/drpowell/vcf/VCFVariant.java import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.logging.Level; import java.util.logging.Logger; import org.drpowell.util.CustomPercentEncoder; package org.drpowell.vcf; /** * Representation of a single row of a VCF file * * INFO flag fields will be set to the special value 'FLAG_INFO' if set * * @author bpow */ public class VCFVariant { private Map<String, String[]> info; private String qual; private String [] row; private int start; // fixme should this be final? private int end; private boolean urlEncode = true; private volatile double [][] logLikelihoods; private static final String [] FLAG_INFO = new String[0];
private static final CustomPercentEncoder INFO_ENCODER = CustomPercentEncoder.allowAsciiPrintable(true).recodeAdditionalCharacters(" ;=".toCharArray());
bpow/varitas
src/main/java/org/drpowell/tabix/TabixBuilder.java
// Path: src/main/java/org/drpowell/tabix/TabixIndex.java // public static class TabixConfig { // public final int preset, seqCol, beginCol, endCol, commentChar, linesToSkip; // public final String commentString; // public TabixConfig (int p, int sc, int bc, int ec, int comment, int skipLines) { // preset = p; seqCol = sc; beginCol = bc; endCol = ec; commentChar = comment; linesToSkip = skipLines; // commentString = Character.toString((char) commentChar); // } // public static final TabixConfig GFF = new TabixConfig(0, 1, 4, 5, '#', 0); // public static final TabixConfig BED = new TabixConfig(TBX_FLAG_UCSC, 1, 2, 3, '#', 0); // public static final TabixConfig PSLTBL = new TabixConfig(TBX_FLAG_UCSC, 15, 17, 18, '#', 0); // public static final TabixConfig SAM = new TabixConfig(TBX_PRESET_SAM, 3, 4, 0, '@', 0); // public static final TabixConfig VCF = new TabixConfig(TBX_PRESET_VCF, 1, 2, 0, '#', 0); // } // // Path: src/main/java/org/drpowell/util/LineIterator.java // public class LineIterator extends AbstractPeekableIterator<String> { // public final BufferedReader reader; // // public boolean handleException(Exception e) { // Logger.getGlobal().log(Level.WARNING, e.toString()); // return true; // } // // public LineIterator(BufferedReader reader) { // this.reader = reader; // } // // @Override // protected String computeNext() { // String next = null; // try { // next = reader.readLine(); // } catch (IOException e) { // if (!handleException(e)) { // return computeNext(); // } // } // return next == null ? endOfData() : next; // } // // }
import java.util.List; import net.sf.samtools.util.BlockCompressedFilePointerUtil; import net.sf.samtools.util.BlockCompressedInputStream; import net.sf.samtools.util.BlockCompressedOutputStream; import org.drpowell.tabix.TabixIndex.TabixConfig; import org.drpowell.util.LineIterator; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Iterator;
/* The MIT License Copyright (c) 2012 Baylor College of Medicine. 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 org.drpowell.tabix; public class TabixBuilder { private final TabixIndex tabix; private int tidCurr = -1; private BinIndex currBinningIndex = new BinIndex(); private LinearIndex currLinearIndex = new LinearIndex(); // FIXME- arguably could just stick with '\n'... private static final byte [] LINE_SEPARATOR = System.getProperty("line.separator").getBytes();
// Path: src/main/java/org/drpowell/tabix/TabixIndex.java // public static class TabixConfig { // public final int preset, seqCol, beginCol, endCol, commentChar, linesToSkip; // public final String commentString; // public TabixConfig (int p, int sc, int bc, int ec, int comment, int skipLines) { // preset = p; seqCol = sc; beginCol = bc; endCol = ec; commentChar = comment; linesToSkip = skipLines; // commentString = Character.toString((char) commentChar); // } // public static final TabixConfig GFF = new TabixConfig(0, 1, 4, 5, '#', 0); // public static final TabixConfig BED = new TabixConfig(TBX_FLAG_UCSC, 1, 2, 3, '#', 0); // public static final TabixConfig PSLTBL = new TabixConfig(TBX_FLAG_UCSC, 15, 17, 18, '#', 0); // public static final TabixConfig SAM = new TabixConfig(TBX_PRESET_SAM, 3, 4, 0, '@', 0); // public static final TabixConfig VCF = new TabixConfig(TBX_PRESET_VCF, 1, 2, 0, '#', 0); // } // // Path: src/main/java/org/drpowell/util/LineIterator.java // public class LineIterator extends AbstractPeekableIterator<String> { // public final BufferedReader reader; // // public boolean handleException(Exception e) { // Logger.getGlobal().log(Level.WARNING, e.toString()); // return true; // } // // public LineIterator(BufferedReader reader) { // this.reader = reader; // } // // @Override // protected String computeNext() { // String next = null; // try { // next = reader.readLine(); // } catch (IOException e) { // if (!handleException(e)) { // return computeNext(); // } // } // return next == null ? endOfData() : next; // } // // } // Path: src/main/java/org/drpowell/tabix/TabixBuilder.java import java.util.List; import net.sf.samtools.util.BlockCompressedFilePointerUtil; import net.sf.samtools.util.BlockCompressedInputStream; import net.sf.samtools.util.BlockCompressedOutputStream; import org.drpowell.tabix.TabixIndex.TabixConfig; import org.drpowell.util.LineIterator; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; /* The MIT License Copyright (c) 2012 Baylor College of Medicine. 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 org.drpowell.tabix; public class TabixBuilder { private final TabixIndex tabix; private int tidCurr = -1; private BinIndex currBinningIndex = new BinIndex(); private LinearIndex currLinearIndex = new LinearIndex(); // FIXME- arguably could just stick with '\n'... private static final byte [] LINE_SEPARATOR = System.getProperty("line.separator").getBytes();
private TabixBuilder(String fileName, TabixConfig config) throws IOException {
bpow/varitas
src/main/java/org/drpowell/tabix/TabixBuilder.java
// Path: src/main/java/org/drpowell/tabix/TabixIndex.java // public static class TabixConfig { // public final int preset, seqCol, beginCol, endCol, commentChar, linesToSkip; // public final String commentString; // public TabixConfig (int p, int sc, int bc, int ec, int comment, int skipLines) { // preset = p; seqCol = sc; beginCol = bc; endCol = ec; commentChar = comment; linesToSkip = skipLines; // commentString = Character.toString((char) commentChar); // } // public static final TabixConfig GFF = new TabixConfig(0, 1, 4, 5, '#', 0); // public static final TabixConfig BED = new TabixConfig(TBX_FLAG_UCSC, 1, 2, 3, '#', 0); // public static final TabixConfig PSLTBL = new TabixConfig(TBX_FLAG_UCSC, 15, 17, 18, '#', 0); // public static final TabixConfig SAM = new TabixConfig(TBX_PRESET_SAM, 3, 4, 0, '@', 0); // public static final TabixConfig VCF = new TabixConfig(TBX_PRESET_VCF, 1, 2, 0, '#', 0); // } // // Path: src/main/java/org/drpowell/util/LineIterator.java // public class LineIterator extends AbstractPeekableIterator<String> { // public final BufferedReader reader; // // public boolean handleException(Exception e) { // Logger.getGlobal().log(Level.WARNING, e.toString()); // return true; // } // // public LineIterator(BufferedReader reader) { // this.reader = reader; // } // // @Override // protected String computeNext() { // String next = null; // try { // next = reader.readLine(); // } catch (IOException e) { // if (!handleException(e)) { // return computeNext(); // } // } // return next == null ? endOfData() : next; // } // // }
import java.util.List; import net.sf.samtools.util.BlockCompressedFilePointerUtil; import net.sf.samtools.util.BlockCompressedInputStream; import net.sf.samtools.util.BlockCompressedOutputStream; import org.drpowell.tabix.TabixIndex.TabixConfig; import org.drpowell.util.LineIterator; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Iterator;
bin.add(chunk); } } // process linear index int startWindow = LinearIndex.convertToLinearIndexOffset(intv.getBegin()); int endWindow = LinearIndex.convertToLinearIndexOffset(intv.getEnd()); for (int win = startWindow; win <= endWindow; win++) { if (currLinearIndex.getPrimitive(win) == 0 || chunk.begin < currLinearIndex.getPrimitive(win)) { currLinearIndex.setPrimitive(win, chunk.begin); } } } private void finishPrevChromosome(int tidPrev) { if (currBinningIndex.isEmpty()) return; // saw nothing for this reference tabix.linearIndex.set(tidPrev, currLinearIndex.getCompacted()); currLinearIndex.clear(); // make things as compact as possible... tabix.binningIndex.set(tidPrev, new BinIndex(currBinningIndex)); currBinningIndex = new BinIndex(); } public void finish() throws IOException { finishPrevChromosome(tidCurr); } public static TabixIndex buildIndex(BufferedReader reader, String compressedFilename, TabixConfig config) throws IOException {
// Path: src/main/java/org/drpowell/tabix/TabixIndex.java // public static class TabixConfig { // public final int preset, seqCol, beginCol, endCol, commentChar, linesToSkip; // public final String commentString; // public TabixConfig (int p, int sc, int bc, int ec, int comment, int skipLines) { // preset = p; seqCol = sc; beginCol = bc; endCol = ec; commentChar = comment; linesToSkip = skipLines; // commentString = Character.toString((char) commentChar); // } // public static final TabixConfig GFF = new TabixConfig(0, 1, 4, 5, '#', 0); // public static final TabixConfig BED = new TabixConfig(TBX_FLAG_UCSC, 1, 2, 3, '#', 0); // public static final TabixConfig PSLTBL = new TabixConfig(TBX_FLAG_UCSC, 15, 17, 18, '#', 0); // public static final TabixConfig SAM = new TabixConfig(TBX_PRESET_SAM, 3, 4, 0, '@', 0); // public static final TabixConfig VCF = new TabixConfig(TBX_PRESET_VCF, 1, 2, 0, '#', 0); // } // // Path: src/main/java/org/drpowell/util/LineIterator.java // public class LineIterator extends AbstractPeekableIterator<String> { // public final BufferedReader reader; // // public boolean handleException(Exception e) { // Logger.getGlobal().log(Level.WARNING, e.toString()); // return true; // } // // public LineIterator(BufferedReader reader) { // this.reader = reader; // } // // @Override // protected String computeNext() { // String next = null; // try { // next = reader.readLine(); // } catch (IOException e) { // if (!handleException(e)) { // return computeNext(); // } // } // return next == null ? endOfData() : next; // } // // } // Path: src/main/java/org/drpowell/tabix/TabixBuilder.java import java.util.List; import net.sf.samtools.util.BlockCompressedFilePointerUtil; import net.sf.samtools.util.BlockCompressedInputStream; import net.sf.samtools.util.BlockCompressedOutputStream; import org.drpowell.tabix.TabixIndex.TabixConfig; import org.drpowell.util.LineIterator; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; bin.add(chunk); } } // process linear index int startWindow = LinearIndex.convertToLinearIndexOffset(intv.getBegin()); int endWindow = LinearIndex.convertToLinearIndexOffset(intv.getEnd()); for (int win = startWindow; win <= endWindow; win++) { if (currLinearIndex.getPrimitive(win) == 0 || chunk.begin < currLinearIndex.getPrimitive(win)) { currLinearIndex.setPrimitive(win, chunk.begin); } } } private void finishPrevChromosome(int tidPrev) { if (currBinningIndex.isEmpty()) return; // saw nothing for this reference tabix.linearIndex.set(tidPrev, currLinearIndex.getCompacted()); currLinearIndex.clear(); // make things as compact as possible... tabix.binningIndex.set(tidPrev, new BinIndex(currBinningIndex)); currBinningIndex = new BinIndex(); } public void finish() throws IOException { finishPrevChromosome(tidCurr); } public static TabixIndex buildIndex(BufferedReader reader, String compressedFilename, TabixConfig config) throws IOException {
return buildIndex(new LineIterator(reader), compressedFilename, config);
bpow/varitas
src/main/java/org/drpowell/tabix/TabixReader.java
// Path: src/main/java/org/drpowell/tabix/TabixIndex.java // public static class TabixConfig { // public final int preset, seqCol, beginCol, endCol, commentChar, linesToSkip; // public final String commentString; // public TabixConfig (int p, int sc, int bc, int ec, int comment, int skipLines) { // preset = p; seqCol = sc; beginCol = bc; endCol = ec; commentChar = comment; linesToSkip = skipLines; // commentString = Character.toString((char) commentChar); // } // public static final TabixConfig GFF = new TabixConfig(0, 1, 4, 5, '#', 0); // public static final TabixConfig BED = new TabixConfig(TBX_FLAG_UCSC, 1, 2, 3, '#', 0); // public static final TabixConfig PSLTBL = new TabixConfig(TBX_FLAG_UCSC, 15, 17, 18, '#', 0); // public static final TabixConfig SAM = new TabixConfig(TBX_PRESET_SAM, 3, 4, 0, '@', 0); // public static final TabixConfig VCF = new TabixConfig(TBX_PRESET_VCF, 1, 2, 0, '#', 0); // }
import java.util.List; import net.sf.samtools.util.BinaryCodec; import net.sf.samtools.util.BlockCompressedInputStream; import net.sf.samtools.util.StringUtil; import org.drpowell.tabix.TabixIndex.TabixConfig; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator;
/* The MIT License Copyright (c) 2010 Broad Institute. Portions Copyright (c) 2012 Baylor College of Medicine. 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 org.drpowell.tabix; public class TabixReader { public final String filename; BlockCompressedInputStream mFp; // private static Logger logger = Logger.getLogger(TabixReader.class.getCanonicalName()); public final TabixIndex tabix;
// Path: src/main/java/org/drpowell/tabix/TabixIndex.java // public static class TabixConfig { // public final int preset, seqCol, beginCol, endCol, commentChar, linesToSkip; // public final String commentString; // public TabixConfig (int p, int sc, int bc, int ec, int comment, int skipLines) { // preset = p; seqCol = sc; beginCol = bc; endCol = ec; commentChar = comment; linesToSkip = skipLines; // commentString = Character.toString((char) commentChar); // } // public static final TabixConfig GFF = new TabixConfig(0, 1, 4, 5, '#', 0); // public static final TabixConfig BED = new TabixConfig(TBX_FLAG_UCSC, 1, 2, 3, '#', 0); // public static final TabixConfig PSLTBL = new TabixConfig(TBX_FLAG_UCSC, 15, 17, 18, '#', 0); // public static final TabixConfig SAM = new TabixConfig(TBX_PRESET_SAM, 3, 4, 0, '@', 0); // public static final TabixConfig VCF = new TabixConfig(TBX_PRESET_VCF, 1, 2, 0, '#', 0); // } // Path: src/main/java/org/drpowell/tabix/TabixReader.java import java.util.List; import net.sf.samtools.util.BinaryCodec; import net.sf.samtools.util.BlockCompressedInputStream; import net.sf.samtools.util.StringUtil; import org.drpowell.tabix.TabixIndex.TabixConfig; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; /* The MIT License Copyright (c) 2010 Broad Institute. Portions Copyright (c) 2012 Baylor College of Medicine. 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 org.drpowell.tabix; public class TabixReader { public final String filename; BlockCompressedInputStream mFp; // private static Logger logger = Logger.getLogger(TabixReader.class.getCanonicalName()); public final TabixIndex tabix;
public final TabixConfig conf;
bpow/varitas
src/main/java/org/drpowell/tabix/TabixIterator.java
// Path: src/main/java/org/drpowell/tabix/TabixIndex.java // public static class Chunk implements Comparable<Chunk> { // public final long begin; // public final long end; // public Chunk(final long begin, final long end) { // this.begin = begin; this.end = end; // } // public int compareTo(final Chunk p) { // if (begin == p.begin) { // return cmpUInt64(end, p.end); // } else { // return cmpUInt64(begin, p.begin); // } // } // public static final int cmpUInt64(long u, long v) { // if (u == v) return 0; // return ((u<v) ^ (u<0) ^ (v<0))? -1 : 1; // } // };
import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.samtools.util.BlockCompressedInputStream; import org.drpowell.tabix.TabixIndex.Chunk; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet;
/* The MIT License Copyright (c) 2010 Broad Institute. Portions Copyright (c) 2012 Baylor College of Medicine. 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 org.drpowell.tabix; /** * An Iterator implementation for tabix-indexed files. * * Much of the trickier code in the advance() method is from Heng Li's original TabixReader.java * @author bpow * */ public class TabixIterator implements Iterator<String []>{ private int i; private long curr_off; private boolean iseof; private final TabixIndex tabix; private final GenomicInterval intv; private String [] next = null;
// Path: src/main/java/org/drpowell/tabix/TabixIndex.java // public static class Chunk implements Comparable<Chunk> { // public final long begin; // public final long end; // public Chunk(final long begin, final long end) { // this.begin = begin; this.end = end; // } // public int compareTo(final Chunk p) { // if (begin == p.begin) { // return cmpUInt64(end, p.end); // } else { // return cmpUInt64(begin, p.begin); // } // } // public static final int cmpUInt64(long u, long v) { // if (u == v) return 0; // return ((u<v) ^ (u<0) ^ (v<0))? -1 : 1; // } // }; // Path: src/main/java/org/drpowell/tabix/TabixIterator.java import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.samtools.util.BlockCompressedInputStream; import org.drpowell.tabix.TabixIndex.Chunk; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; /* The MIT License Copyright (c) 2010 Broad Institute. Portions Copyright (c) 2012 Baylor College of Medicine. 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 org.drpowell.tabix; /** * An Iterator implementation for tabix-indexed files. * * Much of the trickier code in the advance() method is from Heng Li's original TabixReader.java * @author bpow * */ public class TabixIterator implements Iterator<String []>{ private int i; private long curr_off; private boolean iseof; private final TabixIndex tabix; private final GenomicInterval intv; private String [] next = null;
private List<Chunk> candidateChunks;
xuyt11/androidBackFlow
app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity_and_fragment/ContainerAF2Activity.java
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowFragment.java // public class BaseBackFlowFragment extends Fragment { // // protected View root; // // public void setRoot(View root) { // this.root = root; // } // // public <T extends View> T $(@IdRes int id) { // return (T) root.findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // public void onActivityResult(int requestCode, int resultCode, Intent data) { // BackFlow.Logger.logIntent(this, data); // super.onActivityResult(requestCode, resultCode, data); // } // // }
import android.os.Bundle; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.BaseBackFlowFragment; import cn.ytxu.androidbackflow.R;
package cn.ytxu.androidbackflow.sample.normal.request_activity_and_fragment; /** * Created by ytxu on 16/12/31. */ public class ContainerAF2Activity extends BaseBackFlowActivity { /** * sample: XXXFragment.class.getName() */ public final static String PARAM_CLASSNAME = "className"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_container);
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowFragment.java // public class BaseBackFlowFragment extends Fragment { // // protected View root; // // public void setRoot(View root) { // this.root = root; // } // // public <T extends View> T $(@IdRes int id) { // return (T) root.findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // public void onActivityResult(int requestCode, int resultCode, Intent data) { // BackFlow.Logger.logIntent(this, data); // super.onActivityResult(requestCode, resultCode, data); // } // // } // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity_and_fragment/ContainerAF2Activity.java import android.os.Bundle; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.BaseBackFlowFragment; import cn.ytxu.androidbackflow.R; package cn.ytxu.androidbackflow.sample.normal.request_activity_and_fragment; /** * Created by ytxu on 16/12/31. */ public class ContainerAF2Activity extends BaseBackFlowActivity { /** * sample: XXXFragment.class.getName() */ public final static String PARAM_CLASSNAME = "className"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_container);
BaseBackFlowFragment fragment = getFragment();
xuyt11/androidBackFlow
app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity_and_fragment/letter/LetterAFFFragment.java
// Path: app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity_and_fragment/BaseLetterAFFragment.java // public class BaseLetterAFFragment extends BaseBackFlowFragment { // // private TextView tipTxt; // private Button jumpBtn, rollbackFlowBtn; // // // @Nullable // @Override // public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.container_letter_fragment, container, false); // setRoot(view); // // tipTxt = $(R.id.letter_tip_txt); // jumpBtn = $(R.id.letter_jump_btn); // rollbackFlowBtn = $(R.id.letter_back_flow_btn); // rollbackFlowBtn.setVisibility(View.GONE); // tipTxt.setText(getActivity().getClass().getSimpleName() + "\n" + getClass().getSimpleName()); // // jumpBtn.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if (getActivity() instanceof ContainerAF1Activity) { // if (gotoAF1()) { // return; // } // gotoAF2Header(); // } else { // gotoAF2(); // } // // } // }); // // finishApp(); // // initView(); // return view; // } // // private boolean gotoAF1() { // try { // Intent intent = new Intent(getActivity(), ContainerAF1Activity.class); // intent.putExtra(ContainerAF1Activity.PARAM_CLASSNAME, LetterAFFragmentType.getNextFragmentName(BaseLetterAFFragment.this)); // startActivity(intent); // return true; // } catch (ArrayIndexOutOfBoundsException e) { // e.printStackTrace(); // return false; // } // } // // private void gotoAF2Header() { // Intent intent = new Intent(getActivity(), ContainerAF2Activity.class); // intent.putExtra(ContainerAF2Activity.PARAM_CLASSNAME, LetterAFAFragment.class.getName()); // startActivity(intent); // } // // private boolean gotoAF2() { // try { // Intent intent = new Intent(getActivity(), ContainerAF2Activity.class); // intent.putExtra(ContainerAF2Activity.PARAM_CLASSNAME, LetterAFFragmentType.getNextFragmentName(BaseLetterAFFragment.this)); // startActivity(intent); // return true; // } catch (ArrayIndexOutOfBoundsException e) { // e.printStackTrace(); // return false; // } // } // // protected void initView() { // } // // protected void setRollbackFlow(final Class<? extends Activity> atyClass, final Class<? extends Fragment> fragmentClass) { // setRollbackFlow(atyClass, fragmentClass, // "rollback :" + atyClass.getSimpleName() + ", " + fragmentClass.getSimpleName()); // } // // protected void setRollbackFlow(final Class<? extends Activity> atyClass, final Class<? extends Fragment> fragmentClass, String text) { // rollbackFlowBtn.setVisibility(View.VISIBLE); // rollbackFlowBtn.setText(text); // rollbackFlowBtn.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // BackFlow.request(BaseLetterAFFragment.this, atyClass, fragmentClass); // } // }); // } // // private void finishApp() { // $(R.id.letter_finish_task_btn).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // BackFlow.finishTask(BaseLetterAFFragment.this); // } // }); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity_and_fragment/ContainerAF1Activity.java // public class ContainerAF1Activity extends BaseBackFlowActivity { // // /** // * sample: XXXFragment.class.getName() // */ // public final static String PARAM_CLASSNAME = "className"; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.fragment_container); // // BaseBackFlowFragment fragment = getFragment(); // if (fragment == null) { // // finish(); // return; // } // // getSupportFragmentManager().beginTransaction() // .replace(R.id.fragment_container, fragment) // .commitAllowingStateLoss(); // } // // private BaseBackFlowFragment getFragment() { // String className = getIntent().getStringExtra(PARAM_CLASSNAME); // BaseBackFlowFragment fragment = null; // if (className != null && !className.isEmpty()) { // try { // fragment = (BaseBackFlowFragment) getClassLoader().loadClass(className).newInstance(); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } catch (InstantiationException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // return fragment; // } // // }
import cn.ytxu.androidbackflow.sample.normal.request_activity_and_fragment.BaseLetterAFFragment; import cn.ytxu.androidbackflow.sample.normal.request_activity_and_fragment.ContainerAF1Activity;
package cn.ytxu.androidbackflow.sample.normal.request_activity_and_fragment.letter; /** * Created by newchama on 17/1/3. */ public class LetterAFFFragment extends BaseLetterAFFragment { @Override protected void initView() { super.initView();
// Path: app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity_and_fragment/BaseLetterAFFragment.java // public class BaseLetterAFFragment extends BaseBackFlowFragment { // // private TextView tipTxt; // private Button jumpBtn, rollbackFlowBtn; // // // @Nullable // @Override // public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.container_letter_fragment, container, false); // setRoot(view); // // tipTxt = $(R.id.letter_tip_txt); // jumpBtn = $(R.id.letter_jump_btn); // rollbackFlowBtn = $(R.id.letter_back_flow_btn); // rollbackFlowBtn.setVisibility(View.GONE); // tipTxt.setText(getActivity().getClass().getSimpleName() + "\n" + getClass().getSimpleName()); // // jumpBtn.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if (getActivity() instanceof ContainerAF1Activity) { // if (gotoAF1()) { // return; // } // gotoAF2Header(); // } else { // gotoAF2(); // } // // } // }); // // finishApp(); // // initView(); // return view; // } // // private boolean gotoAF1() { // try { // Intent intent = new Intent(getActivity(), ContainerAF1Activity.class); // intent.putExtra(ContainerAF1Activity.PARAM_CLASSNAME, LetterAFFragmentType.getNextFragmentName(BaseLetterAFFragment.this)); // startActivity(intent); // return true; // } catch (ArrayIndexOutOfBoundsException e) { // e.printStackTrace(); // return false; // } // } // // private void gotoAF2Header() { // Intent intent = new Intent(getActivity(), ContainerAF2Activity.class); // intent.putExtra(ContainerAF2Activity.PARAM_CLASSNAME, LetterAFAFragment.class.getName()); // startActivity(intent); // } // // private boolean gotoAF2() { // try { // Intent intent = new Intent(getActivity(), ContainerAF2Activity.class); // intent.putExtra(ContainerAF2Activity.PARAM_CLASSNAME, LetterAFFragmentType.getNextFragmentName(BaseLetterAFFragment.this)); // startActivity(intent); // return true; // } catch (ArrayIndexOutOfBoundsException e) { // e.printStackTrace(); // return false; // } // } // // protected void initView() { // } // // protected void setRollbackFlow(final Class<? extends Activity> atyClass, final Class<? extends Fragment> fragmentClass) { // setRollbackFlow(atyClass, fragmentClass, // "rollback :" + atyClass.getSimpleName() + ", " + fragmentClass.getSimpleName()); // } // // protected void setRollbackFlow(final Class<? extends Activity> atyClass, final Class<? extends Fragment> fragmentClass, String text) { // rollbackFlowBtn.setVisibility(View.VISIBLE); // rollbackFlowBtn.setText(text); // rollbackFlowBtn.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // BackFlow.request(BaseLetterAFFragment.this, atyClass, fragmentClass); // } // }); // } // // private void finishApp() { // $(R.id.letter_finish_task_btn).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // BackFlow.finishTask(BaseLetterAFFragment.this); // } // }); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity_and_fragment/ContainerAF1Activity.java // public class ContainerAF1Activity extends BaseBackFlowActivity { // // /** // * sample: XXXFragment.class.getName() // */ // public final static String PARAM_CLASSNAME = "className"; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.fragment_container); // // BaseBackFlowFragment fragment = getFragment(); // if (fragment == null) { // // finish(); // return; // } // // getSupportFragmentManager().beginTransaction() // .replace(R.id.fragment_container, fragment) // .commitAllowingStateLoss(); // } // // private BaseBackFlowFragment getFragment() { // String className = getIntent().getStringExtra(PARAM_CLASSNAME); // BaseBackFlowFragment fragment = null; // if (className != null && !className.isEmpty()) { // try { // fragment = (BaseBackFlowFragment) getClassLoader().loadClass(className).newInstance(); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } catch (InstantiationException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // return fragment; // } // // } // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity_and_fragment/letter/LetterAFFFragment.java import cn.ytxu.androidbackflow.sample.normal.request_activity_and_fragment.BaseLetterAFFragment; import cn.ytxu.androidbackflow.sample.normal.request_activity_and_fragment.ContainerAF1Activity; package cn.ytxu.androidbackflow.sample.normal.request_activity_and_fragment.letter; /** * Created by newchama on 17/1/3. */ public class LetterAFFFragment extends BaseLetterAFFragment { @Override protected void initView() { super.initView();
if (getActivity() instanceof ContainerAF1Activity) {
xuyt11/androidBackFlow
app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity/letter/LetterGActivity.java
// Path: app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity/base/BaseLetterActivity.java // public class BaseLetterActivity extends BaseBackFlowActivity { // // private Button jumpBtn, rollbackFlowBtn; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_letter); // // jumpBtn = $(R.id.letter_jump_btn); // rollbackFlowBtn = $(R.id.letter_back_flow_btn); // rollbackFlowBtn.setVisibility(View.GONE); // // setTitle(getClass().getSimpleName()); // jumpBtn.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // try { // startActivity(new Intent(BaseLetterActivity.this, LetterType.getNextActivity(BaseLetterActivity.this))); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } catch (ArrayIndexOutOfBoundsException e) { // e.printStackTrace(); // } // } // }); // // finishApp(); // } // // protected void setRollbackFlow(final Class<? extends Activity> atyClass) { // setRollbackFlow(atyClass, "rollback :" + atyClass.getSimpleName()); // } // // protected void setRollbackFlow(final Class<? extends Activity> atyClass, String text) { // rollbackFlowBtn.setVisibility(View.VISIBLE); // rollbackFlowBtn.setText(text); // rollbackFlowBtn.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // BackFlow.request(BaseLetterActivity.this, atyClass); // } // }); // } // // private void finishApp() { // $(R.id.letter_finish_task_btn).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // BackFlow.finishTask(BaseLetterActivity.this); // } // }); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/ContainerActivity.java // public class ContainerActivity extends BaseBackFlowActivity { // // /** // * sample: XXXFragment.class.getName() // */ // public final static String PARAM_CLASSNAME = "className"; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.fragment_container); // // BaseBackFlowFragment fragment = getFragment(); // if (fragment == null) { // // finish(); // return; // } // // getSupportFragmentManager().beginTransaction() // .replace(R.id.fragment_container, fragment) // .commitAllowingStateLoss(); // } // // private BaseBackFlowFragment getFragment() { // String className = getIntent().getStringExtra(PARAM_CLASSNAME); // BaseBackFlowFragment fragment = null; // if (className != null && !className.isEmpty()) { // try { // fragment = (BaseBackFlowFragment) getClassLoader().loadClass(className).newInstance(); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } catch (InstantiationException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // return fragment; // } // // }
import android.os.Bundle; import cn.ytxu.androidbackflow.sample.normal.request_activity.base.BaseLetterActivity; import cn.ytxu.androidbackflow.sample.ContainerActivity;
package cn.ytxu.androidbackflow.sample.normal.request_activity.letter; public class LetterGActivity extends BaseLetterActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity/base/BaseLetterActivity.java // public class BaseLetterActivity extends BaseBackFlowActivity { // // private Button jumpBtn, rollbackFlowBtn; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_letter); // // jumpBtn = $(R.id.letter_jump_btn); // rollbackFlowBtn = $(R.id.letter_back_flow_btn); // rollbackFlowBtn.setVisibility(View.GONE); // // setTitle(getClass().getSimpleName()); // jumpBtn.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // try { // startActivity(new Intent(BaseLetterActivity.this, LetterType.getNextActivity(BaseLetterActivity.this))); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } catch (ArrayIndexOutOfBoundsException e) { // e.printStackTrace(); // } // } // }); // // finishApp(); // } // // protected void setRollbackFlow(final Class<? extends Activity> atyClass) { // setRollbackFlow(atyClass, "rollback :" + atyClass.getSimpleName()); // } // // protected void setRollbackFlow(final Class<? extends Activity> atyClass, String text) { // rollbackFlowBtn.setVisibility(View.VISIBLE); // rollbackFlowBtn.setText(text); // rollbackFlowBtn.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // BackFlow.request(BaseLetterActivity.this, atyClass); // } // }); // } // // private void finishApp() { // $(R.id.letter_finish_task_btn).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // BackFlow.finishTask(BaseLetterActivity.this); // } // }); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/ContainerActivity.java // public class ContainerActivity extends BaseBackFlowActivity { // // /** // * sample: XXXFragment.class.getName() // */ // public final static String PARAM_CLASSNAME = "className"; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.fragment_container); // // BaseBackFlowFragment fragment = getFragment(); // if (fragment == null) { // // finish(); // return; // } // // getSupportFragmentManager().beginTransaction() // .replace(R.id.fragment_container, fragment) // .commitAllowingStateLoss(); // } // // private BaseBackFlowFragment getFragment() { // String className = getIntent().getStringExtra(PARAM_CLASSNAME); // BaseBackFlowFragment fragment = null; // if (className != null && !className.isEmpty()) { // try { // fragment = (BaseBackFlowFragment) getClassLoader().loadClass(className).newInstance(); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } catch (InstantiationException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // } // return fragment; // } // // } // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity/letter/LetterGActivity.java import android.os.Bundle; import cn.ytxu.androidbackflow.sample.normal.request_activity.base.BaseLetterActivity; import cn.ytxu.androidbackflow.sample.ContainerActivity; package cn.ytxu.androidbackflow.sample.normal.request_activity.letter; public class LetterGActivity extends BaseLetterActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setRollbackFlow(ContainerActivity.class, "回退栈中没有ContainerActivity,所以,会变为finish_task的效果");
xuyt11/androidBackFlow
app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/MultiFragmentActivity.java
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterAFragment.java // public class MFLetterAFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterBFragment.java // public class MFLetterBFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterCFragment.java // public class MFLetterCFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterDFragment.java // public class MFLetterDFragment extends MFBaseLetterFragment { // }
import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.R; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterAFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterBFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterCFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterDFragment;
package cn.ytxu.androidbackflow.sample.fragments.multi_fragment; public class MultiFragmentActivity extends BaseBackFlowActivity { private String[] mTitles = new String[]{"唐僧", "大师兄", "二师兄", "沙师弟"}; private ViewPager viewPager; private TabLayout tabLayout; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.multi_fragment_activity); $(R.id.multi_fragment_4_requedst_activity).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MultiFragmentActivity.this, MFSecondActivity.class)); } }); tabLayout = $(R.id.multi_fragment_tab); viewPager = $(R.id.multi_fragment_viewPager); // TODO init all fragment or init only two viewPager.setOffscreenPageLimit(mTitles.length); setPagerAdapter(); } private void setPagerAdapter() { viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public int getCount() { return mTitles.length; } @Override public Fragment getItem(int position) { switch (position) { case 0:
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterAFragment.java // public class MFLetterAFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterBFragment.java // public class MFLetterBFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterCFragment.java // public class MFLetterCFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterDFragment.java // public class MFLetterDFragment extends MFBaseLetterFragment { // } // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/MultiFragmentActivity.java import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.R; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterAFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterBFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterCFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterDFragment; package cn.ytxu.androidbackflow.sample.fragments.multi_fragment; public class MultiFragmentActivity extends BaseBackFlowActivity { private String[] mTitles = new String[]{"唐僧", "大师兄", "二师兄", "沙师弟"}; private ViewPager viewPager; private TabLayout tabLayout; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.multi_fragment_activity); $(R.id.multi_fragment_4_requedst_activity).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MultiFragmentActivity.this, MFSecondActivity.class)); } }); tabLayout = $(R.id.multi_fragment_tab); viewPager = $(R.id.multi_fragment_viewPager); // TODO init all fragment or init only two viewPager.setOffscreenPageLimit(mTitles.length); setPagerAdapter(); } private void setPagerAdapter() { viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public int getCount() { return mTitles.length; } @Override public Fragment getItem(int position) { switch (position) { case 0:
return new MFLetterAFragment();
xuyt11/androidBackFlow
app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/MultiFragmentActivity.java
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterAFragment.java // public class MFLetterAFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterBFragment.java // public class MFLetterBFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterCFragment.java // public class MFLetterCFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterDFragment.java // public class MFLetterDFragment extends MFBaseLetterFragment { // }
import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.R; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterAFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterBFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterCFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterDFragment;
setContentView(R.layout.multi_fragment_activity); $(R.id.multi_fragment_4_requedst_activity).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MultiFragmentActivity.this, MFSecondActivity.class)); } }); tabLayout = $(R.id.multi_fragment_tab); viewPager = $(R.id.multi_fragment_viewPager); // TODO init all fragment or init only two viewPager.setOffscreenPageLimit(mTitles.length); setPagerAdapter(); } private void setPagerAdapter() { viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public int getCount() { return mTitles.length; } @Override public Fragment getItem(int position) { switch (position) { case 0: return new MFLetterAFragment(); case 1:
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterAFragment.java // public class MFLetterAFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterBFragment.java // public class MFLetterBFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterCFragment.java // public class MFLetterCFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterDFragment.java // public class MFLetterDFragment extends MFBaseLetterFragment { // } // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/MultiFragmentActivity.java import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.R; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterAFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterBFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterCFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterDFragment; setContentView(R.layout.multi_fragment_activity); $(R.id.multi_fragment_4_requedst_activity).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MultiFragmentActivity.this, MFSecondActivity.class)); } }); tabLayout = $(R.id.multi_fragment_tab); viewPager = $(R.id.multi_fragment_viewPager); // TODO init all fragment or init only two viewPager.setOffscreenPageLimit(mTitles.length); setPagerAdapter(); } private void setPagerAdapter() { viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public int getCount() { return mTitles.length; } @Override public Fragment getItem(int position) { switch (position) { case 0: return new MFLetterAFragment(); case 1:
return new MFLetterBFragment();
xuyt11/androidBackFlow
app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/MultiFragmentActivity.java
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterAFragment.java // public class MFLetterAFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterBFragment.java // public class MFLetterBFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterCFragment.java // public class MFLetterCFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterDFragment.java // public class MFLetterDFragment extends MFBaseLetterFragment { // }
import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.R; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterAFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterBFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterCFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterDFragment;
$(R.id.multi_fragment_4_requedst_activity).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MultiFragmentActivity.this, MFSecondActivity.class)); } }); tabLayout = $(R.id.multi_fragment_tab); viewPager = $(R.id.multi_fragment_viewPager); // TODO init all fragment or init only two viewPager.setOffscreenPageLimit(mTitles.length); setPagerAdapter(); } private void setPagerAdapter() { viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public int getCount() { return mTitles.length; } @Override public Fragment getItem(int position) { switch (position) { case 0: return new MFLetterAFragment(); case 1: return new MFLetterBFragment(); case 2:
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterAFragment.java // public class MFLetterAFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterBFragment.java // public class MFLetterBFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterCFragment.java // public class MFLetterCFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterDFragment.java // public class MFLetterDFragment extends MFBaseLetterFragment { // } // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/MultiFragmentActivity.java import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.R; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterAFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterBFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterCFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterDFragment; $(R.id.multi_fragment_4_requedst_activity).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MultiFragmentActivity.this, MFSecondActivity.class)); } }); tabLayout = $(R.id.multi_fragment_tab); viewPager = $(R.id.multi_fragment_viewPager); // TODO init all fragment or init only two viewPager.setOffscreenPageLimit(mTitles.length); setPagerAdapter(); } private void setPagerAdapter() { viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public int getCount() { return mTitles.length; } @Override public Fragment getItem(int position) { switch (position) { case 0: return new MFLetterAFragment(); case 1: return new MFLetterBFragment(); case 2:
return new MFLetterCFragment();
xuyt11/androidBackFlow
app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/MultiFragmentActivity.java
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterAFragment.java // public class MFLetterAFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterBFragment.java // public class MFLetterBFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterCFragment.java // public class MFLetterCFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterDFragment.java // public class MFLetterDFragment extends MFBaseLetterFragment { // }
import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.R; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterAFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterBFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterCFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterDFragment;
public void onClick(View v) { startActivity(new Intent(MultiFragmentActivity.this, MFSecondActivity.class)); } }); tabLayout = $(R.id.multi_fragment_tab); viewPager = $(R.id.multi_fragment_viewPager); // TODO init all fragment or init only two viewPager.setOffscreenPageLimit(mTitles.length); setPagerAdapter(); } private void setPagerAdapter() { viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public int getCount() { return mTitles.length; } @Override public Fragment getItem(int position) { switch (position) { case 0: return new MFLetterAFragment(); case 1: return new MFLetterBFragment(); case 2: return new MFLetterCFragment(); case 3:
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterAFragment.java // public class MFLetterAFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterBFragment.java // public class MFLetterBFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterCFragment.java // public class MFLetterCFragment extends MFBaseLetterFragment { // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/letter/MFLetterDFragment.java // public class MFLetterDFragment extends MFBaseLetterFragment { // } // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/fragments/multi_fragment/MultiFragmentActivity.java import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.R; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterAFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterBFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterCFragment; import cn.ytxu.androidbackflow.sample.fragments.multi_fragment.letter.MFLetterDFragment; public void onClick(View v) { startActivity(new Intent(MultiFragmentActivity.this, MFSecondActivity.class)); } }); tabLayout = $(R.id.multi_fragment_tab); viewPager = $(R.id.multi_fragment_viewPager); // TODO init all fragment or init only two viewPager.setOffscreenPageLimit(mTitles.length); setPagerAdapter(); } private void setPagerAdapter() { viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public int getCount() { return mTitles.length; } @Override public Fragment getItem(int position) { switch (position) { case 0: return new MFLetterAFragment(); case 1: return new MFLetterBFragment(); case 2: return new MFLetterCFragment(); case 3:
return new MFLetterDFragment();
xuyt11/androidBackFlow
app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity_and_fragment/ContainerAF1Activity.java
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowFragment.java // public class BaseBackFlowFragment extends Fragment { // // protected View root; // // public void setRoot(View root) { // this.root = root; // } // // public <T extends View> T $(@IdRes int id) { // return (T) root.findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // public void onActivityResult(int requestCode, int resultCode, Intent data) { // BackFlow.Logger.logIntent(this, data); // super.onActivityResult(requestCode, resultCode, data); // } // // }
import android.os.Bundle; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.BaseBackFlowFragment; import cn.ytxu.androidbackflow.R;
package cn.ytxu.androidbackflow.sample.normal.request_activity_and_fragment; /** * Created by ytxu on 16/12/31. */ public class ContainerAF1Activity extends BaseBackFlowActivity { /** * sample: XXXFragment.class.getName() */ public final static String PARAM_CLASSNAME = "className"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_container);
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowFragment.java // public class BaseBackFlowFragment extends Fragment { // // protected View root; // // public void setRoot(View root) { // this.root = root; // } // // public <T extends View> T $(@IdRes int id) { // return (T) root.findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // public void onActivityResult(int requestCode, int resultCode, Intent data) { // BackFlow.Logger.logIntent(this, data); // super.onActivityResult(requestCode, resultCode, data); // } // // } // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/normal/request_activity_and_fragment/ContainerAF1Activity.java import android.os.Bundle; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.BaseBackFlowFragment; import cn.ytxu.androidbackflow.R; package cn.ytxu.androidbackflow.sample.normal.request_activity_and_fragment; /** * Created by ytxu on 16/12/31. */ public class ContainerAF1Activity extends BaseBackFlowActivity { /** * sample: XXXFragment.class.getName() */ public final static String PARAM_CLASSNAME = "className"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_container);
BaseBackFlowFragment fragment = getFragment();
xuyt11/androidBackFlow
app/src/main/java/cn/ytxu/androidbackflow/sample/ContainerActivity.java
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowFragment.java // public class BaseBackFlowFragment extends Fragment { // // protected View root; // // public void setRoot(View root) { // this.root = root; // } // // public <T extends View> T $(@IdRes int id) { // return (T) root.findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // public void onActivityResult(int requestCode, int resultCode, Intent data) { // BackFlow.Logger.logIntent(this, data); // super.onActivityResult(requestCode, resultCode, data); // } // // }
import android.os.Bundle; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.BaseBackFlowFragment; import cn.ytxu.androidbackflow.R;
package cn.ytxu.androidbackflow.sample; /** * Created by ytxu on 16/12/31. */ public class ContainerActivity extends BaseBackFlowActivity { /** * sample: XXXFragment.class.getName() */ public final static String PARAM_CLASSNAME = "className"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_container);
// Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowActivity.java // public class BaseBackFlowActivity extends AppCompatActivity { // private final String TAG = this.getClass().getSimpleName(); // // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // BackFlow.Logger.log(TAG, "taskId:" + getTaskId() // + ", obj:" + Integer.toHexString(hashCode()) // + ", myPid:" + android.os.Process.myPid() //获取当前进程的id // + ", process:" + BackFlow.getCurProcessName(this)); // } // // public <T extends View> T $(@IdRes int id) { // return (T) findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (BackFlow.handle(this, getSupportFragmentManager().getFragments(), requestCode, resultCode, data)) { // return; // } // super.onActivityResult(requestCode, resultCode, data); // } // // @Override // protected void onDestroy() { // BackFlow.Logger.log("onDestroy", this.getClass().getSimpleName()); // super.onDestroy(); // } // } // // Path: app/src/main/java/cn/ytxu/androidbackflow/BaseBackFlowFragment.java // public class BaseBackFlowFragment extends Fragment { // // protected View root; // // public void setRoot(View root) { // this.root = root; // } // // public <T extends View> T $(@IdRes int id) { // return (T) root.findViewById(id); // } // // // //******************** start activity replace method ******************** // public void startActivity4NonBackFlow(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW); // } // // public void startActivity4NonBackFlow(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE_4_NON_BACK_FLOW, options); // } // // // //******************** back flow ******************** // @Override // public void startActivity(Intent intent) { // startActivityForResult(intent, BackFlow.REQUEST_CODE); // } // // @Override // public void startActivity(Intent intent, @Nullable Bundle options) { // startActivityForResult(intent, BackFlow.REQUEST_CODE, options); // } // // @Override // public void onActivityResult(int requestCode, int resultCode, Intent data) { // BackFlow.Logger.logIntent(this, data); // super.onActivityResult(requestCode, resultCode, data); // } // // } // Path: app/src/main/java/cn/ytxu/androidbackflow/sample/ContainerActivity.java import android.os.Bundle; import cn.ytxu.androidbackflow.BaseBackFlowActivity; import cn.ytxu.androidbackflow.BaseBackFlowFragment; import cn.ytxu.androidbackflow.R; package cn.ytxu.androidbackflow.sample; /** * Created by ytxu on 16/12/31. */ public class ContainerActivity extends BaseBackFlowActivity { /** * sample: XXXFragment.class.getName() */ public final static String PARAM_CLASSNAME = "className"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_container);
BaseBackFlowFragment fragment = getFragment();
mast-group/sequence-mining
sequence-miner/src/main/java/sequencemining/eval/FrequentSequenceMining.java
// Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // }
import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.SortedMap; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import com.google.common.base.Functions; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Ordering; import ca.pfv.spmf.algorithms.sequentialpatterns.BIDE_and_prefixspan.AlgoBIDEPlus; import ca.pfv.spmf.algorithms.sequentialpatterns.BIDE_and_prefixspan.AlgoPrefixSpan; import ca.pfv.spmf.algorithms.sequentialpatterns.BIDE_and_prefixspan.SequentialPattern; import ca.pfv.spmf.algorithms.sequentialpatterns.BIDE_and_prefixspan.SequentialPatterns; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.AlgoSPADE; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.AlgoSPAM_AGP; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.candidatePatternsGeneration.CandidateGenerator; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.candidatePatternsGeneration.CandidateGenerator_Qualitative; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.creators.AbstractionCreator; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.creators.AbstractionCreator_Qualitative; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.idLists.creators.IdListCreator_FatBitmap; import ca.pfv.spmf.input.sequence_database_list_integers.SequenceDatabase; import ca.pfv.spmf.patterns.itemset_list_integers_without_support.Itemset; import sequencemining.sequence.Sequence;
package sequencemining.eval; public class FrequentSequenceMining { public static void main(final String[] args) throws IOException { // Datasets and parameters final String[] datasets = { "alice_punc", "GAZELLE1", "jmlr", "SIGN", "auslan2", "pioneer", "aslbu", "skating", "aslgt", "context" }; final double[] minSupps = new double[] { 0.02, 0.004, 0.15, 0.45, 0.0001, 0.1, 0.04, 0.43, 0.25, 0.49 }; for (int i = 0; i < datasets.length; i++) { final String dbPath = "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Sequences/Datasets/Paper/" + datasets[i] + ".dat"; final String saveFile = "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Sequences/BIDE/" + datasets[i] + ".txt"; mineClosedFrequentSequencesBIDE(dbPath, saveFile, minSupps[i]); } } /** Run PrefixSpan algorithm */
// Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // } // Path: sequence-miner/src/main/java/sequencemining/eval/FrequentSequenceMining.java import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.SortedMap; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import com.google.common.base.Functions; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Ordering; import ca.pfv.spmf.algorithms.sequentialpatterns.BIDE_and_prefixspan.AlgoBIDEPlus; import ca.pfv.spmf.algorithms.sequentialpatterns.BIDE_and_prefixspan.AlgoPrefixSpan; import ca.pfv.spmf.algorithms.sequentialpatterns.BIDE_and_prefixspan.SequentialPattern; import ca.pfv.spmf.algorithms.sequentialpatterns.BIDE_and_prefixspan.SequentialPatterns; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.AlgoSPADE; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.AlgoSPAM_AGP; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.candidatePatternsGeneration.CandidateGenerator; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.candidatePatternsGeneration.CandidateGenerator_Qualitative; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.creators.AbstractionCreator; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.creators.AbstractionCreator_Qualitative; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.idLists.creators.IdListCreator_FatBitmap; import ca.pfv.spmf.input.sequence_database_list_integers.SequenceDatabase; import ca.pfv.spmf.patterns.itemset_list_integers_without_support.Itemset; import sequencemining.sequence.Sequence; package sequencemining.eval; public class FrequentSequenceMining { public static void main(final String[] args) throws IOException { // Datasets and parameters final String[] datasets = { "alice_punc", "GAZELLE1", "jmlr", "SIGN", "auslan2", "pioneer", "aslbu", "skating", "aslgt", "context" }; final double[] minSupps = new double[] { 0.02, 0.004, 0.15, 0.45, 0.0001, 0.1, 0.04, 0.43, 0.25, 0.49 }; for (int i = 0; i < datasets.length; i++) { final String dbPath = "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Sequences/Datasets/Paper/" + datasets[i] + ".dat"; final String saveFile = "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Sequences/BIDE/" + datasets[i] + ".txt"; mineClosedFrequentSequencesBIDE(dbPath, saveFile, minSupps[i]); } } /** Run PrefixSpan algorithm */
public static SortedMap<Sequence, Integer> mineFrequentSequencesPrefixSpan(final String dataset,
mast-group/sequence-mining
sequence-miner/src/main/java/sequencemining/main/SequenceMiningCore.java
// Path: sequence-miner/src/main/java/sequencemining/main/InferenceAlgorithms.java // public interface InferenceAlgorithm { // public Multiset<Sequence> infer(final Transaction transaction); // } // // Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // } // // Path: sequence-miner/src/main/java/sequencemining/transaction/TransactionDatabase.java // public abstract class TransactionDatabase { // // /** Set to true if candidate generation iteration limit exceeded */ // private boolean iterationLimitExceeded = false; // // /** Average cost across the transactions */ // private double averageCost = Double.POSITIVE_INFINITY; // // /** Set the average cost */ // public void setAverageCost(final double averageCost) { // this.averageCost = averageCost; // } // // /** Get the average cost */ // public double getAverageCost() { // return averageCost; // } // // public void setIterationLimitExceeded() { // iterationLimitExceeded = true; // } // // public boolean getIterationLimitExceeded() { // return iterationLimitExceeded; // } // // /** Get a list of transactions */ // public abstract List<Transaction> getTransactionList(); // // // /** Get a JavaRDD of transactions */ // // public abstract JavaRDD<Transaction> getTransactionRDD(); // // // // /** Update the transaction cache */ // // public abstract void updateTransactionCache( // // final JavaRDD<Transaction> updatedTransactions); // // /** Get the number of transactions in this database */ // public abstract int size(); // // } // // Path: sequence-miner/src/main/java/sequencemining/util/Tuple2.java // public class Tuple2<T1, T2> { // public final T1 _1; // public final T2 _2; // // public Tuple2(final T1 _1, final T2 _2) { // this._1 = _1; // this._2 = _2; // } // // @Override // public String toString() { // return "(" + _1 + "," + _2 + ")"; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((_1 == null) ? 0 : _1.hashCode()); // result = prime * result + ((_2 == null) ? 0 : _2.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) // return true; // if (!(obj instanceof Tuple2)) // return false; // final Tuple2<?, ?> other = (Tuple2<?, ?>) obj; // return (_1 == null ? other._1 == null : _1.equals(other._1)) // && (_2 == null ? other._2 == null : _2.equals(other._2)); // } // // }
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.ExecutionException; import org.apache.commons.io.FileUtils; import com.google.common.base.Functions; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Ordering; import com.google.common.collect.Table; import sequencemining.main.InferenceAlgorithms.InferenceAlgorithm; import sequencemining.sequence.Sequence; import sequencemining.transaction.TransactionDatabase; import sequencemining.util.Tuple2;
package sequencemining.main; public abstract class SequenceMiningCore { /** Main fixed settings */ private static final int OPTIMIZE_PARAMS_EVERY = 1; private static final double OPTIMIZE_TOL = 1e-5; protected static final Logger logger = Logger.getLogger(SequenceMiningCore.class.getName()); public static final File LOG_DIR = new File("/tmp/"); /** Variable settings */ protected static Level LOG_LEVEL = Level.FINE; protected static long MAX_RUNTIME = 24 * 60 * 60 * 1_000; // 24hrs /** * Learn itemsets model using structural EM */ protected static Table<Sequence, Integer, Double> structuralEM(final TransactionDatabase transactions,
// Path: sequence-miner/src/main/java/sequencemining/main/InferenceAlgorithms.java // public interface InferenceAlgorithm { // public Multiset<Sequence> infer(final Transaction transaction); // } // // Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // } // // Path: sequence-miner/src/main/java/sequencemining/transaction/TransactionDatabase.java // public abstract class TransactionDatabase { // // /** Set to true if candidate generation iteration limit exceeded */ // private boolean iterationLimitExceeded = false; // // /** Average cost across the transactions */ // private double averageCost = Double.POSITIVE_INFINITY; // // /** Set the average cost */ // public void setAverageCost(final double averageCost) { // this.averageCost = averageCost; // } // // /** Get the average cost */ // public double getAverageCost() { // return averageCost; // } // // public void setIterationLimitExceeded() { // iterationLimitExceeded = true; // } // // public boolean getIterationLimitExceeded() { // return iterationLimitExceeded; // } // // /** Get a list of transactions */ // public abstract List<Transaction> getTransactionList(); // // // /** Get a JavaRDD of transactions */ // // public abstract JavaRDD<Transaction> getTransactionRDD(); // // // // /** Update the transaction cache */ // // public abstract void updateTransactionCache( // // final JavaRDD<Transaction> updatedTransactions); // // /** Get the number of transactions in this database */ // public abstract int size(); // // } // // Path: sequence-miner/src/main/java/sequencemining/util/Tuple2.java // public class Tuple2<T1, T2> { // public final T1 _1; // public final T2 _2; // // public Tuple2(final T1 _1, final T2 _2) { // this._1 = _1; // this._2 = _2; // } // // @Override // public String toString() { // return "(" + _1 + "," + _2 + ")"; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((_1 == null) ? 0 : _1.hashCode()); // result = prime * result + ((_2 == null) ? 0 : _2.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) // return true; // if (!(obj instanceof Tuple2)) // return false; // final Tuple2<?, ?> other = (Tuple2<?, ?>) obj; // return (_1 == null ? other._1 == null : _1.equals(other._1)) // && (_2 == null ? other._2 == null : _2.equals(other._2)); // } // // } // Path: sequence-miner/src/main/java/sequencemining/main/SequenceMiningCore.java import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.ExecutionException; import org.apache.commons.io.FileUtils; import com.google.common.base.Functions; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Ordering; import com.google.common.collect.Table; import sequencemining.main.InferenceAlgorithms.InferenceAlgorithm; import sequencemining.sequence.Sequence; import sequencemining.transaction.TransactionDatabase; import sequencemining.util.Tuple2; package sequencemining.main; public abstract class SequenceMiningCore { /** Main fixed settings */ private static final int OPTIMIZE_PARAMS_EVERY = 1; private static final double OPTIMIZE_TOL = 1e-5; protected static final Logger logger = Logger.getLogger(SequenceMiningCore.class.getName()); public static final File LOG_DIR = new File("/tmp/"); /** Variable settings */ protected static Level LOG_LEVEL = Level.FINE; protected static long MAX_RUNTIME = 24 * 60 * 60 * 1_000; // 24hrs /** * Learn itemsets model using structural EM */ protected static Table<Sequence, Integer, Double> structuralEM(final TransactionDatabase transactions,
final Table<Sequence, Integer, Double> sequences, final InferenceAlgorithm inferenceAlgorithm,
mast-group/sequence-mining
sequence-miner/src/test/java/sequencemining/main/SupportCountingTest.java
// Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // } // // Path: sequence-miner/src/main/java/sequencemining/transaction/TransactionList.java // public class TransactionList extends TransactionDatabase { // // private final List<Transaction> transactions; // // public TransactionList(final List<Transaction> transactions) { // this.transactions = transactions; // } // // @Override // public List<Transaction> getTransactionList() { // return transactions; // } // // // @Override // // public JavaRDD<Transaction> getTransactionRDD() { // // throw new UnsupportedOperationException("This is a list is not a RDD!!"); // // } // // @Override // public int size() { // return transactions.size(); // } // // // @Override // // public void updateTransactionCache( // // final JavaRDD<Transaction> updatedTransactions) { // // throw new UnsupportedOperationException("This is a list is not a RDD!!"); // // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.HashSet; import org.junit.Test; import sequencemining.sequence.Sequence; import sequencemining.transaction.TransactionList;
package sequencemining.main; public class SupportCountingTest { @Test public void testSupportCounting() throws IOException { final File input = getTestFile("TOY.txt"); // database
// Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // } // // Path: sequence-miner/src/main/java/sequencemining/transaction/TransactionList.java // public class TransactionList extends TransactionDatabase { // // private final List<Transaction> transactions; // // public TransactionList(final List<Transaction> transactions) { // this.transactions = transactions; // } // // @Override // public List<Transaction> getTransactionList() { // return transactions; // } // // // @Override // // public JavaRDD<Transaction> getTransactionRDD() { // // throw new UnsupportedOperationException("This is a list is not a RDD!!"); // // } // // @Override // public int size() { // return transactions.size(); // } // // // @Override // // public void updateTransactionCache( // // final JavaRDD<Transaction> updatedTransactions) { // // throw new UnsupportedOperationException("This is a list is not a RDD!!"); // // } // // } // Path: sequence-miner/src/test/java/sequencemining/main/SupportCountingTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.HashSet; import org.junit.Test; import sequencemining.sequence.Sequence; import sequencemining.transaction.TransactionList; package sequencemining.main; public class SupportCountingTest { @Test public void testSupportCounting() throws IOException { final File input = getTestFile("TOY.txt"); // database
final TransactionList transactions = SequenceMining.readTransactions(input);
mast-group/sequence-mining
sequence-miner/src/test/java/sequencemining/main/SupportCountingTest.java
// Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // } // // Path: sequence-miner/src/main/java/sequencemining/transaction/TransactionList.java // public class TransactionList extends TransactionDatabase { // // private final List<Transaction> transactions; // // public TransactionList(final List<Transaction> transactions) { // this.transactions = transactions; // } // // @Override // public List<Transaction> getTransactionList() { // return transactions; // } // // // @Override // // public JavaRDD<Transaction> getTransactionRDD() { // // throw new UnsupportedOperationException("This is a list is not a RDD!!"); // // } // // @Override // public int size() { // return transactions.size(); // } // // // @Override // // public void updateTransactionCache( // // final JavaRDD<Transaction> updatedTransactions) { // // throw new UnsupportedOperationException("This is a list is not a RDD!!"); // // } // // }
import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.HashSet; import org.junit.Test; import sequencemining.sequence.Sequence; import sequencemining.transaction.TransactionList;
package sequencemining.main; public class SupportCountingTest { @Test public void testSupportCounting() throws IOException { final File input = getTestFile("TOY.txt"); // database final TransactionList transactions = SequenceMining.readTransactions(input);
// Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // } // // Path: sequence-miner/src/main/java/sequencemining/transaction/TransactionList.java // public class TransactionList extends TransactionDatabase { // // private final List<Transaction> transactions; // // public TransactionList(final List<Transaction> transactions) { // this.transactions = transactions; // } // // @Override // public List<Transaction> getTransactionList() { // return transactions; // } // // // @Override // // public JavaRDD<Transaction> getTransactionRDD() { // // throw new UnsupportedOperationException("This is a list is not a RDD!!"); // // } // // @Override // public int size() { // return transactions.size(); // } // // // @Override // // public void updateTransactionCache( // // final JavaRDD<Transaction> updatedTransactions) { // // throw new UnsupportedOperationException("This is a list is not a RDD!!"); // // } // // } // Path: sequence-miner/src/test/java/sequencemining/main/SupportCountingTest.java import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.HashSet; import org.junit.Test; import sequencemining.sequence.Sequence; import sequencemining.transaction.TransactionList; package sequencemining.main; public class SupportCountingTest { @Test public void testSupportCounting() throws IOException { final File input = getTestFile("TOY.txt"); // database final TransactionList transactions = SequenceMining.readTransactions(input);
final Sequence seq = new Sequence(7, 3);
mast-group/sequence-mining
sequence-miner/src/main/java/sequencemining/transaction/TransactionGenerator.java
// Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // }
import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import org.apache.commons.io.LineIterator; import org.apache.commons.math3.distribution.EnumeratedIntegerDistribution; import org.apache.commons.math3.random.JDKRandomGenerator; import org.apache.commons.math3.random.RandomGenerator; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import com.google.common.collect.Table; import com.google.common.primitives.Doubles; import com.google.common.primitives.Ints; import sequencemining.sequence.Sequence;
package sequencemining.transaction; public class TransactionGenerator { private static final boolean VERBOSE = false; /** * Generate transactions from set of interesting sequences * * @return set of sequences added to transaction */
// Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // } // Path: sequence-miner/src/main/java/sequencemining/transaction/TransactionGenerator.java import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import org.apache.commons.io.LineIterator; import org.apache.commons.math3.distribution.EnumeratedIntegerDistribution; import org.apache.commons.math3.random.JDKRandomGenerator; import org.apache.commons.math3.random.RandomGenerator; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import com.google.common.collect.Table; import com.google.common.primitives.Doubles; import com.google.common.primitives.Ints; import sequencemining.sequence.Sequence; package sequencemining.transaction; public class TransactionGenerator { private static final boolean VERBOSE = false; /** * Generate transactions from set of interesting sequences * * @return set of sequences added to transaction */
public static HashMap<Sequence, Double> generateTransactionDatabase(final Map<Sequence, Double> sequences,
mast-group/sequence-mining
sequence-miner/src/main/java/sequencemining/eval/StatisticalSequenceMining.java
// Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // }
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.ProcessBuilder.Redirect; import java.util.LinkedHashMap; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import ca.pfv.spmf.algorithms.sequentialpatterns.goKrimp.AlgoGoKrimp; import ca.pfv.spmf.algorithms.sequentialpatterns.goKrimp.DataReader; import sequencemining.sequence.Sequence;
package sequencemining.eval; public class StatisticalSequenceMining { public static void main(final String[] args) throws IOException { // Datasets final String[] datasets = new String[] { "GAZELLE1" }; for (int i = 0; i < datasets.length; i++) { final File dbPath = new File( "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Sequences/Datasets/Paper/" + datasets[i] + ".dat"); // Run GoKRIMP //final File saveFileGoKRIMP = new File( // "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Sequences/GoKrimp/" + datasets[i] + ".txt"); //mineGoKrimpSequences(dbPath, saveFileGoKRIMP); // Run SQS final File saveFileSQS = new File( "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Sequences/SQS/" + datasets[i] + ".txt"); mineSQSSequences(dbPath, saveFileSQS, 1); } }
// Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // } // Path: sequence-miner/src/main/java/sequencemining/eval/StatisticalSequenceMining.java import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.ProcessBuilder.Redirect; import java.util.LinkedHashMap; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import ca.pfv.spmf.algorithms.sequentialpatterns.goKrimp.AlgoGoKrimp; import ca.pfv.spmf.algorithms.sequentialpatterns.goKrimp.DataReader; import sequencemining.sequence.Sequence; package sequencemining.eval; public class StatisticalSequenceMining { public static void main(final String[] args) throws IOException { // Datasets final String[] datasets = new String[] { "GAZELLE1" }; for (int i = 0; i < datasets.length; i++) { final File dbPath = new File( "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Sequences/Datasets/Paper/" + datasets[i] + ".dat"); // Run GoKRIMP //final File saveFileGoKRIMP = new File( // "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Sequences/GoKrimp/" + datasets[i] + ".txt"); //mineGoKrimpSequences(dbPath, saveFileGoKRIMP); // Run SQS final File saveFileSQS = new File( "/afs/inf.ed.ac.uk/user/j/jfowkes/Code/Sequences/SQS/" + datasets[i] + ".txt"); mineSQSSequences(dbPath, saveFileSQS, 1); } }
public static LinkedHashMap<Sequence, Double> mineGoKrimpSequences(final File dataset, final File saveFile)
mast-group/sequence-mining
sequence-miner/src/test/java/sequencemining/main/InitialProbabilitiesTest.java
// Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // }
import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import org.junit.Test; import com.google.common.collect.Table; import sequencemining.sequence.Sequence;
package sequencemining.main; public class InitialProbabilitiesTest { @Test public void testScanDatabaseToDetermineInitialProbabilities() throws IOException { final File input = getTestFile("TOY.txt"); // database
// Path: sequence-miner/src/main/java/sequencemining/sequence/Sequence.java // public class Sequence extends AbstractSequence implements Serializable { // private static final long serialVersionUID = -2766830126344921771L; // // /** // * Constructor // */ // public Sequence() { // this.items = new ArrayList<>(); // } // // /** // * Shallow Copy Constructor // * // * @param seq // * sequence to shallow copy // */ // public Sequence(final Sequence seq) { // this.items = seq.items; // } // // /** // * Constructor // * // * @param items // * a list of items that should be added to the new sequence // */ // public Sequence(final List<Integer> items) { // this.items = new ArrayList<>(items); // } // // /** // * Constructor // * // * @param items // * an array of items that should be added to the new sequence // */ // public Sequence(final Integer... items) { // this.items = new ArrayList<>(Arrays.asList(items)); // } // // /** // * Join Constructor // * // * @param seqs // * two sequences that should be joined // */ // public Sequence(final Sequence seq1, final Sequence seq2) { // this.items = new ArrayList<>(seq1.items); // this.items.addAll(seq2.items); // } // // } // Path: sequence-miner/src/test/java/sequencemining/main/InitialProbabilitiesTest.java import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import org.junit.Test; import com.google.common.collect.Table; import sequencemining.sequence.Sequence; package sequencemining.main; public class InitialProbabilitiesTest { @Test public void testScanDatabaseToDetermineInitialProbabilities() throws IOException { final File input = getTestFile("TOY.txt"); // database
final Table<Sequence, Integer, Double> probs = SequenceMining
uPhyca/IdobataAndroid
Idovatar/src/main/java/com/uphyca/idobata/android/data/ExponentialBackoff.java
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/data/api/BackoffPolicy.java // public interface BackoffPolicy { // // void backoff(); // // void reset(); // // long getNextBackOffMillis(); // // boolean isFailed(); // } // // Path: Idovatar/src/main/java/com/uphyca/idobata/android/data/api/Environment.java // public interface Environment { // // long elapsedRealtime(); // // long currentTimeMillis(); // }
import com.uphyca.idobata.android.data.api.BackoffPolicy; import com.uphyca.idobata.android.data.api.Environment;
package com.uphyca.idobata.android.data; public class ExponentialBackoff implements BackoffPolicy { private static final double MULTPLIER = 2;
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/data/api/BackoffPolicy.java // public interface BackoffPolicy { // // void backoff(); // // void reset(); // // long getNextBackOffMillis(); // // boolean isFailed(); // } // // Path: Idovatar/src/main/java/com/uphyca/idobata/android/data/api/Environment.java // public interface Environment { // // long elapsedRealtime(); // // long currentTimeMillis(); // } // Path: Idovatar/src/main/java/com/uphyca/idobata/android/data/ExponentialBackoff.java import com.uphyca.idobata.android.data.api.BackoffPolicy; import com.uphyca.idobata.android.data.api.Environment; package com.uphyca.idobata.android.data; public class ExponentialBackoff implements BackoffPolicy { private static final double MULTPLIER = 2;
private final Environment mEnvironment;
uPhyca/IdobataAndroid
Idovatar/src/main/java/com/uphyca/idobata/android/ui/NotificationsSettingActivity.java
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/IdobataModule.java // @Module(injects = { // IdobataService.class, // // PostImageService.class, // // PostTextService.class, // // PostTouchService.class, // // MainActivity.class, // // SendTo.Rooms.class, // // OssLicensesActivity.LicenseDialogFragment.class, // // NotificationsSettingActivity.PrefsFragment.class, // // MentionsFilter.class, // // }) // public class IdobataModule { // // public static final String PREFS_NAME = "prefs"; // // private final Application mApplication; // private static final long DEFAULT_POLLING_INTERVAL_MILLIS = TimeUnit.MINUTES.toMillis(5); // private static final long BACKOFF_SLEEP_MILLIS = TimeUnit.SECONDS.toMillis(5); // private static final int BACKOFF_TRIES = Integer.MAX_VALUE; // // public IdobataModule(Application application) { // mApplication = application; // } // // @Provides // @Singleton // OkHttpClient provideOkHttpClient() { // OkHttpClient okHttpClient = new OkHttpClient(); // File cacheDir = new File(mApplication.getCacheDir(), "okhttp"); // final HttpResponseCache cache; // try { // cache = new HttpResponseCache(cacheDir, 10 * 1024 * 1024); // } catch (IOException e) { // throw new IllegalStateException(e); // } // okHttpClient.setResponseCache(cache); // return okHttpClient; // } // // @Provides // @Singleton // Client provideClient(OkHttpClient okHttpClient, CookieHandler cookieHandler) { // return new OkClient(okHttpClient, cookieHandler); // } // // @Provides // @Singleton // Idobata provideIdobata(RequestInterceptor requestInterceptor, Client client) { // return new IdobataBuilder().setRequestInterceptor(requestInterceptor) // .setClient(client) // .build(); // } // // @Provides // @Singleton // CookieHandler provideCookieHandler() { // return new CookieHandlerAdapter(CookieManager.getInstance()); // } // // @Provides // @Singleton // RequestInterceptor provideRequestInterceptor() { // return new CookieAuthenticator(); // } // // @Provides // @Singleton // NotificationManager provideNotificationManager() { // return (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); // } // // @Provides // @Singleton // AlarmManager provideAlarmManager() { // return (AlarmManager) mApplication.getSystemService(Context.ALARM_SERVICE); // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences() { // return mApplication.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); // } // // @Provides // @Singleton // @PollingInterval // LongPreference providePollingIntervalPreference(SharedPreferences pref) { // return new LongPreference(pref, "polling_interval", DEFAULT_POLLING_INTERVAL_MILLIS); // } // // @Provides // @Singleton // @NotificationsMentions // BooleanPreference provideNotificationsMentionsPreference(SharedPreferences pref) { // return new BooleanPreference(pref, "notifications_mentions", false); // } // // @Provides // @Singleton // @NotificationsEffectsVibrate // BooleanPreference provideNotificationsEffectsVibratePreference(SharedPreferences pref) { // return new BooleanPreference(pref, "notifications_effects_vibrate", false); // } // // @Provides // @Singleton // @NotificationsEffectsLEDFlash // BooleanPreference provideNotificationsEffectsLEDFlashPreference(SharedPreferences pref) { // return new BooleanPreference(pref, "notifications_effects_led_flash", false); // } // // @Provides // @Singleton // @NotificationsEffectsSound // BooleanPreference provideNotificationsEffectsSoundPreference(SharedPreferences pref) { // return new BooleanPreference(pref, "notifications_effects_sound", false); // } // // @Provides(type = Provides.Type.SET) // @Singleton // MessageFilter provideMentionFilter(MentionsFilter filter) { // return filter; // } // // @Provides // @Singleton // @Networking // Executor provideHttpExecutor() { // return Executors.newCachedThreadPool(); // } // // @Provides // @Singleton // @Main // Executor provideUiExecutor() { // return new AndroidExecutor(); // } // // @Provides // @Singleton // Environment provideEnvironment() { // return new AndroidEnvironment(); // } // // @Provides // @Singleton // @StreamConnection // BackoffPolicy provideBackoffPolicy(Environment environment) { // return new ExponentialBackoff(environment, BACKOFF_SLEEP_MILLIS, BACKOFF_TRIES); // } // }
import android.app.Activity; import android.os.Bundle; import android.preference.PreferenceFragment; import com.uphyca.idobata.android.IdobataModule; import com.uphyca.idobata.android.R;
/* * Copyright (C) 2014 uPhyca Inc. * * 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 com.uphyca.idobata.android.ui; /** * @author Sosuke Masui (masui@uphyca.com) */ public class NotificationsSettingActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notifications_settings); } public static class PrefsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getPreferenceManager().setSharedPreferencesName("");
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/IdobataModule.java // @Module(injects = { // IdobataService.class, // // PostImageService.class, // // PostTextService.class, // // PostTouchService.class, // // MainActivity.class, // // SendTo.Rooms.class, // // OssLicensesActivity.LicenseDialogFragment.class, // // NotificationsSettingActivity.PrefsFragment.class, // // MentionsFilter.class, // // }) // public class IdobataModule { // // public static final String PREFS_NAME = "prefs"; // // private final Application mApplication; // private static final long DEFAULT_POLLING_INTERVAL_MILLIS = TimeUnit.MINUTES.toMillis(5); // private static final long BACKOFF_SLEEP_MILLIS = TimeUnit.SECONDS.toMillis(5); // private static final int BACKOFF_TRIES = Integer.MAX_VALUE; // // public IdobataModule(Application application) { // mApplication = application; // } // // @Provides // @Singleton // OkHttpClient provideOkHttpClient() { // OkHttpClient okHttpClient = new OkHttpClient(); // File cacheDir = new File(mApplication.getCacheDir(), "okhttp"); // final HttpResponseCache cache; // try { // cache = new HttpResponseCache(cacheDir, 10 * 1024 * 1024); // } catch (IOException e) { // throw new IllegalStateException(e); // } // okHttpClient.setResponseCache(cache); // return okHttpClient; // } // // @Provides // @Singleton // Client provideClient(OkHttpClient okHttpClient, CookieHandler cookieHandler) { // return new OkClient(okHttpClient, cookieHandler); // } // // @Provides // @Singleton // Idobata provideIdobata(RequestInterceptor requestInterceptor, Client client) { // return new IdobataBuilder().setRequestInterceptor(requestInterceptor) // .setClient(client) // .build(); // } // // @Provides // @Singleton // CookieHandler provideCookieHandler() { // return new CookieHandlerAdapter(CookieManager.getInstance()); // } // // @Provides // @Singleton // RequestInterceptor provideRequestInterceptor() { // return new CookieAuthenticator(); // } // // @Provides // @Singleton // NotificationManager provideNotificationManager() { // return (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE); // } // // @Provides // @Singleton // AlarmManager provideAlarmManager() { // return (AlarmManager) mApplication.getSystemService(Context.ALARM_SERVICE); // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences() { // return mApplication.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); // } // // @Provides // @Singleton // @PollingInterval // LongPreference providePollingIntervalPreference(SharedPreferences pref) { // return new LongPreference(pref, "polling_interval", DEFAULT_POLLING_INTERVAL_MILLIS); // } // // @Provides // @Singleton // @NotificationsMentions // BooleanPreference provideNotificationsMentionsPreference(SharedPreferences pref) { // return new BooleanPreference(pref, "notifications_mentions", false); // } // // @Provides // @Singleton // @NotificationsEffectsVibrate // BooleanPreference provideNotificationsEffectsVibratePreference(SharedPreferences pref) { // return new BooleanPreference(pref, "notifications_effects_vibrate", false); // } // // @Provides // @Singleton // @NotificationsEffectsLEDFlash // BooleanPreference provideNotificationsEffectsLEDFlashPreference(SharedPreferences pref) { // return new BooleanPreference(pref, "notifications_effects_led_flash", false); // } // // @Provides // @Singleton // @NotificationsEffectsSound // BooleanPreference provideNotificationsEffectsSoundPreference(SharedPreferences pref) { // return new BooleanPreference(pref, "notifications_effects_sound", false); // } // // @Provides(type = Provides.Type.SET) // @Singleton // MessageFilter provideMentionFilter(MentionsFilter filter) { // return filter; // } // // @Provides // @Singleton // @Networking // Executor provideHttpExecutor() { // return Executors.newCachedThreadPool(); // } // // @Provides // @Singleton // @Main // Executor provideUiExecutor() { // return new AndroidExecutor(); // } // // @Provides // @Singleton // Environment provideEnvironment() { // return new AndroidEnvironment(); // } // // @Provides // @Singleton // @StreamConnection // BackoffPolicy provideBackoffPolicy(Environment environment) { // return new ExponentialBackoff(environment, BACKOFF_SLEEP_MILLIS, BACKOFF_TRIES); // } // } // Path: Idovatar/src/main/java/com/uphyca/idobata/android/ui/NotificationsSettingActivity.java import android.app.Activity; import android.os.Bundle; import android.preference.PreferenceFragment; import com.uphyca.idobata.android.IdobataModule; import com.uphyca.idobata.android.R; /* * Copyright (C) 2014 uPhyca Inc. * * 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 com.uphyca.idobata.android.ui; /** * @author Sosuke Masui (masui@uphyca.com) */ public class NotificationsSettingActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notifications_settings); } public static class PrefsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getPreferenceManager().setSharedPreferencesName("");
getPreferenceManager().setSharedPreferencesName(IdobataModule.PREFS_NAME);
uPhyca/IdobataAndroid
Idovatar/src/main/java/com/uphyca/idobata/android/ui/SendTo.java
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return IdobataApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // } // // Path: Idovatar/src/main/java/com/uphyca/idobata/android/service/PostImageService.java // public class PostImageService extends IntentService { // // private static final String EXTRA_ROOM_URI = "room_uri"; // // public static void postImage(Context context, Uri roomUri, Uri dataUri) { // Intent intent = new Intent(context, PostImageService.class).setData(dataUri) // .putExtra(EXTRA_ROOM_URI, roomUri); // context.startService(intent); // } // // @Inject // Idobata mIdobata; // // public PostImageService() { // super("PostImageService"); // } // // @Override // public void onCreate() { // super.onCreate(); // InjectionUtils.getObjectGraph(this) // .inject(this); // } // // @Override // protected void onHandleIntent(Intent intent) { // Uri roomUri = intent.getParcelableExtra(EXTRA_ROOM_URI); // Uri dataUri = intent.getData(); // String mimeType = null; // try { // String[] tuple = roomUri.getFragment() // .split("/"); // String organizationSlug = tuple[2]; // String roomName = tuple[4]; // long roomId = mIdobata.getRoom(organizationSlug, roomName) // .getId(); // Cursor meta = getContentResolver().query(dataUri, new String[] { // "mime_type" // }, null, null, null); // try { // if (meta.moveToNext()) { // mimeType = meta.getString(0); // } // } finally { // meta.close(); // } // String fileName = "image." + mimeType.split("/")[1]; // mIdobata.postMessage(roomId, fileName, mimeType, getContentResolver().openInputStream(dataUri)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IdobataError idobataError) { // idobataError.printStackTrace(); // } // } // } // // Path: Idovatar/src/main/java/com/uphyca/idobata/android/service/PostTextService.java // public class PostTextService extends IntentService { // // private static final String EXTRA_ROOM_URI = "room_uri"; // private static final String EXTRA_SOURCE = "source"; // // public static void postText(Context context, Uri roomUri, String source) { // Intent intent = new Intent(context, PostTextService.class).putExtra(EXTRA_SOURCE, source) // .putExtra(EXTRA_ROOM_URI, roomUri); // context.startService(intent); // } // // @Inject // Idobata mIdobata; // // public PostTextService() { // super("PostTextService"); // } // // @Override // public void onCreate() { // super.onCreate(); // InjectionUtils.getObjectGraph(this) // .inject(this); // } // // @Override // protected void onHandleIntent(Intent intent) { // Uri roomUri = intent.getParcelableExtra(EXTRA_ROOM_URI); // String source = intent.getStringExtra(EXTRA_SOURCE); // try { // String[] tuple = roomUri.getFragment() // .split("/"); // String organizationSlug = tuple[2]; // String roomName = tuple[4]; // long roomId = mIdobata.getRoom(organizationSlug, roomName) // .getId(); // mIdobata.postMessage(roomId, source); // } catch (IdobataError idobataError) { // idobataError.printStackTrace(); // } // } // } // // Path: Idovatar/src/main/java/com/uphyca/idobata/android/data/IdobataUtils.java // public static Organization findOrganizationById(long id, List<Organization> organizations) { // for (Organization org : organizations) { // if (org.getId() == id) { // return org; // } // } // return null; // }
import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.ListFragment; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.idobata.android.InjectionUtils; import com.uphyca.idobata.android.R; import com.uphyca.idobata.android.data.api.Main; import com.uphyca.idobata.android.data.api.Networking; import com.uphyca.idobata.android.service.PostImageService; import com.uphyca.idobata.android.service.PostTextService; import com.uphyca.idobata.model.Organization; import com.uphyca.idobata.model.Records; import com.uphyca.idobata.model.Room; import com.uphyca.idobata.model.Seed; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import javax.inject.Inject; import static com.uphyca.idobata.android.data.IdobataUtils.findOrganizationById;
package com.uphyca.idobata.android.ui; public class SendTo extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send_to); } public static class Rooms extends ListFragment { @Inject Idobata mIdobata; @Inject @Networking Executor mExecutor; @Inject @Main Executor mDispatcher; private Seed mSeed; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return IdobataApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // } // // Path: Idovatar/src/main/java/com/uphyca/idobata/android/service/PostImageService.java // public class PostImageService extends IntentService { // // private static final String EXTRA_ROOM_URI = "room_uri"; // // public static void postImage(Context context, Uri roomUri, Uri dataUri) { // Intent intent = new Intent(context, PostImageService.class).setData(dataUri) // .putExtra(EXTRA_ROOM_URI, roomUri); // context.startService(intent); // } // // @Inject // Idobata mIdobata; // // public PostImageService() { // super("PostImageService"); // } // // @Override // public void onCreate() { // super.onCreate(); // InjectionUtils.getObjectGraph(this) // .inject(this); // } // // @Override // protected void onHandleIntent(Intent intent) { // Uri roomUri = intent.getParcelableExtra(EXTRA_ROOM_URI); // Uri dataUri = intent.getData(); // String mimeType = null; // try { // String[] tuple = roomUri.getFragment() // .split("/"); // String organizationSlug = tuple[2]; // String roomName = tuple[4]; // long roomId = mIdobata.getRoom(organizationSlug, roomName) // .getId(); // Cursor meta = getContentResolver().query(dataUri, new String[] { // "mime_type" // }, null, null, null); // try { // if (meta.moveToNext()) { // mimeType = meta.getString(0); // } // } finally { // meta.close(); // } // String fileName = "image." + mimeType.split("/")[1]; // mIdobata.postMessage(roomId, fileName, mimeType, getContentResolver().openInputStream(dataUri)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IdobataError idobataError) { // idobataError.printStackTrace(); // } // } // } // // Path: Idovatar/src/main/java/com/uphyca/idobata/android/service/PostTextService.java // public class PostTextService extends IntentService { // // private static final String EXTRA_ROOM_URI = "room_uri"; // private static final String EXTRA_SOURCE = "source"; // // public static void postText(Context context, Uri roomUri, String source) { // Intent intent = new Intent(context, PostTextService.class).putExtra(EXTRA_SOURCE, source) // .putExtra(EXTRA_ROOM_URI, roomUri); // context.startService(intent); // } // // @Inject // Idobata mIdobata; // // public PostTextService() { // super("PostTextService"); // } // // @Override // public void onCreate() { // super.onCreate(); // InjectionUtils.getObjectGraph(this) // .inject(this); // } // // @Override // protected void onHandleIntent(Intent intent) { // Uri roomUri = intent.getParcelableExtra(EXTRA_ROOM_URI); // String source = intent.getStringExtra(EXTRA_SOURCE); // try { // String[] tuple = roomUri.getFragment() // .split("/"); // String organizationSlug = tuple[2]; // String roomName = tuple[4]; // long roomId = mIdobata.getRoom(organizationSlug, roomName) // .getId(); // mIdobata.postMessage(roomId, source); // } catch (IdobataError idobataError) { // idobataError.printStackTrace(); // } // } // } // // Path: Idovatar/src/main/java/com/uphyca/idobata/android/data/IdobataUtils.java // public static Organization findOrganizationById(long id, List<Organization> organizations) { // for (Organization org : organizations) { // if (org.getId() == id) { // return org; // } // } // return null; // } // Path: Idovatar/src/main/java/com/uphyca/idobata/android/ui/SendTo.java import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.ListFragment; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.idobata.android.InjectionUtils; import com.uphyca.idobata.android.R; import com.uphyca.idobata.android.data.api.Main; import com.uphyca.idobata.android.data.api.Networking; import com.uphyca.idobata.android.service.PostImageService; import com.uphyca.idobata.android.service.PostTextService; import com.uphyca.idobata.model.Organization; import com.uphyca.idobata.model.Records; import com.uphyca.idobata.model.Room; import com.uphyca.idobata.model.Seed; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import javax.inject.Inject; import static com.uphyca.idobata.android.data.IdobataUtils.findOrganizationById; package com.uphyca.idobata.android.ui; public class SendTo extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send_to); } public static class Rooms extends ListFragment { @Inject Idobata mIdobata; @Inject @Networking Executor mExecutor; @Inject @Main Executor mDispatcher; private Seed mSeed; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
InjectionUtils.getObjectGraph(getActivity())
uPhyca/IdobataAndroid
Idovatar/src/main/java/com/uphyca/idobata/android/ui/OssLicensesActivity.java
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return IdobataApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // }
import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.FragmentManager; import android.app.ListFragment; import android.content.res.Resources; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.uphyca.idobata.android.InjectionUtils; import com.uphyca.idobata.android.R; import com.uphyca.idobata.android.data.api.Main; import com.uphyca.idobata.android.data.api.Networking; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.Executor; import javax.inject.Inject;
private static final String ARGS_TITLE = "title"; private static final String ARGS_FILE_NAME = "file_name"; public static LicenseDialogFragment newInstance(String title, String fileName) { LicenseDialogFragment f = new LicenseDialogFragment(); Bundle args = new Bundle(); args.putString(ARGS_TITLE, title); args.putString(ARGS_FILE_NAME, fileName); f.setArguments(args); return f; } @Inject @Networking Executor mExecutor; @Inject @Main Executor mDispatcher; private String mTitle; private String mFileName; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); mTitle = args.getString(ARGS_TITLE); mFileName = args.getString(ARGS_FILE_NAME);
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return IdobataApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // } // Path: Idovatar/src/main/java/com/uphyca/idobata/android/ui/OssLicensesActivity.java import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.FragmentManager; import android.app.ListFragment; import android.content.res.Resources; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.uphyca.idobata.android.InjectionUtils; import com.uphyca.idobata.android.R; import com.uphyca.idobata.android.data.api.Main; import com.uphyca.idobata.android.data.api.Networking; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.Executor; import javax.inject.Inject; private static final String ARGS_TITLE = "title"; private static final String ARGS_FILE_NAME = "file_name"; public static LicenseDialogFragment newInstance(String title, String fileName) { LicenseDialogFragment f = new LicenseDialogFragment(); Bundle args = new Bundle(); args.putString(ARGS_TITLE, title); args.putString(ARGS_FILE_NAME, fileName); f.setArguments(args); return f; } @Inject @Networking Executor mExecutor; @Inject @Main Executor mDispatcher; private String mTitle; private String mFileName; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); mTitle = args.getString(ARGS_TITLE); mFileName = args.getString(ARGS_FILE_NAME);
InjectionUtils.getObjectGraph(getActivity())
uPhyca/IdobataAndroid
Idovatar/src/main/java/com/uphyca/idobata/android/service/PostImageService.java
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return IdobataApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // }
import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.idobata.android.InjectionUtils; import java.io.FileNotFoundException; import javax.inject.Inject;
package com.uphyca.idobata.android.service; public class PostImageService extends IntentService { private static final String EXTRA_ROOM_URI = "room_uri"; public static void postImage(Context context, Uri roomUri, Uri dataUri) { Intent intent = new Intent(context, PostImageService.class).setData(dataUri) .putExtra(EXTRA_ROOM_URI, roomUri); context.startService(intent); } @Inject Idobata mIdobata; public PostImageService() { super("PostImageService"); } @Override public void onCreate() { super.onCreate();
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return IdobataApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // } // Path: Idovatar/src/main/java/com/uphyca/idobata/android/service/PostImageService.java import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.idobata.android.InjectionUtils; import java.io.FileNotFoundException; import javax.inject.Inject; package com.uphyca.idobata.android.service; public class PostImageService extends IntentService { private static final String EXTRA_ROOM_URI = "room_uri"; public static void postImage(Context context, Uri roomUri, Uri dataUri) { Intent intent = new Intent(context, PostImageService.class).setData(dataUri) .putExtra(EXTRA_ROOM_URI, roomUri); context.startService(intent); } @Inject Idobata mIdobata; public PostImageService() { super("PostImageService"); } @Override public void onCreate() { super.onCreate();
InjectionUtils.getObjectGraph(this)
uPhyca/IdobataAndroid
Idovatar/src/main/java/com/uphyca/idobata/android/service/PostTouchService.java
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return IdobataApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // }
import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.net.Uri; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.idobata.android.InjectionUtils; import javax.inject.Inject;
package com.uphyca.idobata.android.service; public class PostTouchService extends IntentService { public static void postTouch(Context context, Uri roomUri) { Intent intent = new Intent(context, PostTouchService.class).setData(roomUri); context.startService(intent); } @Inject Idobata mIdobata; public PostTouchService() { super("PostTouchService"); } @Override public void onCreate() { super.onCreate();
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return IdobataApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // } // Path: Idovatar/src/main/java/com/uphyca/idobata/android/service/PostTouchService.java import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.net.Uri; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.idobata.android.InjectionUtils; import javax.inject.Inject; package com.uphyca.idobata.android.service; public class PostTouchService extends IntentService { public static void postTouch(Context context, Uri roomUri) { Intent intent = new Intent(context, PostTouchService.class).setData(roomUri); context.startService(intent); } @Inject Idobata mIdobata; public PostTouchService() { super("PostTouchService"); } @Override public void onCreate() { super.onCreate();
InjectionUtils.getObjectGraph(this)
uPhyca/IdobataAndroid
Idovatar/src/main/java/com/uphyca/idobata/android/service/PostTextService.java
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return IdobataApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // }
import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.net.Uri; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.idobata.android.InjectionUtils; import javax.inject.Inject;
package com.uphyca.idobata.android.service; public class PostTextService extends IntentService { private static final String EXTRA_ROOM_URI = "room_uri"; private static final String EXTRA_SOURCE = "source"; public static void postText(Context context, Uri roomUri, String source) { Intent intent = new Intent(context, PostTextService.class).putExtra(EXTRA_SOURCE, source) .putExtra(EXTRA_ROOM_URI, roomUri); context.startService(intent); } @Inject Idobata mIdobata; public PostTextService() { super("PostTextService"); } @Override public void onCreate() { super.onCreate();
// Path: Idovatar/src/main/java/com/uphyca/idobata/android/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return IdobataApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // } // Path: Idovatar/src/main/java/com/uphyca/idobata/android/service/PostTextService.java import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.net.Uri; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.idobata.android.InjectionUtils; import javax.inject.Inject; package com.uphyca.idobata.android.service; public class PostTextService extends IntentService { private static final String EXTRA_ROOM_URI = "room_uri"; private static final String EXTRA_SOURCE = "source"; public static void postText(Context context, Uri roomUri, String source) { Intent intent = new Intent(context, PostTextService.class).putExtra(EXTRA_SOURCE, source) .putExtra(EXTRA_ROOM_URI, roomUri); context.startService(intent); } @Inject Idobata mIdobata; public PostTextService() { super("PostTextService"); } @Override public void onCreate() { super.onCreate();
InjectionUtils.getObjectGraph(this)
playframework/modules.playframework.org
app/services/UserServices.java
// Path: app/models/Rate.java // @Entity // public class Rate extends AbstractModel { // // @OneToOne(optional = false) // public Module playModule; // // @Column(nullable = false) // public Integer rating; // } // // Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model implements Role // { // @Id // public Long id; // // @Column(nullable = false, unique = true) // public String roleName; // // @Column(nullable = false, length = 1000) // public String description; // // public static final Finder<Long, UserRole> FIND = new Finder<Long, UserRole>(Long.class, // UserRole.class); // // @Override // public String getRoleName() // { // return roleName; // } // // public static UserRole findByRoleName(String roleName) // { // return FIND.where() // .eq("roleName", // roleName) // .findUnique(); // // } // }
import models.Rate; import models.User; import models.UserRole; import java.util.ArrayList; import java.util.Collections; import java.util.List;
/* * Copyright 2012 The Play! Framework * * 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 services; /** * @author Steve Chaloner (steve@objectify.be) */ public class UserServices {
// Path: app/models/Rate.java // @Entity // public class Rate extends AbstractModel { // // @OneToOne(optional = false) // public Module playModule; // // @Column(nullable = false) // public Integer rating; // } // // Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model implements Role // { // @Id // public Long id; // // @Column(nullable = false, unique = true) // public String roleName; // // @Column(nullable = false, length = 1000) // public String description; // // public static final Finder<Long, UserRole> FIND = new Finder<Long, UserRole>(Long.class, // UserRole.class); // // @Override // public String getRoleName() // { // return roleName; // } // // public static UserRole findByRoleName(String roleName) // { // return FIND.where() // .eq("roleName", // roleName) // .findUnique(); // // } // } // Path: app/services/UserServices.java import models.Rate; import models.User; import models.UserRole; import java.util.ArrayList; import java.util.Collections; import java.util.List; /* * Copyright 2012 The Play! Framework * * 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 services; /** * @author Steve Chaloner (steve@objectify.be) */ public class UserServices {
public User createUser(String userName,
playframework/modules.playframework.org
app/services/UserServices.java
// Path: app/models/Rate.java // @Entity // public class Rate extends AbstractModel { // // @OneToOne(optional = false) // public Module playModule; // // @Column(nullable = false) // public Integer rating; // } // // Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model implements Role // { // @Id // public Long id; // // @Column(nullable = false, unique = true) // public String roleName; // // @Column(nullable = false, length = 1000) // public String description; // // public static final Finder<Long, UserRole> FIND = new Finder<Long, UserRole>(Long.class, // UserRole.class); // // @Override // public String getRoleName() // { // return roleName; // } // // public static UserRole findByRoleName(String roleName) // { // return FIND.where() // .eq("roleName", // roleName) // .findUnique(); // // } // }
import models.Rate; import models.User; import models.UserRole; import java.util.ArrayList; import java.util.Collections; import java.util.List;
/* * Copyright 2012 The Play! Framework * * 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 services; /** * @author Steve Chaloner (steve@objectify.be) */ public class UserServices { public User createUser(String userName, String displayName, String password) { return createUser(userName, displayName, password,
// Path: app/models/Rate.java // @Entity // public class Rate extends AbstractModel { // // @OneToOne(optional = false) // public Module playModule; // // @Column(nullable = false) // public Integer rating; // } // // Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model implements Role // { // @Id // public Long id; // // @Column(nullable = false, unique = true) // public String roleName; // // @Column(nullable = false, length = 1000) // public String description; // // public static final Finder<Long, UserRole> FIND = new Finder<Long, UserRole>(Long.class, // UserRole.class); // // @Override // public String getRoleName() // { // return roleName; // } // // public static UserRole findByRoleName(String roleName) // { // return FIND.where() // .eq("roleName", // roleName) // .findUnique(); // // } // } // Path: app/services/UserServices.java import models.Rate; import models.User; import models.UserRole; import java.util.ArrayList; import java.util.Collections; import java.util.List; /* * Copyright 2012 The Play! Framework * * 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 services; /** * @author Steve Chaloner (steve@objectify.be) */ public class UserServices { public User createUser(String userName, String displayName, String password) { return createUser(userName, displayName, password,
Collections.<UserRole>emptyList());
playframework/modules.playframework.org
app/services/UserServices.java
// Path: app/models/Rate.java // @Entity // public class Rate extends AbstractModel { // // @OneToOne(optional = false) // public Module playModule; // // @Column(nullable = false) // public Integer rating; // } // // Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model implements Role // { // @Id // public Long id; // // @Column(nullable = false, unique = true) // public String roleName; // // @Column(nullable = false, length = 1000) // public String description; // // public static final Finder<Long, UserRole> FIND = new Finder<Long, UserRole>(Long.class, // UserRole.class); // // @Override // public String getRoleName() // { // return roleName; // } // // public static UserRole findByRoleName(String roleName) // { // return FIND.where() // .eq("roleName", // roleName) // .findUnique(); // // } // }
import models.Rate; import models.User; import models.UserRole; import java.util.ArrayList; import java.util.Collections; import java.util.List;
/* * Copyright 2012 The Play! Framework * * 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 services; /** * @author Steve Chaloner (steve@objectify.be) */ public class UserServices { public User createUser(String userName, String displayName, String password) { return createUser(userName, displayName, password, Collections.<UserRole>emptyList()); } public User createUser(String userName, String displayName, String password, List<UserRole> roles) { User user = new User(); user.userName = userName; user.displayName = displayName; user.password = password; user.accountActive = true; user.roles = new ArrayList<UserRole>(roles);
// Path: app/models/Rate.java // @Entity // public class Rate extends AbstractModel { // // @OneToOne(optional = false) // public Module playModule; // // @Column(nullable = false) // public Integer rating; // } // // Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/models/UserRole.java // @Entity // public class UserRole extends Model implements Role // { // @Id // public Long id; // // @Column(nullable = false, unique = true) // public String roleName; // // @Column(nullable = false, length = 1000) // public String description; // // public static final Finder<Long, UserRole> FIND = new Finder<Long, UserRole>(Long.class, // UserRole.class); // // @Override // public String getRoleName() // { // return roleName; // } // // public static UserRole findByRoleName(String roleName) // { // return FIND.where() // .eq("roleName", // roleName) // .findUnique(); // // } // } // Path: app/services/UserServices.java import models.Rate; import models.User; import models.UserRole; import java.util.ArrayList; import java.util.Collections; import java.util.List; /* * Copyright 2012 The Play! Framework * * 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 services; /** * @author Steve Chaloner (steve@objectify.be) */ public class UserServices { public User createUser(String userName, String displayName, String password) { return createUser(userName, displayName, password, Collections.<UserRole>emptyList()); } public User createUser(String userName, String displayName, String password, List<UserRole> roles) { User user = new User(); user.userName = userName; user.displayName = displayName; user.password = password; user.accountActive = true; user.roles = new ArrayList<UserRole>(roles);
user.rates = new ArrayList<Rate>();
playframework/modules.playframework.org
app/controllers/AbstractController.java
// Path: app/actors/HistoricalEventActor.java // public class HistoricalEventActor extends UntypedActor // { // @Override // public void onReceive(Object o) throws Exception // { // if (o instanceof HistoricalEvent) // { // ((HistoricalEvent)o).save(); // } // } // } // // Path: app/models/HistoricalEvent.java // @Entity // public class HistoricalEvent extends AbstractModel // { // @Column(nullable = false) // public Date creationDate; // // @Column(nullable = false) // public String category; // // @Column(length = 1000, // nullable = false) // public String message; // // public static final Finder<Long, HistoricalEvent> FIND = new Finder<Long, HistoricalEvent>(Long.class, // HistoricalEvent.class); // // public static List<HistoricalEvent> findMostRecent(int count) // { // return FIND.where().orderBy("creationDate DESC").setMaxRows(count).findList(); // } // }
import actors.HistoricalEventActor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import models.HistoricalEvent; import play.libs.Akka; import play.mvc.Controller; import java.util.Date;
/* * Copyright 2012 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AbstractController extends Controller { public static void createHistoricalEvent(String category, String message) {
// Path: app/actors/HistoricalEventActor.java // public class HistoricalEventActor extends UntypedActor // { // @Override // public void onReceive(Object o) throws Exception // { // if (o instanceof HistoricalEvent) // { // ((HistoricalEvent)o).save(); // } // } // } // // Path: app/models/HistoricalEvent.java // @Entity // public class HistoricalEvent extends AbstractModel // { // @Column(nullable = false) // public Date creationDate; // // @Column(nullable = false) // public String category; // // @Column(length = 1000, // nullable = false) // public String message; // // public static final Finder<Long, HistoricalEvent> FIND = new Finder<Long, HistoricalEvent>(Long.class, // HistoricalEvent.class); // // public static List<HistoricalEvent> findMostRecent(int count) // { // return FIND.where().orderBy("creationDate DESC").setMaxRows(count).findList(); // } // } // Path: app/controllers/AbstractController.java import actors.HistoricalEventActor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import models.HistoricalEvent; import play.libs.Akka; import play.mvc.Controller; import java.util.Date; /* * Copyright 2012 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AbstractController extends Controller { public static void createHistoricalEvent(String category, String message) {
HistoricalEvent historicalEvent = new HistoricalEvent();
playframework/modules.playframework.org
app/controllers/AbstractController.java
// Path: app/actors/HistoricalEventActor.java // public class HistoricalEventActor extends UntypedActor // { // @Override // public void onReceive(Object o) throws Exception // { // if (o instanceof HistoricalEvent) // { // ((HistoricalEvent)o).save(); // } // } // } // // Path: app/models/HistoricalEvent.java // @Entity // public class HistoricalEvent extends AbstractModel // { // @Column(nullable = false) // public Date creationDate; // // @Column(nullable = false) // public String category; // // @Column(length = 1000, // nullable = false) // public String message; // // public static final Finder<Long, HistoricalEvent> FIND = new Finder<Long, HistoricalEvent>(Long.class, // HistoricalEvent.class); // // public static List<HistoricalEvent> findMostRecent(int count) // { // return FIND.where().orderBy("creationDate DESC").setMaxRows(count).findList(); // } // }
import actors.HistoricalEventActor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import models.HistoricalEvent; import play.libs.Akka; import play.mvc.Controller; import java.util.Date;
/* * Copyright 2012 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AbstractController extends Controller { public static void createHistoricalEvent(String category, String message) { HistoricalEvent historicalEvent = new HistoricalEvent(); historicalEvent.creationDate = new Date(); historicalEvent.category = category; historicalEvent.message = message; ActorSystem actorSystem = Akka.system();
// Path: app/actors/HistoricalEventActor.java // public class HistoricalEventActor extends UntypedActor // { // @Override // public void onReceive(Object o) throws Exception // { // if (o instanceof HistoricalEvent) // { // ((HistoricalEvent)o).save(); // } // } // } // // Path: app/models/HistoricalEvent.java // @Entity // public class HistoricalEvent extends AbstractModel // { // @Column(nullable = false) // public Date creationDate; // // @Column(nullable = false) // public String category; // // @Column(length = 1000, // nullable = false) // public String message; // // public static final Finder<Long, HistoricalEvent> FIND = new Finder<Long, HistoricalEvent>(Long.class, // HistoricalEvent.class); // // public static List<HistoricalEvent> findMostRecent(int count) // { // return FIND.where().orderBy("creationDate DESC").setMaxRows(count).findList(); // } // } // Path: app/controllers/AbstractController.java import actors.HistoricalEventActor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import models.HistoricalEvent; import play.libs.Akka; import play.mvc.Controller; import java.util.Date; /* * Copyright 2012 Steve Chaloner * * 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 controllers; /** * @author Steve Chaloner (steve@objectify.be) */ public class AbstractController extends Controller { public static void createHistoricalEvent(String category, String message) { HistoricalEvent historicalEvent = new HistoricalEvent(); historicalEvent.creationDate = new Date(); historicalEvent.category = category; historicalEvent.message = message; ActorSystem actorSystem = Akka.system();
ActorRef actor = actorSystem.actorOf(new Props(HistoricalEventActor.class));
playframework/modules.playframework.org
app/forms/login/Register.java
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // }
import models.User; import static play.data.validation.Constraints.Required;
/* * Copyright 2012 The Play! Framework * * 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 forms.login; /** * @author Steve Chaloner (steve@objectify.be) */ public class Register { @Required public String userName; @Required public String password; @Required public String displayName; public String validate() { String result = null;
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // Path: app/forms/login/Register.java import models.User; import static play.data.validation.Constraints.Required; /* * Copyright 2012 The Play! Framework * * 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 forms.login; /** * @author Steve Chaloner (steve@objectify.be) */ public class Register { @Required public String userName; @Required public String password; @Required public String displayName; public String validate() { String result = null;
if (User.findByUserName(userName) != null)
playframework/modules.playframework.org
app/controllers/PlayVersions.java
// Path: app/actions/CurrentUser.java // public class CurrentUser extends Action.Simple // { // @Override // public Result call(Http.Context ctx) throws Throwable // { // accessUser(ctx); // return delegate.call(ctx); // } // // private static User accessUser(Http.Context ctx) // { // User user = (User)ctx.args.get("user"); // if (user == null) // { // String userName = ctx.session().get("userName"); // if (!StringUtils.isEmpty(userName)) // { // user = User.findByUserName(userName); // if (user != null) // { // ctx.args.put("user", // user); // } // } // } // // return user; // } // // public static User currentUser() // { // return currentUser(Http.Context.current()); // } // // public static User currentUser(Http.Context context) // { // return accessUser(context); // } // } // // Path: app/models/PlayVersion.java // @Entity // public class PlayVersion extends AbstractModel { // // public enum MajorVersion { // ONE("1"), // TWO("2"); // // private MajorVersion(String numeric) { // this.numeric = numeric; // } // // public String numeric; // } // // // @Column(nullable = false, unique = true) // @Constraints.Required // public String name; // // @Column(nullable = false) // @Enumerated(EnumType.STRING) // public MajorVersion majorVersion; // // @Column(nullable = false) // @Constraints.Required // public String documentationUrl; // // public static final Finder<Long, PlayVersion> FIND = new Finder<Long, PlayVersion>(Long.class, // PlayVersion.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static List<PlayVersion> getAll() { // return FIND.where() // .order("name ASC") // .findList(); // } // // public static PlayVersion findByName(String name) { // return FIND.where() // .eq("name", name) // .findUnique(); // } // // /** // * Allow 1.2 to match 1.2, 1.2.1, 1.2.2, etc // * // * @param name // * @return // */ // public static List<PlayVersion> findByLooseName(String name) { // return FIND.where() // .startsWith("name", name) // .findList(); // } // // public static List<PlayVersion> findByMajorVersion(MajorVersion majorVersion) { // return FIND.where() // .eq("majorVersion", majorVersion) // .findList(); // } // } // // Path: app/security/RoleDefinitions.java // public class RoleDefinitions // { // public static final String ADMIN = "admin"; // // private RoleDefinitions() // { // // no-op // } // } // // Path: app/actions/CurrentUser.java // public static User currentUser() // { // return currentUser(Http.Context.current()); // }
import actions.CurrentUser; import be.objectify.deadbolt.actions.Restrict; import models.PlayVersion; import play.data.Form; import play.libs.Json; import play.mvc.Controller; import play.mvc.Result; import play.mvc.With; import security.RoleDefinitions; import views.html.admin.playVersions; import static actions.CurrentUser.currentUser;
/* * Copyright 2012 The Play! Framework * * 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 controllers; /** * @author Steve Chaloner (steve@obectify.be) */ @With(CurrentUser.class) @Restrict(RoleDefinitions.ADMIN) public class PlayVersions extends AbstractController { public static Result showPlayVersions() {
// Path: app/actions/CurrentUser.java // public class CurrentUser extends Action.Simple // { // @Override // public Result call(Http.Context ctx) throws Throwable // { // accessUser(ctx); // return delegate.call(ctx); // } // // private static User accessUser(Http.Context ctx) // { // User user = (User)ctx.args.get("user"); // if (user == null) // { // String userName = ctx.session().get("userName"); // if (!StringUtils.isEmpty(userName)) // { // user = User.findByUserName(userName); // if (user != null) // { // ctx.args.put("user", // user); // } // } // } // // return user; // } // // public static User currentUser() // { // return currentUser(Http.Context.current()); // } // // public static User currentUser(Http.Context context) // { // return accessUser(context); // } // } // // Path: app/models/PlayVersion.java // @Entity // public class PlayVersion extends AbstractModel { // // public enum MajorVersion { // ONE("1"), // TWO("2"); // // private MajorVersion(String numeric) { // this.numeric = numeric; // } // // public String numeric; // } // // // @Column(nullable = false, unique = true) // @Constraints.Required // public String name; // // @Column(nullable = false) // @Enumerated(EnumType.STRING) // public MajorVersion majorVersion; // // @Column(nullable = false) // @Constraints.Required // public String documentationUrl; // // public static final Finder<Long, PlayVersion> FIND = new Finder<Long, PlayVersion>(Long.class, // PlayVersion.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static List<PlayVersion> getAll() { // return FIND.where() // .order("name ASC") // .findList(); // } // // public static PlayVersion findByName(String name) { // return FIND.where() // .eq("name", name) // .findUnique(); // } // // /** // * Allow 1.2 to match 1.2, 1.2.1, 1.2.2, etc // * // * @param name // * @return // */ // public static List<PlayVersion> findByLooseName(String name) { // return FIND.where() // .startsWith("name", name) // .findList(); // } // // public static List<PlayVersion> findByMajorVersion(MajorVersion majorVersion) { // return FIND.where() // .eq("majorVersion", majorVersion) // .findList(); // } // } // // Path: app/security/RoleDefinitions.java // public class RoleDefinitions // { // public static final String ADMIN = "admin"; // // private RoleDefinitions() // { // // no-op // } // } // // Path: app/actions/CurrentUser.java // public static User currentUser() // { // return currentUser(Http.Context.current()); // } // Path: app/controllers/PlayVersions.java import actions.CurrentUser; import be.objectify.deadbolt.actions.Restrict; import models.PlayVersion; import play.data.Form; import play.libs.Json; import play.mvc.Controller; import play.mvc.Result; import play.mvc.With; import security.RoleDefinitions; import views.html.admin.playVersions; import static actions.CurrentUser.currentUser; /* * Copyright 2012 The Play! Framework * * 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 controllers; /** * @author Steve Chaloner (steve@obectify.be) */ @With(CurrentUser.class) @Restrict(RoleDefinitions.ADMIN) public class PlayVersions extends AbstractController { public static Result showPlayVersions() {
return ok(playVersions.render(CurrentUser.currentUser(),
playframework/modules.playframework.org
app/controllers/PlayVersions.java
// Path: app/actions/CurrentUser.java // public class CurrentUser extends Action.Simple // { // @Override // public Result call(Http.Context ctx) throws Throwable // { // accessUser(ctx); // return delegate.call(ctx); // } // // private static User accessUser(Http.Context ctx) // { // User user = (User)ctx.args.get("user"); // if (user == null) // { // String userName = ctx.session().get("userName"); // if (!StringUtils.isEmpty(userName)) // { // user = User.findByUserName(userName); // if (user != null) // { // ctx.args.put("user", // user); // } // } // } // // return user; // } // // public static User currentUser() // { // return currentUser(Http.Context.current()); // } // // public static User currentUser(Http.Context context) // { // return accessUser(context); // } // } // // Path: app/models/PlayVersion.java // @Entity // public class PlayVersion extends AbstractModel { // // public enum MajorVersion { // ONE("1"), // TWO("2"); // // private MajorVersion(String numeric) { // this.numeric = numeric; // } // // public String numeric; // } // // // @Column(nullable = false, unique = true) // @Constraints.Required // public String name; // // @Column(nullable = false) // @Enumerated(EnumType.STRING) // public MajorVersion majorVersion; // // @Column(nullable = false) // @Constraints.Required // public String documentationUrl; // // public static final Finder<Long, PlayVersion> FIND = new Finder<Long, PlayVersion>(Long.class, // PlayVersion.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static List<PlayVersion> getAll() { // return FIND.where() // .order("name ASC") // .findList(); // } // // public static PlayVersion findByName(String name) { // return FIND.where() // .eq("name", name) // .findUnique(); // } // // /** // * Allow 1.2 to match 1.2, 1.2.1, 1.2.2, etc // * // * @param name // * @return // */ // public static List<PlayVersion> findByLooseName(String name) { // return FIND.where() // .startsWith("name", name) // .findList(); // } // // public static List<PlayVersion> findByMajorVersion(MajorVersion majorVersion) { // return FIND.where() // .eq("majorVersion", majorVersion) // .findList(); // } // } // // Path: app/security/RoleDefinitions.java // public class RoleDefinitions // { // public static final String ADMIN = "admin"; // // private RoleDefinitions() // { // // no-op // } // } // // Path: app/actions/CurrentUser.java // public static User currentUser() // { // return currentUser(Http.Context.current()); // }
import actions.CurrentUser; import be.objectify.deadbolt.actions.Restrict; import models.PlayVersion; import play.data.Form; import play.libs.Json; import play.mvc.Controller; import play.mvc.Result; import play.mvc.With; import security.RoleDefinitions; import views.html.admin.playVersions; import static actions.CurrentUser.currentUser;
/* * Copyright 2012 The Play! Framework * * 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 controllers; /** * @author Steve Chaloner (steve@obectify.be) */ @With(CurrentUser.class) @Restrict(RoleDefinitions.ADMIN) public class PlayVersions extends AbstractController { public static Result showPlayVersions() { return ok(playVersions.render(CurrentUser.currentUser(),
// Path: app/actions/CurrentUser.java // public class CurrentUser extends Action.Simple // { // @Override // public Result call(Http.Context ctx) throws Throwable // { // accessUser(ctx); // return delegate.call(ctx); // } // // private static User accessUser(Http.Context ctx) // { // User user = (User)ctx.args.get("user"); // if (user == null) // { // String userName = ctx.session().get("userName"); // if (!StringUtils.isEmpty(userName)) // { // user = User.findByUserName(userName); // if (user != null) // { // ctx.args.put("user", // user); // } // } // } // // return user; // } // // public static User currentUser() // { // return currentUser(Http.Context.current()); // } // // public static User currentUser(Http.Context context) // { // return accessUser(context); // } // } // // Path: app/models/PlayVersion.java // @Entity // public class PlayVersion extends AbstractModel { // // public enum MajorVersion { // ONE("1"), // TWO("2"); // // private MajorVersion(String numeric) { // this.numeric = numeric; // } // // public String numeric; // } // // // @Column(nullable = false, unique = true) // @Constraints.Required // public String name; // // @Column(nullable = false) // @Enumerated(EnumType.STRING) // public MajorVersion majorVersion; // // @Column(nullable = false) // @Constraints.Required // public String documentationUrl; // // public static final Finder<Long, PlayVersion> FIND = new Finder<Long, PlayVersion>(Long.class, // PlayVersion.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static List<PlayVersion> getAll() { // return FIND.where() // .order("name ASC") // .findList(); // } // // public static PlayVersion findByName(String name) { // return FIND.where() // .eq("name", name) // .findUnique(); // } // // /** // * Allow 1.2 to match 1.2, 1.2.1, 1.2.2, etc // * // * @param name // * @return // */ // public static List<PlayVersion> findByLooseName(String name) { // return FIND.where() // .startsWith("name", name) // .findList(); // } // // public static List<PlayVersion> findByMajorVersion(MajorVersion majorVersion) { // return FIND.where() // .eq("majorVersion", majorVersion) // .findList(); // } // } // // Path: app/security/RoleDefinitions.java // public class RoleDefinitions // { // public static final String ADMIN = "admin"; // // private RoleDefinitions() // { // // no-op // } // } // // Path: app/actions/CurrentUser.java // public static User currentUser() // { // return currentUser(Http.Context.current()); // } // Path: app/controllers/PlayVersions.java import actions.CurrentUser; import be.objectify.deadbolt.actions.Restrict; import models.PlayVersion; import play.data.Form; import play.libs.Json; import play.mvc.Controller; import play.mvc.Result; import play.mvc.With; import security.RoleDefinitions; import views.html.admin.playVersions; import static actions.CurrentUser.currentUser; /* * Copyright 2012 The Play! Framework * * 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 controllers; /** * @author Steve Chaloner (steve@obectify.be) */ @With(CurrentUser.class) @Restrict(RoleDefinitions.ADMIN) public class PlayVersions extends AbstractController { public static Result showPlayVersions() { return ok(playVersions.render(CurrentUser.currentUser(),
PlayVersion.findByMajorVersion(PlayVersion.MajorVersion.ONE),
playframework/modules.playframework.org
test/models/ModuleValidationTest.java
// Path: test/test/ModulesAssertions.java // public static ValidationAssert assertThat(Model model) { // return new ValidationAssert(model); // }
import org.junit.Test; import static org.apache.commons.lang.RandomStringUtils.random; import static test.ModulesAssertions.assertThat;
package models; public class ModuleValidationTest { @Test public void valid() { Module module = new ModuleBuilder().build();
// Path: test/test/ModulesAssertions.java // public static ValidationAssert assertThat(Model model) { // return new ValidationAssert(model); // } // Path: test/models/ModuleValidationTest.java import org.junit.Test; import static org.apache.commons.lang.RandomStringUtils.random; import static test.ModulesAssertions.assertThat; package models; public class ModuleValidationTest { @Test public void valid() { Module module = new ModuleBuilder().build();
assertThat(module).isValid();
playframework/modules.playframework.org
app/forms/login/Login.java
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // }
import models.User;
/* * Copyright 2012 The Play! Framework * * 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 forms.login; /** * @author Steve Chaloner (steve@objectify.be) */ public class Login { public String userName; public String password; public String validate() { String result = null;
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // Path: app/forms/login/Login.java import models.User; /* * Copyright 2012 The Play! Framework * * 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 forms.login; /** * @author Steve Chaloner (steve@objectify.be) */ public class Login { public String userName; public String password; public String validate() { String result = null;
if (User.authenticate(userName,
playframework/modules.playframework.org
app/security/RepoDynamicResourceHandler.java
// Path: app/security/dynamic/AllowToVote.java // public class AllowToVote extends AbstractDynamicResourceHandler // { // public static final String KEY = "allowToVote"; // // @Override // public boolean isAllowed(String name, // String meta, // DeadboltHandler deadboltHandler, // Http.Context ctx) // { // boolean allowed = true; // if (StringUtils.isEmpty(meta)) // { // Logger.error("HasVoted required a moduleKey in the meta data"); // } // else // { // User user = (User) deadboltHandler.getRoleHolder(ctx); // if (user != null) // { // for (Iterator<Vote> iterator = user.votes.iterator(); allowed && iterator.hasNext(); ) // { // Vote vote = iterator.next(); // allowed = !meta.equals(vote.playModule.key); // } // } // } // return allowed; // } // }
import be.objectify.deadbolt.AbstractDynamicResourceHandler; import be.objectify.deadbolt.DeadboltHandler; import be.objectify.deadbolt.DynamicResourceHandler; import play.mvc.Http; import security.dynamic.AllowToVote;
/* * Copyright 2012 The Play! Framework * * 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 security; /** * @author Steve Chaloner */ public class RepoDynamicResourceHandler extends AbstractDynamicResourceHandler { @Override public boolean isAllowed(String name, String meta, DeadboltHandler deadboltHandler, Http.Context context) { boolean allowed = false; DynamicResourceHandler handler = null;
// Path: app/security/dynamic/AllowToVote.java // public class AllowToVote extends AbstractDynamicResourceHandler // { // public static final String KEY = "allowToVote"; // // @Override // public boolean isAllowed(String name, // String meta, // DeadboltHandler deadboltHandler, // Http.Context ctx) // { // boolean allowed = true; // if (StringUtils.isEmpty(meta)) // { // Logger.error("HasVoted required a moduleKey in the meta data"); // } // else // { // User user = (User) deadboltHandler.getRoleHolder(ctx); // if (user != null) // { // for (Iterator<Vote> iterator = user.votes.iterator(); allowed && iterator.hasNext(); ) // { // Vote vote = iterator.next(); // allowed = !meta.equals(vote.playModule.key); // } // } // } // return allowed; // } // } // Path: app/security/RepoDynamicResourceHandler.java import be.objectify.deadbolt.AbstractDynamicResourceHandler; import be.objectify.deadbolt.DeadboltHandler; import be.objectify.deadbolt.DynamicResourceHandler; import play.mvc.Http; import security.dynamic.AllowToVote; /* * Copyright 2012 The Play! Framework * * 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 security; /** * @author Steve Chaloner */ public class RepoDynamicResourceHandler extends AbstractDynamicResourceHandler { @Override public boolean isAllowed(String name, String meta, DeadboltHandler deadboltHandler, Http.Context context) { boolean allowed = false; DynamicResourceHandler handler = null;
if (AllowToVote.KEY.equals(name))
playframework/modules.playframework.org
app/security/RepoDeadboltHandler.java
// Path: app/actions/CurrentUser.java // public class CurrentUser extends Action.Simple // { // @Override // public Result call(Http.Context ctx) throws Throwable // { // accessUser(ctx); // return delegate.call(ctx); // } // // private static User accessUser(Http.Context ctx) // { // User user = (User)ctx.args.get("user"); // if (user == null) // { // String userName = ctx.session().get("userName"); // if (!StringUtils.isEmpty(userName)) // { // user = User.findByUserName(userName); // if (user != null) // { // ctx.args.put("user", // user); // } // } // } // // return user; // } // // public static User currentUser() // { // return currentUser(Http.Context.current()); // } // // public static User currentUser(Http.Context context) // { // return accessUser(context); // } // } // // Path: app/controllers/Application.java // @With(CurrentUser.class) // public class Application extends AbstractController // { // public static Result index() // { // final List<Module> mostRecentModules = Module.findMostRecent(5); // final List<Module> highestRatedModules = Collections.emptyList(); // best way to use the rating algorithm for the db call? pre-calculate before storing? // final List<FeaturedModule> featuredModules = FeaturedModule.getAll(); // final List<PlayVersion> playVersions = PlayVersion.getAll(); // // return ok(index.render(currentUser(), // mostRecentModules, // highestRatedModules, // featuredModules, // playVersions, // Module.count())); // } // // public static Result login() // { // return ok(login.render(form(Login.class))); // } // // public static Result authenticate() // { // Form<Login> loginForm = form(Login.class).bindFromRequest(); // Result result; // if (loginForm.hasErrors()) // { // result = badRequest(login.render(loginForm)); // } // else // { // session("userName", loginForm.get().userName); // result = redirect(routes.Application.index()); // } // // return result; // } // // public static Result register() // { // return ok(register.render(form(Register.class))); // } // // public static Result createAccount() // { // Form<Register> registerForm = form(Register.class).bindFromRequest(); // Result result; // if (registerForm.hasErrors()) // { // result = badRequest(register.render(registerForm)); // } // else // { // Register register = registerForm.get(); // new UserServices().createUser(register.userName, register.displayName, register.password); // session("userName", register.userName); // result = redirect(routes.Application.index()); // } // return result; // } // // public static Result logout() // { // session().clear(); // return redirect(routes.Application.index()); // } // // /** // * Returns the sitemap of the application // */ // public static Result sitemap() // { // List<Sitemap> list = SitemapServices.generateSitemap(request()); // return ok(sitemap.render(list)).as("application/xml"); // } // }
import actions.CurrentUser; import be.objectify.deadbolt.DeadboltHandler; import be.objectify.deadbolt.DynamicResourceHandler; import be.objectify.deadbolt.models.RoleHolder; import controllers.Application; import controllers.routes; import play.core.Router; import play.mvc.Http; import play.mvc.Result; import play.mvc.Results;
/* * Copyright 2012 The Play! Framework * * 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 security; /** * @author Steve Chaloner */ public class RepoDeadboltHandler extends Results implements DeadboltHandler { @Override public Result beforeRoleCheck(Http.Context context) { return null; } @Override public RoleHolder getRoleHolder(Http.Context context) {
// Path: app/actions/CurrentUser.java // public class CurrentUser extends Action.Simple // { // @Override // public Result call(Http.Context ctx) throws Throwable // { // accessUser(ctx); // return delegate.call(ctx); // } // // private static User accessUser(Http.Context ctx) // { // User user = (User)ctx.args.get("user"); // if (user == null) // { // String userName = ctx.session().get("userName"); // if (!StringUtils.isEmpty(userName)) // { // user = User.findByUserName(userName); // if (user != null) // { // ctx.args.put("user", // user); // } // } // } // // return user; // } // // public static User currentUser() // { // return currentUser(Http.Context.current()); // } // // public static User currentUser(Http.Context context) // { // return accessUser(context); // } // } // // Path: app/controllers/Application.java // @With(CurrentUser.class) // public class Application extends AbstractController // { // public static Result index() // { // final List<Module> mostRecentModules = Module.findMostRecent(5); // final List<Module> highestRatedModules = Collections.emptyList(); // best way to use the rating algorithm for the db call? pre-calculate before storing? // final List<FeaturedModule> featuredModules = FeaturedModule.getAll(); // final List<PlayVersion> playVersions = PlayVersion.getAll(); // // return ok(index.render(currentUser(), // mostRecentModules, // highestRatedModules, // featuredModules, // playVersions, // Module.count())); // } // // public static Result login() // { // return ok(login.render(form(Login.class))); // } // // public static Result authenticate() // { // Form<Login> loginForm = form(Login.class).bindFromRequest(); // Result result; // if (loginForm.hasErrors()) // { // result = badRequest(login.render(loginForm)); // } // else // { // session("userName", loginForm.get().userName); // result = redirect(routes.Application.index()); // } // // return result; // } // // public static Result register() // { // return ok(register.render(form(Register.class))); // } // // public static Result createAccount() // { // Form<Register> registerForm = form(Register.class).bindFromRequest(); // Result result; // if (registerForm.hasErrors()) // { // result = badRequest(register.render(registerForm)); // } // else // { // Register register = registerForm.get(); // new UserServices().createUser(register.userName, register.displayName, register.password); // session("userName", register.userName); // result = redirect(routes.Application.index()); // } // return result; // } // // public static Result logout() // { // session().clear(); // return redirect(routes.Application.index()); // } // // /** // * Returns the sitemap of the application // */ // public static Result sitemap() // { // List<Sitemap> list = SitemapServices.generateSitemap(request()); // return ok(sitemap.render(list)).as("application/xml"); // } // } // Path: app/security/RepoDeadboltHandler.java import actions.CurrentUser; import be.objectify.deadbolt.DeadboltHandler; import be.objectify.deadbolt.DynamicResourceHandler; import be.objectify.deadbolt.models.RoleHolder; import controllers.Application; import controllers.routes; import play.core.Router; import play.mvc.Http; import play.mvc.Result; import play.mvc.Results; /* * Copyright 2012 The Play! Framework * * 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 security; /** * @author Steve Chaloner */ public class RepoDeadboltHandler extends Results implements DeadboltHandler { @Override public Result beforeRoleCheck(Http.Context context) { return null; } @Override public RoleHolder getRoleHolder(Http.Context context) {
return CurrentUser.currentUser(context);
playframework/modules.playframework.org
app/security/RepoDeadboltHandler.java
// Path: app/actions/CurrentUser.java // public class CurrentUser extends Action.Simple // { // @Override // public Result call(Http.Context ctx) throws Throwable // { // accessUser(ctx); // return delegate.call(ctx); // } // // private static User accessUser(Http.Context ctx) // { // User user = (User)ctx.args.get("user"); // if (user == null) // { // String userName = ctx.session().get("userName"); // if (!StringUtils.isEmpty(userName)) // { // user = User.findByUserName(userName); // if (user != null) // { // ctx.args.put("user", // user); // } // } // } // // return user; // } // // public static User currentUser() // { // return currentUser(Http.Context.current()); // } // // public static User currentUser(Http.Context context) // { // return accessUser(context); // } // } // // Path: app/controllers/Application.java // @With(CurrentUser.class) // public class Application extends AbstractController // { // public static Result index() // { // final List<Module> mostRecentModules = Module.findMostRecent(5); // final List<Module> highestRatedModules = Collections.emptyList(); // best way to use the rating algorithm for the db call? pre-calculate before storing? // final List<FeaturedModule> featuredModules = FeaturedModule.getAll(); // final List<PlayVersion> playVersions = PlayVersion.getAll(); // // return ok(index.render(currentUser(), // mostRecentModules, // highestRatedModules, // featuredModules, // playVersions, // Module.count())); // } // // public static Result login() // { // return ok(login.render(form(Login.class))); // } // // public static Result authenticate() // { // Form<Login> loginForm = form(Login.class).bindFromRequest(); // Result result; // if (loginForm.hasErrors()) // { // result = badRequest(login.render(loginForm)); // } // else // { // session("userName", loginForm.get().userName); // result = redirect(routes.Application.index()); // } // // return result; // } // // public static Result register() // { // return ok(register.render(form(Register.class))); // } // // public static Result createAccount() // { // Form<Register> registerForm = form(Register.class).bindFromRequest(); // Result result; // if (registerForm.hasErrors()) // { // result = badRequest(register.render(registerForm)); // } // else // { // Register register = registerForm.get(); // new UserServices().createUser(register.userName, register.displayName, register.password); // session("userName", register.userName); // result = redirect(routes.Application.index()); // } // return result; // } // // public static Result logout() // { // session().clear(); // return redirect(routes.Application.index()); // } // // /** // * Returns the sitemap of the application // */ // public static Result sitemap() // { // List<Sitemap> list = SitemapServices.generateSitemap(request()); // return ok(sitemap.render(list)).as("application/xml"); // } // }
import actions.CurrentUser; import be.objectify.deadbolt.DeadboltHandler; import be.objectify.deadbolt.DynamicResourceHandler; import be.objectify.deadbolt.models.RoleHolder; import controllers.Application; import controllers.routes; import play.core.Router; import play.mvc.Http; import play.mvc.Result; import play.mvc.Results;
/* * Copyright 2012 The Play! Framework * * 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 security; /** * @author Steve Chaloner */ public class RepoDeadboltHandler extends Results implements DeadboltHandler { @Override public Result beforeRoleCheck(Http.Context context) { return null; } @Override public RoleHolder getRoleHolder(Http.Context context) { return CurrentUser.currentUser(context); } @Override public Result onAccessFailure(Http.Context context, String s) { Http.Context.current.set(context);
// Path: app/actions/CurrentUser.java // public class CurrentUser extends Action.Simple // { // @Override // public Result call(Http.Context ctx) throws Throwable // { // accessUser(ctx); // return delegate.call(ctx); // } // // private static User accessUser(Http.Context ctx) // { // User user = (User)ctx.args.get("user"); // if (user == null) // { // String userName = ctx.session().get("userName"); // if (!StringUtils.isEmpty(userName)) // { // user = User.findByUserName(userName); // if (user != null) // { // ctx.args.put("user", // user); // } // } // } // // return user; // } // // public static User currentUser() // { // return currentUser(Http.Context.current()); // } // // public static User currentUser(Http.Context context) // { // return accessUser(context); // } // } // // Path: app/controllers/Application.java // @With(CurrentUser.class) // public class Application extends AbstractController // { // public static Result index() // { // final List<Module> mostRecentModules = Module.findMostRecent(5); // final List<Module> highestRatedModules = Collections.emptyList(); // best way to use the rating algorithm for the db call? pre-calculate before storing? // final List<FeaturedModule> featuredModules = FeaturedModule.getAll(); // final List<PlayVersion> playVersions = PlayVersion.getAll(); // // return ok(index.render(currentUser(), // mostRecentModules, // highestRatedModules, // featuredModules, // playVersions, // Module.count())); // } // // public static Result login() // { // return ok(login.render(form(Login.class))); // } // // public static Result authenticate() // { // Form<Login> loginForm = form(Login.class).bindFromRequest(); // Result result; // if (loginForm.hasErrors()) // { // result = badRequest(login.render(loginForm)); // } // else // { // session("userName", loginForm.get().userName); // result = redirect(routes.Application.index()); // } // // return result; // } // // public static Result register() // { // return ok(register.render(form(Register.class))); // } // // public static Result createAccount() // { // Form<Register> registerForm = form(Register.class).bindFromRequest(); // Result result; // if (registerForm.hasErrors()) // { // result = badRequest(register.render(registerForm)); // } // else // { // Register register = registerForm.get(); // new UserServices().createUser(register.userName, register.displayName, register.password); // session("userName", register.userName); // result = redirect(routes.Application.index()); // } // return result; // } // // public static Result logout() // { // session().clear(); // return redirect(routes.Application.index()); // } // // /** // * Returns the sitemap of the application // */ // public static Result sitemap() // { // List<Sitemap> list = SitemapServices.generateSitemap(request()); // return ok(sitemap.render(list)).as("application/xml"); // } // } // Path: app/security/RepoDeadboltHandler.java import actions.CurrentUser; import be.objectify.deadbolt.DeadboltHandler; import be.objectify.deadbolt.DynamicResourceHandler; import be.objectify.deadbolt.models.RoleHolder; import controllers.Application; import controllers.routes; import play.core.Router; import play.mvc.Http; import play.mvc.Result; import play.mvc.Results; /* * Copyright 2012 The Play! Framework * * 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 security; /** * @author Steve Chaloner */ public class RepoDeadboltHandler extends Results implements DeadboltHandler { @Override public Result beforeRoleCheck(Http.Context context) { return null; } @Override public RoleHolder getRoleHolder(Http.Context context) { return CurrentUser.currentUser(context); } @Override public Result onAccessFailure(Http.Context context, String s) { Http.Context.current.set(context);
return redirect(routes.Application.index());
playframework/modules.playframework.org
app/models/ModuleVersion.java
// Path: app/utils/CollectionUtils.java // public class CollectionUtils // { // private CollectionUtils() // { // // no-op // } // // /** // * Gets the first element of the list. // * // * @param list the list // * @param <T> the list's generic type // * @return the first element of the list, or null if the list is null or empty. The returned value will also be null // * if the first element of the list is null. // */ // public static <T> T first(List<T> list) // { // return isEmpty(list) ? null : list.get(0); // } // // /** // * Gets the last element of the list. // * // * @param list the list // * @param <T> the list's generic type // * @return the last element of the list, or null if the list is null or empty. The returned value will also be null // * if the last element of the list is null. // */ // public static <T> T last(List<T> list) // { // return isEmpty(list) ? null : list.get(list.size() - 1); // } // // /** // * Checks if a collection is null or empty. // * // * @param c the collection // * @return true if the collection is null or has a length of 0. A collection containing null entries is considered // * to be non-empty. // */ // public static boolean isEmpty(Collection c) // { // return c == null || c.isEmpty(); // } // // /** // * Gets the first matching element of collection, using the filter. // * // * @param collection the collection to filter // * @param filter filters the elements // * @param <T> the generic type // * @return the first element that is accepted by the filter, or null if the collection is null, empty or contains // * no acceptable elements // */ // public static <T> T filterFirst(Collection<T> collection, // Filter<T> filter) // { // T t = null; // // if (!isEmpty(collection)) // { // for (Iterator<T> iterator = collection.iterator(); t == null && iterator.hasNext(); ) // { // T element = iterator.next(); // t = filter.isAcceptable(element) ? element : null; // } // } // // return t; // } // // /** // * Transforms a collection of objects of one type into a list of another type. // * // * @param input the collection to transform // * @param transformer transforms individual objects // * @param <I> the input type to tranform // * @param <O> the output type that is the result of the transformation // * @return a list of transformed objects // */ // public static <I, O> List<O> transform(Collection<I> input, // Transformer<I, O> transformer) // { // List<O> output = new ArrayList<O>(); // if (input != null) // { // for (I i : input) // { // if (i != null) // { // output.add(transformer.transform(i)); // } // } // } // return output; // } // // /** // * Convenience method for type erasure when casting lists. // * // * @param list the list to cast // * @param t the class type // * @param <T> the generic type // * @return a list of type T // */ // public static <T> List<T> castTo(List list, // Class<T> t) // { // return (List<T>)list; // } // } // // Path: app/utils/Transformer.java // public interface Transformer<I, O> // { // O transform(I input); // }
import play.data.validation.Constraints; import utils.CollectionUtils; import utils.Transformer; import javax.persistence.*; import java.util.*;
/* * Copyright 2012 The Play! Framework * * 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 models; /** * @author Steve Chaloner (steve@objectify.be) */ @Entity public class ModuleVersion extends AbstractModel { @ManyToOne public Module playModule; // this will be taken from Build.scala @Column(nullable = false) @Constraints.Required public String versionCode; @Column(nullable = false) @Constraints.Required public String releaseNotes; @Column(nullable = false) public Date releaseDate; @ManyToMany public List<PlayVersion> compatibility; @OneToOne(optional = false, fetch = FetchType.LAZY, cascade = CascadeType.ALL) public BinaryContent binaryFile; @OneToOne(optional = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL) public BinaryContent sourceFile; @OneToOne(optional = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL) public BinaryContent documentFile; public static final Finder<Long, ModuleVersion> FIND = new Finder<Long, ModuleVersion>(Long.class, ModuleVersion.class); public static int count() { return FIND.findRowCount(); } public Set<PlayVersion.MajorVersion> getMajorVersions() { Set<PlayVersion.MajorVersion> majorVersions = new HashSet<PlayVersion.MajorVersion>();
// Path: app/utils/CollectionUtils.java // public class CollectionUtils // { // private CollectionUtils() // { // // no-op // } // // /** // * Gets the first element of the list. // * // * @param list the list // * @param <T> the list's generic type // * @return the first element of the list, or null if the list is null or empty. The returned value will also be null // * if the first element of the list is null. // */ // public static <T> T first(List<T> list) // { // return isEmpty(list) ? null : list.get(0); // } // // /** // * Gets the last element of the list. // * // * @param list the list // * @param <T> the list's generic type // * @return the last element of the list, or null if the list is null or empty. The returned value will also be null // * if the last element of the list is null. // */ // public static <T> T last(List<T> list) // { // return isEmpty(list) ? null : list.get(list.size() - 1); // } // // /** // * Checks if a collection is null or empty. // * // * @param c the collection // * @return true if the collection is null or has a length of 0. A collection containing null entries is considered // * to be non-empty. // */ // public static boolean isEmpty(Collection c) // { // return c == null || c.isEmpty(); // } // // /** // * Gets the first matching element of collection, using the filter. // * // * @param collection the collection to filter // * @param filter filters the elements // * @param <T> the generic type // * @return the first element that is accepted by the filter, or null if the collection is null, empty or contains // * no acceptable elements // */ // public static <T> T filterFirst(Collection<T> collection, // Filter<T> filter) // { // T t = null; // // if (!isEmpty(collection)) // { // for (Iterator<T> iterator = collection.iterator(); t == null && iterator.hasNext(); ) // { // T element = iterator.next(); // t = filter.isAcceptable(element) ? element : null; // } // } // // return t; // } // // /** // * Transforms a collection of objects of one type into a list of another type. // * // * @param input the collection to transform // * @param transformer transforms individual objects // * @param <I> the input type to tranform // * @param <O> the output type that is the result of the transformation // * @return a list of transformed objects // */ // public static <I, O> List<O> transform(Collection<I> input, // Transformer<I, O> transformer) // { // List<O> output = new ArrayList<O>(); // if (input != null) // { // for (I i : input) // { // if (i != null) // { // output.add(transformer.transform(i)); // } // } // } // return output; // } // // /** // * Convenience method for type erasure when casting lists. // * // * @param list the list to cast // * @param t the class type // * @param <T> the generic type // * @return a list of type T // */ // public static <T> List<T> castTo(List list, // Class<T> t) // { // return (List<T>)list; // } // } // // Path: app/utils/Transformer.java // public interface Transformer<I, O> // { // O transform(I input); // } // Path: app/models/ModuleVersion.java import play.data.validation.Constraints; import utils.CollectionUtils; import utils.Transformer; import javax.persistence.*; import java.util.*; /* * Copyright 2012 The Play! Framework * * 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 models; /** * @author Steve Chaloner (steve@objectify.be) */ @Entity public class ModuleVersion extends AbstractModel { @ManyToOne public Module playModule; // this will be taken from Build.scala @Column(nullable = false) @Constraints.Required public String versionCode; @Column(nullable = false) @Constraints.Required public String releaseNotes; @Column(nullable = false) public Date releaseDate; @ManyToMany public List<PlayVersion> compatibility; @OneToOne(optional = false, fetch = FetchType.LAZY, cascade = CascadeType.ALL) public BinaryContent binaryFile; @OneToOne(optional = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL) public BinaryContent sourceFile; @OneToOne(optional = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL) public BinaryContent documentFile; public static final Finder<Long, ModuleVersion> FIND = new Finder<Long, ModuleVersion>(Long.class, ModuleVersion.class); public static int count() { return FIND.findRowCount(); } public Set<PlayVersion.MajorVersion> getMajorVersions() { Set<PlayVersion.MajorVersion> majorVersions = new HashSet<PlayVersion.MajorVersion>();
Transformer<PlayVersion, PlayVersion.MajorVersion> transformer = new MajorVersionExtractor();
playframework/modules.playframework.org
app/models/ModuleVersion.java
// Path: app/utils/CollectionUtils.java // public class CollectionUtils // { // private CollectionUtils() // { // // no-op // } // // /** // * Gets the first element of the list. // * // * @param list the list // * @param <T> the list's generic type // * @return the first element of the list, or null if the list is null or empty. The returned value will also be null // * if the first element of the list is null. // */ // public static <T> T first(List<T> list) // { // return isEmpty(list) ? null : list.get(0); // } // // /** // * Gets the last element of the list. // * // * @param list the list // * @param <T> the list's generic type // * @return the last element of the list, or null if the list is null or empty. The returned value will also be null // * if the last element of the list is null. // */ // public static <T> T last(List<T> list) // { // return isEmpty(list) ? null : list.get(list.size() - 1); // } // // /** // * Checks if a collection is null or empty. // * // * @param c the collection // * @return true if the collection is null or has a length of 0. A collection containing null entries is considered // * to be non-empty. // */ // public static boolean isEmpty(Collection c) // { // return c == null || c.isEmpty(); // } // // /** // * Gets the first matching element of collection, using the filter. // * // * @param collection the collection to filter // * @param filter filters the elements // * @param <T> the generic type // * @return the first element that is accepted by the filter, or null if the collection is null, empty or contains // * no acceptable elements // */ // public static <T> T filterFirst(Collection<T> collection, // Filter<T> filter) // { // T t = null; // // if (!isEmpty(collection)) // { // for (Iterator<T> iterator = collection.iterator(); t == null && iterator.hasNext(); ) // { // T element = iterator.next(); // t = filter.isAcceptable(element) ? element : null; // } // } // // return t; // } // // /** // * Transforms a collection of objects of one type into a list of another type. // * // * @param input the collection to transform // * @param transformer transforms individual objects // * @param <I> the input type to tranform // * @param <O> the output type that is the result of the transformation // * @return a list of transformed objects // */ // public static <I, O> List<O> transform(Collection<I> input, // Transformer<I, O> transformer) // { // List<O> output = new ArrayList<O>(); // if (input != null) // { // for (I i : input) // { // if (i != null) // { // output.add(transformer.transform(i)); // } // } // } // return output; // } // // /** // * Convenience method for type erasure when casting lists. // * // * @param list the list to cast // * @param t the class type // * @param <T> the generic type // * @return a list of type T // */ // public static <T> List<T> castTo(List list, // Class<T> t) // { // return (List<T>)list; // } // } // // Path: app/utils/Transformer.java // public interface Transformer<I, O> // { // O transform(I input); // }
import play.data.validation.Constraints; import utils.CollectionUtils; import utils.Transformer; import javax.persistence.*; import java.util.*;
/* * Copyright 2012 The Play! Framework * * 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 models; /** * @author Steve Chaloner (steve@objectify.be) */ @Entity public class ModuleVersion extends AbstractModel { @ManyToOne public Module playModule; // this will be taken from Build.scala @Column(nullable = false) @Constraints.Required public String versionCode; @Column(nullable = false) @Constraints.Required public String releaseNotes; @Column(nullable = false) public Date releaseDate; @ManyToMany public List<PlayVersion> compatibility; @OneToOne(optional = false, fetch = FetchType.LAZY, cascade = CascadeType.ALL) public BinaryContent binaryFile; @OneToOne(optional = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL) public BinaryContent sourceFile; @OneToOne(optional = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL) public BinaryContent documentFile; public static final Finder<Long, ModuleVersion> FIND = new Finder<Long, ModuleVersion>(Long.class, ModuleVersion.class); public static int count() { return FIND.findRowCount(); } public Set<PlayVersion.MajorVersion> getMajorVersions() { Set<PlayVersion.MajorVersion> majorVersions = new HashSet<PlayVersion.MajorVersion>(); Transformer<PlayVersion, PlayVersion.MajorVersion> transformer = new MajorVersionExtractor();
// Path: app/utils/CollectionUtils.java // public class CollectionUtils // { // private CollectionUtils() // { // // no-op // } // // /** // * Gets the first element of the list. // * // * @param list the list // * @param <T> the list's generic type // * @return the first element of the list, or null if the list is null or empty. The returned value will also be null // * if the first element of the list is null. // */ // public static <T> T first(List<T> list) // { // return isEmpty(list) ? null : list.get(0); // } // // /** // * Gets the last element of the list. // * // * @param list the list // * @param <T> the list's generic type // * @return the last element of the list, or null if the list is null or empty. The returned value will also be null // * if the last element of the list is null. // */ // public static <T> T last(List<T> list) // { // return isEmpty(list) ? null : list.get(list.size() - 1); // } // // /** // * Checks if a collection is null or empty. // * // * @param c the collection // * @return true if the collection is null or has a length of 0. A collection containing null entries is considered // * to be non-empty. // */ // public static boolean isEmpty(Collection c) // { // return c == null || c.isEmpty(); // } // // /** // * Gets the first matching element of collection, using the filter. // * // * @param collection the collection to filter // * @param filter filters the elements // * @param <T> the generic type // * @return the first element that is accepted by the filter, or null if the collection is null, empty or contains // * no acceptable elements // */ // public static <T> T filterFirst(Collection<T> collection, // Filter<T> filter) // { // T t = null; // // if (!isEmpty(collection)) // { // for (Iterator<T> iterator = collection.iterator(); t == null && iterator.hasNext(); ) // { // T element = iterator.next(); // t = filter.isAcceptable(element) ? element : null; // } // } // // return t; // } // // /** // * Transforms a collection of objects of one type into a list of another type. // * // * @param input the collection to transform // * @param transformer transforms individual objects // * @param <I> the input type to tranform // * @param <O> the output type that is the result of the transformation // * @return a list of transformed objects // */ // public static <I, O> List<O> transform(Collection<I> input, // Transformer<I, O> transformer) // { // List<O> output = new ArrayList<O>(); // if (input != null) // { // for (I i : input) // { // if (i != null) // { // output.add(transformer.transform(i)); // } // } // } // return output; // } // // /** // * Convenience method for type erasure when casting lists. // * // * @param list the list to cast // * @param t the class type // * @param <T> the generic type // * @return a list of type T // */ // public static <T> List<T> castTo(List list, // Class<T> t) // { // return (List<T>)list; // } // } // // Path: app/utils/Transformer.java // public interface Transformer<I, O> // { // O transform(I input); // } // Path: app/models/ModuleVersion.java import play.data.validation.Constraints; import utils.CollectionUtils; import utils.Transformer; import javax.persistence.*; import java.util.*; /* * Copyright 2012 The Play! Framework * * 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 models; /** * @author Steve Chaloner (steve@objectify.be) */ @Entity public class ModuleVersion extends AbstractModel { @ManyToOne public Module playModule; // this will be taken from Build.scala @Column(nullable = false) @Constraints.Required public String versionCode; @Column(nullable = false) @Constraints.Required public String releaseNotes; @Column(nullable = false) public Date releaseDate; @ManyToMany public List<PlayVersion> compatibility; @OneToOne(optional = false, fetch = FetchType.LAZY, cascade = CascadeType.ALL) public BinaryContent binaryFile; @OneToOne(optional = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL) public BinaryContent sourceFile; @OneToOne(optional = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL) public BinaryContent documentFile; public static final Finder<Long, ModuleVersion> FIND = new Finder<Long, ModuleVersion>(Long.class, ModuleVersion.class); public static int count() { return FIND.findRowCount(); } public Set<PlayVersion.MajorVersion> getMajorVersions() { Set<PlayVersion.MajorVersion> majorVersions = new HashSet<PlayVersion.MajorVersion>(); Transformer<PlayVersion, PlayVersion.MajorVersion> transformer = new MajorVersionExtractor();
majorVersions.addAll(CollectionUtils.transform(compatibility,
playframework/modules.playframework.org
app/models/Module.java
// Path: app/utils/CollectionUtils.java // public class CollectionUtils // { // private CollectionUtils() // { // // no-op // } // // /** // * Gets the first element of the list. // * // * @param list the list // * @param <T> the list's generic type // * @return the first element of the list, or null if the list is null or empty. The returned value will also be null // * if the first element of the list is null. // */ // public static <T> T first(List<T> list) // { // return isEmpty(list) ? null : list.get(0); // } // // /** // * Gets the last element of the list. // * // * @param list the list // * @param <T> the list's generic type // * @return the last element of the list, or null if the list is null or empty. The returned value will also be null // * if the last element of the list is null. // */ // public static <T> T last(List<T> list) // { // return isEmpty(list) ? null : list.get(list.size() - 1); // } // // /** // * Checks if a collection is null or empty. // * // * @param c the collection // * @return true if the collection is null or has a length of 0. A collection containing null entries is considered // * to be non-empty. // */ // public static boolean isEmpty(Collection c) // { // return c == null || c.isEmpty(); // } // // /** // * Gets the first matching element of collection, using the filter. // * // * @param collection the collection to filter // * @param filter filters the elements // * @param <T> the generic type // * @return the first element that is accepted by the filter, or null if the collection is null, empty or contains // * no acceptable elements // */ // public static <T> T filterFirst(Collection<T> collection, // Filter<T> filter) // { // T t = null; // // if (!isEmpty(collection)) // { // for (Iterator<T> iterator = collection.iterator(); t == null && iterator.hasNext(); ) // { // T element = iterator.next(); // t = filter.isAcceptable(element) ? element : null; // } // } // // return t; // } // // /** // * Transforms a collection of objects of one type into a list of another type. // * // * @param input the collection to transform // * @param transformer transforms individual objects // * @param <I> the input type to tranform // * @param <O> the output type that is the result of the transformation // * @return a list of transformed objects // */ // public static <I, O> List<O> transform(Collection<I> input, // Transformer<I, O> transformer) // { // List<O> output = new ArrayList<O>(); // if (input != null) // { // for (I i : input) // { // if (i != null) // { // output.add(transformer.transform(i)); // } // } // } // return output; // } // // /** // * Convenience method for type erasure when casting lists. // * // * @param list the list to cast // * @param t the class type // * @param <T> the generic type // * @return a list of type T // */ // public static <T> List<T> castTo(List list, // Class<T> t) // { // return (List<T>)list; // } // }
import com.petebevin.markdown.MarkdownProcessor; import play.data.validation.Constraints; import utils.CollectionUtils; import javax.persistence.*; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import static javax.persistence.CascadeType.*; import static javax.persistence.FetchType.LAZY; import static play.data.validation.Constraints.MaxLength; import static play.data.validation.Constraints.Required;
public Date createdOn = new Date(); @Column(nullable = false) public Date updatedOn = new Date(); @OneToOne(optional = true, cascade = ALL) public Rating rating; @OneToMany(fetch = LAZY, cascade = ALL, orphanRemoval = true) public List<Comment> comments; @ManyToMany(cascade = {DETACH, PERSIST, REFRESH}) public List<Tag> tags; @Override public int compareTo(Module module) { return name == null ? -1 : name.compareTo(module.name); } public String getDescriptionHtml() { return new MarkdownProcessor().markdown(description); } public static final Finder<Long, Module> FIND = new Finder<Long, Module>(Long.class, Module.class); public List<ModuleVersion> getVersions() { return ModuleVersion.findByModule(this); } public ModuleVersion getMostRecentVersion() {
// Path: app/utils/CollectionUtils.java // public class CollectionUtils // { // private CollectionUtils() // { // // no-op // } // // /** // * Gets the first element of the list. // * // * @param list the list // * @param <T> the list's generic type // * @return the first element of the list, or null if the list is null or empty. The returned value will also be null // * if the first element of the list is null. // */ // public static <T> T first(List<T> list) // { // return isEmpty(list) ? null : list.get(0); // } // // /** // * Gets the last element of the list. // * // * @param list the list // * @param <T> the list's generic type // * @return the last element of the list, or null if the list is null or empty. The returned value will also be null // * if the last element of the list is null. // */ // public static <T> T last(List<T> list) // { // return isEmpty(list) ? null : list.get(list.size() - 1); // } // // /** // * Checks if a collection is null or empty. // * // * @param c the collection // * @return true if the collection is null or has a length of 0. A collection containing null entries is considered // * to be non-empty. // */ // public static boolean isEmpty(Collection c) // { // return c == null || c.isEmpty(); // } // // /** // * Gets the first matching element of collection, using the filter. // * // * @param collection the collection to filter // * @param filter filters the elements // * @param <T> the generic type // * @return the first element that is accepted by the filter, or null if the collection is null, empty or contains // * no acceptable elements // */ // public static <T> T filterFirst(Collection<T> collection, // Filter<T> filter) // { // T t = null; // // if (!isEmpty(collection)) // { // for (Iterator<T> iterator = collection.iterator(); t == null && iterator.hasNext(); ) // { // T element = iterator.next(); // t = filter.isAcceptable(element) ? element : null; // } // } // // return t; // } // // /** // * Transforms a collection of objects of one type into a list of another type. // * // * @param input the collection to transform // * @param transformer transforms individual objects // * @param <I> the input type to tranform // * @param <O> the output type that is the result of the transformation // * @return a list of transformed objects // */ // public static <I, O> List<O> transform(Collection<I> input, // Transformer<I, O> transformer) // { // List<O> output = new ArrayList<O>(); // if (input != null) // { // for (I i : input) // { // if (i != null) // { // output.add(transformer.transform(i)); // } // } // } // return output; // } // // /** // * Convenience method for type erasure when casting lists. // * // * @param list the list to cast // * @param t the class type // * @param <T> the generic type // * @return a list of type T // */ // public static <T> List<T> castTo(List list, // Class<T> t) // { // return (List<T>)list; // } // } // Path: app/models/Module.java import com.petebevin.markdown.MarkdownProcessor; import play.data.validation.Constraints; import utils.CollectionUtils; import javax.persistence.*; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import static javax.persistence.CascadeType.*; import static javax.persistence.FetchType.LAZY; import static play.data.validation.Constraints.MaxLength; import static play.data.validation.Constraints.Required; public Date createdOn = new Date(); @Column(nullable = false) public Date updatedOn = new Date(); @OneToOne(optional = true, cascade = ALL) public Rating rating; @OneToMany(fetch = LAZY, cascade = ALL, orphanRemoval = true) public List<Comment> comments; @ManyToMany(cascade = {DETACH, PERSIST, REFRESH}) public List<Tag> tags; @Override public int compareTo(Module module) { return name == null ? -1 : name.compareTo(module.name); } public String getDescriptionHtml() { return new MarkdownProcessor().markdown(description); } public static final Finder<Long, Module> FIND = new Finder<Long, Module>(Long.class, Module.class); public List<ModuleVersion> getVersions() { return ModuleVersion.findByModule(this); } public ModuleVersion getMostRecentVersion() {
return CollectionUtils.last(getVersions());
playframework/modules.playframework.org
app/actors/HistoricalEventActor.java
// Path: app/models/HistoricalEvent.java // @Entity // public class HistoricalEvent extends AbstractModel // { // @Column(nullable = false) // public Date creationDate; // // @Column(nullable = false) // public String category; // // @Column(length = 1000, // nullable = false) // public String message; // // public static final Finder<Long, HistoricalEvent> FIND = new Finder<Long, HistoricalEvent>(Long.class, // HistoricalEvent.class); // // public static List<HistoricalEvent> findMostRecent(int count) // { // return FIND.where().orderBy("creationDate DESC").setMaxRows(count).findList(); // } // }
import akka.actor.UntypedActor; import models.HistoricalEvent;
/* * Copyright 2012 Steve Chaloner * * 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 actors; /** * @author Steve Chaloner (steve@objectify.be) */ public class HistoricalEventActor extends UntypedActor { @Override public void onReceive(Object o) throws Exception {
// Path: app/models/HistoricalEvent.java // @Entity // public class HistoricalEvent extends AbstractModel // { // @Column(nullable = false) // public Date creationDate; // // @Column(nullable = false) // public String category; // // @Column(length = 1000, // nullable = false) // public String message; // // public static final Finder<Long, HistoricalEvent> FIND = new Finder<Long, HistoricalEvent>(Long.class, // HistoricalEvent.class); // // public static List<HistoricalEvent> findMostRecent(int count) // { // return FIND.where().orderBy("creationDate DESC").setMaxRows(count).findList(); // } // } // Path: app/actors/HistoricalEventActor.java import akka.actor.UntypedActor; import models.HistoricalEvent; /* * Copyright 2012 Steve Chaloner * * 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 actors; /** * @author Steve Chaloner (steve@objectify.be) */ public class HistoricalEventActor extends UntypedActor { @Override public void onReceive(Object o) throws Exception {
if (o instanceof HistoricalEvent)
playframework/modules.playframework.org
app/security/dynamic/AllowToVote.java
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/models/Vote.java // @Entity // public class Vote extends AbstractModel // { // public enum VoteType { UP, DOWN } // // @OneToOne(optional = false) // public Module playModule; // // @Column(nullable = false) // public Boolean publicVote; // // @Column(nullable = false) // @Enumerated(EnumType.STRING) // public VoteType voteType; // // public boolean isUpVote() // { // return voteType == VoteType.UP; // } // // } // // Path: app/utils/StringUtils.java // public class StringUtils // { // /** // * Check if a string has non-empty content. // * // * @param s the string // * @return true if the string is null, empty or comprised only of empty characters spaces, tabs, \n, etc), // * otherwise false // */ // public static boolean isEmpty(String s) // { // return s == null || s.trim().length() == 0; // } // // public static String summarize(String s) // { // String result = ""; // if (!isEmpty(s)) // { // result = s.length() <= 100 ? s : s.substring(0, 100) + "..."; // } // return result; // } // }
import be.objectify.deadbolt.AbstractDynamicResourceHandler; import be.objectify.deadbolt.DeadboltHandler; import models.User; import models.Vote; import play.Logger; import play.mvc.Http; import utils.StringUtils; import java.util.Iterator;
/* * Copyright 2012 The Play! Framework * * 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 security.dynamic; /** * @author Steve Chaloner */ public class AllowToVote extends AbstractDynamicResourceHandler { public static final String KEY = "allowToVote"; @Override public boolean isAllowed(String name, String meta, DeadboltHandler deadboltHandler, Http.Context ctx) { boolean allowed = true;
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/models/Vote.java // @Entity // public class Vote extends AbstractModel // { // public enum VoteType { UP, DOWN } // // @OneToOne(optional = false) // public Module playModule; // // @Column(nullable = false) // public Boolean publicVote; // // @Column(nullable = false) // @Enumerated(EnumType.STRING) // public VoteType voteType; // // public boolean isUpVote() // { // return voteType == VoteType.UP; // } // // } // // Path: app/utils/StringUtils.java // public class StringUtils // { // /** // * Check if a string has non-empty content. // * // * @param s the string // * @return true if the string is null, empty or comprised only of empty characters spaces, tabs, \n, etc), // * otherwise false // */ // public static boolean isEmpty(String s) // { // return s == null || s.trim().length() == 0; // } // // public static String summarize(String s) // { // String result = ""; // if (!isEmpty(s)) // { // result = s.length() <= 100 ? s : s.substring(0, 100) + "..."; // } // return result; // } // } // Path: app/security/dynamic/AllowToVote.java import be.objectify.deadbolt.AbstractDynamicResourceHandler; import be.objectify.deadbolt.DeadboltHandler; import models.User; import models.Vote; import play.Logger; import play.mvc.Http; import utils.StringUtils; import java.util.Iterator; /* * Copyright 2012 The Play! Framework * * 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 security.dynamic; /** * @author Steve Chaloner */ public class AllowToVote extends AbstractDynamicResourceHandler { public static final String KEY = "allowToVote"; @Override public boolean isAllowed(String name, String meta, DeadboltHandler deadboltHandler, Http.Context ctx) { boolean allowed = true;
if (StringUtils.isEmpty(meta))
playframework/modules.playframework.org
app/security/dynamic/AllowToVote.java
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/models/Vote.java // @Entity // public class Vote extends AbstractModel // { // public enum VoteType { UP, DOWN } // // @OneToOne(optional = false) // public Module playModule; // // @Column(nullable = false) // public Boolean publicVote; // // @Column(nullable = false) // @Enumerated(EnumType.STRING) // public VoteType voteType; // // public boolean isUpVote() // { // return voteType == VoteType.UP; // } // // } // // Path: app/utils/StringUtils.java // public class StringUtils // { // /** // * Check if a string has non-empty content. // * // * @param s the string // * @return true if the string is null, empty or comprised only of empty characters spaces, tabs, \n, etc), // * otherwise false // */ // public static boolean isEmpty(String s) // { // return s == null || s.trim().length() == 0; // } // // public static String summarize(String s) // { // String result = ""; // if (!isEmpty(s)) // { // result = s.length() <= 100 ? s : s.substring(0, 100) + "..."; // } // return result; // } // }
import be.objectify.deadbolt.AbstractDynamicResourceHandler; import be.objectify.deadbolt.DeadboltHandler; import models.User; import models.Vote; import play.Logger; import play.mvc.Http; import utils.StringUtils; import java.util.Iterator;
/* * Copyright 2012 The Play! Framework * * 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 security.dynamic; /** * @author Steve Chaloner */ public class AllowToVote extends AbstractDynamicResourceHandler { public static final String KEY = "allowToVote"; @Override public boolean isAllowed(String name, String meta, DeadboltHandler deadboltHandler, Http.Context ctx) { boolean allowed = true; if (StringUtils.isEmpty(meta)) { Logger.error("HasVoted required a moduleKey in the meta data"); } else {
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/models/Vote.java // @Entity // public class Vote extends AbstractModel // { // public enum VoteType { UP, DOWN } // // @OneToOne(optional = false) // public Module playModule; // // @Column(nullable = false) // public Boolean publicVote; // // @Column(nullable = false) // @Enumerated(EnumType.STRING) // public VoteType voteType; // // public boolean isUpVote() // { // return voteType == VoteType.UP; // } // // } // // Path: app/utils/StringUtils.java // public class StringUtils // { // /** // * Check if a string has non-empty content. // * // * @param s the string // * @return true if the string is null, empty or comprised only of empty characters spaces, tabs, \n, etc), // * otherwise false // */ // public static boolean isEmpty(String s) // { // return s == null || s.trim().length() == 0; // } // // public static String summarize(String s) // { // String result = ""; // if (!isEmpty(s)) // { // result = s.length() <= 100 ? s : s.substring(0, 100) + "..."; // } // return result; // } // } // Path: app/security/dynamic/AllowToVote.java import be.objectify.deadbolt.AbstractDynamicResourceHandler; import be.objectify.deadbolt.DeadboltHandler; import models.User; import models.Vote; import play.Logger; import play.mvc.Http; import utils.StringUtils; import java.util.Iterator; /* * Copyright 2012 The Play! Framework * * 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 security.dynamic; /** * @author Steve Chaloner */ public class AllowToVote extends AbstractDynamicResourceHandler { public static final String KEY = "allowToVote"; @Override public boolean isAllowed(String name, String meta, DeadboltHandler deadboltHandler, Http.Context ctx) { boolean allowed = true; if (StringUtils.isEmpty(meta)) { Logger.error("HasVoted required a moduleKey in the meta data"); } else {
User user = (User) deadboltHandler.getRoleHolder(ctx);
playframework/modules.playframework.org
app/security/dynamic/AllowToVote.java
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/models/Vote.java // @Entity // public class Vote extends AbstractModel // { // public enum VoteType { UP, DOWN } // // @OneToOne(optional = false) // public Module playModule; // // @Column(nullable = false) // public Boolean publicVote; // // @Column(nullable = false) // @Enumerated(EnumType.STRING) // public VoteType voteType; // // public boolean isUpVote() // { // return voteType == VoteType.UP; // } // // } // // Path: app/utils/StringUtils.java // public class StringUtils // { // /** // * Check if a string has non-empty content. // * // * @param s the string // * @return true if the string is null, empty or comprised only of empty characters spaces, tabs, \n, etc), // * otherwise false // */ // public static boolean isEmpty(String s) // { // return s == null || s.trim().length() == 0; // } // // public static String summarize(String s) // { // String result = ""; // if (!isEmpty(s)) // { // result = s.length() <= 100 ? s : s.substring(0, 100) + "..."; // } // return result; // } // }
import be.objectify.deadbolt.AbstractDynamicResourceHandler; import be.objectify.deadbolt.DeadboltHandler; import models.User; import models.Vote; import play.Logger; import play.mvc.Http; import utils.StringUtils; import java.util.Iterator;
/* * Copyright 2012 The Play! Framework * * 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 security.dynamic; /** * @author Steve Chaloner */ public class AllowToVote extends AbstractDynamicResourceHandler { public static final String KEY = "allowToVote"; @Override public boolean isAllowed(String name, String meta, DeadboltHandler deadboltHandler, Http.Context ctx) { boolean allowed = true; if (StringUtils.isEmpty(meta)) { Logger.error("HasVoted required a moduleKey in the meta data"); } else { User user = (User) deadboltHandler.getRoleHolder(ctx); if (user != null) {
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/models/Vote.java // @Entity // public class Vote extends AbstractModel // { // public enum VoteType { UP, DOWN } // // @OneToOne(optional = false) // public Module playModule; // // @Column(nullable = false) // public Boolean publicVote; // // @Column(nullable = false) // @Enumerated(EnumType.STRING) // public VoteType voteType; // // public boolean isUpVote() // { // return voteType == VoteType.UP; // } // // } // // Path: app/utils/StringUtils.java // public class StringUtils // { // /** // * Check if a string has non-empty content. // * // * @param s the string // * @return true if the string is null, empty or comprised only of empty characters spaces, tabs, \n, etc), // * otherwise false // */ // public static boolean isEmpty(String s) // { // return s == null || s.trim().length() == 0; // } // // public static String summarize(String s) // { // String result = ""; // if (!isEmpty(s)) // { // result = s.length() <= 100 ? s : s.substring(0, 100) + "..."; // } // return result; // } // } // Path: app/security/dynamic/AllowToVote.java import be.objectify.deadbolt.AbstractDynamicResourceHandler; import be.objectify.deadbolt.DeadboltHandler; import models.User; import models.Vote; import play.Logger; import play.mvc.Http; import utils.StringUtils; import java.util.Iterator; /* * Copyright 2012 The Play! Framework * * 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 security.dynamic; /** * @author Steve Chaloner */ public class AllowToVote extends AbstractDynamicResourceHandler { public static final String KEY = "allowToVote"; @Override public boolean isAllowed(String name, String meta, DeadboltHandler deadboltHandler, Http.Context ctx) { boolean allowed = true; if (StringUtils.isEmpty(meta)) { Logger.error("HasVoted required a moduleKey in the meta data"); } else { User user = (User) deadboltHandler.getRoleHolder(ctx); if (user != null) {
for (Iterator<Vote> iterator = user.votes.iterator(); allowed && iterator.hasNext(); )
playframework/modules.playframework.org
app/actors/FeedCreationActor.java
// Path: app/models/HistoricalEvent.java // @Entity // public class HistoricalEvent extends AbstractModel // { // @Column(nullable = false) // public Date creationDate; // // @Column(nullable = false) // public String category; // // @Column(length = 1000, // nullable = false) // public String message; // // public static final Finder<Long, HistoricalEvent> FIND = new Finder<Long, HistoricalEvent>(Long.class, // HistoricalEvent.class); // // public static List<HistoricalEvent> findMostRecent(int count) // { // return FIND.where().orderBy("creationDate DESC").setMaxRows(count).findList(); // } // } // // Path: app/utils/IOUtils.java // public class IOUtils // { // private IOUtils() // { // // no-op // } // // public static void close(Closeable closeable) // { // if (closeable != null) // { // try // { // closeable.close(); // } // catch (IOException e) // { // Logger.error("Unable to close", // e); // } // } // } // }
import akka.actor.UntypedActor; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndContentImpl; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndEntryImpl; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.feed.synd.SyndFeedImpl; import com.sun.syndication.io.FeedException; import com.sun.syndication.io.SyndFeedOutput; import models.HistoricalEvent; import play.Logger; import play.Play; import utils.IOUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;
/* * Copyright 2012 The Play! Framework * * 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 actors; /** * @author Steve Chaloner (steve@objectify.be) */ public class FeedCreationActor extends UntypedActor { public final Map<String, String> feedDetails = new LinkedHashMap<String, String>(); public FeedCreationActor() { feedDetails.put("atom_1.0", "atom"); feedDetails.put("rss_1.0", "rss1"); feedDetails.put("rss_2.0", "rss2"); } @Override public void onReceive(Object o) throws Exception {
// Path: app/models/HistoricalEvent.java // @Entity // public class HistoricalEvent extends AbstractModel // { // @Column(nullable = false) // public Date creationDate; // // @Column(nullable = false) // public String category; // // @Column(length = 1000, // nullable = false) // public String message; // // public static final Finder<Long, HistoricalEvent> FIND = new Finder<Long, HistoricalEvent>(Long.class, // HistoricalEvent.class); // // public static List<HistoricalEvent> findMostRecent(int count) // { // return FIND.where().orderBy("creationDate DESC").setMaxRows(count).findList(); // } // } // // Path: app/utils/IOUtils.java // public class IOUtils // { // private IOUtils() // { // // no-op // } // // public static void close(Closeable closeable) // { // if (closeable != null) // { // try // { // closeable.close(); // } // catch (IOException e) // { // Logger.error("Unable to close", // e); // } // } // } // } // Path: app/actors/FeedCreationActor.java import akka.actor.UntypedActor; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndContentImpl; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndEntryImpl; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.feed.synd.SyndFeedImpl; import com.sun.syndication.io.FeedException; import com.sun.syndication.io.SyndFeedOutput; import models.HistoricalEvent; import play.Logger; import play.Play; import utils.IOUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /* * Copyright 2012 The Play! Framework * * 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 actors; /** * @author Steve Chaloner (steve@objectify.be) */ public class FeedCreationActor extends UntypedActor { public final Map<String, String> feedDetails = new LinkedHashMap<String, String>(); public FeedCreationActor() { feedDetails.put("atom_1.0", "atom"); feedDetails.put("rss_1.0", "rss1"); feedDetails.put("rss_2.0", "rss2"); } @Override public void onReceive(Object o) throws Exception {
List<HistoricalEvent> historicalEvents = HistoricalEvent.findMostRecent(10);
playframework/modules.playframework.org
app/actors/FeedCreationActor.java
// Path: app/models/HistoricalEvent.java // @Entity // public class HistoricalEvent extends AbstractModel // { // @Column(nullable = false) // public Date creationDate; // // @Column(nullable = false) // public String category; // // @Column(length = 1000, // nullable = false) // public String message; // // public static final Finder<Long, HistoricalEvent> FIND = new Finder<Long, HistoricalEvent>(Long.class, // HistoricalEvent.class); // // public static List<HistoricalEvent> findMostRecent(int count) // { // return FIND.where().orderBy("creationDate DESC").setMaxRows(count).findList(); // } // } // // Path: app/utils/IOUtils.java // public class IOUtils // { // private IOUtils() // { // // no-op // } // // public static void close(Closeable closeable) // { // if (closeable != null) // { // try // { // closeable.close(); // } // catch (IOException e) // { // Logger.error("Unable to close", // e); // } // } // } // }
import akka.actor.UntypedActor; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndContentImpl; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndEntryImpl; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.feed.synd.SyndFeedImpl; import com.sun.syndication.io.FeedException; import com.sun.syndication.io.SyndFeedOutput; import models.HistoricalEvent; import play.Logger; import play.Play; import utils.IOUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;
entries.add(entry); } feed.setEntries(entries); Writer writer = null; try { File outputFile = new File(outputDirectory, String.format("mpo.%s.xml", classifier)); writer = new FileWriter(outputFile); SyndFeedOutput output = new SyndFeedOutput(); output.output(feed,writer); writer.close(); } catch (IOException e) { Logger.error(String.format("A problem occurred when generating the %s feed", classifier), e); } catch (FeedException e) { Logger.error(String.format("A problem occurred when generating the %s feed", classifier), e); } finally {
// Path: app/models/HistoricalEvent.java // @Entity // public class HistoricalEvent extends AbstractModel // { // @Column(nullable = false) // public Date creationDate; // // @Column(nullable = false) // public String category; // // @Column(length = 1000, // nullable = false) // public String message; // // public static final Finder<Long, HistoricalEvent> FIND = new Finder<Long, HistoricalEvent>(Long.class, // HistoricalEvent.class); // // public static List<HistoricalEvent> findMostRecent(int count) // { // return FIND.where().orderBy("creationDate DESC").setMaxRows(count).findList(); // } // } // // Path: app/utils/IOUtils.java // public class IOUtils // { // private IOUtils() // { // // no-op // } // // public static void close(Closeable closeable) // { // if (closeable != null) // { // try // { // closeable.close(); // } // catch (IOException e) // { // Logger.error("Unable to close", // e); // } // } // } // } // Path: app/actors/FeedCreationActor.java import akka.actor.UntypedActor; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndContentImpl; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndEntryImpl; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.feed.synd.SyndFeedImpl; import com.sun.syndication.io.FeedException; import com.sun.syndication.io.SyndFeedOutput; import models.HistoricalEvent; import play.Logger; import play.Play; import utils.IOUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; entries.add(entry); } feed.setEntries(entries); Writer writer = null; try { File outputFile = new File(outputDirectory, String.format("mpo.%s.xml", classifier)); writer = new FileWriter(outputFile); SyndFeedOutput output = new SyndFeedOutput(); output.output(feed,writer); writer.close(); } catch (IOException e) { Logger.error(String.format("A problem occurred when generating the %s feed", classifier), e); } catch (FeedException e) { Logger.error(String.format("A problem occurred when generating the %s feed", classifier), e); } finally {
IOUtils.close(writer);
playframework/modules.playframework.org
app/actions/CurrentUser.java
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/utils/StringUtils.java // public class StringUtils // { // /** // * Check if a string has non-empty content. // * // * @param s the string // * @return true if the string is null, empty or comprised only of empty characters spaces, tabs, \n, etc), // * otherwise false // */ // public static boolean isEmpty(String s) // { // return s == null || s.trim().length() == 0; // } // // public static String summarize(String s) // { // String result = ""; // if (!isEmpty(s)) // { // result = s.length() <= 100 ? s : s.substring(0, 100) + "..."; // } // return result; // } // }
import com.avaje.ebean.Ebean; import models.User; import play.mvc.Action; import play.mvc.Http; import play.mvc.Result; import utils.StringUtils;
/* * Copyright 2012 The Play! Framework * * 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 actions; /** * @author Steve Chaloner (steve@objectify.be) */ public class CurrentUser extends Action.Simple { @Override public Result call(Http.Context ctx) throws Throwable { accessUser(ctx); return delegate.call(ctx); }
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/utils/StringUtils.java // public class StringUtils // { // /** // * Check if a string has non-empty content. // * // * @param s the string // * @return true if the string is null, empty or comprised only of empty characters spaces, tabs, \n, etc), // * otherwise false // */ // public static boolean isEmpty(String s) // { // return s == null || s.trim().length() == 0; // } // // public static String summarize(String s) // { // String result = ""; // if (!isEmpty(s)) // { // result = s.length() <= 100 ? s : s.substring(0, 100) + "..."; // } // return result; // } // } // Path: app/actions/CurrentUser.java import com.avaje.ebean.Ebean; import models.User; import play.mvc.Action; import play.mvc.Http; import play.mvc.Result; import utils.StringUtils; /* * Copyright 2012 The Play! Framework * * 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 actions; /** * @author Steve Chaloner (steve@objectify.be) */ public class CurrentUser extends Action.Simple { @Override public Result call(Http.Context ctx) throws Throwable { accessUser(ctx); return delegate.call(ctx); }
private static User accessUser(Http.Context ctx)
playframework/modules.playframework.org
app/actions/CurrentUser.java
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/utils/StringUtils.java // public class StringUtils // { // /** // * Check if a string has non-empty content. // * // * @param s the string // * @return true if the string is null, empty or comprised only of empty characters spaces, tabs, \n, etc), // * otherwise false // */ // public static boolean isEmpty(String s) // { // return s == null || s.trim().length() == 0; // } // // public static String summarize(String s) // { // String result = ""; // if (!isEmpty(s)) // { // result = s.length() <= 100 ? s : s.substring(0, 100) + "..."; // } // return result; // } // }
import com.avaje.ebean.Ebean; import models.User; import play.mvc.Action; import play.mvc.Http; import play.mvc.Result; import utils.StringUtils;
/* * Copyright 2012 The Play! Framework * * 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 actions; /** * @author Steve Chaloner (steve@objectify.be) */ public class CurrentUser extends Action.Simple { @Override public Result call(Http.Context ctx) throws Throwable { accessUser(ctx); return delegate.call(ctx); } private static User accessUser(Http.Context ctx) { User user = (User)ctx.args.get("user"); if (user == null) { String userName = ctx.session().get("userName");
// Path: app/models/User.java // @Entity // @Table(name = "MPO_USER") // public class User extends AbstractModel implements RoleHolder // { // // @Column(nullable = false, length = 40, unique = true) // public String userName; // // @Column(nullable = false, length = 100) // public String displayName; // // @Column(name = "passwd", nullable = false, length = 64) // public String password; // // @Column(nullable = true, length = 2500) // public String avatarUrl; // // @Column(nullable = false) // public Boolean accountActive; // // @Column(nullable = true, length = 36) // public String confirmationCode; // // @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.REFRESH}) // public List<UserRole> roles; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Vote> votes; // // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // public List<Rate> rates; // // public static final Finder<Long, User> FIND = new Finder<Long, User>(Long.class, // User.class); // // public static int count() { // return FIND.findRowCount(); // } // // public static User findByUserName(String userName) { // return FIND.where() // .eq("userName", userName) // .findUnique(); // } // // public static User authenticate(String userName, // String password) { // return FIND.where() // .eq("userName", userName) // .eq("password", password) // .findUnique(); // } // // @Override // public List<? extends Role> getRoles() // { // return roles; // } // // @Override // public List<? extends Permission> getPermissions() // { // // for now, let's go with role-based security. I don't think we need any fine-grained control. // return Collections.emptyList(); // } // } // // Path: app/utils/StringUtils.java // public class StringUtils // { // /** // * Check if a string has non-empty content. // * // * @param s the string // * @return true if the string is null, empty or comprised only of empty characters spaces, tabs, \n, etc), // * otherwise false // */ // public static boolean isEmpty(String s) // { // return s == null || s.trim().length() == 0; // } // // public static String summarize(String s) // { // String result = ""; // if (!isEmpty(s)) // { // result = s.length() <= 100 ? s : s.substring(0, 100) + "..."; // } // return result; // } // } // Path: app/actions/CurrentUser.java import com.avaje.ebean.Ebean; import models.User; import play.mvc.Action; import play.mvc.Http; import play.mvc.Result; import utils.StringUtils; /* * Copyright 2012 The Play! Framework * * 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 actions; /** * @author Steve Chaloner (steve@objectify.be) */ public class CurrentUser extends Action.Simple { @Override public Result call(Http.Context ctx) throws Throwable { accessUser(ctx); return delegate.call(ctx); } private static User accessUser(Http.Context ctx) { User user = (User)ctx.args.get("user"); if (user == null) { String userName = ctx.session().get("userName");
if (!StringUtils.isEmpty(userName))
playframework/modules.playframework.org
test/test/ValidationAssert.java
// Path: test/test/ModulesAssertions.java // public static ValidationAssert assertThat(Model model) { // return new ValidationAssert(model); // }
import org.fest.assertions.GenericAssert; import javax.validation.ConstraintViolation; import java.util.Set; import static play.data.validation.Validation.getValidator; import static test.ModulesAssertions.assertThat;
package test; public class ValidationAssert extends GenericAssert<ValidationAssert, Object> { public ValidationAssert(Object model) { super(ValidationAssert.class, model); } public ValidationAssert isValid() {
// Path: test/test/ModulesAssertions.java // public static ValidationAssert assertThat(Model model) { // return new ValidationAssert(model); // } // Path: test/test/ValidationAssert.java import org.fest.assertions.GenericAssert; import javax.validation.ConstraintViolation; import java.util.Set; import static play.data.validation.Validation.getValidator; import static test.ModulesAssertions.assertThat; package test; public class ValidationAssert extends GenericAssert<ValidationAssert, Object> { public ValidationAssert(Object model) { super(ValidationAssert.class, model); } public ValidationAssert isValid() {
assertThat(validate()).isEmpty();